-
Notifications
You must be signed in to change notification settings - Fork 169
/
default.py
executable file
·1171 lines (950 loc) · 46.9 KB
/
default.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
import urllib,urllib2,re,xbmcplugin,xbmcgui,xbmcaddon
import os,datetime, time
from BeautifulSoup import BeautifulStoneSoup
#Get the setting from the appropriate file.
__settings__ = xbmcaddon.Addon(id='plugin.video.plexbmc')
g_host = __settings__.getSetting('ipaddress')
g_stream = __settings__.getSetting('streaming')
g_extended = __settings__.getSetting('extended')
g_loc = "special://home/addon/plugin.video.plexbmc"
print "Settings hostname: " + g_host
print "Settings streaming: " + g_stream
pluginhandle = int(sys.argv[1])
################################ Common
# Connect to a server and retrieve the HTML page
def getURL( url ):
try:
print 'PleXBMC--> getURL :: url = '+url
txdata = None
txheaders = {
'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US;rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 ( .NET CLR 3.5.30729)'
}
req = urllib2.Request(url, txdata, txheaders)
response = urllib2.urlopen(req)
link=response.read()
response.close()
except urllib2.URLError, e:
error = 'Error code: '+ str(e.code)
xbmcgui.Dialog().ok(error,error)
print 'Error code: ', e.code
return False
else:
return link
#Used to add playable media files to directory listing
#properties is a dictionary {} which contains a list of setInfo properties to apply
#Arguments is a dictionary {} which contains other arguments used in teh creation of the listing (such as name, resume time, etc)
def addLink(id,name,url,mode,properties,arguments):
url=urllib.quote(str(url))
#Build url to activate playback.
u=sys.argv[0]+"?url="+str(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&resume="+str(arguments['resume'])+"&id="+id+"&duration="+str(arguments['duration'])
ok=True
#If we have a positive playcount, then set the watched icon to watched (overlay 7). Overlay 6 is unwatched
if properties['playcount'] > 0:
#we have a watched film. I can't see a way of displaying a partial like Plex, which uses resume time to decide.
print "Watched file, setting overlay to 7"
properties['overlay']=7 # watched icon
#Create ListItem object, which is what is displayed on screen
liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=arguments['thumb'])
print "Setting thumbnail as " + arguments['thumb']
print "Property is " + str(properties)
#Set properties of the listitem object, such as name, plot, rating, content type, etc
liz.setInfo( type="Video", infoLabels=properties )
#Set the file as playable, otherwise setresolvedurl will fail
liz.setProperty('IsPlayable', 'true')
#Set the fanart image if it has been enabled
if arguments.has_key('fanart_image'):
print "Setting fan art"
liz.setProperty('fanart_image', str(arguments['fanart_image']))
#Finally add the item to the on screen list, with url created above
ok=xbmcplugin.addDirectoryItem(handle=pluginhandle,url=u,listitem=liz)
return ok
#Used to add directory item to the listing. These are non-playable items. They can be mixed with playable items created above.
#properties is a dictionary {} which contains a list of setInfo properties to apply
#Arguments is a dictionary {} which contains other arguments used in teh creation of the listing (such as name, resume time, etc)
def addDir(name,url,mode,properties,arguments):
#Create the URL to pass to the item
u=sys.argv[0]+"?url="+str(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
ok=True
#Create the ListItem that will be displayed
liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=arguments['thumb'])
#Set the properties of the item, such as summary, name, season, etc
liz.setInfo( type="Video", infoLabels=properties )
print 'harley:'+ u
#If we have set a number of watched episodes per season
if arguments.has_key('WatchedEpisodes'):
#Then set the number of watched and unwatched, which will be displayed per season
liz.setProperty('WatchedEpisodes', str(arguments['WatchedEpisodes']))
liz.setProperty('UnWatchedEpisodes', str(arguments['UnWatchedEpisodes']))
#Set the fanart image if it has been enabled
if arguments.has_key('fanart_image'):
print "Setting fan art to " + str(arguments['fanart_image'])
liz.setProperty('fanart_image', str(arguments['fanart_image']))
#Finally add the item to the on screen list, with url created above
ok=xbmcplugin.addDirectoryItem(handle=pluginhandle,url=u,listitem=liz,isFolder=True)
return ok
################################ Root listing
# Root listing is the main listing showing all sections. It is used when these is a non-playable generic link content
def ROOT():
#xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_LABEL)
#Get the global host variable set in settings
host=g_host
#Get the HTML for the URL
url = 'http://'+host+':32400/servers'
html=getURL(url)
#Pass HTML to BSS to convert it into a nice parasble tree.
tree=BeautifulStoneSoup(html, convertEntities=BeautifulStoneSoup.HTML_ENTITIES)
#Now, find all those server tags
LibraryTags=tree.findAll('server')
print tree
print LibraryTags
Servers=[]
Sections=[]
#Now, for each tag, pull out the name of the server and it's network name
for object in LibraryTags:
name=object.get('name').encode('utf-8')
host=object.get('host')
Servers.append([name,host])
#For each of the servers we have identified
for server in Servers:
#dive into the library section with BS
url='http://'+server[1]+':32400/library/sections'
html=getURL(url)
tree=BeautifulStoneSoup(html, convertEntities=BeautifulStoneSoup.HTML_ENTITIES)
#Find all the directory tags, as they contain further levels to follow
#For each directory tag we find, build an onscreen link to drill down into the library
SectionTags=tree.findAll('directory')
for object in SectionTags:
#Set up some dictionaries with defaults that we are going to pass to addDir/addLink
arguments={'thumb':''}
properties={}
#Start pulling out information from the parsed XML output. Assign to various variables
key=object.get('key')
properties['title']=arguments['name']=object.get('title')
type=object.get('type')
#Determine what we are going to do process after a link is selected by the user, based on the content we find
if type == 'show':
mode=1
if type == 'movie':
mode=2
if type == 'artist':
mode=3
#Build URL with the mode to use and key to further XML data in the library
s_url='http://'+server[1]+':32400/library/sections/'+key+'/all'
#Build that listing..
addDir(arguments['name'],s_url,mode, properties,arguments)
#Plex plugin handling
#Simple check if any plugins are present.
#If so, create a link to drill down later. One link is created for each PMS server available
#Plugin data is held in /videos directory (well, video data is anyway)
pluginurl='http://'+server[1]+':32400/video'
pluginhtml=getURL(pluginurl)
plugintree=BeautifulStoneSoup(pluginhtml, convertEntities=BeautifulStoneSoup.HTML_ENTITIES)
head = plugintree.find('mediacontainer')
#Check the number of items in the mediacontainer tag.
items = head['size']
#If we have at least one item listed, then we have some plugin. In which case, create a link
if items > 0:
arguments={'thumb':''}
properties={}
#URL contains the location of the server plugin. We'll display the content later
s_url=pluginurl
mode=7
properties['title']="Plex Plugins: "+ server[0]
#Add an on screen link
addDir(properties['title'], s_url, mode, properties,arguments)
#All XML entries have been parsed and we are ready to allow the user to browse around. So end the screen listing.
xbmcplugin.endOfDirectory(pluginhandle)
################################ Movies listing
#Used by the skin to automatically start a movie listing. Might not be needed now - copies functionality in ROOT
def StartMovies():
print '=========================='
print 'Starting with Movies'
host=g_host
url = 'http://'+host+':32400/library/sections'
html=getURL(url)
tree=BeautifulStoneSoup(html, convertEntities=BeautifulStoneSoup.HTML_ENTITIES)
SectionTags=tree.findAll('directory')
for object in SectionTags:
key=object.get('key')
name=object.get('title')
type=object.get('type')
if type== 'movie':
url='http://'+host+':32400/library/sections/'+key+'/all'
Movies(url)
################################ TV listing
#Used by the skin to automatically start a TV listing. Might not be needed now - copies functionality in ROOT
def StartTV():
print '=========================='
print 'Starting with TV Shows'
host=g_host
url = 'http://'+host+':32400/library/sections'
html=getURL(url)
tree=BeautifulStoneSoup(html, convertEntities=BeautifulStoneSoup.HTML_ENTITIES)
SectionTags=tree.findAll('directory')
for object in SectionTags:
key=object.get('key')
name=object.get('title')
type=object.get('type')
if type== 'show':
url='http://'+host+':32400/library/sections/'+key+'/all'
SHOWS(url)
################################ Movies listing
# Used to display movie on screen.
def Movies(url):
xbmcplugin.setContent(pluginhandle, 'movies')
print '=============='
print 'Getting Movies'
xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_LABEL)
#get the server name from the URL, which was passed via the on screen listing..
server=url.split('/')[2]
print server
#Get some XML and parse it
html=getURL(url)
tree= BeautifulStoneSoup(html, convertEntities=BeautifulStoneSoup.HTML_ENTITIES)
#Find all the video tags, as they contain the data we need to link to a file.
MovieTags=tree.findAll('video')
for movie in MovieTags:
#Create some structures to pass to Addlink
properties={'overlay': 6, 'playcount': 0} #Create a dictionary for properties (i.e. ListItem properties)
arguments={'type': "movies", 'resume': 0, 'duration': 0} #Create a dictionary for file arguments (i.e. stuff you need, but are no listitems)
#get the ID
id=movie.get('ratingkey')
arguments['id']=id
#Get name
name=movie.get('title')
arguments['name']=name.encode('utf-8')
if arguments['name'].find(''') >0:
arguments['name'] = arguments['name'].replace("'","'")
properties['title']=arguments['name']
#Get the Plot
plot=movie.get('summary')
if plot is not None:
properties['plot']=plot.encode('utf-8')
if properties['plot'].find(''') >0:
properties['plot'] = properties['plot'].replace("'","'")
#Get the watched status
playcount=movie.get('viewcount')
if playcount is not None:
properties['playcount']=int(playcount)
#Get how good it is, based on your votes...
rating=movie.get('rating')
if rating is not None:
properties['rating']=float(rating)
#Get the last played position
resume=movie.get('viewoffset')
if resume is not None:
arguments['resume']=resume
#Get the studio
studio=movie.get('studio')
if studio is not None:
properties['studio']=studio.encode('utf-8')
#Get the Movie certificate, so you know if the kids can watch it.
certificate=movie.get('contentrating')
if certificate is not None:
properties['certificate'] = certificate
#year
year=movie.get('year')
if year is not None:
properties['year']=int(year)
#That memorable 6 word summary..
tagline=movie.get('tagline')
if tagline is not None:
properties['tagline']=tagline.encode('utf-8')
#Get the length of the film, directly from the media analysis
duration=movie.findAll('media')[0].get('duration')
if duration is not None:
#If we've found a duration, convert it into something we can read..
arguments['duration']=int(duration)/1000
properties['duration']=str(datetime.timedelta(milliseconds=int(duration)))
else:
#Fall back to the standard duration as discovered by PMS if we can analyse media
duration=movie.get('duration')
if duration is not None:
arguments['duration']=int(duration)/1000
properties['duration']=str(datetime.timedelta(milliseconds=int(duration)))
#Get the picture to use
thumb=movie.get('thumb')
if thumb is not None:
thumb_url='http://'+server+thumb.encode('utf')
else:
#Or use a stock default one
thumb_url=g_loc+'/resources/movie.png'
print thumb
arguments['thumb']=thumb_url
#Get a nice big picture
fanart=movie.get('art')
if fanart is not None:
fanart=fanart.split('?')[0] #drops the guid from the fanart image
art_url='http://'+server+fanart.encode('utf-8')
art_url='http://'+server+':32400/photo/:/transcode?url='+art_url+'&width=1280&height=720'
else:
#or use a stock default one
art_url=g_loc+'/resources/movie_art.jpg'
print art_url
arguments['fanart_image']=art_url
#Get the extended metadata, based on the g_extended setting. It's a bit slow...
if g_extended == "true":
extended={}
#Call another function and store the returned data ina dictionary
extended=getextendedmetadata('http://'+server+'/library/metadata/'+id)
#Check for data before adding it to the property list
if extended.has_key('genre'):
properties['genre']=extended['genre']
if extended.has_key('writer'):
properties['writer']=extended['writer']
if extended.has_key('director'):
properties['director']=extended['director']
if extended.has_key('cast'):
properties['castandrole']=extended['cast']
else:
#Else just used the shortened genre list, which is easy to do
genreList=[]
try:
tempgenres=movie.findAll('genre')
for item in tempgenres:
genreList.append(item.get('tag'))
except: pass
#Join that data with a / becuase that is what XBMC use as default..
genre = " / ".join(genreList)
properties['genre']=genre
#If the streaming option is true, then get the virtual listing
if g_stream == "true":
location=movie.findAll('part')[0].get('key')
url='http://'+server+location
else:
#Else get the actual location, and use this via SMB if configured
location=movie.findAll('part')[0].get('file')
location=location.replace("Volumes",server)
location=location.replace(":32400","")
url='smb:/'+location
#This is playable media, so link to a path to a play function
mode=5
#required to grab to check if file is a .strm file
location=movie.findAll('part')[0].get('file')
strUrl=str(location)
print strUrl
#Can't play strm files, so lets not bother listing them.
if strUrl.find('.strm') >0:
continue
else:
print '============='
print "properties is " + str(properties)
print "arguments is " + str(arguments)
#Right, add that link...and loop around for another entry
addLink(id,arguments['name'],url,mode,properties,arguments)
#If we get here, then we've been through the XML and it's time to finish.
xbmcplugin.endOfDirectory(pluginhandle)
################################ Grabs Extended metadata
#How to get that extended metadata. It comes from a seperate XML request.
def getextendedmetadata(url):
print "=========="
print "Getting extended metadata"
#USe URL to get XML, and parse.
html=getURL(url)
tree=BeautifulStoneSoup(html, convertEntities=BeautifulStoneSoup.HTML_ENTITIES)
genrelist=[]
writerlist=[]
directorlist=[]
castlist=[]
#Find all the genre tag. Build into a list, then join list into a sting. Done
genreTag=tree.findAll('genre')
for tags in genreTag:
genrelist.append(tags.get('tag'))
genrestring=" / ".join(genrelist)
#Same as abaove but for writers
writerTag=tree.findAll('writer')
for tags in writerTag:
writerlist.append(tags.get('tag'))
writerstring=" / ".join(writerlist)
#And again for directors
directorTag=tree.findAll('director')
for tags in directorTag:
directorlist.append(tags.get('tag'))
directorstring=" / ".join(directorlist)
#Cast is returned as a list of strings (containing people and roles)
castTag=tree.findAll('role')
for tags in castTag:
person=tags.get('tag')
role=tags.get('role')
#Pop the string into the list
castlist.append(person+' as '+role)
#Return the entire data set as a dictionary
returnlist={'genre':genrestring , 'writer':writerstring, 'director' : directorstring , 'cast' : castlist}
return returnlist
################################ TV Show Listings
#This is the function use to parse the top level list of TV shows
def SHOWS(url):
xbmcplugin.setContent(pluginhandle, 'tvshows')
print '=============='
print 'Getting TV Shows'
xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_LABEL)
#Get the URL and server name. Get the XML and parse
server=url.split('/')[2]
print server
html=getURL(url)
tree=BeautifulStoneSoup(html, convertEntities=BeautifulStoneSoup.HTML_ENTITIES)
#For each directory tag we find
ShowTags=tree.findAll('directory') # These type of calls seriously slow down plugins
for show in ShowTags:
#Create the basic data structures to pass up
properties={'overlay': 6, 'playcount': 0, 'season' : 0 , 'episode':0 } #Create a dictionary for properties with some defaults(i.e. ListItem properties)
arguments={'type': "tvshows", 'resume': 0, 'duration': 0} #Create a dictionary for file arguments (i.e. stuff you need, but are no listitems)
#Get the ID
try:id=show.get('ratingkey').encode('utf-8') # These not so much, unless there's a bunch of them
except: id=show.get('key')
#get the name
name=show.get('title')
arguments['name']=name.encode('utf-8')
if arguments['name'].find(''') >0:
arguments['name'] = arguments['name'].replace("'","'")
properties['title']=properties['showname']=arguments['name']
#Get the studio
studio=show.get('studio')
if studio is not None:
properties['studio']=studio.encode('utf-8')
#Get the plot
plot=show.get('summary')
if plot is not None:
properties['plot']=plot.encode('utf-8')
#get some fan art
fanart=show.get('art')
if fanart is not None:
fanart
arguments['fanart_image']='http://'+server+fanart.encode('utf-8')
#Get the certificate to see how scary it is..
contentrating=show.get('contentrating')
if contentrating is not None:
properties['mpaa']=contentrating.encode('utf-8')
#Get the total number of episodes
episodes=show.get('leafcount')
if episodes is not None:
properties['episode']=int(episodes)
#Get the number of watched episodes
watched=show.get('viewedleafcount')
if watched is not None:
#And then work out the number of unwatched ones..
arguments['WatchedEpisodes']=int(watched)
arguments['UnWatchedEpisodes']=properties['episode']-arguments['WatchedEpisodes']
#Get the Genre info
genreList=[]
try:
tempgenres=show.findAll('genre')
for item in tempgenres:
genreList.append(item.get('tag'))
except: pass
genre = " / ".join(genreList)
properties['genre']=genre
#get the aired date
aired=show.get('originallyavailableat')
if aired is not None:
properties['aired']=aired
#get the picture
thumb="nothing"
if show.get('thumb') is not None:
thumb='http://'+server+show.get('thumb').encode('utf')
arguments['thumb']=thumb
strid=str(id)
print 'id: '+strid
if str(id).find('allLeaves') >0:
mode=4 # grab episodes
url='http://'+server+id
else:
mode=4 # grab episodes
url='http://'+server+'/library/metadata/'+id+'/children'
addDir(arguments['name'],url,mode,properties,arguments)
#End the listing
xbmcplugin.endOfDirectory(pluginhandle)
################################ TV Season listing
#Used to display the season data
def Seasons(url):
xbmcplugin.setContent(pluginhandle, 'tvshows')
print '=============='
print 'Getting TV Seasons'
xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_LABEL)
#Get URL, XML and parse
server=url.split('/')[2]
print server
html=getURL(url)
tree=BeautifulStoneSoup(html, convertEntities=BeautifulStoneSoup.HTML_ENTITIES)
#For all the directory tags
ShowTags=tree.findAll('directory')
for show in ShowTags:
#Build basic data structures
properties={'overlay': 6, 'playcount': 0, 'season' : 0 , 'episode':0 } #Create a dictionary for properties with some defaults(i.e. ListItem properties)
arguments={'type': "tvshows", 'resume': 0, 'duration': 0} #Create a dictionary for file arguments (i.e. stuff you need, but are no listitems)
#get the ID
id=show.get('key').encode('utf-8')
#get the show name
name=show.get('title')
arguments['name']=name.encode('utf-8')
if arguments['name'].find(''') >0:
arguments['name'] = arguments['name'].replace("'","'")
properties['title']=properties['showname']=arguments['name']
#Get the season picture
thumb='http://'+server+show.get('thumb').encode('utf')
if thumb is not None:
arguments['thumb']=thumb
#Get number of episodes in season
episodes=show.get('leafcount')
if episodes is not None:
properties['episode']=int(episodes)
#Get number of watched episodes
watched=show.get('viewedleafcount')
if watched is not None:
#and work out the number of unwatched ones
arguments['WatchedEpisodes']=int(watched)
arguments['UnWatchedEpisodes']=properties['episode']-arguments['WatchedEpisodes']
#Get the plot, although there isn;t one for seasons. But just in case....
plot=show.get('summary')
if plot is not None:
properties['plot']=plot.encode('utf-8')
url='http://'+server+id
#Set the mode to episodes, as that is what's next
mode=6
print '============='
#Build teh screen directory listing
addDir(name,url,mode,properties,arguments)
#All done, so end the listing
xbmcplugin.endOfDirectory(pluginhandle)
################################ TV Episode listing
#Displays teh actual playable media
def EPISODES(url):
xbmcplugin.setContent(pluginhandle, 'episodes')
print '=============='
print url
print 'Getting TV Episodes'
xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_EPISODE)
#Get the server
server=url.split('/')[2]
#Get the end part of teh URL, as we need to get different data if parsing "All Episodes"
target=url.split('/')[-1]
print server
print target
#Get URL, XML and Parse
html=getURL(url)
tree=BeautifulStoneSoup(html, convertEntities=BeautifulStoneSoup.HTML_ENTITIES)
ShowTags=tree.findAll('video')
#print "using Tags: " + str(ShowTags)
#get a bit of metadata that sits inside the main mediacontainer
#If it doesn't exist, we'll check later and get it from elsewhere
MainTag=tree.findAll('mediacontainer')[0]
#Name of the show
showname=MainTag.get('grandparenttitle')
#the kiddie rating
certificate = MainTag.get('grandparentcontentrating')
#the studio
studio = MainTag.get('grandparentstudio')
#If we are processing individual season, then get the season number, else we'll get it later
if target != "allLeaves":
season=MainTag.get('parentindex')
#right, not for each show we find
for show in ShowTags:
#print show
#Set basic structure with some defaults. Overlay 6 is unwatched
properties={'overlay': 6, 'playcount': 0, 'season' : 0} #Create a dictionary for properties with some defaults(i.e. ListItem properties)
arguments={'type': "tvshows", 'resume': 0, 'duration': 0} #Create a dictionary for file arguments (i.e. stuff you need, but are no listitems)
#get ID
id=show.get('ratingkey')
arguments['id']=id
#Get the episode number
episode=show.get('index')
if episode is not None:
properties['episode']=int(episode)
#get the episode name
name=show.get('title')
arguments['name']=name.encode('utf-8')
if arguments['name'].find(''') >0:
arguments['name'] = arguments['name'].replace("'","'")
properties['title']=arguments['name']
#Get plot
plot=show.get('summary')
if plot is not None:
properties['plot']=plot.encode('utf-8')
if properties['plot'].find(''') >0:
properties['plot'] = properties['plot'].replace("'","'")
#If we are processing an "All Episodes" directory, then get the season from the video tag
if target == "allLeaves":
season = show.get('parentindex')
if season is not None:
properties['season']=int(season)
else:
properties['season']=int(season)
#check if we got the kiddie rating from the main tag
if certificate:
properties['mpaa']=certificate
else:
#If not, get it from teh video tag instead
print "cert not set"
certificate = show.get('contentrating')
if certificate is not None:
properties['mpaa']=certificate
#Check if we got the showname from the main tag
if showname:
properties['showname']=showname
else:
#if not then get it form video tag
print "showname not set"
showname = show.get('grandparenttitle')
if certificate is not None:
properties['showname']=showname
#check if we got the studio from the main tag.
if studio:
properties['studio']=studio
else:
#if not, then get from the video tag
print "studio not set"
studio = show.get('studio')
if studio is not None:
properties['studio']=studio
#Get the last played position
resume=show.get('viewoffset')
if resume is not None:
arguments['resume']=resume
#get the picture
thumb=show.get('thumb')
if thumb is not None:
thumb=('http://'+server+thumb).encode('utf')
arguments['thumb']=thumb
#get the rating out of 10...
rating=show.get('rating')
if rating is not None:
properties['rating']=float(rating)
#get the air date
aired=show.get('originallyavailableat')
if aired is not None:
properties['aired']=aired
#get the length
duration=show.findAll('media')[0].get('duration')
if duration is not None:
#Set both a number and human readable time
arguments['duration']=int(duration)/1000
properties['duration']=str(datetime.timedelta(milliseconds=int(duration)))
#If we are streaming, then get the virtual location
if g_stream == "true":
location=show.findAll('part')[0].get('key')
url='http://'+server+location
else:
#Else get the actual location to use with SMB
location=show.findAll('part')[0].get('file')
location=location.replace("Volumes",server)
location=location.replace(":32400","")
url='smb:/'+location
location=show.findAll('part')[0].get('file')
#Required to check if file is a PlexFlix stream
strUrl=str(location)
print strUrl
if strUrl.find('.strm') >0:
continue
else:
#Set mode 5, which is play
mode=5
print '============='
print "properties is " + str(properties)
print "arguments is " + str(arguments)
#Build a file link and loop
addLink(id,arguments['name'],url,mode,properties,arguments)
#End the listing
xbmcplugin.endOfDirectory(pluginhandle)
#What to do to process Plex Plugin structures
def PlexPlugins(url):
xbmcplugin.setContent(pluginhandle, 'video')
print '=============='
print 'Getting Plugin Details'
xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_LABEL)
#get the serverm URL, XML and parse
server=url.split('/')[2]
print server
html=getURL(url)
tree= BeautifulStoneSoup(html, convertEntities=BeautifulStoneSoup.HTML_ENTITIES)
head = tree.find('mediacontainer')
print "head " + str(head)
#In the mediacontainer, check for the contents type.
try:
#Look for plugin content
content = head.get('content')
except:
content = "None"
print "content is " + str(content)
#If the contents is plugins, we have a top level dir.
if content == "plugins":
#then we have found an initial plugin list
print "Found plugin list"
DirectoryTags=tree.findAll('directory')
for links in DirectoryTags:
#Set up teh baxic structures
properties={}
arguments={'thumb':''}
#get the ID
id=links.get('key')
#get the plugin name
name=links.get('title')
arguments['name']=name.encode('utf-8')
if arguments['name'].find(''') >0:
arguments['name'] = arguments['name'].replace("'","'")
properties['title']=arguments['name']
#Set the mode to 7, which is running thie function again
mode=7
#Get the picture
thumb='http://'+server+links.get('thumb').encode('utf')
if thumb is not None:
arguments['thumb']=thumb
#Build the next level URL and add the link on screen
d_url=url+'/'+id
addDir(name, d_url, mode, properties, arguments)
else:
print "Found plugin details"
#this is either a secondary list of plugin menus (directory) or a list of plugin video (or even a mix)
#Find all the directory links
DirectoryTags=tree.findAll('directory')
#Find all the video files
VideoTags=tree.findAll('video')
print "Found some dirs: " + str(DirectoryTags)
print "Found some videos: " + str(VideoTags)
#For the directory tags we found
if DirectoryTags:
#We have directories, in which case process as adddirs
for tags in DirectoryTags:
#As normal, build the structures
properties={}
arguments={'thumb':''}
print str(tags)
id=tags.get('key')
#get the name
name=tags.get('title')
arguments['name']=name.encode('utf-8')
if arguments['name'].find(''') >0:
arguments['name'] = arguments['name'].replace("'","'")
properties['title']=arguments['name']
#Set the mode, to loop back into here again
mode=7
#get the picture
thumb='http://'+server+tags.get('thumb').encode('utf')
if thumb is not None:
arguments['thumb']=thumb
#Set the URL and build the directory link
d_url='http://'+server+id
print "url is " + d_url
addDir(name, d_url, mode, properties, arguments)
#If we have some video links as well
if VideoTags:
#We have video items, that we need to addlinks for
for tags in VideoTags:
#build structures
properties={'overlay': 6, 'playcount': 0} #Create a dictionary for properties with some defaults(i.e. ListItem properties)
arguments={'type': "video", 'resume': 0, 'duration': 0} #Create a dictionary for file arguments (i.e. stuff you need, but are no listitems)
id=tags.get('key')
#get name
name=tags.get('title')
arguments['name']=name.encode('utf-8')
if arguments['name'].find(''') >0:
arguments['name'] = arguments['name'].replace("'","'")
properties['title']=arguments['name']
#Set the mode to play them this time
mode=12
#Get picture
thumb='http://'+server+tags.get('thumb')
if thumb is not None:
arguments['thumb']=thumb.encode('utf')
#Build the URl and add a link to the file
v_url='http://'+server+id
addLink(id,name, v_url, mode, properties, arguments)
#Ahh, end of the list
xbmcplugin.endOfDirectory(pluginhandle)
#Right, this is used to play PMS library data file. This function will attempt to update PMS as well.
#Only use this to play stuff you want to update in the library
def PLAYEPISODE(id,vids,seek, duration):
#Use this to play PMS library items that you want up dated (Movies, TV shows)
url = vids
resume = seek
#Build a listitem, based on the url of the file
item = xbmcgui.ListItem(path=url)
result=1
#If we passed a positive resume time, then we need to display the dialog box to ask the user what they want to do
if resume > 0:
resumeseconds = resume/1000
#Human readable time
displayTime = str(datetime.timedelta(seconds=int(resumeseconds)))
#Build the dialog text
dialogOptions = [ "Resume from " + str(displayTime) , "Start from beginning"]
print "We are part way through this video!"
#Create a dialog object
startTime = xbmcgui.Dialog()
#Box displaying resume time or start at beginning
result = startTime.select('',dialogOptions)
#result contains an integer based on the selected text.
if result == -1:
#-1 is an exit without choosing, so end the function and start again when the user selects a new file.
return
#ok - this will start playback for the file pointed to by the url
start = xbmcplugin.setResolvedUrl(pluginhandle, True, item)
#Set a loop to wait for positive confirmation of playback
count = 0
while not xbmc.Player().isPlaying():
print "not playing yet...sleep for 2"
count = count + 2
if count >= 20:
#Waited 20 seconds and still no movie playing - assume it isn't going to..
return
else:
time.sleep(2)
#If we get this far, then XBMC must be playing
#If the user chose to resume...
if result == 0:
#Need to skip forward (seconds)
xbmc.Player().seekTime((resumeseconds))
#OK, we have a file, playing at the correct stop. Now we need to monitor the file playback to allow updates into PMS
monitorPlayback(id,url, resume, duration)
return
#Monitor function so we can update PMS
def monitorPlayback(id, url, resume, duration):
#Need to monitor the running playback, so we can determine a few things: