-
Notifications
You must be signed in to change notification settings - Fork 62
/
websocket_client.go
267 lines (222 loc) · 7.47 KB
/
websocket_client.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
package plex
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"time"
"github.com/gorilla/websocket"
)
// TimelineEntry ...
type TimelineEntry struct {
Identifier string `json:"identifier"`
ItemID int64 `json:"itemID"`
MetadataState string `json:"metadataState"`
SectionID int64 `json:"sectionID"`
State int64 `json:"state"`
Title string `json:"title"`
Type int64 `json:"type"`
UpdatedAt int64 `json:"updatedAt"`
}
// ActivityNotification ...
type ActivityNotification struct {
Activity struct {
Cancellable bool `json:"cancellable"`
Progress int64 `json:"progress"`
Subtitle string `json:"subtitle"`
Title string `json:"title"`
Type string `json:"type"`
UserID int64 `json:"userID"`
UUID string `json:"uuid"`
} `json:"Activity"`
Event string `json:"event"`
UUID string `json:"uuid"`
}
// StatusNotification ...
type StatusNotification struct {
Description string `json:"description"`
NotificationName string `json:"notificationName"`
Title string `json:"title"`
}
// PlaySessionStateNotification ...
type PlaySessionStateNotification struct {
GUID string `json:"guid"`
Key string `json:"key"`
PlayQueueItemID int64 `json:"playQueueItemID"`
RatingKey string `json:"ratingKey"`
SessionKey string `json:"sessionKey"`
State string `json:"state"`
URL string `json:"url"`
ViewOffset int64 `json:"viewOffset"`
TranscodeSession string `json:"transcodeSession"`
}
// ReachabilityNotification ...
type ReachabilityNotification struct {
Reachability bool `json:"reachability"`
}
// BackgroundProcessingQueueEventNotification ...
type BackgroundProcessingQueueEventNotification struct {
Event string `json:"event"`
QueueID int64 `json:"queueID"`
}
// TranscodeSession ...
type TranscodeSession struct {
AudioChannels int64 `json:"audioChannels"`
AudioCodec string `json:"audioCodec"`
AudioDecision string `json:"audioDecision"`
Complete bool `json:"complete"`
Container string `json:"container"`
Context string `json:"context"`
Duration int64 `json:"duration"`
Key string `json:"key"`
Progress float64 `json:"progress"`
Protocol string `json:"protocol"`
Remaining int64 `json:"remaining"`
SourceAudioCodec string `json:"sourceAudioCodec"`
SourceVideoCodec string `json:"sourceVideoCodec"`
Speed float64 `json:"speed"`
Throttled bool `json:"throttled"`
TranscodeHwRequested bool `json:"transcodeHwRequested"`
VideoCodec string `json:"videoCodec"`
VideoDecision string `json:"videoDecision"`
}
// Setting ...
type Setting struct {
Advanced bool `json:"advanced"`
Default string `json:"default"`
Group string `json:"group"`
Hidden bool `json:"hidden"`
ID string `json:"id"`
Label string `json:"label"`
Summary string `json:"summary"`
Type string `json:"type"`
Value int64 `json:"value"`
}
// NotificationContainer read pms notifications
type NotificationContainer struct {
TimelineEntry []TimelineEntry `json:"TimelineEntry"`
ActivityNotification []ActivityNotification `json:"ActivityNotification"`
StatusNotification []StatusNotification `json:"StatusNotification"`
PlaySessionStateNotification []PlaySessionStateNotification `json:"PlaySessionStateNotification"`
ReachabilityNotification []ReachabilityNotification `json:"ReachabilityNotification"`
BackgroundProcessingQueueEventNotification []BackgroundProcessingQueueEventNotification `json:"BackgroundProcessingQueueEventNotification"`
TranscodeSession []TranscodeSession `json:"TranscodeSession"`
Setting []Setting `json:"Setting"`
Size int64 `json:"size"`
// Type can be one of:
// playing,
// reachability,
// transcode.end,
// preference,
// update.statechange,
// activity,
// backgroundProcessingQueue,
// transcodeSession.update
// transcodeSession.end
Type string `json:"type"`
}
// WebsocketNotification websocket payload of notifications from a plex media server
type WebsocketNotification struct {
NotificationContainer `json:"NotificationContainer"`
}
// NotificationEvents hold callbacks that correspond to notifications
type NotificationEvents struct {
events map[string]func(n NotificationContainer)
}
// NewNotificationEvents initializes the event callbacks
func NewNotificationEvents() *NotificationEvents {
return &NotificationEvents{
events: map[string]func(n NotificationContainer){
"playing": func(n NotificationContainer) {},
"reachability": func(n NotificationContainer) {},
"transcode.end": func(n NotificationContainer) {},
"transcodeSession.end": func(n NotificationContainer) {},
"transcodeSession.update": func(n NotificationContainer) {},
"preference": func(n NotificationContainer) {},
"update.statechange": func(n NotificationContainer) {},
"activity": func(n NotificationContainer) {},
"backgroundProcessingQueue": func(n NotificationContainer) {},
},
}
}
// OnPlaying shows state information (resume, stop, pause) on a user consuming media in plex
func (e *NotificationEvents) OnPlaying(fn func(n NotificationContainer)) {
e.events["playing"] = fn
}
// OnTranscodeUpdate shows transcode information when a transcoding stream changes parameters
func (e *NotificationEvents) OnTranscodeUpdate(fn func(n NotificationContainer)) {
e.events["transcodeSession.update"] = fn
}
// SubscribeToNotifications connects to your server via websockets listening for events
func (p *Plex) SubscribeToNotifications(events *NotificationEvents, interrupt <-chan os.Signal, fn func(error)) {
plexURL, err := url.Parse(p.URL)
if err != nil {
fn(err)
return
}
websocketURL := url.URL{Scheme: "ws", Host: plexURL.Host, Path: "/:/websockets/notifications"}
headers := http.Header{
"X-Plex-Token": []string{p.Token},
}
c, _, err := websocket.DefaultDialer.Dial(websocketURL.String(), headers)
if err != nil {
fn(err)
return
}
done := make(chan struct{})
go func() {
defer c.Close()
defer close(done)
for {
_, message, err := c.ReadMessage()
if err != nil {
fmt.Println("read:", err)
fn(err)
return
}
// fmt.Printf("\t%s\n", string(message))
var notif WebsocketNotification
if err := json.Unmarshal(message, ¬if); err != nil {
fmt.Printf("convert message to json failed: %v\n", err)
continue
}
// fmt.Println(notif.Type)
fn, ok := events.events[notif.Type]
if !ok {
fmt.Printf("unknown websocket event name: %v\n", notif.Type)
continue
}
fn(notif.NotificationContainer)
}
}()
go func() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case t := <-ticker.C:
err := c.WriteMessage(websocket.TextMessage, []byte(t.String()))
if err != nil {
fn(err)
}
case <-interrupt:
fmt.Println("interrupt")
// To cleanly close a connection, a client should send a close
// frame and wait for the server to close the connection.
err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
fmt.Println("write close:", err)
fn(err)
}
select {
case <-done:
case <-time.After(time.Second):
fmt.Println("closing websocket...")
c.Close()
}
return
}
}
}()
}