forked from snapcore/snapd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xdgopenproxy.go
88 lines (75 loc) · 2.19 KB
/
xdgopenproxy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2018 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
// Package xdgopenproxy provides a client for snap userd's xdg-open D-Bus proxy
package xdgopenproxy
import (
"net/url"
"github.com/godbus/dbus"
"golang.org/x/xerrors"
)
type responseError struct {
msg string
}
func (u *responseError) Error() string { return u.msg }
func (u *responseError) Is(err error) bool {
_, ok := err.(*responseError)
return ok
}
type desktopLauncher interface {
OpenFile(bus *dbus.Conn, path string) error
OpenURI(bus *dbus.Conn, url string) error
}
var availableLaunchers = []desktopLauncher{
&portalLauncher{},
&userdLauncher{},
}
// Run attempts to open given file or URL using one of available launchers
func Run(urlOrFile string) error {
bus, err := dbus.SessionBus()
if err != nil {
return err
}
defer bus.Close()
return launch(bus, availableLaunchers, urlOrFile)
}
func launchWithOne(bus *dbus.Conn, l desktopLauncher, urlOrFile string) error {
if u, err := url.Parse(urlOrFile); err == nil {
if u.Scheme == "file" {
return l.OpenFile(bus, u.Path)
} else if u.Scheme != "" {
return l.OpenURI(bus, urlOrFile)
}
}
return l.OpenFile(bus, urlOrFile)
}
func launch(bus *dbus.Conn, launchers []desktopLauncher, urlOrFile string) error {
var err error
for _, l := range launchers {
err = launchWithOne(bus, l, urlOrFile)
if err == nil {
break
}
if xerrors.Is(err, &responseError{}) {
// got a response which indicates the action was either
// explicitly rejected by the user or abandoned due to
// other reasons eg. timeout waiting for user to respond
break
}
}
return err
}