forked from zoli/nordtray
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nordvpn.go
109 lines (91 loc) · 1.73 KB
/
nordvpn.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package main
import (
"context"
"errors"
"regexp"
"sync"
"time"
log "github.com/sirupsen/logrus"
)
type (
Status int
NordVPN struct {
sync.Mutex
status Status
connected bool
}
)
const (
STALLED Status = iota
FAILED
NONETWORK
DONE
CONNECTED = "Connected"
DISCONNECTED = "Disconnected"
noNetErrStr = "Please check your internet connection and try again"
)
var (
ErrNoNet = errors.New("no network connection")
statusRe = regexp.MustCompile("Status: (.*)")
)
func (n *NordVPN) Update() {
n.Lock()
defer n.Unlock()
out, err := execCmd(2*time.Second, "nordvpn", "status")
if err != nil {
n.parseErr("update", err)
return
}
n.status = DONE
n.parse(out)
}
func (n *NordVPN) parse(data string) {
var status string
ss := statusRe.FindStringSubmatch(data)
if len(ss) > 1 {
status = ss[1]
}
switch status {
case CONNECTED:
n.connected = true
case DISCONNECTED:
n.connected = false
default:
n.status = STALLED
log.Warnf("unrecognized status %s", status)
}
}
func (n *NordVPN) parseErr(cmd string, err error) {
if err == context.DeadlineExceeded {
log.Errorf("on %s exceeded timeout", cmd)
n.status = STALLED
} else if err == ErrNoNet {
log.Debugln("on %s: no network", cmd)
n.status = NONETWORK
} else {
log.Errorf("on %s: %s", cmd, err)
n.status = FAILED
}
}
func (n *NordVPN) Status() Status {
return n.status
}
func (n *NordVPN) Connect() {
_, err := execCmd(3*time.Second, "nordvpn", "c")
if err != nil {
n.parseErr("connect", err)
return
}
n.status = DONE
}
func (n *NordVPN) Disconnect() {
_, err := execCmd(3*time.Second, "nordvpn", "d")
if err != nil {
n.parseErr("disconnect", err)
return
}
n.status = DONE
}
func (n *NordVPN) Connected() bool {
return n.connected
}