-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
95 lines (79 loc) · 2.24 KB
/
main.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
package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/jessevdk/go-flags"
"github.com/marcioAlmada/goremote/upnp"
)
type application interface {
PromptPinCode() string
Run(upnp.Client, keyMap, keyMap) error
}
type options struct {
Args struct{ IP string } `positional-args:"yes" required:"yes"`
REPL bool `short:"r" long:"repl" description:"Use a command line REPL session instead of gui"`
}
func main() {
storagePath := getStoragePath()
os.MkdirAll(storagePath, 0777) // setup
var options options
_, e := flags.Parse(&options)
nuke(e)
var app application
if options.REPL {
app = newCursesApplication()
} else {
app = newGtkApplication()
}
client := upnp.NewClient(options.Args.IP, fileGetContents(storagePath+options.Args.IP))
response, e := client.Handshake()
nuke(e, "Could not find device.")
if 401 == response.StatusCode { // authorize in case client is not authorized yet
pin := app.PromptPinCode() // get pin code from device
response, e = client.Authorize(pin)
nuke(e, "Authentication failed. Is the pin code right?")
}
if 200 == response.StatusCode { // authenticated
_, e := client.RequestControlsList() // let's get UPnP control list from device
nuke(e, "Maybe device is off?")
e = client.RequestSystemInformation()
nuke(e, "Failed to retrieve device information")
filePutContents(storagePath+client.IP, client.Mac) // cache device info
e = app.Run(client, defaultKeyMap, alternativeKeyMap) // run!
nuke(e, "Failed to launch application")
}
}
func nuke(err error, msgs ...interface{}) {
if err != nil {
if len(msgs) > 0 {
fmt.Fprintln(os.Stderr, msgs...)
}
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}
func getStoragePath() string {
return os.Getenv("HOME") + "/.gocontroller/"
}
func fileGetContents(filename string) string {
fp, err := os.Open(filename)
if err != nil {
return ""
}
defer fp.Close()
reader := bufio.NewReader(fp)
bytes, _ := ioutil.ReadAll(reader)
return strings.TrimRight(string(bytes), "\n\r")
}
func filePutContents(filename string, content string) (err error) {
fp, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, os.ModePerm)
if err != nil {
return
}
defer fp.Close()
_, err = fp.Write([]byte(content))
return
}