forked from zankich/groku
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgroku.go
400 lines (357 loc) · 9.25 KB
/
groku.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
package main
import (
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/mitchellh/go-homedir"
)
var CONFIG string
const (
VERSION = "0.4.1"
USAGE = `usage: groku [--version] [--help] <command> [<args>]
CLI remote for your Roku
Commands:
home Return to the home screen
rev Reverse
fwd Fast Forward
select Select
left Left
right Right
up Up
down Down
back Back
info Info
backspace Backspace
enter Enter
search Search
replay Replay
play Play
pause Pause
discover Discover Roku devices on your local network
list List known Roku devices
use Set Roku name to use
device-info Display device info
text Send text to the Roku
apps List installed apps on your Roku
app Launch specified app
on Power On
off Power Off
volup Volume Up
voldown Volume Down
mute Volume Mute/Unmute
`
)
type dictionary struct {
XMLName xml.Name `xml:"apps"`
Apps []app `xml:"app"`
}
type deviceinfo struct {
XMLName xml.Name `xml:"device-info"`
UDN string `xml:"udn"`
Serial string `xml:"serial-number"`
DeviceID string `xml:"device-id"`
ModelNum string `xml:"model-number"`
ModelName string `xml:"model-name"`
DeviceName string `xml:"user-device-name"`
}
type roku struct {
Address string `json:"address"`
Name string `json:"name"`
}
type app struct {
Name string `xml:",chardata"`
ID string `xml:"id,attr"`
}
type grokuConfig struct {
LastName string `json:"lastname"`
Current roku `json:"current"`
Rokus []roku `json:"rokus"`
Timestamp int64 `json:"timestamp"`
}
func main() {
home, err := homedir.Dir()
if err != nil {
fmt.Println("Cannot find home directory")
os.Exit(1)
}
CONFIG = fmt.Sprintf("%s/.groku.json", home)
if len(os.Args) == 1 || os.Args[1] == "--help" || os.Args[1] == "-help" ||
os.Args[1] == "--h" || os.Args[1] == "-h" || os.Args[1] == "help" {
fmt.Println(USAGE)
os.Exit(0)
}
if len(os.Args) == 2 && (os.Args[1] == "-v" || os.Args[1] == "--version" ||
os.Args[1] == "--version") {
fmt.Printf("groku version %s\n", VERSION)
os.Exit(0)
}
switch os.Args[1] {
case "home", "rev", "fwd", "select", "left", "right", "down", "up",
"back", "info", "backspace", "enter", "search":
http.PostForm(fmt.Sprintf("%vkeypress/%v", getCurrentRokuAddress(), os.Args[1]), nil)
os.Exit(0)
case "replay":
http.PostForm(fmt.Sprintf("%vkeypress/%v", getCurrentRokuAddress(), "InstantReplay"), nil)
os.Exit(0)
case "play", "pause":
http.PostForm(fmt.Sprintf("%vkeypress/%v", getCurrentRokuAddress(), "Play"), nil)
os.Exit(0)
case "volup", "voldown", "mute":
http.PostForm(fmt.Sprintf("%vkeypress/Volume%v", getCurrentRokuAddress(), strings.TrimPrefix(os.Args[1], "vol")), nil)
os.Exit(0)
case "off", "on":
http.PostForm(fmt.Sprintf("%vkeypress/Power%v", getCurrentRokuAddress(), os.Args[1]), nil)
os.Exit(0)
case "discover":
config := getRokuConfig()
if len(config.Rokus) > 0 {
for _, r := range config.Rokus {
fmt.Print("Found roku at ", r.Address)
if r.Name != "" {
fmt.Print(" named ", r.Name)
}
fmt.Println()
}
}
os.Exit(0)
case "list":
config := getRokuConfig()
for _, r := range config.Rokus {
if r.Name != "" {
fmt.Print(r.Name, ": ")
}
fmt.Println(r.Address)
}
case "use":
config := getRokuConfig()
for _, r := range config.Rokus {
if strings.ToUpper(os.Args[2]) == strings.ToUpper(r.Name) {
config.Current = r
config.LastName = os.Args[2]
writeConfig(config)
fmt.Printf("Using Roku named %v at %v\n", r.Name, r.Address)
os.Exit(0)
}
}
fmt.Printf("Cannot find Roku named %v\n", os.Args[2])
case "device-info":
info, err := queryInfo()
if err == nil && getCurrentRokuName() != "" {
fmt.Printf("Name:\t\t%v\n", info.DeviceName)
}
fmt.Printf("Model:\t\t%v %v\n", info.ModelName, info.ModelNum)
fmt.Printf("Serial:\t\t%v\n", info.Serial)
case "text":
if len(os.Args) < 3 {
fmt.Println(USAGE)
os.Exit(1)
}
roku := getCurrentRokuAddress()
for _, c := range os.Args[2] {
http.PostForm(fmt.Sprintf("%skeypress/Lit_%s", roku, url.QueryEscape(string(c))), nil)
}
os.Exit(0)
case "apps":
dict := queryApps()
for _, a := range dict.Apps {
fmt.Println(a.Name)
}
os.Exit(0)
case "app":
if len(os.Args) < 3 {
fmt.Println(USAGE)
os.Exit(1)
}
dict := queryApps()
for _, a := range dict.Apps {
if a.Name == os.Args[2] {
http.PostForm(fmt.Sprintf("%vlaunch/%v", getCurrentRokuAddress(), a.ID), nil)
os.Exit(0)
}
}
fmt.Printf("App %q not found\n", os.Args[2])
os.Exit(1)
default:
fmt.Println(USAGE)
os.Exit(1)
}
}
func queryApps() dictionary {
resp, err := http.Get(fmt.Sprintf("%squery/apps", getCurrentRokuAddress()))
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer resp.Body.Close()
var dict dictionary
if err := xml.NewDecoder(resp.Body).Decode(&dict); err != nil {
fmt.Println(err)
os.Exit(1)
}
return dict
}
func queryInfoForAddress(address string) (deviceinfo, error) {
resp, err := http.Get(fmt.Sprintf("%squery/device-info", address))
var info deviceinfo
if err != nil {
fmt.Println(err)
return info, err
}
defer resp.Body.Close()
if err := xml.NewDecoder(resp.Body).Decode(&info); err != nil {
fmt.Println(err)
return info, err
}
return info, err
}
func queryInfo() (deviceinfo, error) {
return queryInfoForAddress(getCurrentRokuAddress())
}
func findRokus() []roku {
ssdp, err := net.ResolveUDPAddr("udp", "239.255.255.250:1900")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
addr, err := net.ResolveUDPAddr("udp", ":0")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
socket, err := net.ListenUDP("udp", addr)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
_, err = socket.WriteToUDP([]byte("M-SEARCH * HTTP/1.1\r\n"+
"HOST: 239.255.255.250:1900\r\n"+
"MAN: \"ssdp:discover\"\r\n"+
"ST: roku:ecp\r\n"+
"MX: 3 \r\n\r\n"), ssdp)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
var rokus []roku
listentimer := time.Now().Add(5 * time.Second)
for time.Now().Before(listentimer) {
answerBytes := make([]byte, 1024)
err = socket.SetReadDeadline(listentimer)
if err != nil {
fmt.Println(err)
}
_, _, err = socket.ReadFromUDP(answerBytes[:])
if err == nil {
ret := strings.Split(string(answerBytes), "\r\n")
location := strings.TrimPrefix(ret[6], "LOCATION: ")
id := ret[3]
if !strings.Contains(id, "roku") {
continue
}
info, err := queryInfoForAddress(location)
if err == nil {
duplicateDeviceEntry := false
for _, r := range rokus {
if r.Address == location {
duplicateDeviceEntry = true
fmt.Printf("device already in list %s\n", info.DeviceName)
break
}
}
if !duplicateDeviceEntry {
r := roku{Name: info.DeviceName, Address: location}
rokus = append(rokus, r)
}
}
}
}
return rokus
}
func getCurrentRokuAddress() string {
return getRokuConfig().Current.Address
}
func getCurrentRokuName() string {
return getRokuConfig().Current.Name
}
func getRokuConfigFor(name string) (*roku, error) {
config := getRokuConfig()
for _, e := range config.Rokus {
if strings.ToUpper(e.Name) == strings.ToUpper(name) {
return &e, nil
}
}
return nil, errors.New(fmt.Sprintf("%v not found", name))
}
func getRokuConfig() grokuConfig {
var configFile *os.File
var config grokuConfig
configFile, err := os.Open(CONFIG)
// the config file doesn't exist, but that's okay
if err != nil {
config.Rokus = findRokus()
config.Timestamp = time.Now().Unix()
} else {
// the config file exists
if err := json.NewDecoder(configFile).Decode(&config); err != nil {
config.Rokus = findRokus()
}
//if the config file is over 60 seconds old, then replace it
if config.Timestamp == 0 || time.Now().Unix()-config.Timestamp > 60 {
config.Rokus = findRokus()
config.Timestamp = time.Now().Unix()
}
}
if len(config.Rokus) == 0 {
fmt.Println("No rokus found")
os.Exit(1)
}
if config.LastName != "" {
found := false
for _, e := range config.Rokus {
if strings.ToUpper(e.Name) == strings.ToUpper(config.LastName) {
config.Current = e
found = true
}
}
if !found && len(config.Rokus) > 0 {
config.Current = config.Rokus[0]
fmt.Printf("Previously used Roku %v not found anymore, using %v as new default\n", config.LastName, config.Current.Name)
}
} else {
config.Current = config.Rokus[0]
}
writeConfig(config)
return config
}
func writeConfig(config grokuConfig) error {
var oldConfig grokuConfig
oldConfigBytes, err := ioutil.ReadFile(CONFIG)
if err == nil {
json.Unmarshal(oldConfigBytes, &oldConfig)
}
configRokus := []roku{}
if oldConfigBytes != nil {
for _, newR := range config.Rokus {
thisRoku := newR
for _, oldR := range oldConfig.Rokus {
if oldR.Address == newR.Address {
thisRoku = oldR
}
}
configRokus = append(configRokus, thisRoku)
}
config.Rokus = configRokus
}
if b, err := json.Marshal(config); err == nil {
ioutil.WriteFile(CONFIG, b, os.ModePerm)
}
return nil
}