forked from iBaa/PlexConnect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
XMLConverter.py
executable file
·1486 lines (1222 loc) · 59.1 KB
/
XMLConverter.py
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
#!/usr/bin/env python
"""
Sources:
ElementTree
http://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.SubElement
trailers.apple.com root URL
http://trailers.apple.com/appletv/us/js/application.js
navigation pane
http://trailers.apple.com/appletv/us/nav.xml
->top trailers: http://trailers.apple.com/appletv/us/index.xml
->calendar: http://trailers.apple.com/appletv/us/calendar.xml
->browse: http://trailers.apple.com/appletv/us/browse.xml
"""
import re
import os
import sys
import traceback
import inspect
import string, random
import copy # deepcopy()
try:
import xml.etree.cElementTree as etree
except ImportError:
import xml.etree.ElementTree as etree
import time, uuid, hmac, hashlib, base64
from urllib import quote_plus, unquote_plus
import urllib2
import urlparse
from Version import __VERSION__, __COMMIT__ # for {{EVAL()}}, display in settings page
import Settings, ATVSettings
import PlexAPI
from Debug import * # dprint(), prettyXML()
import Localize
import PILBackgrounds
from PILBackgrounds import isPILinstalled
g_param = {}
def setParams(param):
global g_param
g_param = param
g_ATVSettings = None
def setATVSettings(cfg):
global g_ATVSettings
g_ATVSettings = cfg
"""
# aTV XML ErrorMessage - hardcoded XML File
"""
def XML_Error(title, desc):
errorXML = '\
<?xml version="1.0" encoding="UTF-8"?>\n\
<atv>\n\
<body>\n\
<dialog id="com.sample.error-dialog">\n\
<title>' + title + '</title>\n\
<description>' + desc + '</description>\n\
</dialog>\n\
</body>\n\
</atv>\n\
';
return errorXML
def XML_PlayVideo_ChannelsV1(baseURL, path):
XML = '\
<atv>\n\
<body>\n\
<videoPlayer id="com.sample.video-player">\n\
<httpFileVideoAsset id="' + path + '">\n\
<mediaURL>' + baseURL + path + '</mediaURL>\n\
<title>*title*</title>\n\
<!--bookmarkTime>{{EVAL(int({{VAL(Video/viewOffset:0)}}/1000))}}</bookmarkTime-->\n\
<videoPlayerSettings>\n\
<!-- PMS, OSD settings, ... -->\n\
<baseURL>' + baseURL + '</baseURL>\n\
<accessToken></accessToken>\n\
<showClock>False</showClock>\n\
<timeFormat></timeFormat>\n\
<clockPosition></clockPosition>\n\
<overscanAdjust></overscanAdjust>\n\
<showEndtime>False</showEndtime>\n\
<subtitleSize></subtitleSize>\n\
</videoPlayerSettings>\n\
<myMetadata>\n\
<key></key>\n\
<ratingKey></ratingKey>\n\
<duration></duration>\n\
<subtitleURL></subtitleURL>\n\
</myMetadata>\n\
</httpFileVideoAsset>\n\
</videoPlayer>\n\
</body>\n\
</atv>\n\
';
dprint(__name__,2 , XML)
return XML
"""
global list of known aTVs - to look up UDID by IP if needed
parameters:
udid - from options['PlexConnectUDID']
ip - from client_address btw options['aTVAddress']
"""
g_ATVList = {}
def declareATV(udid, ip):
global g_ATVList
if udid in g_ATVList:
g_ATVList[udid]['ip'] = ip
else:
g_ATVList[udid] = {'ip': ip}
def getATVFromIP(ip):
# find aTV by IP, return UDID
for udid in g_ATVList:
if ip==g_ATVList[udid].get('ip', None):
return udid
return None # IP not found
"""
# XML converter functions
# - translate aTV request and send to PMS
# - receive reply from PMS
# - select XML template
# - translate to aTV XML
"""
def XML_PMS2aTV(PMS_address, path, options):
# double check aTV UDID, redo from client IP if needed/possible
if not 'PlexConnectUDID' in options:
UDID = getATVFromIP(options['aTVAddress'])
if UDID:
options['PlexConnectUDID'] = UDID
else:
# aTV unidentified, UDID not known
return XML_Error('PlexConnect','Unexpected error - unidentified ATV')
else:
declareATV(options['PlexConnectUDID'], options['aTVAddress']) # update with latest info
UDID = options['PlexConnectUDID']
# determine PMS_uuid, PMSBaseURL from IP (PMS_mark)
PMS_uuid = PlexAPI.getPMSFromAddress(UDID, PMS_address)
PMS_baseURL = PlexAPI.getPMSProperty(UDID, PMS_uuid, 'baseURL')
# check cmd to work on
cmd = ''
dir = ''
channelsearchURL = ''
if 'PlexConnect' in options:
cmd = options['PlexConnect']
dprint(__name__, 1, "---------------------------------------------")
dprint(__name__, 1, "PMS, path: {0} {1} ", PMS_address, path)
dprint(__name__, 1, "Initial Command: {0}", cmd)
# check aTV language setting
if not 'aTVLanguage' in options:
dprint(__name__, 1, "no aTVLanguage - pick en")
options['aTVLanguage'] = 'en'
# XML Template selector
# - PlexConnect command
# - path
# - PMS ViewGroup
XMLtemplate = ''
PMS = None
PMSroot = None
# XML direct request or
# XMLtemplate defined by solely PlexConnect Cmd
if path.endswith(".xml"):
XMLtemplate = path.lstrip('/')
path = '' # clear path - we don't need PMS-XML
# Deal with any special commands
if cmd.startswith('SettingsToggle:'):
opt = cmd[len('SettingsToggle:'):] # cut command:
parts = opt.split('+')
g_ATVSettings.toggleSetting(options['PlexConnectUDID'], parts[0].lower())
parts1 = parts[1].split('_', 1)
dir = parts1[0]
cmd = parts1[1]
XMLtemplate = dir + '/' + cmd + '.xml'
dprint(__name__, 2, "ATVSettings->Toggle: {0} in template: {1}", parts[0], parts[1])
path = '' # clear path - we don't need PMS-XML
elif cmd=='SaveSettings':
g_ATVSettings.saveSettings();
return XML_Error('PlexConnect', 'SaveSettings!') # not an error - but aTV won't care anyways.
elif cmd=='PlayVideo_ChannelsV1':
dprint(__name__, 1, "playing Channels XML Version 1: {0}".format(path))
auth_token = PlexAPI.getPMSProperty(UDID, PMS_uuid, 'accesstoken')
path = PlexAPI.getDirectVideoPath(path, auth_token)
return XML_PlayVideo_ChannelsV1(PMS_baseURL, path) # direct link, no PMS XML available
elif cmd=='PlayTrailer':
trailerID = options['PlexConnectTrailerID']
info = urllib2.urlopen("http://youtube.com/get_video_info?video_id=" + trailerID).read()
parsed = urlparse.parse_qs(info)
key = 'url_encoded_fmt_stream_map'
if not key in parsed:
return XML_Error('PlexConnect', 'Youtube: No Trailer Info available')
streams = parsed[key][0].split(',')
url = ''
for i in range(len(streams)):
stream = urlparse.parse_qs(streams[i])
if stream['itag'][0] == '18':
url = stream['url'][0]
if url == '':
return XML_Error('PlexConnect','Youtube: ATV compatible Trailer not available')
return XML_PlayVideo_ChannelsV1('', url.replace('&','&'))
elif cmd=='MyPlexLogin':
dprint(__name__, 2, "MyPlex->Logging In...")
if not 'PlexConnectCredentials' in options:
return XML_Error('PlexConnect', 'MyPlex Sign In called without Credentials.')
parts = options['PlexConnectCredentials'].split(':',1)
(username, auth_token) = PlexAPI.MyPlexSignIn(parts[0], parts[1], options)
PlexAPI.discoverPMS(UDID, g_param['CSettings'], g_param['IP_self'], {'MyPlex': auth_token})
g_ATVSettings.setSetting(UDID, 'myplex_user', username)
g_ATVSettings.setSetting(UDID, 'myplex_auth', auth_token)
g_ATVSettings.setSetting(UDID, 'plexhome_enable', 'False')
g_ATVSettings.setSetting(UDID, 'plexhome_user', '')
g_ATVSettings.setSetting(UDID, 'plexhome_auth', '')
XMLtemplate = 'Settings/Main.xml'
path = '' # clear path - we don't need PMS-XML
elif cmd=='MyPlexLogout':
dprint(__name__, 2, "MyPlex->Logging Out...")
auth_token = g_ATVSettings.getSetting(UDID, 'myplex_auth')
PlexAPI.MyPlexSignOut(auth_token)
PlexAPI.discoverPMS(UDID, g_param['CSettings'], g_param['IP_self'], {'MyPlex': ''})
g_ATVSettings.setSetting(UDID, 'myplex_user', '')
g_ATVSettings.setSetting(UDID, 'myplex_auth', '')
g_ATVSettings.setSetting(UDID, 'plexhome_enable', 'False')
g_ATVSettings.setSetting(UDID, 'plexhome_user', '')
g_ATVSettings.setSetting(UDID, 'plexhome_auth', '')
XMLtemplate = 'Settings/Main.xml'
path = '' # clear path - we don't need PMS-XML
elif cmd=='MyPlexSwitchHomeUser':
dprint(__name__, 2, "MyPlex->switch HomeUser...")
if not 'PlexConnectCredentials' in options:
return XML_Error('PlexConnect', 'MyPlex HomeUser called without Credentials.')
parts = options['PlexConnectCredentials'].split(':',1)
if len(parts)!=2:
return XML_Error('PlexConnect', 'MyPlex HomeUser called with bad Credentials.')
auth_token = g_ATVSettings.getSetting(UDID, 'myplex_auth')
(plexHome_user, plexHome_auth) = PlexAPI.MyPlexSwitchHomeUser(parts[0], parts[1], options, auth_token)
PlexAPI.discoverPMS(UDID, g_param['CSettings'], g_param['IP_self'], {'MyPlex': auth_token, 'PlexHome': plexHome_auth})
g_ATVSettings.setSetting(UDID, 'plexhome_enable', 'True')
g_ATVSettings.setSetting(UDID, 'plexhome_user', plexHome_user)
g_ATVSettings.setSetting(UDID, 'plexhome_auth', plexHome_auth)
XMLtemplate = 'Settings/PlexHome.xml'
elif cmd=='MyPlexLogoutHomeUser':
dprint(__name__, 2, "MyPlex->Logging Out HomeUser...")
auth_token = g_ATVSettings.getSetting(UDID, 'myplex_auth')
PlexAPI.discoverPMS(UDID, g_param['CSettings'], g_param['IP_self'], {'MyPlex': auth_token, 'PlexHome': ''})
g_ATVSettings.setSetting(UDID, 'plexhome_enable', 'True') # stays at PlexHome mode
g_ATVSettings.setSetting(UDID, 'plexhome_user', '')
g_ATVSettings.setSetting(UDID, 'plexhome_auth', '')
XMLtemplate = 'Settings/PlexHome.xml'
elif cmd=='MyPlexLeaveHome':
dprint(__name__, 2, "MyPlex->Leave Home...")
auth_token = g_ATVSettings.getSetting(UDID, 'myplex_auth')
PlexAPI.discoverPMS(UDID, g_param['CSettings'], g_param['IP_self'], {'MyPlex': auth_token})
g_ATVSettings.setSetting(UDID, 'plexhome_enable', 'False') # exit PlexHome mode completely
g_ATVSettings.setSetting(UDID, 'plexhome_user', '')
g_ATVSettings.setSetting(UDID, 'plexhome_auth', '')
XMLtemplate = 'Settings/PlexHome.xml'
elif cmd.startswith('Discover'):
tokenDict = {}
tokenDict['MyPlex'] = g_ATVSettings.getSetting(UDID, 'myplex_auth')
if g_ATVSettings.getSetting(UDID, 'plexhome_enable') == 'True':
tokenDict['PlexHome'] = g_ATVSettings.getSetting(UDID, 'plexhome_auth')
PlexAPI.discoverPMS(UDID, g_param['CSettings'], g_param['IP_self'], tokenDict)
return XML_Error('PlexConnect', 'Discover!') # not an error - but aTV won't care anyways.
elif cmd.startswith('purgeFanart'):
import PILBackgrounds
PILBackgrounds.purgeFanart()
#opt = cmd[len('purgeFanart:'):] # cut command:
#parts = opt.split('+')
#XMLtemplate = parts[1] + ".xml"
dprint(__name__, 1, 'purging: {0}', "Fanart Cache") # Debug
path = '' # clear path - we don't need PMS-XML
elif path.find('serviceSearch') != -1 or (path.find('video') != -1 and path.lower().find('search') != -1):
XMLtemplate = 'Channels/VideoSearchResults.xml'
elif path.find('SearchResults') != -1:
XMLtemplate = 'Channels/VideoSearchResults.xml'
# Special case scanners
if cmd=='S_-_BABS':
dprint(__name__, 1, "Found S - BABS.")
if cmd=='S_-_BABS' or cmd=='BABS':
dprint(__name__, 1, "Found S - BABS / BABS")
dir = 'TVShow'
cmd = 'NavigationBar'
# Overview case scanners
if cmd.find('Overview') != -1:
dprint(__name__, 1, "Overview scanner found, updating command.")
if cmd.find('Series') != -1: dir = 'TVShow'
elif cmd.find('Movie') != -1: dir = 'Movie'
elif cmd.find('Video') != -1 or cmd.find('Personal_Media') != -1:
# Plex Video Files Scanner
# Extended Personal Media Scanner
dir = 'HomeVideo'
elif cmd.find('Photo') != -1: dir = 'Photo'
elif cmd.find('Premium_Music') != -1: dir = 'Music'
elif cmd.find('Music') != -1 or cmd.find('iTunes') != -1: dir ='Music'
else:
return XML_Error('PlexConnect', 'Unknown scanner: '+cmd)
cmd = 'Overview'
elif cmd.find('Scanner') != -1:
dprint(__name__, 1, "Found Scanner.")
if cmd.find('Series') != -1: dir = 'TVShow'
elif cmd.find('Movie') != -1: dir = 'Movie'
elif cmd.find('Video') != -1 or cmd.find('Personal_Media') != -1:
# Plex Video Files Scanner
# Extended Personal Media Scanner
dir = 'HomeVideo'
elif cmd.find('Photo') != -1: dir = 'Photo'
elif cmd.find('Premium_Music') != -1: dir = 'Music'
elif cmd.find('Music') != -1 or cmd.find('iTunes') != -1: dir ='Music'
else:
return XML_Error('PlexConnect', 'Unknown scanner: '+cmd)
cmd = 'NavigationBar'
# Not a special command so split it
elif cmd.find('_') != -1:
parts = cmd.split('_', 1)
dir = parts[0]
cmd = parts[1]
# Commands that contain a directory
if dir != '':
XMLtemplate = dir + '/' + cmd + '.xml'
if path == '/': path = ''
dprint(__name__, 1, "Split Directory: {0} Command: {1}", dir, cmd)
dprint(__name__, 1, "XMLTemplate: {0}", XMLtemplate)
dprint(__name__, 1, "---------------------------------------------")
PMSroot = None
while True:
# request PMS-XML
if not path=='' and not PMSroot and PMS_address:
if PMS_address[0].isdigit() or PMS_address=='plex.tv': # IP:port or plex.tv
auth_token = PlexAPI.getPMSProperty(UDID, PMS_uuid, 'accesstoken')
enableGzip = PlexAPI.getPMSProperty(UDID, PMS_uuid, 'enableGzip')
PMS = PlexAPI.getXMLFromPMS(PMS_baseURL, path, options, auth_token, enableGzip)
else: # owned, shared PMSs
type = PMS_address
PMS = PlexAPI.getXMLFromMultiplePMS(UDID, path, type, options)
if PMS==False:
return XML_Error('PlexConnect', 'No Response from Plex Media Server')
PMSroot = PMS.getroot()
# get XMLtemplate
aTVTree = etree.parse(sys.path[0]+'/assets/templates/'+XMLtemplate)
aTVroot = aTVTree.getroot()
# convert PMS XML to aTV XML using provided XMLtemplate
CommandCollection = CCommandCollection(options, PMSroot, PMS_address, path)
XML_ExpandTree(CommandCollection, aTVroot, PMSroot, 'main')
XML_ExpandAllAttrib(CommandCollection, aTVroot, PMSroot, 'main')
del CommandCollection
# no redirect? exit loop!
redirect = aTVroot.find('redirect')
if redirect==None:
break;
# redirect to new PMS-XML - if necessary
path_rdrct = redirect.get('newPath')
if path_rdrct:
path = path_rdrct
PMSroot = None # force PMS-XML reload
dprint(__name__, 1, "PMS-XML redirect: {0}", path)
# redirect to new XMLtemplate - if necessary
XMLtemplate_rdrct = redirect.get('template')
if XMLtemplate_rdrct:
XMLtemplate = XMLtemplate_rdrct.replace(" ", "")
dprint(__name__, 1, "XMLTemplate redirect: {0}", XMLtemplate)
dprint(__name__, 1, "====== generated aTV-XML ======")
dprint(__name__, 1, aTVroot)
dprint(__name__, 1, "====== aTV-XML finished ======")
dprint(__name__, 1, "====== generated aTV-XML ======")
dprint(__name__, 1, aTVroot)
dprint(__name__, 1, "====== aTV-XML finished ======")
return etree.tostring(aTVroot)
def XML_ExpandTree(CommandCollection, elem, src, srcXML):
# unpack template 'COPY'/'CUT' command in children
res = False
while True:
if list(elem)==[]: # no sub-elements, stop recursion
break
for child in elem:
res = XML_ExpandNode(CommandCollection, elem, child, src, srcXML, 'TEXT')
if res==True: # tree modified: restart from 1st elem
break # "for child"
# recurse into children
XML_ExpandTree(CommandCollection, child, src, srcXML)
res = XML_ExpandNode(CommandCollection, elem, child, src, srcXML, 'TAIL')
if res==True: # tree modified: restart from 1st elem
break # "for child"
if res==False: # complete tree parsed with no change, stop recursion
break # "while True"
def XML_ExpandNode(CommandCollection, elem, child, src, srcXML, text_tail):
if text_tail=='TEXT': # read line from text or tail
line = child.text
elif text_tail=='TAIL':
line = child.tail
else:
dprint(__name__, 0, "XML_ExpandNode - text_tail badly specified: {0}", text_tail)
return False
pos = 0
while line!=None:
cmd_start = line.find('{{',pos)
cmd_end = line.find('}}',pos)
next_start = line.find('{{',cmd_start+2)
while next_start!=-1 and next_start<cmd_end:
cmd_end = line.find('}}',cmd_end+2)
next_start = line.find('{{',next_start+2)
if cmd_start==-1 or cmd_end==-1 or cmd_start>cmd_end:
return False # tree not touched, line unchanged
dprint(__name__, 2, "XML_ExpandNode: {0}", line)
cmd = line[cmd_start+2:cmd_end]
if cmd[-1]!=')':
dprint(__name__, 0, "XML_ExpandNode - closing bracket missing: {0} ", line)
parts = cmd.split('(',1)
cmd = parts[0]
param = parts[1].strip(')') # remove ending bracket
res = False
if hasattr(CCommandCollection, 'TREE_'+cmd): # expand tree, work COPY, CUT
line = line[:cmd_start] + line[cmd_end+2:] # remove cmd from text and tail
if text_tail=='TEXT':
child.text = line
elif text_tail=='TAIL':
child.tail = line
try:
param = XML_ExpandLine(CommandCollection, src, srcXML, param) # expand any attributes in the parameter
res = getattr(CommandCollection, 'TREE_'+cmd)(elem, child, src, srcXML, param)
except:
dprint(__name__, 0, "XML_ExpandNode - Error in cmd {0}, line {1}\n{2}", cmd, line, traceback.format_exc())
if res==True:
return True # tree modified, node added/removed: restart from 1st elem
elif hasattr(CCommandCollection, 'ATTRIB_'+cmd): # check other known cmds: VAL, EVAL...
dprint(__name__, 2, "XML_ExpandNode - Stumbled over {0} in line {1}", cmd, line)
pos = cmd_end
else:
dprint(__name__, 0, "XML_ExpandNode - Found unknown cmd {0} in line {1}", cmd, line)
line = line[:cmd_start] + "((UNKNOWN:"+cmd+"))" + line[cmd_end+2:] # mark unknown cmd in text or tail
if text_tail=='TEXT':
child.text = line
elif text_tail=='TAIL':
child.tail = line
dprint(__name__, 2, "XML_ExpandNode: {0} - done", line)
return False
def XML_ExpandAllAttrib(CommandCollection, elem, src, srcXML):
# unpack template commands in elem.text
line = elem.text
if line!=None:
elem.text = XML_ExpandLine(CommandCollection, src, srcXML, line.strip())
# unpack template commands in elem.tail
line = elem.tail
if line!=None:
elem.tail = XML_ExpandLine(CommandCollection, src, srcXML, line.strip())
# unpack template commands in elem.attrib.value
for attrib in elem.attrib:
line = elem.get(attrib)
elem.set(attrib, XML_ExpandLine(CommandCollection, src, srcXML, line.strip()))
# recurse into children
for el in elem:
XML_ExpandAllAttrib(CommandCollection, el, src, srcXML)
def XML_ExpandLine(CommandCollection, src, srcXML, line):
pos = 0
while True:
cmd_start = line.find('{{',pos)
cmd_end = line.find('}}',pos)
next_start = line.find('{{',cmd_start+2)
while next_start!=-1 and next_start<cmd_end:
cmd_end = line.find('}}',cmd_end+2)
next_start = line.find('{{',next_start+2)
if cmd_start==-1 or cmd_end==-1 or cmd_start>cmd_end:
break;
dprint(__name__, 2, "XML_ExpandLine: {0}", line)
cmd = line[cmd_start+2:cmd_end]
if cmd[-1]!=')':
dprint(__name__, 0, "XML_ExpandLine - closing bracket missing: {0} ", line)
parts = cmd.split('(',1)
cmd = parts[0]
param = parts[1][:-1] # remove ending bracket
if hasattr(CCommandCollection, 'ATTRIB_'+cmd): # expand line, work VAL, EVAL...
try:
param = XML_ExpandLine(CommandCollection, src, srcXML, param) # expand any attributes in the parameter
res = getattr(CommandCollection, 'ATTRIB_'+cmd)(src, srcXML, param)
line = line[:cmd_start] + res + line[cmd_end+2:]
pos = cmd_start+len(res)
except:
dprint(__name__, 0, "XML_ExpandLine - Error in {0}\n{1}", line, traceback.format_exc())
line = line[:cmd_start] + "((ERROR:"+cmd+"))" + line[cmd_end+2:]
elif hasattr(CCommandCollection, 'TREE_'+cmd): # check other known cmds: COPY, CUT
dprint(__name__, 2, "XML_ExpandLine - stumbled over {0} in line {1}", cmd, line)
pos = cmd_end
else:
dprint(__name__, 0, "XML_ExpandLine - Found unknown cmd {0} in line {1}", cmd, line)
line = line[:cmd_start] + "((UNKNOWN:"+cmd+"))" + line[cmd_end+2:]
dprint(__name__, 2, "XML_ExpandLine: {0} - done", line)
return line
"""
# Command expander classes
# CCommandHelper():
# base class to the following, provides basic parsing & evaluation functions
# CCommandCollection():
# cmds to set up sources (ADDXML, VAR)
# cmds with effect on the tree structure (COPY, CUT) - must be expanded first
# cmds dealing with single node keys, text, tail only (VAL, EVAL, ADDR_PMS ,...)
"""
class CCommandHelper():
def __init__(self, options, PMSroot, PMS_address, path):
self.options = options
self.PMSroot = {'main': PMSroot}
self.PMS_address = PMS_address # default PMS if nothing else specified
self.path = {'main': path}
self.ATV_udid = options['PlexConnectUDID']
self.PMS_uuid = PlexAPI.getPMSFromAddress(self.ATV_udid, PMS_address)
self.PMS_baseURL = PlexAPI.getPMSProperty(self.ATV_udid, self.PMS_uuid, 'baseURL')
self.variables = {}
# internal helper functions
def getParam(self, src, param):
parts = param.split(':',1)
param = parts[0]
leftover=''
if len(parts)>1:
leftover = parts[1]
param = param.replace('&col;',':') # colon # replace XML_template special chars
param = param.replace('&ocb;','{') # opening curly brace
param = param.replace('&ccb;','}') # closinging curly brace
param = param.replace('"','"') # replace XML special chars
param = param.replace(''',"'")
param = param.replace('<','<')
param = param.replace('>','>')
param = param.replace('&','&') # must be last
dprint(__name__, 2, "CCmds_getParam: {0}, {1}", param, leftover)
return [param, leftover]
def getKey(self, src, srcXML, param):
attrib, leftover = self.getParam(src, param)
default, leftover = self.getParam(src, leftover)
el, srcXML, attrib = self.getBase(src, srcXML, attrib)
# walk the path if neccessary
while '/' in attrib and el!=None:
parts = attrib.split('/',1)
if parts[0].startswith('#') and attrib[1:] in self.variables: # internal variable in path
el = el.find(self.variables[parts[0][1:]])
elif parts[0].startswith('$'): # setting
el = el.find(g_ATVSettings.getSetting(self.ATV_udid, parts[0][1:]))
elif parts[0].startswith('%'): # PMS property
el = el.find(PlexAPI.getPMSProperty(self.ATV_udid, self.PMS_uuid, parts[0][1:]))
else:
el = el.find(parts[0])
attrib = parts[1]
# check element and get attribute
if attrib.startswith('#') and attrib[1:] in self.variables: # internal variable
res = self.variables[attrib[1:]]
dfltd = False
elif attrib.startswith('$'): # setting
res = g_ATVSettings.getSetting(self.ATV_udid, attrib[1:])
dfltd = False
elif attrib.startswith('%'): # PMS property
res = PlexAPI.getPMSProperty(self.ATV_udid, self.PMS_uuid, attrib[1:])
dfltd = False
elif attrib.startswith('^') and attrib[1:] in self.options: # aTV property, http request options
res = self.options[attrib[1:]]
dfltd = False
elif el!=None and attrib in el.attrib:
res = el.get(attrib)
dfltd = False
else: # path/attribute not found
res = default
dfltd = True
dprint(__name__, 2, "CCmds_getKey: {0},{1},{2}", res, leftover,dfltd)
return [res,leftover,dfltd]
def getElement(self, src, srcXML, param):
tag, leftover = self.getParam(src, param)
el, srcXML, tag = self.getBase(src, srcXML, tag)
# walk the path if neccessary
while len(tag)>0:
parts = tag.split('/',1)
el = el.find(parts[0])
if not '/' in tag or el==None:
break
tag = parts[1]
return [el, leftover]
def getBase(self, src, srcXML, param):
# get base element
if param.startswith('@'): # redirect to additional XML
parts = param.split('/',1)
srcXML = parts[0][1:]
src = self.PMSroot[srcXML]
leftover=''
if len(parts)>1:
leftover = parts[1]
elif param.startswith('/'): # start at root
src = self.PMSroot['main']
leftover = param[1:]
else:
leftover = param
return [src, srcXML, leftover]
def getConversion(self, src, param):
conv, leftover = self.getParam(src, param)
# build conversion "dictionary"
convlist = []
if conv!='':
parts = conv.split('|')
for part in parts:
convstr = part.split('=')
convlist.append((unquote_plus(convstr[0]), unquote_plus(convstr[1])))
dprint(__name__, 2, "CCmds_getConversion: {0},{1}", convlist, leftover)
return [convlist, leftover]
def applyConversion(self, val, convlist):
# apply string conversion
if convlist!=[]:
for part in reversed(sorted(convlist)):
if val>=part[0]:
val = part[1]
break
dprint(__name__, 2, "CCmds_applyConversion: {0}", val)
return val
def applyMath(self, val, math, frmt):
# apply math function - eval
try:
x = eval(val)
if math!='':
x = eval(math)
val = ('{0'+frmt+'}').format(x)
except:
dprint(__name__, 0, "CCmds_applyMath: Error in math {0}, frmt {1}\n{2}", math, frmt, traceback.format_exc())
# apply format specifier
dprint(__name__, 2, "CCmds_applyMath: {0}", val)
return val
def _(self, msgid):
return Localize.getTranslation(self.options['aTVLanguage']).ugettext(msgid)
class CCommandCollection(CCommandHelper):
# XML TREE modifier commands
# add new commands to this list!
def TREE_COPY(self, elem, child, src, srcXML, param):
# is MULTICOPY?
tags=param.split(',')
if len(tags) > 1:
tag, param_enbl = self.getParam(src, tags[0])
else:
tag, param_enbl = self.getParam(src, param)
src, srcXML, tag = self.getBase(src, srcXML, tag)
# walk the src path if neccessary
while '/' in tag and src!=None:
parts = tag.split('/',1)
src = src.find(parts[0])
tag = parts[1]
# find index of child in elem - to keep consistent order
for ix, el in enumerate(list(elem)):
if el==child:
break
#get all requested tags
itemrange = src.findall(tag)
# is MULTICOPY?
for i in range(len(tags)):
if i > 0:
itemrange=itemrange+src.findall(tags[i])
# sort by addedAt (updatedAt?)
if len(tags) > 1:
itemrange = sorted(itemrange, key=lambda x: x.attrib.get('addedAt'), reverse=True)
cnt = 0
for elemSRC in itemrange:
key = 'COPY'
if param_enbl!='':
key, leftover, dfltd = self.getKey(elemSRC, srcXML, param_enbl)
conv, leftover = self.getConversion(elemSRC, leftover)
if not dfltd:
key = self.applyConversion(key, conv)
if key:
self.PMSroot['copy_'+tag] = elemSRC
self.variables['copy_ix'] = str(cnt)
cnt = cnt+1
el = copy.deepcopy(child)
XML_ExpandTree(self, el, elemSRC, srcXML)
XML_ExpandAllAttrib(self, el, elemSRC, srcXML)
if el.tag=='__COPY__':
for el_child in list(el):
elem.insert(ix, el_child)
ix += 1
else:
elem.insert(ix, el)
ix += 1
# remove template child
elem.remove(child)
return True # tree modified, nodes updated: restart from 1st elem
#syntax: Video, playType (Single|Continuous), key to match (^PlexConnectRatingKey), ratingKey
def TREE_COPY_PLAYLIST(self, elem, child, src, srcXML, param):
tag, leftover = self.getParam(src, param)
playType, leftover, dfltd = self.getKey(src, srcXML, leftover) # Single (default), Continuous
key, leftover, dfltd = self.getKey(src, srcXML, leftover)
param_key = leftover
src, srcXML, tag = self.getBase(src, srcXML, tag)
# walk the src path if neccessary
while '/' in tag and src!=None:
parts = tag.split('/',1)
src = src.find(parts[0])
tag = parts[1]
# find index of child in elem - to keep consistent order
for ix, el in enumerate(list(elem)):
if el==child:
break
# filter elements to copy
cnt = 0
copy_enbl = False
elemsSRC = []
for elemSRC in src.findall(tag):
child_key, leftover, dfltd = self.getKey(elemSRC, srcXML, param_key)
if not key:
copy_enbl = True # copy all
elif playType == 'Continuous' or playType== 'Shuffle':
copy_enbl = copy_enbl or (key==child_key) # [0 0 1 1 1 1]
else: # 'Single' (default)
copy_enbl = (key==child_key) # [0 0 1 0 0 0]
if copy_enbl:
elemsSRC.append(elemSRC)
# shuffle elements
if playType == 'Shuffle':
if not key:
random.shuffle(elemsSRC) # shuffle all
else:
elems = elemsSRC[1:] # keep first element fix
random.shuffle(elems)
elemsSRC = [elemsSRC[0]] + elems
# duplicate child and add to tree
cnt = 0
for elemSRC in elemsSRC:
self.PMSroot['copy_'+tag] = elemSRC
self.variables['copy_ix'] = str(cnt)
cnt = cnt+1
el = copy.deepcopy(child)
XML_ExpandTree(self, el, elemSRC, srcXML)
XML_ExpandAllAttrib(self, el, elemSRC, srcXML)
if el.tag=='__COPY__':
for el_child in list(el):
elem.insert(ix, el_child)
ix += 1
else:
elem.insert(ix, el)
ix += 1
# remove template child
elem.remove(child)
return True # tree modified, nodes updated: restart from 1st elem
# remove template child
elem.remove(child)
return True # tree modified, nodes updated: restart from 1st elem
def TREE_CUT(self, elem, child, src, srcXML, param):
key, leftover, dfltd = self.getKey(src, srcXML, param)
conv, leftover = self.getConversion(src, leftover)
if not dfltd:
key = self.applyConversion(key, conv)
if key:
elem.remove(child)
return True # tree modified, node removed: restart from 1st elem
else:
return False # tree unchanged
def TREE_ADDXML(self, elem, child, src, srcXML, param):
tag, leftover = self.getParam(src, param)
key, leftover, dfltd = self.getKey(src, srcXML, leftover)
PMS_address = self.PMS_address
if key.startswith('//'): # local servers signature
pathstart = key.find('/',3)
PMS_address= key[:pathstart]
path = key[pathstart:]
elif key.startswith('/'): # internal full path.
path = key
#elif key.startswith('http://'): # external address
# path = key
elif key == '': # internal path
path = self.path[srcXML]
else: # internal path, add-on
path = self.path[srcXML] + '/' + key
if PMS_address[0].isdigit() or PMS_address=='plex.tv': # IP:port or plex.tv
auth_token = PlexAPI.getPMSProperty(self.ATV_udid, self.PMS_uuid, 'accesstoken')
enableGzip = PlexAPI.getPMSProperty(self.ATV_udid, self.PMS_uuid, 'enableGzip')
PMS = PlexAPI.getXMLFromPMS(self.PMS_baseURL, path, self.options, auth_token, enableGzip)
else: # owned, shared PMSs
type = self.PMS_address
PMS = PlexAPI.getXMLFromMultiplePMS(self.ATV_udid, path, type, self.options)
self.PMSroot[tag] = PMS.getroot() # store additional PMS XML
self.path[tag] = path # store base path
return False # tree unchanged (well, source tree yes. but that doesn't count...)
def TREE_VAR(self, elem, child, src, srcXML, param):
var, leftover = self.getParam(src, param)
key, leftover, dfltd = self.getKey(src, srcXML, leftover)
conv, leftover = self.getConversion(src, leftover)
if not dfltd:
key = self.applyConversion(key, conv)
self.variables[var] = key
return False # tree unchanged
def TREE_MEDIABADGES(self, elem, child, src, srcXML, param):
resolution, leftover, dfltd = self.getKey(src, srcXML, param + "/videoResolution")
container, leftover, dfltd = self.getKey(src, srcXML, param + "/container")
vCodec, leftover, dfltd = self.getKey(src, srcXML, param + "/videoCodec")
aCodec, leftover, dfltd = self.getKey(src, srcXML, param + "/audioCodec")
channels, leftover, dfltd = self.getKey(src, srcXML, param + "/audioChannels")
additionalBadges = etree.Element("additionalMediaBadges")
index = 0
attribs = {'insertIndex': '0', 'required': 'true', 'src': ''}
# Resolution
if resolution not in ['720', '1080', '2k', '4k']:
attribs['src'] = g_param['baseURL'] + '/thumbnails/MediaBadges/sd.png'
else:
attribs['src'] = g_param['baseURL'] + '/thumbnails/MediaBadges/' + resolution + '.png'
urlBadge = etree.SubElement(additionalBadges, "urlBadge", attribs)
index += 1
# Special case iTunes DRM
if vCodec == 'drmi' or aCodec == 'drms':
attribs['insertIndex'] = str(index)
attribs['src'] = g_param['baseURL'] + '/thumbnails/MediaBadges/iTunesDRM.png'
urlBadge = etree.SubElement(additionalBadges, "urlBadge", attribs)
child.append(additionalBadges)
return True # Finish, no more info needed
# File container
if container != '' and self.options['aTVFirmwareVersion'] >= '7.0':
attribs['insertIndex'] = str(index)
attribs['src'] = g_param['baseURL'] + '/thumbnails/MediaBadges/' + container + '.png'
urlBadge = etree.SubElement(additionalBadges, "urlBadge", attribs)
index += 1
# Video Codec
if vCodec != '' and self.options['aTVFirmwareVersion'] >= '7.0':
if vCodec == 'mpeg4':
vCodec = "XVID" # Are there any other mpeg4-part 2 codecs?
attribs['insertIndex'] = str(index)
attribs['src'] = g_param['baseURL'] + '/thumbnails/MediaBadges/' + vCodec + '.png'
urlBadge = etree.SubElement(additionalBadges, "urlBadge", attribs)
index += 1
# Audio Codec
if aCodec != '':
attribs['insertIndex'] = str(index)
attribs['src'] = g_param['baseURL'] + '/thumbnails/MediaBadges/' + aCodec + '.png'
urlBadge = etree.SubElement(additionalBadges, "urlBadge", attribs)
index += 1
# Audio Channels
if channels != '':
attribs['insertIndex'] = str(index)