forked from zeflash/plugin.video.plexbmc
-
Notifications
You must be signed in to change notification settings - Fork 7
/
default.py
executable file
·4747 lines (3705 loc) · 175 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
'''
@document : default.py
@package : PleXBMC add-on
@author : Hippojay (aka Dave Hawes-Johnson)
@copyright : 2011-2012, Hippojay
@version : 3.0 (frodo)
@license : Gnu General Public License - see LICENSE.TXT
@description: pleXBMC XBMC add-on
This file is part of the XBMC PleXBMC Plugin.
PleXBMC Plugin is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
PleXBMC Plugin is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PleXBMC Plugin. If not, see <http://www.gnu.org/licenses/>.
'''
import urllib
import re
import xbmcplugin
import xbmcgui
import xbmcaddon
import httplib
import socket
import sys
import os
import time
import inspect
import base64
import random
import xbmcvfs
import xbmc
import datetime
try:
import cPickle as pickle
except ImportError:
import pickle
__settings__ = xbmcaddon.Addon(id='plugin.video.plexbmc')
__cwd__ = __settings__.getAddonInfo('path')
BASE_RESOURCE_PATH = xbmc.translatePath( os.path.join( __cwd__, 'resources', 'lib' ) )
PLUGINPATH=xbmc.translatePath( os.path.join( __cwd__) )
CACHEDATA=PLUGINPATH+"/cache"
sys.path.append(BASE_RESOURCE_PATH)
PLEXBMC_VERSION="3.2.2"
print "===== PLEXBMC START ====="
print "PleXBMC -> running Python: " + str(sys.version_info)
print "PleXBMC -> running PleXBMC: " + str(PLEXBMC_VERSION)
try:
from lxml import etree
print("PleXBMC -> Running with lxml.etree")
except ImportError:
try:
# Python 2.5
import xml.etree.cElementTree as etree
print("PleXBMC -> Running with cElementTree on Python 2.5+")
except ImportError:
try:
# Python 2.5
import xml.etree.ElementTree as etree
print("PleXBMC -> Running with ElementTree on Python 2.5+")
except ImportError:
try:
# normal cElementTree install
import cElementTree as etree
print("PleXBMC -> Running with built-in cElementTree")
except ImportError:
try:
# normal ElementTree install
import elementtree.ElementTree as etree
print("PleXBMC -> Running with built-in ElementTree")
except ImportError:
try:
import ElementTree as etree
print("PleXBMC -> Running addon ElementTree version")
except ImportError:
print("PleXBMC -> Failed to import ElementTree from any known place")
#Get the setting from the appropriate file.
DEFAULT_PORT="32400"
MYPLEX_SERVER="my.plexapp.com"
_MODE_GETCONTENT=0
_MODE_TVSHOWS=1
_MODE_MOVIES=2
_MODE_ARTISTS=3
_MODE_TVSEASONS=4
_MODE_PLAYLIBRARY=5
_MODE_TVEPISODES=6
_MODE_PLEXPLUGINS=7
_MODE_PROCESSXML=8
_MODE_CHANNELSEARCH=9
_MODE_CHANNELPREFS=10
_MODE_PLAYSHELF=11
_MODE_BASICPLAY=12
_MODE_SHARED_MOVIES=13
_MODE_ALBUMS=14
_MODE_TRACKS=15
_MODE_PHOTOS=16
_MODE_MUSIC=17
_MODE_VIDEOPLUGINPLAY=18
_MODE_PLEXONLINE=19
_MODE_CHANNELINSTALL=20
_MODE_CHANNELVIEW=21
_MODE_DISPLAYSERVERS=22
_MODE_PLAYLIBRARY_TRANSCODE=23
_MODE_MYPLEXQUEUE=24
_MODE_SHARED_SHOWS=25
_MODE_SHARED_MUSIC=26
_MODE_SHARED_PHOTOS=27
_MODE_DELETE_REFRESH=28
_MODE_SHARED_ALL=29
_SUB_AUDIO_XBMC_CONTROL="0"
_SUB_AUDIO_PLEX_CONTROL="1"
_SUB_AUDIO_NEVER_SHOW="2"
#Check debug first...
g_debug = __settings__.getSetting('debug')
def printDebug( msg, functionname=True ):
if g_debug == "true":
if functionname is False:
print str(msg)
else:
print "PleXBMC -> " + inspect.stack()[1][3] + ": " + str(msg)
def getPlatform( ):
if xbmc.getCondVisibility('system.platform.osx'):
return "OSX"
elif xbmc.getCondVisibility('system.platform.atv2'):
return "ATV2"
elif xbmc.getCondVisibility('system.platform.ios'):
return "iOS"
elif xbmc.getCondVisibility('system.platform.windows'):
return "Windows"
elif xbmc.getCondVisibility('system.platform.linux'):
return "Linux/RPi"
elif xbmc.getCondVisibility('system.platform.android'):
return "Linux/Android"
return "Unknown"
PLEXBMC_PLATFORM=getPlatform()
print "PleXBMC -> Platform: " + str(PLEXBMC_PLATFORM)
#Next Check the WOL status - lets give the servers as much time as possible to come up
g_wolon = __settings__.getSetting('wolon')
if g_wolon == "true":
from WOL import wake_on_lan
printDebug("PleXBMC -> Wake On LAN: " + g_wolon, False)
for i in range(1,12):
wakeserver = __settings__.getSetting('wol'+str(i))
if not wakeserver == "":
try:
printDebug ("PleXBMC -> Waking server " + str(i) + " with MAC: " + wakeserver, False)
wake_on_lan(wakeserver)
except ValueError:
printDebug("PleXBMC -> Incorrect MAC address format for server " + str(i), False)
except:
printDebug("PleXBMC -> Unknown wake on lan error", False)
g_stream = __settings__.getSetting('streaming')
g_secondary = __settings__.getSetting('secondary')
g_streamControl = __settings__.getSetting('streamControl')
g_channelview = __settings__.getSetting('channelview')
g_flatten = __settings__.getSetting('flatten')
printDebug("PleXBMC -> Flatten is: "+ g_flatten, False)
g_forcedvd = __settings__.getSetting('forcedvd')
if g_debug == "true":
print "PleXBMC -> Settings streaming: " + g_stream
print "PleXBMC -> Setting filter menus: " + g_secondary
print "PleXBMC -> Setting debug to " + g_debug
if g_streamControl == _SUB_AUDIO_XBMC_CONTROL:
print "PleXBMC -> Setting stream Control to : XBMC CONTROL (%s)" % g_streamControl
elif g_streamControl == _SUB_AUDIO_PLEX_CONTROL:
print "PleXBMC -> Setting stream Control to : PLEX CONTROL (%s)" % g_streamControl
elif g_streamControl == _SUB_AUDIO_NEVER_SHOW:
print "PleXBMC -> Setting stream Control to : NEVER SHOW (%s)" % g_streamControl
print "PleXBMC -> Force DVD playback: " + g_forcedvd
else:
print "PleXBMC -> Debug is turned off. Running silent"
#NAS Override
g_nasoverride = __settings__.getSetting('nasoverride')
printDebug("PleXBMC -> SMB IP Override: " + g_nasoverride, False)
if g_nasoverride == "true":
g_nasoverrideip = __settings__.getSetting('nasoverrideip')
if g_nasoverrideip == "":
printDebug("PleXBMC -> No NAS IP Specified. Ignoring setting")
else:
printDebug("PleXBMC -> NAS IP: " + g_nasoverrideip, False)
g_nasroot = __settings__.getSetting('nasroot')
#Get look and feel
if __settings__.getSetting("contextreplace") == "true":
g_contextReplace=True
else:
g_contextReplace=False
g_skipcontext = __settings__.getSetting("skipcontextmenus")
g_skipmetadata= __settings__.getSetting("skipmetadata")
g_skipmediaflags= __settings__.getSetting("skipflags")
g_skipimages= __settings__.getSetting("skipimages")
g_loc = "special://home/addons/plugin.video.plexbmc"
#Create the standard header structure and load with a User Agent to ensure we get back a response.
g_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)',
}
#Set up holding variable for session ID
global g_sessionID
g_sessionID=None
def discoverAllServers( ):
'''
Take the users settings and add the required master servers
to the server list. These are the devices which will be queried
for complete library listings. There are 3 types:
local server - from IP configuration
bonjour server - from a bonjour lookup
myplex server - from myplex configuration
Alters the global g_serverDict value
@input: None
@return: None
'''
printDebug("== ENTER: discoverAllServers ==", False)
das_servers={}
das_server_index=0
g_discovery = __settings__.getSetting('discovery')
if g_discovery == "1":
printDebug("PleXBMC -> local GDM discovery setting enabled.", False)
try:
import plexgdm
printDebug("Attempting GDM lookup on multicast")
if g_debug == "true":
GDM_debug=3
else:
GDM_debug=0
gdm_cache_file=CACHEDATA+"/gdm.server.cache"
gdm_cache_ok = False
gdm_cache_ok, gdm_server_name = checkCache(gdm_cache_file)
if not gdm_cache_ok:
gdm_client = plexgdm.plexgdm(GDM_debug)
gdm_client.discover()
gdm_server_name = gdm_client.getServerList()
writeCache(gdm_cache_file, gdm_server_name)
if ( gdm_cache_ok or gdm_client.discovery_complete ) and gdm_server_name :
printDebug("GDM discovery completed")
for device in gdm_server_name:
das_servers[das_server_index] = device
das_server_index = das_server_index + 1
else:
printDebug("GDM was not able to discover any servers")
except:
print "PleXBMC -> GDM Issue."
#Set to Disabled
else:
das_host = __settings__.getSetting('ipaddress')
das_port =__settings__.getSetting('port')
if not das_host or das_host == "<none>":
das_host=None
elif not das_port:
printDebug( "PleXBMC -> No port defined. Using default of " + DEFAULT_PORT, False)
das_port=DEFAULT_PORT
printDebug( "PleXBMC -> Settings hostname and port: %s : %s" % ( das_host, das_port), False)
if das_host is not None:
local_server = getLocalServers(das_host, das_port)
if local_server:
das_servers[das_server_index] = local_server
das_server_index = das_server_index + 1
if __settings__.getSetting('myplex_user') != "":
printDebug( "PleXBMC -> Adding myplex as a server location", False)
myplex_cache_file=CACHEDATA+"/myplex.server.cache"
success, das_myplex = checkCache(myplex_cache_file)
if not success:
das_myplex = getMyPlexServers()
writeCache(myplex_cache_file, das_myplex)
if das_myplex:
printDebug("MyPlex discovery completed")
for device in das_myplex:
das_servers[das_server_index] = device
das_server_index = das_server_index + 1
printDebug("PleXBMC -> serverList is " + str(das_servers), False)
return deduplicateServers(das_servers)
def readCache(cachefile):
printDebug("CACHE [%s]: attempting to read" % cachefile)
cache=xbmcvfs.File(cachefile)
cachedata = cache.read()
cache.close()
if cachedata:
printDebug("CACHE [%s]: read: [%s]" % ( cachefile, cachedata))
cacheobject = pickle.loads(cachedata)
return (True, cacheobject)
printDebug("CACHE [%s]: empty" % cachefile)
return (False, None)
def writeCache(cachefile, object):
if __settings__.getSetting("cache") == "false":
return True
printDebug("CACHE [%s]: Writing file" % cachefile)
cache=xbmcvfs.File(cachefile,'w')
cache.write(pickle.dumps(object))
cache.close()
return True
def checkCache(cachefile, life=3600):
if __settings__.getSetting("cache") == "false":
return (False, None)
if xbmcvfs.exists(cachefile):
printDebug("CACHE [%s]: exists" % cachefile)
now = int(round(time.time(),0))
created = int(xbmcvfs.Stat(cachefile).st_ctime())
modified = int(xbmcvfs.Stat(cachefile).st_mtime())
accessed = int(xbmcvfs.Stat(cachefile).st_atime())
printDebug ("CACHE [%s]: mod[%s] now[%s] diff[%s]" % ( cachefile, modified, now, now - modified))
printDebug ("CACHE [%s]: ctd[%s] mod[%s] acc[%s]" % ( cachefile, created, modified, accessed))
if ( modified < 0) or ( now - modified ) > life:
printDebug("CACHE [%s]: too old, delete" % cachefile)
success = xbmcvfs.delete(cachefile)
if success:
printDebug("CACHE [%s]: deleted" % cachefile)
else:
printDebug("CACHE [%s]: not deleted" % cachefile)
else:
printDebug("CACHE [%s]: current" % cachefile)
return readCache(cachefile)
else:
printDebug("CACHE [%s]: does not exist" % cachefile)
return (False, None)
def getLocalServers( ip_address, port ):
'''
Connect to the defined local server (either direct or via bonjour discovery)
and get a list of all known servers.
@input: nothing
@return: a list of servers (as Dict)
'''
printDebug("== ENTER: getLocalServers ==", False)
url_path="/"
html = getURL(ip_address+":"+port+url_path)
if html is False:
return []
server=etree.fromstring(html)
return {'serverName': server.get('friendlyName','Unknown').encode('utf-8') ,
'server' : ip_address,
'port' : port ,
'discovery' : 'local' ,
'token' : None ,
'uuid' : server.get('machineIdentifier') ,
'owned' : '1' ,
'master' : 1 ,
'class' : server.get('serverClass') }
def getMyPlexServers( ):
'''
Connect to the myplex service and get a list of all known
servers.
@input: nothing
@return: a list of servers (as Dict)
'''
printDebug("== ENTER: getMyPlexServers ==", False)
tempServers=[]
url_path="/pms/servers"
html = getMyPlexURL(url_path)
if html is False:
return {}
server=etree.fromstring(html).findall('Server')
count=0
for servers in server:
data=dict(servers.items())
if data.get('owned',None) == "1":
if count == 0:
master=1
count=-1
accessToken=getMyPlexToken()
else:
master='0'
accessToken=data.get('accessToken',None)
tempServers.append({'serverName': data['name'].encode('utf-8') ,
'server' : data['address'] ,
'port' : data['port'] ,
'discovery' : 'myplex' ,
'token' : accessToken ,
'uuid' : data['machineIdentifier'] ,
'owned' : data.get('owned',0) ,
'master' : master ,
'class' : data.get('serverClass') })
return tempServers
def deduplicateServers( server_list ):
'''
Return list of all media sections configured
within PleXBMC
@input: None
@Return: unique list of media servers
'''
printDebug("== ENTER: deduplicateServers ==", False)
if len(server_list) <= 1:
return server_list
temp_list=server_list.values()
oneCount=0
for onedevice in temp_list:
twoCount=0
for twodevice in temp_list:
#printDebug( "["+str(oneCount)+":"+str(twoCount)+"] Checking " + onedevice['uuid'] + " and " + twodevice['uuid'])
if oneCount == twoCount:
#printDebug( "skip" )
twoCount+=1
continue
if onedevice['uuid'] == twodevice['uuid']:
#printDebug ( "match" )
if onedevice['discovery'] == "auto" or onedevice['discovery'] == "local":
temp_list.pop(twoCount)
else:
temp_list.pop(oneCount)
#else:
# printDebug( "no match" )
twoCount+=1
oneCount+=1
count=0
unique_list={}
for i in temp_list:
unique_list[count] = i
count = count + 1
printDebug ("Unique server List: " + str(unique_list))
return unique_list
def getServerSections ( ip_address, port, name, uuid):
printDebug("== ENTER: getServerSections ==", False)
cache_file = "%s/%s.sections.cache" % (CACHEDATA, uuid)
success, temp_list = checkCache(cache_file)
if not success:
html=getURL('http://%s:%s/library/sections' % ( ip_address, port))
if html is False:
return {}
tree = etree.fromstring(html).getiterator("Directory")
temp_list=[]
for sections in tree:
path = sections.get('key')
if not path[0] == "/":
path='/library/sections/%s' % path
temp_list.append( {'title' : sections.get('title','Unknown').encode('utf-8'),
'address' : ip_address+":"+port ,
'serverName' : name ,
'uuid' : uuid ,
'sectionuuid' : sections.get('uuid','').encode('utf-8'),
'path' : path ,
'token' : sections.get('accessToken',None) ,
'location' : "local" ,
'art' : sections.get('art','') ,
'local' : '1' ,
'type' : sections.get('type','Unknown'),
'owned' : '1' })
writeCache(cache_file, temp_list)
return temp_list
def getMyplexSections ( ):
printDebug("== ENTER: getMyplexSections ==", False)
cache_file = "%s/myplex.sections.cache" % (CACHEDATA)
success, temp_list = checkCache(cache_file)
if not success:
html=getMyPlexURL('/pms/system/library/sections')
if html is False:
return {}
tree = etree.fromstring(html).getiterator("Directory")
temp_list=[]
for sections in tree:
temp_list.append( {'title' : sections.get('title','Unknown').encode('utf-8'),
'address' : sections.get('host','Unknown')+":"+sections.get('port'),
'serverName' : sections.get('serverName','Unknown').encode('utf-8'),
'uuid' : sections.get('machineIdentifier','Unknown') ,
'sectionuuid' : sections.get('uuid','').encode('utf-8'),
'path' : sections.get('path') ,
'token' : sections.get('accessToken',None) ,
'location' : "myplex" ,
'art' : sections.get('art') ,
'local' : sections.get('local') ,
'type' : sections.get('type','Unknown'),
'owned' : sections.get('owned','0') })
writeCache(cache_file, temp_list)
return temp_list
def getAllSections( server_list = None ):
'''
from server_list, get a list of all the available sections
and deduplicate the sections list
@input: None
@return: None (alters the global value g_sectionList)
'''
printDebug("== ENTER: getAllSections ==", False)
if not server_list:
server_list = discoverAllServers()
printDebug("Using servers list: " + str(server_list))
section_list=[]
myplex_section_list=[]
myplex_complete=False
local_complete=False
for server in server_list.itervalues():
if server['discovery'] == "local" or server['discovery'] == "auto":
section_details = getServerSections( server['server'], server['port'] , server['serverName'], server['uuid'])
section_list += section_details
local_complete=True
elif server['discovery'] == "myplex":
if not myplex_complete:
section_details = getMyplexSections()
myplex_section_list += section_details
myplex_complete = True
'''Remove any myplex sections that are locally available'''
if myplex_complete and local_complete:
printDebug ("Deduplicating myplex sections list")
for each_server in server_list.values():
printDebug ("Checking server [%s]" % each_server)
if each_server['discovery'] == 'myplex':
printDebug ("Skipping as a myplex server")
continue
myplex_section_list = [x for x in myplex_section_list if not x['uuid'] == each_server['uuid']]
section_list += myplex_section_list
return section_list
def getAuthDetails( details, url_format=True, prefix="&" ):
'''
Takes the token and creates the required arguments to allow
authentication. This is really just a formatting tools
@input: token as dict, style of output [opt] and prefix style [opt]
@return: header string or header dict
'''
token = details.get('token', None)
if url_format:
if token:
return prefix+"X-Plex-Token="+str(token)
else:
return ""
else:
if token:
return {'X-Plex-Token' : token }
else:
return {}
def getMyPlexURL( url_path, renew=False, suppress=True ):
'''
Connect to the my.plexapp.com service and get an XML pages
A seperate function is required as interfacing into myplex
is slightly different than getting a standard URL
@input: url to get, whether we need a new token, whether to display on screen err
@return: an xml page as string or false
'''
printDebug("== ENTER: getMyPlexURL ==", False)
printDebug("url = "+MYPLEX_SERVER+url_path)
try:
conn = httplib.HTTPSConnection(MYPLEX_SERVER)#, timeout=5)
conn.request("GET", url_path+"?X-Plex-Token="+getMyPlexToken(renew))
data = conn.getresponse()
if ( int(data.status) == 401 ) and not ( renew ):
try: conn.close()
except: pass
return getMyPlexURL(url_path,True)
if int(data.status) >= 400:
error = "HTTP response error: " + str(data.status) + " " + str(data.reason)
if suppress is False:
xbmcgui.Dialog().ok("Error",error)
print error
try: conn.close()
except: pass
return False
elif int(data.status) == 301 and type == "HEAD":
try: conn.close()
except: pass
return str(data.status)+"@"+data.getheader('Location')
else:
link=data.read()
printDebug("====== XML returned =======")
printDebug(link, False)
printDebug("====== XML finished ======")
except socket.gaierror :
error = 'Unable to lookup host: ' + MYPLEX_SERVER + "\nCheck host name is correct"
if suppress is False:
xbmcgui.Dialog().ok("Error",error)
print error
return False
except socket.error, msg :
error="Unable to connect to " + MYPLEX_SERVER +"\nReason: " + str(msg)
if suppress is False:
xbmcgui.Dialog().ok("Error",error)
print error
return False
else:
try: conn.close()
except: pass
if link:
return link
else:
return False
def getMyPlexToken( renew=False ):
'''
Get the myplex token. If the user ID stored with the token
does not match the current userid, then get new token. This stops old token
being used if plex ID is changed. If token is unavailable, then get a new one
@input: whether to get new token
@return: myplex token
'''
printDebug("== ENTER: getMyPlexToken ==", False)
try:
user,token=(__settings__.getSetting('myplex_token')).split('|')
except:
token=""
if ( token == "" ) or (renew) or (user != __settings__.getSetting('myplex_user')):
token = getNewMyPlexToken()
printDebug("Using token: " + str(token) + "[Renew: " + str(renew) + "]")
return token
def getNewMyPlexToken( suppress=True , title="Error" ):
'''
Get a new myplex token from myplex API
@input: nothing
@return: myplex token
'''
printDebug("== ENTER: getNewMyPlexToken ==", False)
printDebug("Getting New token")
myplex_username = __settings__.getSetting('myplex_user')
myplex_password = __settings__.getSetting('myplex_pass')
if ( myplex_username or myplex_password ) == "":
printDebug("No myplex details in config..")
return ""
base64string = base64.encodestring('%s:%s' % (myplex_username, myplex_password)).replace('\n', '')
txdata=""
token=False
myplex_headers={'X-Plex-Platform': "XBMC",
'X-Plex-Platform-Version': "12.00/Frodo",
'X-Plex-Provides': "player",
'X-Plex-Product': "PleXBMC",
'X-Plex-Version': PLEXBMC_VERSION,
'X-Plex-Device': PLEXBMC_PLATFORM,
'X-Plex-Client-Identifier': "PleXBMC",
'Authorization': "Basic %s" % base64string }
try:
conn = httplib.HTTPSConnection(MYPLEX_SERVER)
conn.request("POST", "/users/sign_in.xml", txdata, myplex_headers)
data = conn.getresponse()
if int(data.status) == 201:
link=data.read()
printDebug("====== XML returned =======")
try:
token=etree.fromstring(link).findtext('authentication-token')
__settings__.setSetting('myplex_token',myplex_username+"|"+token)
except:
printDebug(link)
printDebug("====== XML finished ======")
else:
error = "HTTP response error: " + str(data.status) + " " + str(data.reason)
if suppress is False:
xbmcgui.Dialog().ok(title,error)
print error
return ""
except socket.gaierror :
error = 'Unable to lookup host: ' + server + "\nCheck host name is correct"
if suppress is False:
xbmcgui.Dialog().ok(title,error)
print error
return ""
except socket.error, msg :
error="Unable to connect to " + server +"\nReason: " + str(msg)
if suppress is False:
xbmcgui.Dialog().ok(title,error)
print error
return ""
return token
def getURL( url, suppress=True, type="GET", popup=0 ):
printDebug("== ENTER: getURL ==", False)
try:
if url[0:4] == "http":
serversplit=2
urlsplit=3
else:
serversplit=0
urlsplit=1
server=url.split('/')[serversplit]
urlPath="/"+"/".join(url.split('/')[urlsplit:])
authHeader=getAuthDetails({'token':_PARAM_TOKEN}, False)
printDebug("url = "+url)
printDebug("header = "+str(authHeader))
conn = httplib.HTTPConnection(server)#,timeout=5)
conn.request(type, urlPath, headers=authHeader)
data = conn.getresponse()
if int(data.status) == 200:
link=data.read()
printDebug("====== XML returned =======")
printDebug(link, False)
printDebug("====== XML finished ======")
try: conn.close()
except: pass
return link
elif ( int(data.status) == 301 ) or ( int(data.status) == 302 ):
try: conn.close()
except: pass
return data.getheader('Location')
elif int(data.status) == 401:
error = "Authentication error on server [%s]. Check user/password." % server
print "PleXBMC -> %s" % error
if suppress is False:
if popup == 0:
xbmc.executebuiltin("XBMC.Notification(Server authentication error,)")
else:
xbmcgui.Dialog().ok("PleXBMC","Authentication require or incorrect")
elif int(data.status) == 404:
error = "Server [%s] XML/web page does not exist." % server
print "PleXBMC -> %s" % error
if suppress is False:
if popup == 0:
xbmc.executebuiltin("XBMC.Notification(Server web/XML page error,)")
else:
xbmcgui.Dialog().ok("PleXBMC","Server error, data does not exist")
elif int(data.status) >= 400:
error = "HTTP response error: " + str(data.status) + " " + str(data.reason)
print error
if suppress is False:
if popup == 0:
xbmc.executebuiltin("XBMC.Notification(URL error: "+ str(data.reason) +",)")
else:
xbmcgui.Dialog().ok("Error",server)
else:
link=data.read()
printDebug("====== XML returned =======")
printDebug(link, False)
printDebug("====== XML finished ======")
try: conn.close()
except: pass
return link
except socket.gaierror :
error = "Unable to locate host [%s]\nCheck host name is correct" % server
print "PleXBMC %s" % error
if suppress is False:
if popup==0:
xbmc.executebuiltin("XBMC.Notification(\"PleXBMC\": Server name incorrect,)")
else:
xbmcgui.Dialog().ok("PleXBMC","Server [%s] not found" % server)
except socket.error, msg :
error="Server[%s] is offline, or not responding\nReason: %s" % (server, str(msg))
print "PleXBMC -> %s" % error
if suppress is False:
if popup == 0:
xbmc.executebuiltin("XBMC.Notification(\"PleXBMC\": Server offline or not responding,)")
else:
xbmcgui.Dialog().ok("PleXBMC","Server is offline or not responding")
try: conn.close()
except: pass
return False
def mediaType( partData, server, dvdplayback=False ):
printDebug("== ENTER: mediaType ==", False)
stream=partData['key']
file=partData['file']
global g_stream
if ( file is None ) or ( g_stream == "1" ):
printDebug( "Selecting stream")
return "http://"+server+stream
#First determine what sort of 'file' file is
if file[0:2] == "\\\\":
printDebug("Looks like a UNC")
type="UNC"
elif file[0:1] == "/" or file[0:1] == "\\":
printDebug("looks like a unix file")
type="nixfile"
elif file[1:3] == ":\\" or file[1:2] == ":/":
printDebug("looks like a windows file")
type="winfile"
else:
printDebug("uknown file type")
printDebug(str(file))
type="notsure"
# 0 is auto select. basically check for local file first, then stream if not found
if g_stream == "0":
#check if the file can be found locally
if type == "nixfile" or type == "winfile":
try:
printDebug("Checking for local file")
exists = open(file, 'r')
printDebug("Local file found, will use this")
exists.close()
return "file:"+file
except: pass
printDebug("No local file")
if dvdplayback:
printDebug("Forcing SMB for DVD playback")
g_stream="2"
else:
return "http://"+server+stream
# 2 is use SMB
elif g_stream == "2" or g_stream == "3":
if g_stream == "2":
protocol="smb"
else:
protocol="afp"
printDebug( "Selecting smb/unc")
if type=="UNC":
filelocation=protocol+":"+file.replace("\\","/")
else:
#Might be OSX type, in which case, remove Volumes and replace with server
server=server.split(':')[0]
loginstring=""
if g_nasoverride == "true":
if not g_nasoverrideip == "":
server=g_nasoverrideip
printDebug("Overriding server with: " + server)
nasuser=__settings__.getSetting('nasuserid')
if not nasuser == "":
loginstring=__settings__.getSetting('nasuserid')+":"+__settings__.getSetting('naspass')+"@"
printDebug("Adding AFP/SMB login info for user " + nasuser)
if file.find('Volumes') > 0:
filelocation=protocol+":/"+file.replace("Volumes",loginstring+server)
else:
if type == "winfile":
filelocation=protocol+"://"+loginstring+server+"/"+file[3:]
else:
#else assume its a file local to server available over smb/samba (now we have linux PMS). Add server name to file path.
filelocation=protocol+"://"+loginstring+server+file
if g_nasoverride == "true" and g_nasroot != "":
#Re-root the file path
printDebug("Altering path " + filelocation + " so root is: " + g_nasroot)
if '/'+g_nasroot+'/' in filelocation:
components = filelocation.split('/')
index = components.index(g_nasroot)
for i in range(3,index):
components.pop(3)
filelocation='/'.join(components)
else:
printDebug( "No option detected, streaming is safest to choose" )
filelocation="http://"+server+stream
printDebug("Returning URL: " + filelocation)
return filelocation
def addGUIItem( url, details, extraData, context=None, folder=True ):
printDebug("== ENTER: addGUIItem ==", False)
printDebug("Adding Dir for [%s]" % details.get('title','Unknown'))
printDebug("Passed details: " + str(details))
printDebug("Passed extraData: " + str(extraData))
if details.get('title','') == '':
return
if (extraData.get('token',None) is None) and _PARAM_TOKEN:
extraData['token']=_PARAM_TOKEN
aToken=getAuthDetails(extraData)
qToken=getAuthDetails(extraData, prefix='?')
if extraData.get('mode',None) is None:
mode="&mode=0"