-
Notifications
You must be signed in to change notification settings - Fork 62
/
plextv.go
291 lines (214 loc) · 6.59 KB
/
plextv.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
package plex
// I'll slowly migrate plex.tv related functions to this file
import (
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
)
// ErrorResponse contains a code and an error message
type ErrorResponse struct {
Code int `json:"code"`
Message string `json:"message"`
}
// PinResponse holds information to successfully check a pin when linking an account
type PinResponse struct {
ID int `json:"id"`
Code string `json:"code"`
ClientIdentifier string `json:"clientIdentifier"`
CreatedAt string `json:"createdAt"`
ExpiresAt string `json:"expiresAt"`
ExpiresIn json.Number `json:"expiresIn"`
AuthToken string `json:"authToken"`
Errors []ErrorResponse `json:"errors"`
Trusted bool `json:"trusted"`
Location struct {
Code string `json:"code"`
Country string `json:"country"`
City string `json:"city"`
Subdivisions string `json:"subdivisions"`
Coordinates string `json:"coordinates"`
}
}
// RequestPIN will retrieve a code (valid for 15 minutes) from plex.tv to link an app to your plex account
func RequestPIN(requestHeaders headers) (PinResponse, error) {
endpoint := "/api/v2/pins.json"
// POST request and returns a 201 status code
// response body returns json
//
// {
// id: 123456,
// code: "ABCD",
// clientIdentifier: "goplexclient",
// expiresAt: 15463757,
// authToken: null
// }
var pinInformation PinResponse
if requestHeaders.ClientIdentifier == "" {
requestHeaders = defaultHeaders()
}
resp, err := post(plexURL+endpoint, nil, requestHeaders)
if err != nil {
return pinInformation, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
return pinInformation, errors.New(resp.Status)
}
if err := json.NewDecoder(resp.Body).Decode(&pinInformation); err != nil {
return pinInformation, err
}
return pinInformation, nil
}
// CheckPIN will return information related to the pin such as the auth token if your code has been approved.
// will return an error if code expired or still not linked
// clientIdentifier must be the same when requesting a pin
func CheckPIN(id int, clientIdentifier string) (PinResponse, error) {
endpoint := "/api/v2/pins/"
endpoint = endpoint + strconv.Itoa(id) + ".json"
headers := defaultHeaders()
if clientIdentifier != "" {
headers.ClientIdentifier = clientIdentifier
}
resp, err := get(plexURL+endpoint, headers)
if err != nil {
return PinResponse{}, err
}
defer resp.Body.Close()
var pinInformation PinResponse
if err := json.NewDecoder(resp.Body).Decode(&pinInformation); err != nil {
return pinInformation, err
}
// code doesn't exist or expired
if len(pinInformation.Errors) > 0 {
return pinInformation, errors.New(pinInformation.Errors[0].Message)
}
// we are not authorized yet
if pinInformation.AuthToken == "" {
return pinInformation, errors.New(ErrorPINNotAuthorized)
}
// we are authorized! Yay!
return pinInformation, nil
}
// LinkAccount allows you to authorize an app via a 4 character pin. returns nil on success
func (p Plex) LinkAccount(code string) error {
endpoint := "/api/v2/pins/link.json"
body := url.Values{
"code": []string{code},
}
headers := p.Headers
headers.ContentType = "application/x-www-form-urlencoded"
// PUT request with 'code: <4-character-pin>' in the body
resp, err := p.put(plexURL+endpoint, []byte(body.Encode()), headers)
if err != nil {
return err
}
defer resp.Body.Close()
// type linkAccountResponse struct {
// }
// var
// json.NewDecoder(resp.Body).Decode()
// should return 204 for success
if resp.StatusCode != http.StatusNoContent {
return fmt.Errorf(ErrorLinkAccount, resp.Status)
}
return nil
}
type webhookErr struct {
Err []struct {
Code int `json:"code"`
Message string `json:"message"`
Status int `json:"status"`
} `json:"errors"`
}
func (w webhookErr) Error() string {
if len(w.Err) == 0 {
return ""
}
return w.Err[0].Message
}
// GetWebhooks fetches all webhooks - requires plex pass
func (p Plex) GetWebhooks() ([]string, error) {
type Hooks struct {
URL string `json:"url"`
}
var webhooks []string
endpoint := "/api/v2/user/webhooks"
resp, err := p.get(plexURL+endpoint, p.Headers)
if err != nil {
return webhooks, err
}
defer resp.Body.Close()
if resp.StatusCode >= http.StatusBadRequest && resp.StatusCode < http.StatusInternalServerError {
var webhookErr webhookErr
if err := json.NewDecoder(resp.Body).Decode(&webhookErr); err != nil {
return webhooks, err
}
return webhooks, fmt.Errorf(ErrorWebhook, webhookErr.Error())
} else if resp.StatusCode != http.StatusOK {
return webhooks, fmt.Errorf(ErrorWebhook, resp.Status)
}
var hook []Hooks
if err := json.NewDecoder(resp.Body).Decode(&hook); err != nil {
return webhooks, err
}
for _, h := range hook {
webhooks = append(webhooks, h.URL)
}
return webhooks, nil
}
// AddWebhook creates a new webhook for your plex server to send metadata - requires plex pass
func (p Plex) AddWebhook(webhook string) error {
// get current webhooks and append ours to it
currentWebhooks, err := p.GetWebhooks()
if err != nil {
return err
}
currentWebhooks = append(currentWebhooks, webhook)
return p.SetWebhooks(currentWebhooks)
}
// SetWebhooks will set your webhooks to whatever you pass as an argument
// webhooks with a length of 0 will remove all webhooks
func (p Plex) SetWebhooks(webhooks []string) error {
endpoint := "/api/v2/user/webhooks"
body := url.Values{}
if len(webhooks) == 0 {
body.Add("urls[]", "")
}
for _, hook := range webhooks {
body.Add("urls[]", hook)
}
headers := p.Headers
headers.ContentType = "application/x-www-form-urlencoded"
resp, err := p.post(plexURL+endpoint, []byte(body.Encode()), headers)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
return errors.New(ErrorFailedToSetWebhook)
}
return nil
}
// MyAccount gets account info (i.e. plex pass, servers, username, etc) from plex tv
func (p Plex) MyAccount() (UserPlexTV, error) {
endpoint := "/users/account"
var account UserPlexTV
resp, err := p.get(plexURL+endpoint, p.Headers)
if err != nil {
return account, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusUnprocessableEntity {
return account, errors.New(ErrorInvalidToken)
} else if resp.StatusCode != http.StatusOK {
return account, errors.New(resp.Status)
}
if err := xml.NewDecoder(resp.Body).Decode(&account); err != nil {
return account, err
}
return account, err
}