github.com/rigado/snapd@v2.42.5-go-mod+incompatible/xdgopenproxy/xdgopenproxy.go (about) 1 // -*- Mode: Go; indent-tabs-mode: t -*- 2 3 /* 4 * Copyright (C) 2018 Canonical Ltd 5 * 6 * This program is free software: you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License version 3 as 8 * published by the Free Software Foundation. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License 16 * along with this program. If not, see <http://www.gnu.org/licenses/>. 17 * 18 */ 19 20 // Package xdgopenproxy provides a client for snap userd's xdg-open D-Bus proxy 21 package xdgopenproxy 22 23 import ( 24 "net/url" 25 "syscall" 26 27 "github.com/godbus/dbus" 28 ) 29 30 func Run(urlOrFile string) error { 31 bus, err := dbus.SessionBus() 32 if err != nil { 33 return err 34 } 35 defer bus.Close() 36 launcher := bus.Object("io.snapcraft.Launcher", "/io/snapcraft/Launcher") 37 return launch(launcher, urlOrFile) 38 } 39 40 func launch(launcher dbus.BusObject, urlOrFile string) error { 41 if u, err := url.Parse(urlOrFile); err == nil { 42 if u.Scheme == "file" { 43 return openFile(launcher, u.Path) 44 } else if u.Scheme != "" { 45 return openUrl(launcher, urlOrFile) 46 } 47 } 48 return openFile(launcher, urlOrFile) 49 } 50 51 func openUrl(launcher dbus.BusObject, url string) error { 52 return launcher.Call("io.snapcraft.Launcher.OpenURL", 0, url).Err 53 } 54 55 func openFile(launcher dbus.BusObject, filename string) error { 56 fd, err := syscall.Open(filename, syscall.O_RDONLY, 0) 57 if err != nil { 58 return err 59 } 60 defer syscall.Close(fd) 61 62 return launcher.Call("io.snapcraft.Launcher.OpenFile", 0, "", dbus.UnixFD(fd)).Err 63 }