forked from iBaa/PlexConnect
-
Notifications
You must be signed in to change notification settings - Fork 1
/
XMLConverter.py
executable file
·1347 lines (1072 loc) · 50.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 os
import sys
import traceback
import inspect
import string, cgi, time
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
import urllib2
import urlparse
from Version import __VERSION__ # for {{EVAL()}}, display in settings page
import Settings, ATVSettings
import PlexAPI
from Debug import * # dprint(), prettyXML()
import Localize
g_param = {}
def setParams(param):
global g_param
g_param = param
g_ATVSettings = None
def setATVSettings(cfg):
global g_ATVSettings
g_ATVSettings = cfg
# links to CMD class for module wide usage
g_CommandCollection = None
"""
# 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\
<myMetadata>\n\
<!-- PMS, OSD settings, ... -->\n\
<baseURL>' + baseURL + '</baseURL>\n\
<accessToken></accessToken>\n\
<key></key>\n\
<ratingKey></ratingKey>\n\
<duration></duration>\n\
<showClock>False</showClock>\n\
<timeFormat></timeFormat>\n\
<clockPosition></clockPosition>\n\
<overscanAdjust></overscanAdjust>\n\
<showEndtime>False</showEndtime>\n\
<subtitleURL></subtitleURL>\n\
<subtitleSize></subtitleSize>\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 = ''
channelsearchURL = ''
if 'PlexConnect' in options:
cmd = options['PlexConnect']
if 'PlexConnectChannelsSearch' in options:
channelsearchURL = options['PlexConnectChannelsSearch'].replace('+amp+', '&')
dprint(__name__, 1, "PlexConnect Cmd: " + cmd)
dprint(__name__, 1, "PlexConnectChannelsSearch: " + channelsearchURL)
# 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
elif cmd=='ChannelsSearch':
XMLtemplate = 'ChannelsSearch.xml'
path = ''
elif cmd=='Play':
XMLtemplate = 'PlayVideo.xml'
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=='ScrobbleMenu':
XMLtemplate = 'ScrobbleMenu.xml'
elif cmd=='ScrobbleMenuVideo':
XMLtemplate = 'ScrobbleMenuVideo.xml'
elif cmd=='ScrobbleMenuTVOnDeck':
XMLtemplate = 'ScrobbleMenuTVOnDeck.xml'
elif cmd=='ChangeShowArtwork':
XMLtemplate = 'ChangeShowArtwork.xml'
elif cmd=='ChangeSingleArtwork':
XMLtemplate = 'ChangeSingleArtwork.xml'
elif cmd=='ChangeSingleArtworkVideo':
XMLtemplate = 'ChangeSingleArtworkVideo.xml'
elif cmd=='PhotoBrowser':
XMLtemplate = 'Photo_Browser.xml'
elif cmd=='MoviePreview':
XMLtemplate = 'MoviePreview.xml'
elif cmd=='HomeVideoPrePlay':
XMLtemplate = 'HomeVideoPrePlay.xml'
elif cmd=='MoviePrePlay':
XMLtemplate = 'MoviePrePlay.xml'
elif cmd=='EpisodePrePlay':
XMLtemplate = 'EpisodePrePlay.xml'
elif cmd=='ChannelPrePlay':
XMLtemplate = 'ChannelPrePlay.xml'
elif cmd=='ChannelsVideo':
XMLtemplate = 'ChannelsVideo.xml'
elif cmd=='ByFolder':
XMLtemplate = 'ByFolder.xml'
elif cmd=='HomeVideoByFolder':
XMLtemplate = 'HomeVideoByFolder.xml'
elif cmd == 'HomeVideoDirectory':
XMLtemplate = 'HomeVideoDirectory.xml'
elif cmd=='MovieByFolder':
XMLtemplate = 'MovieByFolder.xml'
elif cmd == 'MovieDirectory':
XMLtemplate = 'MovieDirectory.xml'
elif cmd == 'MovieSection':
XMLtemplate = 'MovieSection.xml'
elif cmd == 'HomeVideoSection':
XMLtemplate = 'HomeVideoSection.xml'
elif cmd == 'TVSection':
XMLtemplate = 'TVSection.xml'
elif cmd.find('SectionPreview') != -1:
XMLtemplate = cmd + '.xml'
elif cmd == 'AllMovies':
XMLtemplate = 'Movie_'+g_ATVSettings.getSetting(options['PlexConnectUDID'], 'movieview').replace(' ','')+'.xml'
elif cmd == 'AllHomeVideos':
XMLtemplate = 'HomeVideo_'+g_ATVSettings.getSetting(options['PlexConnectUDID'], 'homevideoview').replace(' ','')+'.xml'
elif cmd == 'MovieSecondary':
XMLtemplate = 'MovieSecondary.xml'
elif cmd == 'AllShows':
XMLtemplate = 'Show_'+g_ATVSettings.getSetting(options['PlexConnectUDID'], 'showview')+'.xml'
elif cmd == 'TVSecondary':
XMLtemplate = 'TVSecondary.xml'
elif cmd == 'PhotoSecondary':
XMLtemplate = 'PhotoSecondary.xml'
elif cmd == 'Directory':
XMLtemplate = 'Directory.xml'
elif cmd == 'DirectoryWithPreview':
XMLtemplate = 'DirectoryWithPreview.xml'
elif cmd == 'DirectoryWithPreviewActors':
XMLtemplate = 'DirectoryWithPreviewActors.xml'
elif cmd=='Settings':
XMLtemplate = 'Settings.xml'
path = '' # clear path - we don't need PMS-XML
elif cmd=='SettingsVideoOSD':
XMLtemplate = 'Settings_VideoOSD.xml'
path = '' # clear path - we don't need PMS-XML
elif cmd=='SettingsMovies':
XMLtemplate = 'Settings_Movies.xml'
path = '' # clear path - we don't need PMS-XML
elif cmd=='SettingsTVShows':
XMLtemplate = 'Settings_TVShows.xml'
path = '' # clear path - we don't need PMS-XML
elif cmd=='SettingsHomeVideos':
XMLtemplate = 'Settings_HomeVideos.xml'
path = '' # clear path - we don't need PMS-XML
elif cmd=='SettingsTopLevel':
XMLtemplate = 'Settings_TopLevel.xml'
path = '' # clear path - we don't need PMS-XML
elif cmd.startswith('SettingsToggle:'):
opt = cmd[len('SettingsToggle:'):] # cut command:
parts = opt.split('+')
g_ATVSettings.toggleSetting(options['PlexConnectUDID'], parts[0].lower())
XMLtemplate = parts[1] + ".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==('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)
g_ATVSettings.setSetting(UDID, 'myplex_user', username)
g_ATVSettings.setSetting(UDID, 'myplex_auth', auth_token)
XMLtemplate = 'Settings.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)
g_ATVSettings.setSetting(UDID, 'myplex_user', '')
g_ATVSettings.setSetting(UDID, 'myplex_auth', '')
XMLtemplate = 'Settings.xml'
path = '' # clear path - we don't need PMS-XML
elif cmd.startswith('Discover'):
auth_token = g_ATVSettings.getSetting(UDID, 'myplex_auth')
PlexAPI.discoverPMS(UDID, g_param['CSettings'], auth_token)
return XML_Error('PlexConnect', 'Discover!') # not an error - but aTV won't care anyways.
elif path.startswith('/search?'):
XMLtemplate = 'Search_Results.xml'
elif path.find('serviceSearch') != -1 or (path.find('video') != -1 and path.lower().find('search') != -1):
XMLtemplate = 'ChannelsVideoSearchResults.xml'
elif path.find('SearchResults') != -1:
XMLtemplate = 'ChannelsVideoSearchResults.xml'
elif path=='/library/sections': # from PlexConnect.xml -> for //local, //myplex
XMLtemplate = 'Library.xml'
elif path=='/channels/all':
XMLtemplate = 'Channel_'+g_ATVSettings.getSetting(options['PlexConnectUDID'], 'channelview')+'.xml'
path = ''
# request PMS XML
if not path=='':
if PMS_address[0].isalpha(): # owned, shared
type = PMS_address
PMS = PlexAPI.getXMLFromMultiplePMS(UDID, path, type, options)
else: # IP
auth_token = PlexAPI.getPMSProperty(UDID, PMS_uuid, 'accesstoken')
PMS = PlexAPI.getXMLFromPMS(PMS_baseURL, path, options, authtoken=auth_token)
if PMS==False:
return XML_Error('PlexConnect', 'No Response from Plex Media Server')
PMSroot = PMS.getroot()
dprint(__name__, 1, "viewGroup: "+PMSroot.get('viewGroup','None'))
# XMLtemplate defined by PMS XML content
if path=='':
pass # nothing to load
elif not XMLtemplate=='':
pass # template already selected
elif PMSroot.get('viewGroup','')=="secondary" and (PMSroot.get('art','').find('video') != -1 or PMSroot.get('thumb','').find('video') != -1):
XMLtemplate = 'HomeVideoSectionTopLevel.xml'
elif PMSroot.get('viewGroup','')=="secondary" and (PMSroot.get('art','').find('movie') != -1 or PMSroot.get('thumb','').find('movie') != -1):
XMLtemplate = 'MovieSectionTopLevel.xml'
elif PMSroot.get('viewGroup','')=="secondary" and (PMSroot.get('art','').find('show') != -1 or PMSroot.get('thumb','').find('show') != -1):
XMLtemplate = 'TVSectionTopLevel.xml'
elif PMSroot.get('viewGroup','')=="secondary" and (PMSroot.get('art','').find('photo') != -1 or PMSroot.get('thumb','').find('photo') != -1):
XMLtemplate = 'PhotoSectionTopLevel.xml'
elif PMSroot.get('viewGroup','')=="secondary":
XMLtemplate = 'Directory.xml'
elif PMSroot.get('viewGroup','')=='show':
if PMSroot.get('title2')=='By Folder':
# By Folder View
XMLtemplate = 'ByFolder.xml'
else:
# TV Show grid view
XMLtemplate = 'Show_'+g_ATVSettings.getSetting(options['PlexConnectUDID'], 'showview')+'.xml'
elif PMSroot.get('viewGroup','')=='season':
# TV Season view
XMLtemplate = 'Season_'+g_ATVSettings.getSetting(options['PlexConnectUDID'], 'seasonview')+'.xml'
elif PMSroot.get('viewGroup','')=='movie' and PMSroot.get('thumb','').find('video') != -1:
if PMSroot.get('title2')=='By Folder':
# By Folder View
XMLtemplate = 'HomeVideoByFolder.xml'
else:
# Home Video listing
XMLtemplate = 'HomeVideo_'+g_ATVSettings.getSetting(options['PlexConnectUDID'], 'homevideoview').replace(' ','')+'.xml'
elif PMSroot.get('viewGroup','')=='movie' and PMSroot.get('thumb','').find('movie') != -1:
if PMSroot.get('title2')=='By Folder':
# By Folder View
XMLtemplate = 'MovieByFolder.xml'
else:
# Movie listing
XMLtemplate = 'Movie_'+g_ATVSettings.getSetting(options['PlexConnectUDID'], 'homevideoview').replace(' ','')+'.xml'
elif PMSroot.get('viewGroup','')=='track':
XMLtemplate = 'Music_Track.xml'
elif PMSroot.get('viewGroup','')=='episode':
if PMSroot.get('title2')=='On Deck' or \
PMSroot.get('title2')=='Recently Viewed Episodes' or \
PMSroot.get('title2')=='Recently Aired' or \
PMSroot.get('title2')=='Recently Added':
# TV On Deck View
XMLtemplate = 'TV_OnDeck.xml'
else:
# TV Episode view
XMLtemplate = 'Episode.xml'
elif PMSroot.get('viewGroup','')=='photo' or \
path.startswith('/photos') or \
PMSroot.find('Photo')!=None:
if PMSroot.find('Directory')==None:
# Photos only - directly show
XMLtemplate = 'Photo_Browser.xml'
else:
# Photo listing / directory
XMLtemplate = 'Photo_Directories.xml'
else:
XMLtemplate = 'Directory.xml'
dprint(__name__, 1, "XMLTemplate: "+XMLtemplate)
# get XMLtemplate
aTVTree = etree.parse(sys.path[0]+'/assets/templates/'+XMLtemplate)
aTVroot = aTVTree.getroot()
# convert PMS XML to aTV XML using provided XMLtemplate
global g_CommandCollection
g_CommandCollection = CCommandCollection(options, PMSroot, PMS_address, path)
XML_ExpandTree(aTVroot, PMSroot, 'main')
XML_ExpandAllAttrib(aTVroot, PMSroot, 'main')
del g_CommandCollection
if cmd=='ChannelsSearch':
for bURL in aTVroot.iter('baseURL'):
if channelsearchURL.find('?') == -1:
bURL.text = channelsearchURL + '?query='
else:
bURL.text = channelsearchURL + '&query='
dprint(__name__, 1, "====== generated aTV-XML ======")
dprint(__name__, 1, prettyXML(aTVTree))
dprint(__name__, 1, "====== aTV-XML finished ======")
return etree.tostring(aTVroot)
def XML_ExpandTree(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(elem, child, src, srcXML, 'TEXT')
if res==True: # tree modified: restart from 1st elem
break # "for child"
# recurse into children
XML_ExpandTree(child, src, srcXML)
res = XML_ExpandNode(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(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
param = XML_ExpandLine(src, srcXML, param) # expand any attributes in the parameter
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:
res = getattr(g_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(elem, src, srcXML):
# unpack template commands in elem.text
line = elem.text
if line!=None:
elem.text = XML_ExpandLine(src, srcXML, line.strip())
# unpack template commands in elem.tail
line = elem.tail
if line!=None:
elem.tail = XML_ExpandLine(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(src, srcXML, line.strip()))
# recurse into children
for el in elem:
XML_ExpandAllAttrib(el, src, srcXML)
def XML_ExpandLine(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
param = XML_ExpandLine(src, srcXML, param) # expand any attributes in the parameter
if hasattr(CCommandCollection, 'ATTRIB_'+cmd): # expand line, work VAL, EVAL...
try:
res = getattr(g_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('#'): # 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('#'): # 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('^'): # 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((convstr[0], 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):
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
# duplicate child and add to tree
for elemSRC in src.findall(tag):
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:
el = copy.deepcopy(child)
XML_ExpandTree(el, elemSRC, srcXML)
XML_ExpandAllAttrib(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
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].isalpha(): # owned, shared
type = self.PMS_address
PMS = PlexAPI.getXMLFromMultiplePMS(self.ATV_udid, path, type, self.options)
else: # IP
auth_token = PlexAPI.getPMSProperty(self.ATV_udid, self.PMS_uuid, 'accesstoken')
PMS = PlexAPI.getXMLFromPMS(self.PMS_baseURL, path, self.options, auth_token)
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
# XML ATTRIB modifier commands
# add new commands to this list!
def ATTRIB_VAL(self, 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)
return key
def ATTRIB_EVAL(self, src, srcXML, param):
return str(eval(param))
def ATTRIB_SVAL(self, 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)
return quote_plus(unicode(key).encode("utf-8"))
def ATTRIB_SETTING(self, src, srcXML, param):
opt, leftover = self.getParam(src, param)
return g_ATVSettings.getSetting(self.ATV_udid, opt)
def ATTRIB_ADDPATH(self, src, srcXML, param):
addpath, leftover, dfltd = self.getKey(src, srcXML, param)
if addpath.startswith('/'):
res = addpath
elif addpath == '':
res = self.path[srcXML]
else:
res = self.path[srcXML]+'/'+addpath
return res
def ATTRIB_IMAGEURL(self, src, srcXML, param):
key, leftover, dfltd = self.getKey(src, srcXML, param)
width, leftover = self.getParam(src, leftover)
height, leftover = self.getParam(src, leftover)
if height=='':
height = width
PMS_uuid = self.PMS_uuid
PMS_baseURL = self.PMS_baseURL
cmd_start = key.find('PMS(')
cmd_end = key.find(')', cmd_start)
if cmd_start>-1 and cmd_end>-1 and cmd_end>cmd_start:
PMS_address = key[cmd_start+4:cmd_end]
PMS_uuid = PlexAPI.getPMSFromAddress(self.ATV_udid, PMS_address)
PMS_baseURL = PlexAPI.getPMSProperty(self.ATV_udid, PMS_uuid, 'baseURL')
key = key[cmd_end+1:]
AuthToken = PlexAPI.getPMSProperty(self.ATV_udid, PMS_uuid, 'accesstoken')
# transcoder action
transcoderAction = g_ATVSettings.getSetting(self.ATV_udid, 'phototranscoderaction')
# aTV native filetypes
parts = key.rsplit('.',1)
photoATVNative = parts[-1].lower() in ['jpg','jpeg','tif','tiff','gif','png']
dprint(__name__, 2, "photo: ATVNative - {0}", photoATVNative)
if width=='' and \
transcoderAction=='Auto' and \
photoATVNative:
# direct play
res = PlexAPI.getDirectImagePath(key, AuthToken)