forked from m0ngr31/kanzi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kodi.py
1239 lines (900 loc) · 37.1 KB
/
kodi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# For a complete discussion, see http://forum.kodi.tv/showthread.php?tid=254502
import datetime
import json
import requests
import time
import codecs
import urllib
import os
import random
import re
import string
import sys
import codecs
import unicodedata
import roman
from fuzzywuzzy import fuzz, process
from yaep import populate_env, env
sys.path += [os.path.dirname(__file__)]
ENV_FILE = os.path.join(os.path.dirname(__file__), ".env")
os.environ['ENV_FILE'] = ENV_FILE
populate_env()
# Do not use below for your own settings, use the .env file
# We don't use the fallback param in os.getenv() because AWS Lambda actually
# sets any environment variables included in LAMBDA_ENV_VARS, regardless if
# it was unset before.
#
# Furthermore, os.getenv() under AWS Lambda returns 'None' as a string
# instead of None as NoneType as we'd normally expect, so we have to
# explicitly test for that.
SCHEME = os.getenv('KODI_SCHEME')
if not SCHEME or SCHEME == 'None':
SCHEME = 'http'
SUBPATH = os.getenv('KODI_SUBPATH')
if not SUBPATH or SUBPATH == 'None':
SUBPATH = ''
KODI = os.getenv('KODI_ADDRESS')
if not KODI or KODI == 'None':
KODI = '127.0.0.1'
PORT = os.getenv('KODI_PORT')
if not PORT or PORT == 'None':
PORT = '8080'
USER = os.getenv('KODI_USERNAME')
if not USER or USER == 'None':
USER = 'kodi'
PASS = os.getenv('KODI_PASSWORD')
if not PASS or PASS == 'None':
PASS = 'kodi'
# These are words that we ignore when doing a non-exact match on show names
STOPWORDS = [
"a",
"about",
"an",
"and",
"are",
"as",
"at",
"be",
"by",
"for",
"from",
"how",
"in",
"is",
"it",
"of",
"on",
"or",
"that",
"the",
"this",
"to",
"was",
"what",
"when",
"where",
"will",
"with",
]
def sanitize_name(media_name, remove_between=False):
# Normalize string
name = unicodedata.normalize('NFKD', media_name).encode('ASCII', 'ignore')
if remove_between:
# Strip things between and including brackets and parentheses
name = re.sub(r'\([^)]*\)', '', name)
name = re.sub(r'\[[^)]*\]', '', name)
else:
# Just remove the actual brackets and parentheses
name = name.translate(None, '[]()')
name = name.translate(None, '"')
if len(name) > 140:
name = name[:140].rsplit(' ', 1)[0]
name = name.strip()
return name
# Very naive method to remove a leading "the" from the given string
def remove_the(name):
if name[:4].lower() == "the ":
return name[4:]
else:
return name
# Remove extra slashes
def http_normalize_slashes(url):
url = str(url)
segments = url.split('/')
correct_segments = []
for segment in segments:
if segment != '':
correct_segments.append(segment)
first_segment = str(correct_segments[0])
if first_segment.find('http') == -1:
correct_segments = ['http:'] + correct_segments
correct_segments[0] = correct_segments[0] + '/'
normalized_url = '/'.join(correct_segments)
return normalized_url
def PopulateEnv():
populate_env()
# These two methods construct the JSON-RPC message and send it to the Kodi player
def SendCommand(command):
# Join the environment variables into a url
url = "%s://%s:%s/%s/%s" % (SCHEME, KODI, PORT, SUBPATH, 'jsonrpc')
# Remove any double slashes in the url
url = http_normalize_slashes(url)
print "Sending request to %s" % (url)
try:
r = requests.post(url, data=command, auth=(USER, PASS))
except:
return {}
return json.loads(r.text)
def RPCString(method, params=None):
j = {"jsonrpc":"2.0", "method":method, "id":1}
if params:
j["params"] = params
return json.dumps(j)
# Convert numbers to words.
# XXXLANG: This is currently English-only and shouldn't be!
def num2word(number):
# based on stackoverflow answer from https://github.com/ralphembree/Loquitor
leading_zero = 0
ones = ("", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
tens = ("", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety")
teens = ("ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen")
levels = ("", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion", "nonillion")
word = ""
if number[0] == "0":
leading_zero = 1
# number will now be the reverse of the string form of itself.
num = reversed(str(number))
number = ""
for x in num:
number += x
del num
if len(number) % 3 == 1:
number += "0"
x = 0
for digit in number:
if x % 3 == 0:
word = levels[x / 3] + " " + word
n = int(digit)
elif x % 3 == 1:
if digit == "1":
num = teens[n]
else:
num = tens[int(digit)]
if n:
if num:
num += " " + ones[n]
else:
num = ones[n]
word = num + " " + word
elif x % 3 == 2:
if digit != "0":
word = ones[int(digit)] + " hundred and " + word
x += 1
reply = word.strip(", ")
if leading_zero:
reply = "zero " +reply
return reply
# Replace word-form numbers with digits.
# XXXLANG: This is currently English-only and shouldn't be!
def word2num(textnum):
numwords = {}
units = [
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen",
]
tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
scales = ["hundred", "thousand", "million", "billion", "trillion"]
numwords["and"] = (1, 0)
for idx, word in enumerate(units):
numwords[word] = (1, idx)
for idx, word in enumerate(tens):
numwords[word] = (1, idx * 10)
for idx, word in enumerate(scales):
numwords[word] = (10 ** (idx * 3 or 2), 0)
current = result = 0
for word in textnum.split():
if word not in numwords:
raise Exception("Illegal word: " + word)
scale, increment = numwords[word]
current = current * scale + increment
if scale > 100:
result += current
current = 0
return result + current
# Replace digits with word-form numbers.
# XXXLANG: This is currently English-only and shouldn't be!
def digits2words(phrase):
# all word variant of the heard phrase if it contains digits
wordified = ''
for word in phrase.split():
word = word.decode('utf-8')
if word.isnumeric():
word = num2word(word)
wordified = wordified + word + " "
return wordified[:-1]
# Replace digits with roman numerals.
# XXXLANG: This is currently English-only and shouldn't be!
def digits2roman(phrase):
wordified = ''
for word in phrase.split():
word = word.decode('utf-8')
if word.isnumeric():
word = roman.toRoman(int(word))
wordified = wordified + word + " "
return wordified[:-1]
# Replace word-form numbers with roman numerals.
# XXXLANG: This is currently English-only and shouldn't be!
def words2roman(phrase):
wordified = ''
for word in phrase.split():
word = word.decode('utf-8')
try:
word = roman.toRoman(word2num(word))
except:
pass
wordified = wordified + word + " "
return wordified[:-1]
# Match heard string to something in the results
def matchHeard(heard, results, lookingFor='label'):
located = None
heard_minus_the = remove_the(heard)
print 'Trying to match: ' + heard
heard_list = set([x for x in heard.split() if x not in STOPWORDS])
for result in results:
# Strip out non-ascii symbols and lowercase it
result_name = sanitize_name(result[lookingFor]).lower()
# Direct comparison
if heard == result_name:
print 'Simple match on direct comparison'
located = result
break
# Remove 'the'
if remove_the(result_name) == heard_minus_the:
print 'Simple match minus "the"'
located = result
break
# Remove parentheses
removed_paren = sanitize_name(result[lookingFor], True).lower()
if heard == removed_paren:
print 'Simple match minus parentheses'
located = result
break
if not located:
print 'Simple match failed, trying fuzzy match...'
fuzzy_result = False
for f in (digits2roman, words2roman, str, digits2words):
try:
ms = f(heard)
print "Trying to match %s from %s" % (ms, f)
rv = process.extract(ms, [d[lookingFor] for d in results], limit=1, scorer=fuzz.QRatio)
if rv[0][1] >= 75:
fuzzy_result = rv
break
except:
continue
# Got a match?
if fuzzy_result:
print 'Fuzzy match %s%%' % (fuzzy_result[0][1])
located = (item for item in results if item[lookingFor] == fuzzy_result[0][0]).next()
return located
# Helpers to find media
def FindVideoPlaylist(heard_search):
print 'Searching for video playlist "%s"' % (heard_search)
playlists = GetVideoPlaylists()
if 'result' in playlists and 'files' in playlists['result']:
playlists_list = playlists['result']['files']
located = matchHeard(heard_search, playlists_list, 'label')
if located:
print 'Located video playlist "%s"' % (located['file'])
return located['file']
def FindAudioPlaylist(heard_search):
print 'Searching for audio playlist "%s"' % (heard_search)
playlists = GetMusicPlaylists()
if 'result' in playlists and 'files' in playlists['result']:
playlists_list = playlists['result']['files']
located = matchHeard(heard_search, playlists_list, 'label')
if located:
print 'Located audio playlist "%s"' % (located['file'])
return located['file']
def FindMovie(heard_search):
print 'Searching for movie "%s"' % (heard_search)
movies = GetMovies()
if 'result' in movies and 'movies' in movies['result']:
movies_array = movies['result']['movies']
located = matchHeard(heard_search, movies_array)
if located:
print 'Located movie "%s"' % (located['label'])
return located['movieid']
def FindTvShow(heard_search):
print 'Searching for show "%s"' % (heard_search)
shows = GetTvShows()
if 'result' in shows and 'tvshows' in shows['result']:
shows_array = shows['result']['tvshows']
located = matchHeard(heard_search, shows_array)
if located:
print 'Located tvshow "%s"' % (located['label'])
return located['tvshowid']
def FindArtist(heard_search):
print 'Searching for artist "%s"' % (heard_search)
artists = GetMusicArtists()
if 'result' in artists and 'artists' in artists['result']:
artists_list = artists['result']['artists']
located = matchHeard(heard_search, artists_list, 'artist')
if located:
print 'Located artist "%s"' % (located['label'])
return located['artistid']
def FindAlbum(heard_search):
print 'Searching for album "%s"' % (heard_search)
albums = GetAlbums()
if 'result' in albums and 'albums' in albums['result']:
albums_list = albums['result']['albums']
located = matchHeard(heard_search, albums_list, 'label')
if located:
print 'Located album "%s"' % (located['label'])
return located['albumid']
def FindSong(heard_search):
print 'Searching for song "%s"' % (heard_search)
songs = GetSongs()
if 'result' in songs and 'songs' in songs['result']:
songs_list = songs['result']['songs']
located = matchHeard(heard_search, songs_list, 'label')
if located:
print 'Located song "%s"' % (located['label'])
return located['songid']
# Playlists
def ClearAudioPlaylist():
return SendCommand(RPCString("Playlist.Clear", {"playlistid": 0}))
def AddSongToPlaylist(song_id):
return SendCommand(RPCString("Playlist.Add", {"playlistid": 0, "item": {"songid": int(song_id)}}))
def AddSongsToPlaylist(song_ids, shuffle=False):
songs_array = []
for song_id in song_ids:
temp_song = {}
temp_song['songid'] = song_id
songs_array.append(temp_song)
if shuffle:
random.shuffle(songs_array)
# Segment the requests into chunks that Kodi will accept in a single call
song_groups = [songs_array[x:x+2000] for x in range(0, len(songs_array), 2000)]
for a in song_groups:
print "Adding %d items to the queue..." % (len(a))
res = SendCommand(RPCString("Playlist.Add", {"playlistid": 0, "item": a}))
return res
def AddAlbumToPlaylist(album_id):
return SendCommand(RPCString("Playlist.Add", {"playlistid": 0, "item": {"albumid": int(album_id)}}))
def GetAudioPlaylistItems():
return SendCommand(RPCString("Playlist.GetItems", {"playlistid": 0}))
def StartAudioPlaylist(playlist_file=None):
if playlist_file is not None and playlist_file != '':
return SendCommand(RPCString("Player.Open", {"item": {"file": playlist_file}}))
else:
return SendCommand(RPCString("Player.Open", {"item": {"playlistid": 0}}))
def ClearVideoPlaylist():
return SendCommand(RPCString("Playlist.Clear", {"playlistid": 1}))
def AddEpisodeToPlayList(ep_id):
return SendCommand(RPCString("Playlist.Add", {"playlistid": 1, "item": {"episodeid": int(ep_id)}}))
def AddMovieToPlaylist(movie_id):
return SendCommand(RPCString("Playlist.Add", {"playlistid": 1, "item": {"movieid": int(movie_id)}}))
def AddVideosToPlaylist(video_files, shuffle=False):
videos_array = []
for video_file in video_files:
temp_video = {}
temp_video['file'] = video_file
videos_array.append(temp_video)
if shuffle:
random.shuffle(videos_array)
# Segment the requests into chunks that Kodi will accept in a single call
video_groups = [videos_array[x:x+2000] for x in range(0, len(videos_array), 2000)]
for a in video_groups:
print "Adding %d items to the queue..." % (len(a))
res = SendCommand(RPCString("Playlist.Add", {"playlistid": 1, "item": a}))
return res
def GetVideoPlaylistItems():
return SendCommand(RPCString("Playlist.GetItems", {"playlistid": 1}))
def StartVideoPlaylist(playlist_file=None):
if playlist_file is not None and playlist_file != '':
return SendCommand(RPCString("Player.Open", {"item": {"file": playlist_file}}))
else:
return SendCommand(RPCString("Player.Open", {"item": {"playlistid": 1}}))
# Direct plays
def PlayEpisode(ep_id, resume=True):
return SendCommand(RPCString("Player.Open", {"item": {"episodeid": ep_id}, "options": {"resume": resume}}))
def PlayMovie(movie_id, resume=True):
return SendCommand(RPCString("Player.Open", {"item": {"movieid": movie_id}, "options": {"resume": resume}}))
def PartyPlayMusic():
return SendCommand(RPCString("Player.Open", {"item": {"partymode": "music"}}))
# Tell Kodi to update its video or music libraries
def UpdateVideo():
return SendCommand(RPCString("VideoLibrary.Scan"))
def CleanVideo():
return SendCommand(RPCString("VideoLibrary.Clean"))
def UpdateMusic():
return SendCommand(RPCString("AudioLibrary.Scan"))
def CleanMusic():
return SendCommand(RPCString("AudioLibrary.Clean"))
# Perform UI actions that match the normal remote control buttons
def PageUp():
return SendCommand(RPCString("Input.ExecuteAction", {"action":"pageup"}))
def PageDown():
return SendCommand(RPCString("Input.ExecuteAction", {"action":"pagedown"}))
def ToggleWatched():
return SendCommand(RPCString("Input.ExecuteAction", {"action":"togglewatched"}))
def Info():
return SendCommand(RPCString("Input.Info"))
def Menu():
return SendCommand(RPCString("Input.ContextMenu"))
def Home():
return SendCommand(RPCString("Input.Home"))
def Select():
return SendCommand(RPCString("Input.Select"))
def Up():
return SendCommand(RPCString("Input.Up"))
def Down():
return SendCommand(RPCString("Input.Down"))
def Left():
return SendCommand(RPCString("Input.Left"))
def Right():
return SendCommand(RPCString("Input.Right"))
def Back():
return SendCommand(RPCString("Input.Back"))
def ToggleFullscreen():
return SendCommand(RPCString("GUI.SetFullscreen", {"fullscreen":"toggle"}))
def ToggleMute():
return SendCommand(RPCString("Application.SetMute", {"mute":"toggle"}))
def GetCurrentVolume():
return SendCommand(RPCString("Application.GetProperties", {"properties":["volume", "muted"]}))
def VolumeUp():
resp = GetCurrentVolume()
vol = resp['result']['volume']
if vol % 10 == 0:
# already modulo 10, so just add 10
vol += 10
else:
# round up to nearest 10
vol -= vol % -10
if vol > 100:
vol = 100
return SendCommand(RPCString("Application.SetVolume", {"volume":vol}))
def VolumeDown():
resp = GetCurrentVolume()
vol = resp['result']['volume']
if vol % 10 != 0:
# round up to nearest 10 first
vol -= vol % -10
vol -= 10
if vol < 0:
vol = 0
return SendCommand(RPCString("Application.SetVolume", {"volume":vol}))
def VolumeSet(vol, percent=True):
if vol < 0:
vol = 0
if not percent:
# specified with scale of 0 to 10
vol *= 10
if vol > 100:
vol = 100
return SendCommand(RPCString("Application.SetVolume", {"volume":vol}))
# Player controls
def PlayerPlayPause():
playerid = GetPlayerID()
if playerid is not None:
return SendCommand(RPCString("Player.PlayPause", {"playerid":playerid}))
def PlayerSkip():
playerid = GetPlayerID()
if playerid is not None:
return SendCommand(RPCString("Player.GoTo", {"playerid":playerid, "to": "next"}))
def PlayerPrev():
playerid = GetPlayerID()
if playerid is not None:
SendCommand(RPCString("Player.GoTo", {"playerid":playerid, "to": "previous"}))
return SendCommand(RPCString("Player.GoTo", {"playerid":playerid, "to": "previous"}))
def PlayerStartOver():
playerid = GetPlayerID()
if playerid is not None:
return SendCommand(RPCString("Player.Seek", {"playerid":playerid, "value": 0}))
def PlayerStop():
playerid = GetPlayerID()
if playerid is not None:
return SendCommand(RPCString("Player.Stop", {"playerid":playerid}))
def PlayerSeek(seconds):
playerid = GetPlayerID()
if playerid:
return SendCommand(RPCString("Player.Seek", {"playerid":playerid, "value":{"seconds":seconds}}))
def PlayerSeekSmallForward():
playerid = GetPlayerID()
if playerid:
return SendCommand(RPCString("Player.Seek", {"playerid":playerid, "value":"smallforward"}))
def PlayerSeekSmallBackward():
playerid = GetPlayerID()
if playerid:
return SendCommand(RPCString("Player.Seek", {"playerid":playerid, "value":"smallbackward"}))
def PlayerSeekBigForward():
playerid = GetPlayerID()
if playerid:
return SendCommand(RPCString("Player.Seek", {"playerid":playerid, "value":"bigforward"}))
def PlayerSeekBigBackward():
playerid = GetPlayerID()
if playerid:
return SendCommand(RPCString("Player.Seek", {"playerid":playerid, "value":"bigbackward"}))
def PlayerShuffleOn():
playerid = GetPlayerID()
if playerid is not None:
return SendCommand(RPCString("Player.SetShuffle", {"playerid":playerid, "shuffle":True}))
def PlayerShuffleOff():
playerid = GetPlayerID()
if playerid is not None:
return SendCommand(RPCString("Player.SetShuffle", {"playerid":playerid, "shuffle":False}))
def PlayerLoopOn():
playerid = GetPlayerID()
if playerid is not None:
return SendCommand(RPCString("Player.SetRepeat", {"playerid":playerid, "repeat":"cycle"}))
def PlayerLoopOff():
playerid = GetPlayerID()
if playerid is not None:
return SendCommand(RPCString("Player.SetRepeat", {"playerid":playerid, "repeat":"off"}))
def PlayerSubtitlesOn():
playerid = GetVideoPlayerID()
if playerid:
return SendCommand(RPCString("Player.SetSubtitle", {"playerid":playerid, "subtitle":"on"}))
def PlayerSubtitlesOff():
playerid = GetVideoPlayerID()
if playerid:
return SendCommand(RPCString("Player.SetSubtitle", {"playerid":playerid, "subtitle":"off"}))
def PlayerSubtitlesNext():
playerid = GetVideoPlayerID()
if playerid:
return SendCommand(RPCString("Player.SetSubtitle", {"playerid":playerid, "subtitle":"next", "enable":True}))
def PlayerSubtitlesPrevious():
playerid = GetVideoPlayerID()
if playerid:
return SendCommand(RPCString("Player.SetSubtitle", {"playerid":playerid, "subtitle":"previous", "enable":True}))
def PlayerAudioStreamNext():
playerid = GetVideoPlayerID()
if playerid:
return SendCommand(RPCString("Player.SetAudioStream", {"playerid":playerid, "stream":"next"}))
def PlayerAudioStreamPrevious():
playerid = GetVideoPlayerID()
if playerid:
return SendCommand(RPCString("Player.SetAudioStream", {"playerid":playerid, "stream":"previous"}))
def PlayerMoveUp():
playerid = GetPicturePlayerID()
if playerid:
return SendCommand(RPCString("Player.Move", {"playerid":playerid, "direction":"up"}))
def PlayerMoveDown():
playerid = GetPicturePlayerID()
if playerid:
return SendCommand(RPCString("Player.Move", {"playerid":playerid, "direction":"down"}))
def PlayerMoveLeft():
playerid = GetPicturePlayerID()
if playerid:
return SendCommand(RPCString("Player.Move", {"playerid":playerid, "direction":"left"}))
def PlayerMoveRight():
playerid = GetPicturePlayerID()
if playerid:
return SendCommand(RPCString("Player.Move", {"playerid":playerid, "direction":"right"}))
def PlayerZoom(lvl=0):
playerid = GetPicturePlayerID()
if playerid and lvl > 0 and lvl < 11:
return SendCommand(RPCString("Player.Zoom", {"playerid":playerid, "zoom":lvl}))
def PlayerZoomIn():
playerid = GetPicturePlayerID()
if playerid:
return SendCommand(RPCString("Player.Zoom", {"playerid":playerid, "zoom":"in"}))
def PlayerZoomOut():
playerid = GetPicturePlayerID()
if playerid:
return SendCommand(RPCString("Player.Zoom", {"playerid":playerid, "zoom":"out"}))
def PlayerRotateClockwise():
playerid = GetPicturePlayerID()
if playerid:
return SendCommand(RPCString("Player.Rotate", {"playerid":playerid, "value":"clockwise"}))
def PlayerRotateCounterClockwise():
playerid = GetPicturePlayerID()
if playerid:
return SendCommand(RPCString("Player.Rotate", {"playerid":playerid, "value":"counterclockwise"}))
# Addons
def AddonExecute(addon_id, params={}):
return SendCommand(RPCString("Addons.ExecuteAddon", {"addonid":addon_id, "params":params}))
def AddonGlobalSearch(needle=''):
return AddonExecute("script.globalsearch", {"searchstring":needle})
def AddonCinemaVision():
return AddonExecute("script.cinemavision", ["experience"])
# Library queries
# content can be: video, audio, image, executable, or unknown
def GetAddons(content):
if content:
return SendCommand(RPCString("Addons.GetAddons", {"content":content, "properties":["name"]}))
else:
return SendCommand(RPCString("Addons.GetAddons", {"properties":["name"]}))
def GetAddonDetails(addon_id):
return SendCommand(RPCString("Addons.GetAddonDetails", {"addonid":addon_id, "properties":["name", "version", "description", "summary"]}))
def GetPlaylistItems(playlist_file):
return SendCommand(RPCString("Files.GetDirectory", {"directory": playlist_file}))
def GetMusicPlaylists():
return SendCommand(RPCString("Files.GetDirectory", {"directory": "special://musicplaylists"}))
def GetMusicArtists():
return SendCommand(RPCString("AudioLibrary.GetArtists"))
def GetMusicGenres():
return SendCommand(RPCString("AudioLibrary.GetGenres"))
def GetArtistAlbums(artist_id):
return SendCommand(RPCString("AudioLibrary.GetAlbums", {"filter": {"artistid": int(artist_id)}}))
def GetAlbums():
return SendCommand(RPCString("AudioLibrary.GetAlbums"))
def GetArtistSongs(artist_id):
return SendCommand(RPCString("AudioLibrary.GetSongs", {"filter": {"artistid": int(artist_id)}}))
def GetArtistSongsPath(artist_id):
return SendCommand(RPCString("AudioLibrary.GetSongs", {"filter": {"artistid": int(artist_id)}, "properties":["file"]}))
def GetAlbumSongsPath(album_id):
return SendCommand(RPCString("AudioLibrary.GetSongs", {"filter": {"albumid": int(album_id)}, "properties":["file"]}))
def GetSongs():
return SendCommand(RPCString("AudioLibrary.GetSongs"))
def GetSongsPath():
return SendCommand(RPCString("AudioLibrary.GetSongs", {"properties":["file"]}))
def GetSongIdPath(song_id):
return SendCommand(RPCString("AudioLibrary.GetSongDetails", {"songid": int(song_id), "properties":["file"]}))
def GetRecentlyAddedAlbums():
return SendCommand(RPCString("AudioLibrary.GetRecentlyAddedAlbums", {'properties':['artist']}))
def GetRecentlyAddedSongs():
return SendCommand(RPCString("AudioLibrary.GetRecentlyAddedSongs", {'properties':['artist']}))
def GetRecentlyAddedSongsPath():
return SendCommand(RPCString("AudioLibrary.GetRecentlyAddedSongs", {'properties':['artist', 'file']}))
def GetVideoPlaylists():
return SendCommand(RPCString("Files.GetDirectory", {"directory": "special://videoplaylists"}))
def GetTvShowDetails(show_id):
data = SendCommand(RPCString("VideoLibrary.GetTVShowDetails", {'tvshowid':show_id, 'properties':['art']}))
return data['result']['tvshowdetails']
def GetTvShows():
return SendCommand(RPCString("VideoLibrary.GetTVShows"))
def GetMovieDetails(movie_id):
data = SendCommand(RPCString("VideoLibrary.GetMovieDetails", {'movieid':movie_id, 'properties':['resume']}))
return data['result']['moviedetails']
def GetMovies():
return SendCommand(RPCString("VideoLibrary.GetMovies"))
def GetMoviesByGenre(genre):
return SendCommand(RPCString("VideoLibrary.GetMovies", {"filter":{"genre":genre}}))
def GetMovieGenres():
return SendCommand(RPCString("VideoLibrary.GetGenres", {"type": "movie"}))
def GetEpisodeDetails(ep_id):
data = SendCommand(RPCString("VideoLibrary.GetEpisodeDetails", {"episodeid": int(ep_id), "properties":["season", "episode", "resume"]}))
return data['result']['episodedetails']
def GetEpisodesFromShow(show_id):
return SendCommand(RPCString("VideoLibrary.GetEpisodes", {"tvshowid": int(show_id)}))
def GetUnwatchedEpisodesFromShow(show_id):
return SendCommand(RPCString("VideoLibrary.GetEpisodes", {"tvshowid": int(show_id), "filter":{"field":"playcount", "operator":"lessthan", "value":"1"}}))
def GetNewestEpisodeFromShow(show_id):
data = SendCommand(RPCString("VideoLibrary.GetEpisodes", {"limits":{"end":1},"tvshowid": int(show_id), "sort":{"method":"dateadded", "order":"descending"}}))
if 'episodes' in data['result']:
episode = data['result']['episodes'][0]
return episode['episodeid']
else:
return None
def GetNextUnwatchedEpisode(show_id):
data = SendCommand(RPCString("VideoLibrary.GetEpisodes", {"limits":{"end":1},"tvshowid": int(show_id), "filter":{"field":"lastplayed", "operator":"greaterthan", "value":"0"}, "properties":["season", "episode", "lastplayed", "firstaired", "resume"], "sort":{"method":"lastplayed", "order":"descending"}}))
if 'episodes' in data['result']:
episode = data['result']['episodes'][0]
episode_season = episode['season']
episode_number = episode['episode']
if episode['resume']['position'] > 0.0:
next_episode_id = episode['episodeid']
else:
next_episode_id = GetSpecificEpisode(show_id, episode_season, int(episode_number) + 1)
if next_episode_id:
return next_episode_id
else:
next_episode_id = GetSpecificEpisode(show_id, int(episode_season) + 1, 1)
if next_episode_id:
return next_episode_id
else:
return None
else:
return None
def GetLastWatchedShow():
return SendCommand(RPCString("VideoLibrary.GetEpisodes", {"limits":{"end":1}, "filter":{"field":"playcount", "operator":"greaterthan", "value":"0"}, "filter":{"field":"lastplayed", "operator":"greaterthan", "value":"0"}, "sort":{"method":"lastplayed", "order":"descending"}, "properties":["tvshowid", "showtitle"]}))
def GetSpecificEpisode(show_id, season, episode):
data = SendCommand(RPCString("VideoLibrary.GetEpisodes", {"tvshowid": int(show_id), "season": int(season), "properties": ["season", "episode"]}))
if 'episodes' in data['result']:
correct_id = None
for episode_data in data['result']['episodes']:
if int(episode_data['episode']) == int(episode):
correct_id = episode_data['episodeid']
break