-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstatus.go
92 lines (77 loc) · 1.71 KB
/
status.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
package main
import (
"fmt"
"github.com/ziutek/telnet"
"io"
"log"
"os"
"strings"
"sync"
"time"
)
type status struct {
mu sync.Mutex
Online int `json:"online"`
Usernames []string `json:"usernames"`
}
func (st *status) set(online int, usernames []string) {
st.mu.Lock()
defer st.mu.Unlock()
st.Online = online
st.Usernames = usernames
}
func (st *status) get() (int, []string) {
st.mu.Lock()
defer st.mu.Unlock()
return st.Online, st.Usernames
}
func fetchTsStatus(host, username, password string) status {
timeout, err := time.ParseDuration("5s")
if err != nil {
panic(err)
}
conn, err := telnet.DialTimeout("tcp", host, timeout)
if err != nil {
panic(err)
}
err = conn.SkipUntil("command.\n\r")
if err != nil {
panic(err)
}
cmd := fmt.Sprintf("login %v %v\nuse 1\nclientlist\nquit\n", username, password)
_, err = conn.Write([]byte(cmd))
if err != nil {
panic(err)
}
usernames := make([]string, 0)
for {
response, err := conn.ReadString('\r')
if err == io.EOF {
break
} else if err != nil {
log.Panic(err)
}
if response == "error id=0 msg=ok\n\r" {
continue
}
matches := userRegex.FindAllStringSubmatch(response, -1)
for _, match := range matches {
if strings.HasPrefix(match[1], username) || excludeUsername(match[1]) {
continue
}
usernames = append(usernames, match[1])
}
}
return status{
Online: len(usernames),
Usernames: usernames,
}
}
func fetchTsStatusCron() {
host := os.Getenv("TS_HOST")
username := os.Getenv("TS_USERNAME")
password := os.Getenv("TS_PASSWORD")
newStatus := fetchTsStatus(host, username, password)
currentStatus.set(newStatus.Online, newStatus.Usernames)
connectedSockets.PushStatus(¤tStatus)
}