-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.go
101 lines (83 loc) · 1.85 KB
/
api.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
package sendxbmc
import (
"bytes"
"encoding/json"
"fmt"
"log"
"math/rand"
"net/http"
)
type XbmcApi struct {
Host string
Port uint
}
func NewXbmcApi(h string, p uint) *XbmcApi {
return &XbmcApi{
Host: h,
Port: p,
}
}
type XbmcRequest struct {
Method string `json:"method"`
Id uint32 `json:"id"`
JsonRpc string `json:"jsonrpc"`
Params interface{} `json:"params"`
}
func NewXbmcRequest(method string, params interface{}) *XbmcRequest {
return &XbmcRequest{
Method: method,
Id: rand.Uint32(),
JsonRpc: "2.0",
Params: params,
}
}
type PlayerOpenParams struct {
Item PlayerOpenParamsItem `json:"item"`
}
type PlayerOpenParamsItem struct {
File string `json:"file"`
}
func NewPlayerOpenParams(url string) *PlayerOpenParams {
return &PlayerOpenParams{
Item: PlayerOpenParamsItem{
File: url,
},
}
}
type Notification struct {
Title string `json:"title"`
Message string `json:"message"`
}
func NewNotification(title, msg string) *Notification {
return &Notification{
Title: title,
Message: msg,
}
}
func (a XbmcApi) SendXbmc(r *XbmcRequest) error {
xbmcUrl := fmt.Sprintf("http://%s:%d/jsonrpc", a.Host, a.Port)
log.Println(xbmcUrl)
enc, err := json.Marshal(r)
if err != nil {
return err
log.Printf("%s\n", enc)
}
resp, err := http.Post(xbmcUrl, "application/json", bytes.NewReader(enc))
if err != nil {
return err
}
log.Printf("%v\n", resp)
return nil
}
func (a XbmcApi) SendNotification(title, msg string) error {
return a.SendXbmc(NewXbmcRequest("GUI.ShowNotification", NewNotification(title, msg)))
}
func (a XbmcApi) SendErrorNotification(err error) {
log.Println(err)
if err := a.SendNotification("send-xbmc error", err.Error()); err != nil {
log.Fatal(err)
}
}
func (a XbmcApi) Play(url string) error {
return a.SendXbmc(NewXbmcRequest("Player.Open", NewPlayerOpenParams(url)))
}