forked from BigNoid/script.skinshortcuts
-
Notifications
You must be signed in to change notification settings - Fork 21
/
library.py
executable file
·2163 lines (1831 loc) · 104 KB
/
library.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 os, sys, datetime, unicodedata
import xbmc, xbmcaddon, xbmcgui, xbmcvfs
import xml.etree.ElementTree as xmltree
from xml.dom.minidom import parse
from xml.sax.saxutils import escape as escapeXML
from traceback import print_exc
from unidecode import unidecode
from resources.lib import datafunctions, nodefunctions
import json as simplejson
import urllib.request, urllib.parse, urllib.error
DATA = datafunctions.DataFunctions()
NODE = nodefunctions.NodeFunctions()
ADDON = xbmcaddon.Addon()
ADDONID = ADDON.getAddonInfo('id')
CWD = ADDON.getAddonInfo('path')
DATAPATH = os.path.join(xbmc.translatePath("special://profile/"), "addon_data", ADDONID)
LANGUAGE = ADDON.getLocalizedString
KODIVERSION = xbmc.getInfoLabel( "System.BuildVersion" ).split(".")[0]
def log(txt):
if ADDON.getSetting( "enable_logging" ) == "true":
message = u'%s: %s' % (ADDONID, txt)
xbmc.log(msg=message, level=xbmc.LOGDEBUG)
def kodiwalk(path, stringForce = False):
json_query = xbmc.executeJSONRPC('{"jsonrpc":"2.0","method":"Files.GetDirectory","params":{"directory":"%s","media":"files"},"id":1}' % str(path))
json_response = simplejson.loads(json_query)
files = []
if 'result' in json_response and 'files' in json_response['result'] and json_response['result']['files'] is not None:
for item in json_response['result']['files']:
if 'file' in item and 'filetype' in item and 'label' in item:
if item['filetype'] == 'directory' and not item['file'].endswith(('.xsp', '.m3u', '.xml/', '.xml' )):
if stringForce and item['file'].startswith(stringForce):
files = files + kodiwalk( xbmc.translatePath( item['file'] ), stringForce )
else:
files = files + kodiwalk( item['file'], stringForce )
else:
if stringForce and item['file'].startswith(stringForce):
files.append({'path':xbmc.translatePath(item['file']), 'label':item['label']})
else:
files.append({'path':item['file'], 'label':item['label']})
return files
class LibraryFunctions():
def __init__( self, *args, **kwargs ):
# Dictionary to make checking whether things are loaded easier
self.loaded = { "common": [False, "common shortcuts"],
"more": [False, "more commands"],
"videolibrary": [False, "video library"],
"musiclibrary": [False, "music library"],
"librarysources": [False, "library sources"],
"pvrlibrary": [False, "live tv"],
"radiolibrary": [False, "live radio"],
"playlists": [False, "playlists"],
"addons": [False, "add-ons"],
"favourites": [False, "favourites"],
"upnp": [False, "upnp sources"],
"settings": [False, "settings"],
"widgets": [False, "widgets"] }
self.widgetPlaylistsList = []
# Empty dictionary for different shortcut types
self.dictionaryGroupings = {"common":None,
"commands":None,
"video":None, "movie":None,
"movie-flat":None,
"tvshow":None,
"tvshow-flat":None,
"musicvideo":None,
"musicvideo-flat":None,
"customvideonode":None,
"customvideonode-flat":None,
"videosources":None,
"pvr":None,
"radio":None,
"pvr-tv":None,
"pvr-radio":None,
"music":None,
"musicsources":None,
"picturesources":None,
"playlist-video":None,
"playlist-audio":None,
"addon-program":None,
"addon-program-plugin":None,
"addon-video":None,
"addon-audio":None,
"addon-image":None,
"favourite":None,
"settings":None,
"widgets":None,
"widgets-classic":[] }
self.folders = {}
self.foldersCount = 0
# Widget providers, for auto-installing
self.widgetProviders = [ [ "service.library.data.provider", None, "Library Data Provider" ],
[ "script.extendedinfo", None, "ExtendedInfo Script" ],
[ "service.smartish.widgets", "Skin.HasSetting(enable.smartish.widgets)", "Smart(ish) Widgets" ] ]
self.allowWidgetInstall = False
self.skinhelperWidgetInstall = True
self.useDefaultThumbAsIcon = None
def loadLibrary( self, library ):
# Common entry point for loading available shortcuts
# Handle whether the shortcuts are already loaded/loading
if self.loaded[ library ][ 0 ] is True:
return True
elif self.loaded[ library ][ 0 ] == "Loading":
# The list is currently being populated, wait and then return it
for i in range( 0, 50 ):
if xbmc.Monitor().waitForAbort(0.1) or self.loaded[ library ][ 0 ] is True:
return True
else:
# We're going to populate the list
self.loaded[ library ][ 0 ] = "Loading"
# Call the function responsible for loading the library type we've been passed
log( "Listing %s..." %( self.loaded[ library ][ 1 ] ) )
try:
if library == "common":
self.common()
elif library == "more":
self.more()
elif library == "videolibrary":
self.videolibrary()
elif library == "musiclibrary":
self.musiclibrary()
elif library == "librarysources":
self.librarysources()
elif library == "pvrlibrary":
self.pvrlibrary()
elif library == "radiolibrary":
self.radiolibrary()
elif library == "playlists":
self.playlists()
elif library == "addons":
self.addons()
elif library == "favourites":
self.favourites()
elif library == "settings":
self.settings()
elif library == "widgets":
self.widgets()
except:
log( "Failed to load %s" %( self.loaded[ library ][ 1 ] ) )
print_exc()
# Mark library type as loaded
self.loaded[ library ][ 0 ] = True
return True
def loadAllLibrary( self ):
# Load all library data, for use with threading
self.loadLibrary( "common" )
self.loadLibrary( "more" )
self.loadLibrary( "videolibrary" )
self.loadLibrary( "musiclibrary" )
self.loadLibrary( "pvrlibrary" )
self.loadLibrary( "radiolibrary" )
self.loadLibrary( "librarysources" )
self.loadLibrary( "playlists" )
self.loadLibrary( "addons" )
self.loadLibrary( "favourites" )
self.loadLibrary( "settings" )
self.loadLibrary( "widgets" )
# Do a JSON query for upnp sources (so that they'll show first time the user asks to see them)
if self.loaded[ "upnp" ][ 0 ] == False:
json_query = xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "id": 0, "method": "Files.GetDirectory", "params": { "properties": ["title", "file", "thumbnail"], "directory": "upnp://", "media": "files" } }')
self.loaded[ "upnp" ][ 0 ] = True
# ==============================================
# === BUILD/DISPLAY AVAILABLE SHORTCUT NODES ===
# ==============================================
def retrieveGroup( self, group, flat = True, grouping = None ):
trees = [DATA._get_overrides_skin(), DATA._get_overrides_script()]
nodes = None
for tree in trees:
if flat:
nodes = tree.find( "flatgroupings" )
if nodes is not None:
nodes = nodes.findall( "node" )
elif grouping is None:
nodes = tree.find( "groupings" )
else:
nodes = tree.find( "%s-groupings" %( grouping ) )
if nodes is not None:
break
if nodes is None:
return [ "Error", [] ]
returnList = []
if flat:
# Flat groupings
count = 0
# Cycle through nodes till we find the one specified
for node in nodes:
count += 1
if "condition" in node.attrib:
if not xbmc.getCondVisibility( node.attrib.get( "condition" ) ):
group += 1
continue
if "version" in node.attrib:
version = node.attrib.get( "version" )
if KODIVERSION != version and DATA.checkVersionEquivalency( version, node.attrib.get( "condition" ), "groupings" ) == False:
group += 1
continue
if "installWidget" in node.attrib and node.attrib.get( "installWidget" ).lower() == "true":
self.installWidget = True
else:
self.installWidget = False
if count == group:
# We found it :)
return( node.attrib.get( "label" ), self.buildNodeListing( node, True ) )
return ["Error", []]
else:
# Heirachical groupings
if group == "":
# We're going to get the root nodes
self.installWidget = False
windowTitle = LANGUAGE(32048)
if grouping == "widget":
windowTitle = LANGUAGE(32044)
return [ windowTitle, self.buildNodeListing( nodes, False ) ]
else:
groups = group.split( "," )
nodes = [ "", nodes ]
for groupNum in groups:
nodes = self.getNode( nodes[1], int( groupNum ) )
return [ nodes[0], self.buildNodeListing( nodes[1], False ) ]
def getNode( self, tree, number ):
count = 0
for subnode in tree:
count += 1
# If not visible, skip it
if "condition" in subnode.attrib:
if not xbmc.getCondVisibility( subnode.attrib.get( "condition" ) ):
number += 1
continue
if "version" in subnode.attrib:
version = subnode.attrib.get( "version" )
if KODIVERSION != version and DATA.checkVersionEquivalency( version, subnode.attrib.get( "condition" ), "groupings" ) == False:
number += 1
continue
if "installWidget" in subnode.attrib and subnode.attrib.get( "installWidget" ).lower() == "true":
self.installWidget = True
else:
self.installWidget = False
if count == number:
label = DATA.local( subnode.attrib.get( "label" ) )[2]
return [ label, subnode ]
def buildNodeListing( self, nodes, flat ):
returnList = []
count = 0
for node in nodes:
if "condition" in node.attrib:
if not xbmc.getCondVisibility( node.attrib.get( "condition" ) ):
continue
if "version" in node.attrib:
version = node.attrib.get( "version" )
if KODIVERSION != version and DATA.checkVersionEquivalency( version, node.attrib.get( "condition" ), "groupings" ) == False:
continue
count += 1
if node.tag == "content":
returnList = returnList + self.retrieveContent( node.text )
if node.tag == "shortcut":
shortcutItem = self._create( [node.text, node.attrib.get( "label" ), node.attrib.get( "type" ), {"icon": node.attrib.get( "icon" )}] )
if "widget" in node.attrib:
# This is a widget shortcut, so add the relevant widget information
shortcutItem.setProperty( "widget", node.attrib.get( "widget" ) )
if "widgetName" in node.attrib:
shortcutItem.setProperty( "widgetName", node.attrib.get( "widgetName" ) )
else:
shortcutItem.setProperty( "widgetName", node.attrib.get( "label" ) )
shortcutItem.setProperty( "widgetPath", node.text )
if "widgetType" in node.attrib:
shortcutItem.setProperty( "widgetType", node.attrib.get( "widgetType" ) )
else:
shortcutItem.setProperty( "widgetType", "" )
if "widgetTarget" in node.attrib:
shortcutItem.setProperty( "widgetTarget", node.attrib.get( "widgetTarget" ) )
else:
shortcutItem.setProperty( "widgetTarget", "" )
returnList.append( shortcutItem )
#returnList.append( self._create( [node.text, node.attrib.get( "label" ), node.attrib.get( "type" ), {"icon": node.attrib.get( "icon" )}] ) )
if node.tag == "node" and flat == False:
returnList.append( self._create( ["||NODE||" + str( count ), node.attrib.get( "label" ), "", {"icon": "DefaultFolder.png"}] ) )
# Override icons
tree = DATA._get_overrides_skin()
for item in returnList:
item = self._get_icon_overrides( tree, item, None )
return returnList
def retrieveContent( self, content ):
if content == "upnp-video":
items = [ self._create(["||UPNP||", "32070", "32069", {"icon": "DefaultFolder.png"}]) ]
elif content == "upnp-music":
items = [ self._create(["||UPNP||", "32070", "32073", {"icon": "DefaultFolder.png"}]) ]
elif self.dictionaryGroupings[ content ] is None:
# The data hasn't been loaded yet
items = self.loadGrouping( content )
else:
items = self.dictionaryGroupings[ content ]
if items is not None:
items = self.checkForFolder( items )
else:
items = []
# Add widget information for video/audio nodes
if content in [ "video", "music" ]:
# Video nodes - add widget information
for listitem in items:
path = listitem.getProperty( "path" )
if path.lower().startswith( "activatewindow" ):
path = DATA.getListProperty( path )
listitem.setProperty( "widget", "Library" )
if content == "video":
listitem.setProperty( "widgetType", "video" )
listitem.setProperty( "widgetTarget", "videos" )
else:
listitem.setProperty( "widgetType", "audio" )
listitem.setProperty( "widgetTarget", "music" )
listitem.setProperty( "widgetName", listitem.getLabel() )
listitem.setProperty( "widgetPath", path )
widgetType = NODE.get_mediaType( path )
if widgetType != "unknown":
listitem.setProperty( "widgetType", widgetType )
# Check for any icon overrides for these items
tree = DATA._get_overrides_skin()
for item in items:
item = self._get_icon_overrides( tree, item, content )
return items
def checkForFolder( self, items ):
# This function will check for any folders in the listings that are being returned
# and, if found, move their sub-items into a property
returnItems = []
for item in items:
if isinstance( item, list ):
self.foldersCount += 1
self.folders[ str( self.foldersCount ) ] = item[1]
newItem = item[0]
newItem.setProperty( "folder", str( self.foldersCount ) )
returnItems.append( newItem )
else:
returnItems.append( item )
return( returnItems )
def loadGrouping( self, content ):
# Display a busy dialog
dialog = xbmcgui.DialogProgress()
dialog.create( "Skin Shortcuts", LANGUAGE( 32063 ) )
# We'll be called if the data for a wanted group hasn't been loaded yet
if content == "common":
self.loadLibrary( "common" )
if content == "commands":
self.loadLibrary( "more" )
if content == "movie" or content == "tvshow" or content == "musicvideo" or content == "customvideonode" or content == "movie-flat" or content == "tvshow-flat" or content == "musicvideo-flat" or content == "customvideonode-flat":
# These have been deprecated
return []
if content == "video":
self.loadLibrary( "videolibrary" )
if content == "videosources" or content == "musicsources" or content == "picturesources":
self.loadLibrary( "librarysources" )
if content == "music":
self.loadLibrary( "musiclibrary" )
if content == "pvr" or content == "pvr-tv" or content == "pvr-radio":
self.loadLibrary( "pvrlibrary" )
if content == "radio":
self.loadLibrary( "radiolibrary" )
if content == "playlist-video" or content == "playlist-audio":
self.loadLibrary( "playlists" )
if content == "addon-program" or content == "addon-video" or content == "addon-audio" or content == "addon-image":
self.loadLibrary( "addons" )
if content == "favourite":
self.loadLibrary( "favourites" )
if content == "settings":
self.loadLibrary( "settings" )
if content == "widgets":
self.loadLibrary( "widgets" )
# The data has now been loaded, return it
dialog.close()
return self.dictionaryGroupings[ content ]
def flatGroupingsCount( self ):
# Return how many nodes there are in the the flat grouping
tree = DATA._get_overrides_script()
if tree is None:
return 1
groupings = tree.find( "flatgroupings" )
nodes = groupings.findall( "node" )
count = 0
for node in nodes:
if "condition" in node.attrib:
if not xbmc.getCondVisibility( node.attrib.get( "condition" ) ):
continue
if "version" in node.attrib:
if KODIVERSION != node.attrib.get( "version" ):
continue
count += 1
return count
def addToDictionary( self, group, content ):
# This function adds content to the dictionaryGroupings - including
# adding any skin-provided shortcuts to the group
tree = DATA._get_overrides_skin()
# Search for skin-provided shortcuts for this group
originalGroup = group
if group.endswith( "-flat" ):
group = group.replace( "-flat", "" )
if group not in [ "movie", "tvshow", "musicvideo" ]:
for elem in tree.findall( "shortcut" ):
if "grouping" in elem.attrib:
if group == elem.attrib.get( "grouping" ):
# We want to add this shortcut
label = elem.attrib.get( "label" )
type = elem.attrib.get( "type" )
thumb = elem.attrib.get( "thumbnail" )
icon = elem.attrib.get( "icon" )
action = elem.text
#if label.isdigit():
# label = "::LOCAL::" + label
if type is None:
type = "32024"
#elif type.isdigit():
# type = "::LOCAL::" + type
if icon is None:
icon = ""
if thumb is None:
thumb = ""
listitem = self._create( [action, label, type, {"icon": icon, "thumb": thumb}] )
if "condition" in elem.attrib:
if xbmc.getCondVisibility( elem.attrib.get( "condition" ) ):
content.insert( 0, listitem )
else:
content.insert( 0, listitem )
elif group == "common":
# We want to add this shortcut
label = elem.attrib.get( "label" )
type = elem.attrib.get( "type" )
thumb = elem.attrib.get( "thumbnail" )
icon = elem.attrib.get( "icon" )
action = elem.text
#if label.isdigit():
# label = "::LOCAL::" + label
if type is None:
type = "32024"
#elif type.isdigit():
# type = "::LOCAL::" + type
if type is None or type == "":
type = "Skin Provided"
if icon is None:
icon = ""
if thumb is None:
thumb = ""
listitem = self._create( [action, label, type, {"icon": icon, "thumb":thumb}] )
if "condition" in elem.attrib:
if xbmc.getCondVisibility( elem.attrib.get( "condition" ) ):
content.append( listitem )
else:
content.append( listitem )
self.dictionaryGroupings[ originalGroup ] = content
# ================================
# === BUILD AVAILABLE SHORTCUT ===
# ================================
def _create ( self, item, allowOverrideLabel = True ):
# Retrieve label
localLabel = DATA.local( item[1] )[0]
# Create localised label2
displayLabel2 = DATA.local( item[2] )[2]
shortcutType = DATA.local( item[2] )[0]
if allowOverrideLabel:
# Check for a replaced label
replacementLabel = DATA.checkShortcutLabelOverride( item[0] )
if replacementLabel is not None:
localLabel = DATA.local( replacementLabel[0] )[0]
if len( replacementLabel ) == 2:
# We're also overriding the type
displayLabel2 = DATA.local( replacementLabel[1] )[2]
shortcutType = DATA.local( replacementLabel[1] )[0]
# Try localising it
displayLabel = DATA.local( localLabel )[2]
if displayLabel.startswith( "$NUMBER[" ):
displayLabel = displayLabel[8:-1]
# Create localised label2
displayLabel2 = DATA.local( displayLabel2 )[2]
shortcutType = DATA.local( shortcutType )[0]
# If either displayLabel starts with a $, ask Kodi to parse it for us
if displayLabel.startswith( "$" ):
displayLabel = xbmc.getInfoLabel( displayLabel )
if displayLabel2.startswith( "$" ):
displayLabel2 = xbmc.getInfoLabel( displayLabel2 )
# If this launches our explorer, append a notation to the displayLabel
noNonLocalized = False
if item[0].startswith( "||" ):
displayLabel = displayLabel + " >"
# We'll also mark that we don't want to use a non-localised labelID, as this
# causes issues with some folders picking up overriden icons incorrectly
noNonLocalized = True
# Get the items labelID
DATA._clear_labelID()
labelID = DATA._get_labelID( DATA.createNiceName( DATA.local( localLabel )[0], noNonLocalized = noNonLocalized ), item[0], noNonLocalized = noNonLocalized )
# Retrieve icon and thumbnail
if item[3]:
if "icon" in list(item[3].keys()) and item[3]["icon"] is not None:
icon = item[3]["icon"]
else:
icon = "DefaultShortcut.png"
if "thumb" in list(item[3].keys()):
thumbnail = item[3]["thumb"]
else:
thumbnail = None
else:
icon = "DefaultShortcut.png"
thumbnail = None
# Check if the option to use the thumb as the icon is enabled
if self.useDefaultThumbAsIcon is None:
# Retrieve the choice from the overrides.xml
tree = DATA._get_overrides_skin()
node = tree.getroot().find( "useDefaultThumbAsIcon" )
if node is None:
self.useDefaultThumbAsIcon = False
else:
if node.text.lower() == "true":
self.useDefaultThumbAsIcon = True
else:
self.useDefaultThumbAsIcon = False
usedDefaultThumbAsIcon = False
if self.useDefaultThumbAsIcon == True and thumbnail is not None:
icon = thumbnail
thumbnail = None
usedDefaultThumbAsIcon = True
oldicon = None
# If the icon starts with a $, ask Kodi to parse it for us
displayIcon = icon
iconIsVar = False
if icon.startswith( "$" ):
displayIcon = xbmc.getInfoLabel( icon )
iconIsVar = True
#special treatment for image resource addons
if icon.startswith("resource://"):
iconIsVar = True
# If the skin doesn't have the icon, replace it with DefaultShortcut.png
if ( not displayIcon or not xbmc.skinHasImage( displayIcon ) ) and not iconIsVar:
if not usedDefaultThumbAsIcon:
displayIcon = "DefaultShortcut.png"
# Build listitem
if thumbnail is not None:
listitem = xbmcgui.ListItem(label=displayLabel, label2=displayLabel2)
listitem.setArt({'icon': displayIcon})
listitem.setArt({'thumb': thumbnail})
listitem.setProperty( "thumbnail", thumbnail)
else:
listitem = xbmcgui.ListItem(label=displayLabel, label2=displayLabel2)
listitem.setArt({'icon': thumbnail})
listitem.setProperty( "path", item[0] )
listitem.setProperty( "localizedString", localLabel )
listitem.setProperty( "shortcutType", shortcutType )
listitem.setProperty( "icon", displayIcon )
listitem.setProperty( "tempLabelID", labelID )
listitem.setProperty( "defaultLabel", labelID )
if displayIcon != icon:
listitem.setProperty( "untranslatedIcon", icon )
return( listitem )
def _get_icon_overrides( self, tree, item, content, setToDefault = True ):
if tree is None:
return item
oldicon = None
newicon = item.getProperty( "icon" )
for elem in tree.findall( "icon" ):
if oldicon is None:
if ("labelID" in elem.attrib and elem.attrib.get( "labelID" ) == item.getProperty( "tempLabelID" )) or ("image" in elem.attrib and elem.attrib.get( "image" ) == item.getProperty( "icon" )):
# LabelID matched
if "grouping" in elem.attrib:
if elem.attrib.get( "grouping" ) == content:
# Group also matches - change icon
oldicon = item.getProperty( "icon" )
newicon = elem.text
elif "group" not in elem.attrib:
# No group - change icon
oldicon = item.getProperty( "icon" )
newicon = elem.text
# If the icon doesn't exist, set icon to default
setDefault = False
if not xbmc.skinHasImage( newicon ) and setToDefault == True:
oldicon = item.getProperty( "icon" )
icon = "DefaultShortcut.png"
setDefault = True
if oldicon is not None:
# we found an icon override
item.setProperty( "icon", newicon )
item.setArt({'icon': 'newicon'})
if setDefault == True:
item = self._get_icon_overrides( tree, item, content, False )
return item
# ===================================
# === LOAD VIDEO LIBRARY HEIRACHY ===
# ===================================
def videolibrary( self ):
# Try loading custom nodes first
try:
if self._parse_libraryNodes( "video", "custom" ) == False:
log( "Failed to load custom video nodes" )
self._parse_libraryNodes( "video", "default" )
except:
log( "Failed to load custom video nodes" )
print_exc()
try:
# Try loading default nodes
self._parse_libraryNodes( "video", "default" )
except:
# Empty library
log( "Failed to load default video nodes" )
print_exc()
def _parse_libraryNodes( self, library, type ):
#items = {"video":[], "movies":[], "tvshows":[], "musicvideos":[], "custom":{}}
items = {}
if library == "video":
windowID = "Videos"
prefix = "library://video"
action = "||VIDEO||"
elif library == "music":
windowID = "music"
prefix = "library://music"
action = "||AUDIO||"
rootdir = os.path.join(xbmc.translatePath("special://profile"), "library", library)
if type == "custom":
log( "Listing custom %s nodes..." %( library ) )
else:
rootdir = os.path.join(xbmc.translatePath("special://xbmc"), "system", "library", library)
log("Listing default %s nodes..." %(library))
nodes = NODE.get_nodes( rootdir, prefix )
if nodes == False or len( nodes ) == 0:
return False
items = []
for key in nodes:
# 0 = Label
# 1 = Icon
# 2 = Path
# 3 = Type
# 4 = Order
# 5 = Media type (not folders...?)
#make sure the path ends with a trailing slash to prevent weird kodi behaviour
if "/" in nodes[key][2] and not nodes[key][2].endswith("/"):
nodes[key][2] += "/"
if nodes[ key ][ 3 ] == "folder":
item = self._create( [ "%s%s" % ( action, nodes[ key ][ 2 ] ), nodes[ key ][ 0 ], nodes[ key ][ 3 ], { "icon": nodes[ key ][ 1 ] } ] )
elif nodes[ key ][ 3 ] == "grouped":
item = self._create( [ "%s%s" % ( action, nodes[ key ][ 2 ] ), nodes[ key ][ 0 ], nodes[ key ][ 3 ], { "icon": nodes[ key ][ 1 ] } ] )
else:
item = self._create( [ "ActivateWindow(%s,%s,return)" %( windowID, nodes[ key ][ 2 ] ), nodes[ key ][ 0 ], nodes[ key ][ 3 ], { "icon": nodes[ key ][ 1 ] } ] )
if nodes[ key ][ 5 ] is not None:
item.setProperty( "widgetType", nodes[ key ][ 5 ] )
item.setProperty( "widgetTarget", library )
items.append( item )
self.addToDictionary( library, items )
# ============================
# === LOAD OTHER LIBRARIES ===
# ============================
def common( self ):
listitems = []
# Videos, Movies, TV Shows, Live TV, Music, Music Videos, Pictures, Weather, Programs,
# Play dvd, eject tray
# Settings, File Manager, Profiles, System Info
listitems.append( self._create(["ActivateWindow(Videos)", "3", "32034", {"icon": "DefaultVideo.png"} ]) )
listitems.append( self._create(["ActivateWindow(Videos,videodb://movies/titles/,return)", "342", "32034", {"icon": "DefaultMovies.png"} ]) )
listitems.append( self._create(["ActivateWindow(Videos,videodb://tvshows/titles/,return)", "20343", "32034", {"icon": "DefaultTVShows.png"} ]) )
listitems.append( self._create(["ActivateWindow(TVGuide)", "32022", "32034", {"icon": "DefaultTVShows.png"} ]) )
listitems.append( self._create(["ActivateWindow(RadioGuide)", "32087", "32034", {"icon": "DefaultTVShows.png"} ]) )
listitems.append( self._create(["ActivateWindow(Music)", "2", "32034", {"icon": "DefaultMusicAlbums.png"} ]) )
listitems.append( self._create(["PlayerControl(PartyMode)", "589", "32034", {"icon": "DefaultMusicAlbums.png"} ]) )
listitems.append( self._create(["PlayerControl(PartyMode(Video))", "32108", "32034", {"icon": "DefaultMusicVideos.png"} ]) )
listitems.append( self._create(["ActivateWindow(Videos,videodb://musicvideos/titles/,return)", "20389", "32034", {"icon": "DefaultMusicVideos.png"} ] ) )
listitems.append( self._create(["ActivateWindow(Pictures)", "10002", "32034", {"icon": "DefaultPicture.png"} ] ) )
listitems.append( self._create(["ActivateWindow(Weather)", "12600", "32034", {"icon": "Weather.png"} ]) )
listitems.append( self._create(["ActivateWindow(Programs,Addons,return)", "10001", "32034", {"icon": "DefaultProgram.png"} ] ) )
listitems.append( self._create(["PlayDVD", "32032", "32034", {"icon": "DefaultDVDFull.png"} ] ) )
listitems.append( self._create(["EjectTray()", "32033", "32034", {"icon": "DefaultDVDFull.png"} ] ) )
listitems.append( self._create(["ActivateWindow(Settings)", "10004", "32034", {"icon": "Settings.png"} ]) )
listitems.append( self._create(["ActivateWindow(FileManager)", "7", "32034", {"icon": "DefaultFolder.png"} ] ) )
listitems.append( self._create(["ActivateWindow(Profiles)", "13200", "32034", {"icon": "UnknownUser.png"} ] ) )
listitems.append( self._create(["ActivateWindow(SystemInfo)", "10007", "32034", {"icon": "SystemInfo.png"} ]) )
listitems.append( self._create(["ActivateWindow(EventLog,events://,return)", "14111", "32034", {"icon": "Events.png"} ]) )
listitems.append( self._create(["ActivateWindow(Favourites)", "1036", "32034", {"icon": "Favourites.png"} ]) )
self.addToDictionary( "common", listitems )
def more( self ):
listitems = []
listitems.append( self._create(["Reboot", "13013", "32054", {"icon": "Reboot.png"} ]) )
listitems.append( self._create(["ShutDown", "13005", "32054", {"icon": "Shutdown.png"} ]) )
listitems.append( self._create(["PowerDown", "13016", "32054", {"icon": "PowerDown.png"} ]) )
listitems.append( self._create(["Quit", "13009", "32054", {"icon": "Quit.png"} ]) )
if (xbmc.getCondVisibility( "System.Platform.Windows" ) or xbmc.getCondVisibility( "System.Platform.Linux" )) and not xbmc.getCondVisibility( "System.Platform.Linux.RaspberryPi" ):
listitems.append( self._create(["RestartApp", "13313", "32054", {"icon": "RestartApp.png"} ]) )
listitems.append( self._create(["Hibernate", "13010", "32054", {"icon": "Hibernate.png"} ]) )
listitems.append( self._create(["Suspend", "13011", "32054", {"icon": "Suspend.png"} ]) )
listitems.append( self._create(["AlarmClock(shutdowntimer,XBMC.Shutdown())", "19026", "32054", {"icon": "ShutdownTimer.png"} ]) )
listitems.append( self._create(["CancelAlarm(shutdowntimer)", "20151", "32054", {"icon": "CancelShutdownTimer.png"} ]) )
if xbmc.getCondVisibility( "System.HasLoginScreen" ):
listitems.append( self._create(["System.LogOff", "20126", "32054", {"icon": "LogOff.png"} ]) )
listitems.append( self._create(["ActivateScreensaver", "360", "32054", {"icon": "ActivateScreensaver.png"} ]) )
listitems.append( self._create(["Minimize", "13014", "32054", {"icon": "Minimize.png"} ]) )
listitems.append( self._create(["Mastermode", "20045", "32054", {"icon": "Mastermode.png"} ]) )
listitems.append( self._create(["RipCD", "600", "32054", {"icon": "RipCD.png"} ]) )
listitems.append( self._create(["UpdateLibrary(video,,true)", "32046", "32054", {"icon": "UpdateVideoLibrary.png"} ]) )
listitems.append( self._create(["UpdateLibrary(music,,true)", "32047", "32054", {"icon": "UpdateMusicLibrary.png"} ]) )
listitems.append( self._create(["CleanLibrary(video,true)", "32055", "32054", {"icon": "CleanVideoLibrary.png"} ]) )
listitems.append( self._create(["CleanLibrary(music,true)", "32056", "32054", {"icon": "CleanMusicLibrary.png"} ]) )
self.addToDictionary( "commands", listitems )
def settings( self ):
listitems = []
listitems.append( self._create(["ActivateWindow(Settings)", "10004", "10004", {"icon": "Settings.png"} ]) )
listitems.append( self._create(["ActivateWindow(PVRSettings)", "19020", "10004", {"icon": "PVRSettings.png"} ]) )
listitems.append( self._create(["ActivateWindow(AddonBrowser)", "24001", "10004", {"icon": "DefaultAddon.png"} ]) )
listitems.append( self._create(["ActivateWindow(ServiceSettings)", "14036", "10004", {"icon": "ServiceSettings.png"} ]) )
listitems.append( self._create(["ActivateWindow(SystemSettings)", "13000", "10004", {"icon": "SystemSettings.png"} ]) )
listitems.append( self._create(["ActivateWindow(SkinSettings)", "20077", "10004", {"icon": "SkinSettings.png"} ]) )
listitems.append( self._create(["ActivateWindow(PlayerSettings)", "14200", "10004", {"icon": "PlayerSettings.png"} ]) )
listitems.append( self._create(["ActivateWindow(LibrarySettings)", "14202", "10004", {"icon": "LibrarySettings.png"} ]) )
listitems.append( self._create(["ActivateWindow(InterfaceSettings)", "14206", "10004", {"icon": "InterfaceSettings.png"} ]) )
self.addToDictionary( "settings", listitems )
def pvrlibrary( self ):
# PVR
listitems = []
listitems.append( self._create(["ActivateWindow(TVChannels)", "19019", "32017", {"icon": "DefaultTVShows.png"} ] ) )
listitems.append( self._create(["ActivateWindow(TVGuide)", "22020", "32017", {"icon": "DefaultTVShows.png"} ] ) )
listitems.append( self._create(["ActivateWindow(TVRecordings)", "19163", "32017", {"icon": "DefaultTVShows.png"} ] ) )
listitems.append( self._create(["ActivateWindow(TVTimers)", "19040", "32017", {"icon": "DefaultTVShows.png"} ] ) )
listitems.append( self._create(["ActivateWindow(TVTimerRules)", "19138", "32017", {"icon": "DefaultTVShows.png"} ] ) )
listitems.append( self._create(["ActivateWindow(TVSearch)", "137", "32017", {"icon": "DefaultTVShows.png"} ] ) )
listitems.append( self._create(["PlayPvrTV", "32066", "32017", {"icon": "DefaultTVShows.png"} ] ) )
listitems.append( self._create(["PlayPvr", "32068", "32017", {"icon": "DefaultTVShows.png"} ] ) )
self.addToDictionary( "pvr", listitems )
# Add tv channels
listitems = []
json_query = xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "id": 0, "method": "PVR.GetChannels", "params": { "channelgroupid": "alltv", "properties": ["thumbnail", "channeltype", "hidden", "locked", "channel", "lastplayed"] } }')
json_response = simplejson.loads(json_query)
# Add all directories returned by the json query
if 'result' in json_response and 'channels' in json_response['result'] and json_response['result']['channels'] is not None:
for item in json_response['result']['channels']:
listitems.append( self._create(["pvr-channel://" + str( item['channelid'] ), item['label'], "::SCRIPT::32076", {"icon": "DefaultTVShows.png", "thumb": item[ "thumbnail"]}]) )
self.addToDictionary( "pvr-tv", listitems )
# Add radio channels
listitems = []
json_query = xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "id": 0, "method": "PVR.GetChannels", "params": { "channelgroupid": "allradio", "properties": ["thumbnail", "channeltype", "hidden", "locked", "channel", "lastplayed"] } }')
json_response = simplejson.loads(json_query)
# Add all directories returned by the json query
if 'result' in json_response and 'channels' in json_response['result'] and json_response['result']['channels'] is not None:
for item in json_response['result']['channels']:
listitems.append( self._create(["pvr-channel://" + str( item['channelid'] ), item['label'], "::SCRIPT::32077", {"icon": "DefaultTVShows.png", "thumb": item[ "thumbnail"]}]) )
log( "Found " + str( len( listitems ) ) + " radio channels" )
self.addToDictionary( "pvr-radio", listitems )
def radiolibrary( self ):
listitems = []
# PVR
listitems.append( self._create(["ActivateWindow(RadioChannels)", "19019", "32087", {"icon": "DefaultAudio.png"} ] ) )
listitems.append( self._create(["ActivateWindow(RadioGuide)", "22020", "32087", {"icon": "DefaultAudio.png"} ] ) )
listitems.append( self._create(["ActivateWindow(RadioRecordings)", "19163", "32087", {"icon": "DefaultAudio.png"} ] ) )
listitems.append( self._create(["ActivateWindow(RadioTimers)", "19040", "32087", {"icon": "DefaultAudio.png"} ] ) )
listitems.append( self._create(["ActivateWindow(RadioTimerRules)", "19138", "32087", {"icon": "DefaultAudio.png"} ] ) )
listitems.append( self._create(["ActivateWindow(RadioSearch)", "137", "32087", {"icon": "DefaultAudio.png"} ] ) )
listitems.append( self._create(["PlayPvrRadio", "32067", "32087", {"icon": "DefaultAudio.png"} ] ) )
listitems.append( self._create(["PlayPvr", "32068", "32087", {"icon": "DefaultAudio.png"} ] ) )
self.addToDictionary( "radio", listitems )
def musiclibrary( self ):
# Try loading custom nodes first
try:
if self._parse_libraryNodes( "music", "custom" ) == False:
log( "Failed to load custom music nodes" )
self._parse_libraryNodes( "music", "default" )
except:
log( "Failed to load custom music nodes" )
print_exc()
try:
# Try loading default nodes
self._parse_libraryNodes( "music", "default" )
except:
# Empty library
log( "Failed to load default music nodes" )
print_exc()
# Do a JSON query for upnp sources (so that they'll show first time the user asks to see them)
if self.loaded[ "upnp" ][ 0 ] == False:
json_query = xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "id": 0, "method": "Files.GetDirectory", "params": { "properties": ["title", "file", "thumbnail"], "directory": "upnp://", "media": "files" } }')
self.loaded[ "upnp" ][ 0 ] = True
def librarysources( self ):
# Add video sources
listitems = []
json_query = xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "id": 0, "method": "Files.GetSources", "params": { "media": "video" } }')
json_response = simplejson.loads(json_query)
# Add all directories returned by the json query
if 'result' in json_response and 'sources' in json_response['result'] and json_response['result']['sources'] is not None:
for item in json_response['result']['sources']:
listitems.append( self._create(["||SOURCE||" + item['file'], item['label'], "32069", {"icon": "DefaultFolder.png"} ]) )
self.addToDictionary( "videosources", listitems )
log( " - " + str( len( listitems ) ) + " video sources" )
# Add audio sources
listitems = []
json_query = xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "id": 0, "method": "Files.GetSources", "params": { "media": "music" } }')
json_response = simplejson.loads(json_query)
# Add all directories returned by the json query
if 'result' in json_response and 'sources' in json_response['result'] and json_response['result']['sources'] is not None:
for item in json_response['result']['sources']:
listitems.append( self._create(["||SOURCE||" + item['file'], item['label'], "32073", {"icon": "DefaultFolder.png"} ]) )
self.addToDictionary( "musicsources", listitems )
log( " - " + str( len( listitems ) ) + " audio sources" )
# Add picture sources
listitems = []
json_query = xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "id": 0, "method": "Files.GetSources", "params": { "media": "pictures" } }')
json_response = simplejson.loads(json_query)
# Add all directories returned by the json query
if 'result' in json_response and 'sources' in json_response['result'] and json_response['result']['sources'] is not None:
for item in json_response['result']['sources']:
listitems.append( self._create(["||SOURCE||" + item['file'], item['label'], "32089", {"icon": "DefaultFolder.png"} ]) )
self.addToDictionary( "picturesources", listitems )
log( " - " + str( len( listitems ) ) + " picture sources" )
def playlists( self ):
audiolist = []
videolist = []
paths = [['special://videoplaylists/','32004','Videos'], ['special://musicplaylists/','32005','Music'], ["special://skin/playlists/",'32059',None], ["special://skin/extras/",'32059',None]]
for path in paths:
count = 0
if not xbmcvfs.exists(path[0]): continue
for file in kodiwalk( path[0] ):
try:
playlist = file['path']
label = file['label']
playlistfile = xbmc.translatePath(playlist)
mediaLibrary = path[2]
if playlist.endswith( '.xsp' ):
contents = xbmcvfs.File(playlistfile, 'r')
contents_data = contents.read()
xmldata = xmltree.fromstring(contents_data)
mediaType = "unknown"
for line in xmldata.getiterator():
if line.tag == "smartplaylist":
mediaType = line.attrib['type']
if mediaType == "movies" or mediaType == "tvshows" or mediaType == "seasons" or mediaType == "episodes" or mediaType == "musicvideos" or mediaType == "sets":
mediaLibrary = "Videos"
mediaContent = "video"
elif mediaType == "albums" or mediaType == "artists" or mediaType == "songs":
mediaLibrary = "Music"
mediaContent = "music"
if line.tag == "name" and mediaLibrary is not None:
name = line.text
if not name:
name = label
# Create a list item
listitem = self._create(["::PLAYLIST>%s::" %( mediaLibrary ), name, path[1], {"icon": "DefaultPlaylist.png"} ])
listitem.setProperty( "action-play", "PlayMedia(" + playlist + ")" )
listitem.setProperty("action-show", "ActivateWindow(" + mediaLibrary + "," + playlist + ",return)")
listitem.setProperty( "action-party", "PlayerControl(PartyMode(%s))" %( playlist ) )
# Add widget information
listitem.setProperty( "widget", "Playlist" )
listitem.setProperty( "widgetType", mediaType )
listitem.setProperty( "widgetTarget", mediaContent )
listitem.setProperty( "widgetName", name )
listitem.setProperty( "widgetPath", playlist )
if mediaLibrary == "Videos":
videolist.append( listitem )
else: