-
Notifications
You must be signed in to change notification settings - Fork 62
/
plex.go
1316 lines (921 loc) · 29.1 KB
/
plex.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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package plex
// plex is a Plex Media Server and Plex.tv client
import (
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/google/uuid"
)
const (
plexURL = "https://plex.tv"
applicationXml = "application/xml"
applicationJson = "application/json"
)
func defaultHeaders() headers {
version := "0.0.1"
return headers{
Platform: runtime.GOOS,
PlatformVersion: "0.0.0",
Product: "Go Plex Client",
Version: version,
Device: runtime.GOOS + " " + runtime.GOARCH,
ClientIdentifier: "go-plex-client-v" + version,
ContainerSize: "Plex-Container-Size=50",
ContainerStart: "X-Plex-Container-Start=0",
Accept: applicationJson,
ContentType: applicationJson,
}
}
// New creates a new plex instance that is required to
// to make requests to your Plex Media Server
func New(baseURL, token string) (*Plex, error) {
var p Plex
// allow empty url so caller can use GetServers() to set the server url later
if baseURL == "" && token == "" {
return &p, errors.New(ErrorUrlTokenRequired)
}
p.HTTPClient = http.Client{
Timeout: 3 * time.Second,
}
p.DownloadClient = http.Client{}
p.Headers = defaultHeaders()
// id, err := uuid.NewRandom()
// if err != nil {
// return &p, err
// }
// p.ClientIdentifier = id.String()
p.ClientIdentifier = p.Headers.ClientIdentifier
p.Headers.ClientIdentifier = p.ClientIdentifier
// has url and token
if baseURL != "" && token != "" {
_, err := url.ParseRequestURI(baseURL)
p.URL = baseURL
p.Token = token
return &p, err
}
// just has token
if baseURL == "" && token != "" {
p.Token = token
return &p, nil
}
// just url
p.URL = baseURL
return &p, nil
}
// SignIn creates a plex instance using a user name and password instead of an auth
// token.
func SignIn(username, password string) (*Plex, error) {
id, err := uuid.NewRandom()
if err != nil {
return &Plex{}, err
}
p := Plex{
ClientIdentifier: id.String(),
HTTPClient: http.Client{
Timeout: 3 * time.Second,
},
}
query := plexURL + "/api/v2/users/signin"
// Encode login in the specific format they require
body := url.Values{}
body.Add("login", username)
body.Add("password", password)
body.Add("noGuest", "true")
body.Add("skipAuthentication", "true")
newHeaders := p.Headers
// Doesn't like having a content type, even form-data
newHeaders.ContentType = "application/x-www-form-urlencoded"
newHeaders.Accept = applicationJson
resp, err := p.post(query, []byte(body.Encode()), newHeaders)
if err != nil {
return &Plex{}, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
return &Plex{}, errors.New(resp.Status)
}
var signInResponse SignInResponse
if err := json.NewDecoder(resp.Body).Decode(&signInResponse); err != nil {
return &Plex{}, err
}
p.Token = signInResponse.AuthToken
return &p, err
}
// Search your Plex Server for media
func (p *Plex) Search(title string) (SearchResults, error) {
if title == "" {
return SearchResults{}, fmt.Errorf(ErrorCommon, ErrorTitleRequired)
}
title = url.QueryEscape(title)
query := p.URL + "/search?query=" + title
var results SearchResults
resp, err := p.get(query, p.Headers)
if err != nil {
return SearchResults{}, err
}
// Unauthorized
if resp.StatusCode == http.StatusUnauthorized {
return SearchResults{}, errors.New(ErrorNotAuthorized)
}
defer resp.Body.Close()
if err := json.NewDecoder(resp.Body).Decode(&results); err != nil {
return SearchResults{}, err
}
return results, nil
}
// GetMetadata can get some media info
func (p *Plex) GetMetadata(key string) (MediaMetadata, error) {
if key == "" {
return MediaMetadata{}, fmt.Errorf(ErrorCommon, ErrorKeyIsRequired)
}
var results MediaMetadata
query := fmt.Sprintf("%s/library/metadata/%s", p.URL, key)
newHeaders := p.Headers
resp, err := p.get(query, newHeaders)
if err != nil {
return results, err
}
if resp.StatusCode != http.StatusOK {
return results, fmt.Errorf(ErrorServer, resp.Status)
}
defer resp.Body.Close()
if err := json.NewDecoder(resp.Body).Decode(&results); err != nil {
return results, err
}
return results, nil
}
// GetMetadataChildren can get a show's season titles. My use-case would be getting the season titles after using Search()
func (p *Plex) GetMetadataChildren(key string) (MetadataChildren, error) {
if key == "" {
return MetadataChildren{}, fmt.Errorf(ErrorCommon, ErrorKeyIsRequired)
}
query := fmt.Sprintf("%s/library/metadata/%s/children", p.URL, key)
newHeaders := p.Headers
resp, err := p.get(query, newHeaders)
if err != nil {
return MetadataChildren{}, err
}
// Unauthorized
if resp.StatusCode == http.StatusUnauthorized {
return MetadataChildren{}, errors.New(ErrorNotAuthorized)
}
defer resp.Body.Close()
var results MetadataChildren
if err := json.NewDecoder(resp.Body).Decode(&results); err != nil {
return MetadataChildren{}, err
}
return results, nil
}
// GetEpisodes returns episodes of a season of a show
func (p *Plex) GetEpisodes(key string) (SearchResultsEpisode, error) {
if key == "" {
return SearchResultsEpisode{}, fmt.Errorf(ErrorCommon, ErrorKeyIsRequired)
}
query := fmt.Sprintf("%s/library/metadata/%s/children", p.URL, key)
resp, err := p.get(query, p.Headers)
if err != nil {
return SearchResultsEpisode{}, err
}
// Unauthorized
if resp.StatusCode == http.StatusUnauthorized {
return SearchResultsEpisode{}, errors.New(ErrorNotAuthorized)
}
defer resp.Body.Close()
var results SearchResultsEpisode
if err := json.NewDecoder(resp.Body).Decode(&results); err != nil {
return SearchResultsEpisode{}, err
}
return results, nil
}
// GetEpisode returns a single episode of a show.
func (p *Plex) GetEpisode(key string) (SearchResultsEpisode, error) {
if key == "" {
return SearchResultsEpisode{}, fmt.Errorf(ErrorCommon, ErrorKeyIsRequired)
}
query := fmt.Sprintf("%s/library/metadata/%s", p.URL, key)
resp, err := p.get(query, p.Headers)
if err != nil {
return SearchResultsEpisode{}, err
}
// Unauthorized
if resp.StatusCode == http.StatusUnauthorized {
return SearchResultsEpisode{}, errors.New(ErrorNotAuthorized)
}
defer resp.Body.Close()
var results SearchResultsEpisode
if err := json.NewDecoder(resp.Body).Decode(&results); err != nil {
return SearchResultsEpisode{}, err
}
return results, nil
}
// GetOnDeck gets the on-deck videos.
func (p *Plex) GetOnDeck() (SearchResultsEpisode, error) {
query := fmt.Sprintf("%s/library/onDeck", p.URL)
resp, err := p.get(query, p.Headers)
if err != nil {
return SearchResultsEpisode{}, err
}
// Unauthorized
if resp.StatusCode == http.StatusUnauthorized {
return SearchResultsEpisode{}, errors.New(ErrorNotAuthorized)
}
defer resp.Body.Close()
var results SearchResultsEpisode
if err := json.NewDecoder(resp.Body).Decode(&results); err != nil {
return SearchResultsEpisode{}, err
}
return results, nil
}
// Download media associated with metadata
func (p *Plex) Download(meta Metadata, path string, createFolders bool, skipIfExists bool) error {
if len(meta.Media) == 0 {
return fmt.Errorf("no media associated with metadata, skipping")
}
path = filepath.Join(path)
if createFolders {
if meta.ParentTitle != "" && meta.GrandparentTitle != "" { // for tv shows and music
path = filepath.Join(path, meta.GrandparentTitle, meta.ParentTitle)
} else { // for movies
path = filepath.Join(path, meta.Title)
}
if err := os.MkdirAll(path, 0700); err != nil {
return err
}
}
for _, media := range meta.Media {
for _, part := range media.Part {
// get original filename from original path
split := strings.Split(part.File, "/")
file := split[len(split)-1]
fp := filepath.Join(path, file)
_, exists := os.Stat(fp)
if exists == nil && skipIfExists {
return nil
}
query := fmt.Sprintf("%s%s?download=1", p.URL, part.Key)
resp, err := p.grab(query, p.Headers)
if err != nil {
return err
}
// Unauthorized
if resp.StatusCode == http.StatusUnauthorized {
return errors.New(ErrorNotAuthorized)
}
out, err := os.Create(fp)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
}
}
return nil
}
// GetPlaylist gets all videos in a playlist.
func (p *Plex) GetPlaylist(key int) (SearchResultsEpisode, error) {
query := fmt.Sprintf("%s/playlists/%d/items", p.URL, key)
resp, err := p.get(query, p.Headers)
if err != nil {
return SearchResultsEpisode{}, err
}
// Unauthorized
if resp.StatusCode == http.StatusUnauthorized {
return SearchResultsEpisode{}, errors.New(ErrorNotAuthorized)
} else if resp.StatusCode != http.StatusOK {
return SearchResultsEpisode{}, fmt.Errorf(ErrorServer, resp.Status)
}
defer resp.Body.Close()
var results SearchResultsEpisode
if err := json.NewDecoder(resp.Body).Decode(&results); err != nil {
return SearchResultsEpisode{}, err
}
return results, nil
}
// GetThumbnail returns the response of a request to pms thumbnail
// My ideal use case would be to proxy a request to pms without exposing the plex token
func (p *Plex) GetThumbnail(key, thumbnailID string) (*http.Response, error) {
query := fmt.Sprintf("%s/library/metadata/%s/thumb/%s", p.URL, key, thumbnailID)
return p.get(query, p.Headers)
}
// Test your connection to your Plex Media Server
func (p *Plex) Test() (bool, error) {
resp, err := p.get(plexURL+"/api/servers", p.Headers)
if err != nil {
return false, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusUnauthorized {
return false, errors.New(ErrorNotAuthorized)
} else if resp.StatusCode != http.StatusOK {
return false, fmt.Errorf(ErrorServerReplied, resp.StatusCode)
}
return true, nil
}
// KillTranscodeSession stops a transcode session
func (p *Plex) KillTranscodeSession(sessionKey string) (bool, error) {
if sessionKey == "" {
return false, errors.New(ErrorMissingSessionKey)
}
query := p.URL + "/video/:/transcode/universal/stop?session=" + sessionKey
resp, err := p.get(query, p.Headers)
if err != nil {
return false, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusUnauthorized {
return false, errors.New(ErrorNotAuthorized)
} else if resp.StatusCode != http.StatusOK {
return false, fmt.Errorf(ErrorServerReplied, resp.StatusCode)
}
return true, nil
}
// GetTranscodeSessions retrieves a list of all active transcode sessions
func (p *Plex) GetTranscodeSessions() (TranscodeSessionsResponse, error) {
var result TranscodeSessionsResponse
query := p.URL + "/transcode/sessions"
resp, err := p.get(query, p.Headers)
if err != nil {
return result, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusUnauthorized {
return result, errors.New(ErrorNotAuthorized)
} else if resp.StatusCode != http.StatusOK {
return result, fmt.Errorf(ErrorServerReplied, resp.StatusCode)
}
return result, json.NewDecoder(resp.Body).Decode(&result)
}
// GetPlexTokens not sure if it works
func (p *Plex) GetPlexTokens(token string) (DevicesResponse, error) {
var result DevicesResponse
query := plexURL + "/devices.json"
resp, err := p.get(query, p.Headers)
if err != nil {
return result, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusUnauthorized {
return result, errors.New(ErrorNotAuthorized)
} else if resp.StatusCode != http.StatusOK {
return result, fmt.Errorf(ErrorServerReplied, resp.StatusCode)
}
return result, json.NewDecoder(resp.Body).Decode(&result)
}
// DeletePlexToken is currently not tested
func (p *Plex) DeletePlexToken(token string) (bool, error) {
var result bool
query := plexURL + "/devices/" + token + ".json"
resp, err := p.get(query, p.Headers)
if err != nil {
return result, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusUnauthorized {
return result, errors.New(ErrorNotAuthorized)
} else if resp.StatusCode != http.StatusOK {
return result, fmt.Errorf(ErrorServerReplied, resp.StatusCode)
}
return result, json.NewDecoder(resp.Body).Decode(&result)
}
// GetFriends returns all of your plex friends
func (p *Plex) GetFriends() ([]Friends, error) {
var plexFriendsResp friendsResponse
query := plexURL + "/api/users"
newHeaders := p.Headers
newHeaders.Accept = applicationXml
resp, err := p.get(query, newHeaders)
if err != nil {
return []Friends{}, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusUnauthorized {
return []Friends{}, errors.New(ErrorNotAuthorized)
} else if resp.StatusCode != http.StatusOK {
return []Friends{}, fmt.Errorf(ErrorServerReplied, resp.StatusCode)
}
respBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return []Friends{}, err
}
err = xml.Unmarshal(respBytes, &plexFriendsResp)
if err != nil {
return []Friends{}, err
}
friendCount := plexFriendsResp.Size
plexFriends := make([]Friends, friendCount)
for ii, f := range plexFriendsResp.User {
plexFriends[ii] = f
}
return plexFriends, nil
}
// RemoveFriend from your friend's list which stops access to your Plex server
func (p *Plex) RemoveFriend(id string) (bool, error) {
query := plexURL + "/api/friends/" + id
resp, err := p.delete(query, p.Headers)
if err != nil {
return false, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusBadRequest {
return false, errors.New(resp.Status)
}
result := new(resultResponse)
if err := xml.NewDecoder(resp.Body).Decode(result); err != nil {
return false, err
}
return result.Response.Code == 0, nil
}
// InviteFriend to access your Plex server. Add restrictions to media or give them full access.
func (p *Plex) InviteFriend(params InviteFriendParams) error {
label := url.QueryEscape(params.Label)
query := fmt.Sprintf("%s/api/v2/shared_servers", plexURL)
var requestBody inviteFriendBody
requestBody.MachineIdentifier = params.MachineID
requestBody.InvitedEmail = params.UsernameOrEmail
requestBody.LibrarySectionIDs = params.LibraryIDs
settings := inviteFriendSettings{}
if label != "" {
settings.FilterMovies = fmt.Sprintf("label=%s", label)
settings.FilterTelevision = fmt.Sprintf("label=%s", label)
}
requestBody.Settings = settings
jsonBody, jsonErr := json.Marshal(requestBody)
if jsonErr != nil {
return jsonErr
}
resp, err := p.post(query, jsonBody, p.Headers)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
return errors.New(resp.Status)
}
result := new(inviteFriendResponse)
if err := json.NewDecoder(resp.Body).Decode(result); err != nil {
return err
}
return nil
}
// UpdateFriendAccess limit your friends access to your plex server
func (p *Plex) UpdateFriendAccess(userID string, params UpdateFriendParams) (bool, error) {
// Fix any defaults to statisfy what plex expects
if params.AllowSync == "" {
params.AllowSync = "0"
}
if params.AllowCameraUpload == "" {
params.AllowCameraUpload = "0"
}
if params.AllowChannels == "" {
params.AllowChannels = "0"
}
query := fmt.Sprintf("%s/api/friends/%s", plexURL, userID)
parsedQuery, parseErr := url.Parse(query)
if parseErr != nil {
return false, parseErr
}
vals := parsedQuery.Query()
vals.Add("allowSync", params.AllowSync)
vals.Add("allowCameraUpload", params.AllowCameraUpload)
vals.Add("allowChannels", params.AllowChannels)
vals.Add("filterMovies", params.FilterMovies)
vals.Add("filterMusic", params.FilterMusic)
vals.Add("filterTelevision", params.FilterTelevision)
vals.Add("filterPhotos", params.FilterPhotos)
parsedQuery.RawQuery = vals.Encode()
query = parsedQuery.String()
resp, err := p.put(query, nil, p.Headers)
if err != nil {
return false, err
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return false, errors.New(resp.Status)
}
return true, nil
}
// RemoveFriendAccessToLibrary you can individually revoke access to a library on your server. Such as movies, tv shows, music, etc
func (p *Plex) RemoveFriendAccessToLibrary(userID, machineID, serverID string) (bool, error) {
query := fmt.Sprintf("%s/api/servers/%s/shared_servers/%s", plexURL, machineID, serverID)
resp, err := p.delete(query, p.Headers)
if err != nil {
return false, err
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return false, errors.New(resp.Status)
}
return true, nil
}
// GetInvitedFriends get all invited friends with request still pending
func (p *Plex) GetInvitedFriends() ([]InvitedFriend, error) {
query := plexURL + "/api/invites/requested"
newHeaders := p.Headers
newHeaders.Accept = applicationXml
resp, err := p.get(query, newHeaders)
if err != nil {
return []InvitedFriend{}, err
}
if resp.StatusCode == http.StatusUnauthorized {
return []InvitedFriend{}, errors.New(ErrorNotAuthorized)
} else if resp.StatusCode != http.StatusOK {
return []InvitedFriend{}, fmt.Errorf(ErrorServerReplied, resp.StatusCode)
}
var invitedFriendsResp invitedFriendsResponse
defer resp.Body.Close()
err = xml.NewDecoder(resp.Body).Decode(&invitedFriendsResp)
if err != nil {
return []InvitedFriend{}, err
}
return invitedFriendsResp.InvitedFriends, nil
}
// RemoveInvitedFriend cancel pending friend invite
func (p *Plex) RemoveInvitedFriend(inviteID string, isFriend, isServer, isHome bool) (bool, error) {
query := plexURL + "/api/invites/requested/" + url.QueryEscape(inviteID)
parsedQuery, parseErr := url.Parse(query)
if parseErr != nil {
return false, parseErr
}
vals := parsedQuery.Query()
vals.Add("friend", boolToOneOrZero(isFriend))
vals.Add("server", boolToOneOrZero(isServer))
vals.Add("home", boolToOneOrZero(isHome))
parsedQuery.RawQuery = vals.Encode()
query = parsedQuery.String()
resp, err := p.delete(query, p.Headers)
if err != nil {
return false, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusBadRequest {
return false, errors.New(resp.Status)
}
result := new(resultResponse)
if err := xml.NewDecoder(resp.Body).Decode(result); err != nil {
return false, err
}
return result.Response.Code == 0, nil
}
// CheckUsernameOrEmail will check if the username is a Plex user or will verify an email is valid
func (p *Plex) CheckUsernameOrEmail(usernameOrEmail string) (bool, error) {
usernameOrEmail = url.QueryEscape(usernameOrEmail)
query := fmt.Sprintf("%s/api/users/validate?invited_email=%s", plexURL, usernameOrEmail)
resp, err := p.post(query, nil, p.Headers)
if err != nil {
return false, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusBadRequest {
return false, errors.New(resp.Status)
}
result := new(resultResponse)
if err := xml.NewDecoder(resp.Body).Decode(result); err != nil {
return false, err
}
return result.Response.Code == 0, nil
}
// StopPlayback acts as a remote controller and sends the 'stop' command
func (p *Plex) StopPlayback(machineID string) error {
query := p.URL + "/player/playback/stop"
newHeaders := p.Headers
newHeaders.Accept = applicationXml
newHeaders.TargetClientIdentifier = machineID
resp, err := p.get(query, newHeaders)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf(resp.Status)
}
return nil
}
// GetDevices returns a list of your Plex devices (servers, players, controllers, etc)
func (p *Plex) GetDevices() ([]PMSDevices, error) {
query := plexURL + "/api/resources?includeHttps=1"
resp, err := p.get(query, p.Headers)
if err != nil {
return []PMSDevices{}, err
}
defer resp.Body.Close()
result := new(resourcesResponse)
if resp.StatusCode != http.StatusOK {
return []PMSDevices{}, errors.New(resp.Status)
}
if err := xml.NewDecoder(resp.Body).Decode(result); err != nil {
fmt.Println(err.Error())
return []PMSDevices{}, err
}
return result.Device, nil
}
// GetServers returns a list of your Plex servers
func (p *Plex) GetServers() ([]PMSDevices, error) {
// we can use the https://<pms-ip>/media/providers endpoint
// but if the caller does not know the ip beforehand, we can grab it
// from plex.tv so we'll use https://plex.tv endpoint to give that option
devices, err := p.GetDevices()
if err != nil {
return devices, err
}
// filter devices for servers
var filteredDevices []PMSDevices
for _, r := range devices {
if r.Provides != "server" {
continue
}
filteredDevices = append(filteredDevices, r)
}
return filteredDevices, nil
}
// GetServersInfo returns info about all of your Plex servers
func (p *Plex) GetServersInfo() (ServerInfo, error) {
query := plexURL + "/api/servers"
resp, err := p.get(query, p.Headers)
if err != nil {
return ServerInfo{}, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return ServerInfo{}, errors.New(resp.Status)
}
result := ServerInfo{}
if err := xml.NewDecoder(resp.Body).Decode(&result); err != nil {
fmt.Println(err.Error())
return ServerInfo{}, err
}
return result, nil
}
// GetMachineID returns the machine id of the server with the associated access token
func (p *Plex) GetMachineID() (string, error) {
if p.Token == "" {
return "", errors.New("a token is required to fetch machine id")
}
servers, err := p.GetServersInfo()
if err != nil {
return "", err
}
var machineID string
for _, server := range servers.Server {
if server.AccessToken == p.Token {
machineID = server.MachineIdentifier
}
}
if machineID == "" {
return "", errors.New("could not fetch machine id")
}
return machineID, nil
}
// GetSections of your plex server. This is useful when inviting a user
// as you can restrict the invited user to a library (i.e. Movie's, TV Shows)
func (p *Plex) GetSections(machineID string) ([]ServerSections, error) {
query := fmt.Sprintf("%s/api/servers/%s", plexURL, machineID)
newHeaders := p.Headers
newHeaders.Accept = applicationXml
resp, err := p.get(query, newHeaders)
if err != nil {
return []ServerSections{}, err
}
defer resp.Body.Close()
var result SectionIDResponse
if err := xml.NewDecoder(resp.Body).Decode(&result); err != nil {
fmt.Println(err.Error())
return []ServerSections{}, err
}
// Look for our server via the machine id
for _, server := range result.Server {
if server.MachineIdentifier != machineID {
continue
}
return server.Section, nil
}
return []ServerSections{}, nil
}
// GetLibraries of your Plex server. My ideal use-case would be
// to get library count to determine label index