-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkodi.py
615 lines (478 loc) · 20 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
#!/usr/bin/env python
"""
The MIT License (MIT)
Copyright (c) 2015 Maker Musings && m0ngr31
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
# For a complete discussion, see http://forum.kodi.tv/showthread.php?tid=254502
import datetime
import json
import requests
import time
import urllib
import os
import random
import re
import string
import sys
import pycountry
from yaep import populate_env
# 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 remove_the(name):
# Very naive method to remove a leading "the" from the given string
if name[:4].lower() == "the ":
return name[4:]
else:
return name
def SetupEnvVars():
populate_env()
# These two methods construct the JSON-RPC message and send it to the Kodi player
def SendCommand(command):
# Change this to the IP address of your Kodi server or always pass in an address
KODI = os.getenv('KODI_ADDRESS', '127.0.0.1')
PORT = int(os.getenv('KODI_PORT', 8080))
USER = os.getenv('KODI_USERNAME', 'kodi')
PASS = os.getenv('KODI_PASSWORD', 'kodi')
print KODI
url = "https://%s:%d/jsonrpc" % (KODI, PORT)
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)
# Match heard string to something in the results
def matchHeard(heard, results, lookingFor='label'):
located = None
heard_minus_the = remove_the(heard)
print heard
sys.stdout.flush()
heard_list = set([x for x in heard.split() if x not in STOPWORDS])
for result in results:
ascii_name = result[lookingFor]
# Strip out non-ascii symbols and lowercase it
ascii_name = result[lookingFor].encode('ascii', 'replace')
ascii_name = re.sub(r'\bone\b', '1', ascii_name, flags=re.IGNORECASE)
ascii_name = re.sub(r'\btwo\b', '2', ascii_name, flags=re.IGNORECASE)
ascii_name = re.sub(r'\bthree\b', '3', ascii_name, flags=re.IGNORECASE)
ascii_name = re.sub(r'\bfour\b', '4', ascii_name, flags=re.IGNORECASE)
ascii_name = re.sub(r'\bfive\b', '5', ascii_name, flags=re.IGNORECASE)
ascii_name = re.sub(r'\+', ' plus ', ascii_name, flags=re.IGNORECASE)
result_name = str(ascii_name).lower().translate(None, string.punctuation)
# Direct comparison
if heard == result_name:
located = result
break
# Remove 'the'
if remove_the(result_name) == heard_minus_the:
located = result
break
# Remove parentheses
removed_paren = re.sub(r'\([^)]*\)', '', ascii_name).rstrip().lower().translate(None, string.punctuation)
if heard == removed_paren:
located = result
break
# Remove spaces
removed_paren = re.sub(r'\ ', '', ascii_name).rstrip().lower().translate(None, string.punctuation)
if heard == removed_paren:
located = result
break
if not located:
print 'not located on the first round of checks'
sys.stdout.flush()
# Loop through results again and be a little more liberal with what is accepted
for result in results:
# Strip out non-ascii symbols and lowercase it
ascii_name = result[lookingFor].encode('ascii', 'replace')
ascii_name = re.sub(r'\bone\b', '1', ascii_name, flags=re.IGNORECASE)
ascii_name = re.sub(r'\btwo\b', '2', ascii_name, flags=re.IGNORECASE)
ascii_name = re.sub(r'\bthree\b', '3', ascii_name, flags=re.IGNORECASE)
ascii_name = re.sub(r'\bfour\b', '4', ascii_name, flags=re.IGNORECASE)
ascii_name = re.sub(r'\bfive\b', '5', ascii_name, flags=re.IGNORECASE)
ascii_name = re.sub(r'\+', ' plus ', ascii_name, flags=re.IGNORECASE)
result_name = str(ascii_name).lower().translate(None, string.punctuation)
#print "trying '%s'" % (heard_minus_the)
#sys.stdout.flush()
#print result_name
#sys.stdout.flush()
# Just look for substring
if result_name.find(heard_minus_the) != -1:
located = result
break
# Last resort -- take out some useless words and see if we have a match with
# >= 60% of the heard phrase
result_list = set([x for x in result_name.split() if x not in STOPWORDS])
matched_words = [x for x in heard_list if x in result_list]
#print 'matched words: '
#sys.stdout.flush()
if len(matched_words) > 0:
#print matched_words
sys.stdout.flush()
percentage = float(len(matched_words)) / float(len(heard_list))
if percentage > float(0.6):
located = result
break
return located
# Playlists
def ClearPlaylist():
return SendCommand(RPCString("Playlist.Clear", {"playlistid": 0}))
def ClearVideoPlaylist():
return SendCommand(RPCString("Playlist.Clear", {"playlistid": 1}))
def StartPlaylist(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 AddSongToPlaylist(song_id):
return SendCommand(RPCString("Playlist.Add", {"playlistid": 0, "item": {"songid": int(song_id)}}))
def PrepEpisodePlayList(ep_id):
return SendCommand(RPCString("Playlist.Add", {"playlistid": 1, "item": {"episodeid": int(ep_id)}}))
def PrepMoviePlaylist(movie_id):
return SendCommand(RPCString("Playlist.Add", {"playlistid": 1, "item": {"movieid": int(movie_id)}}))
def StartVideoPlaylist():
return SendCommand(RPCString("Player.Open", {"item": {"playlistid": 1}}))
def AddSongsToPlaylist(song_ids):
songs_array = []
for song_id in song_ids:
temp_song = {}
temp_song['songid'] = song_id
songs_array.append(temp_song)
random.shuffle(songs_array)
return SendCommand(RPCString("Playlist.Add", {"playlistid": 0, "item": songs_array}))
def GetPlaylistItems():
return SendCommand(RPCString("Playlist.GetItems", {"playlistid": 0}))
def GetVideoPlaylistItems():
return SendCommand(RPCString("Playlist.GetItems", {"playlistid": 1}))
# 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"}))
# Player controls
def PlayPause():
playerid = GetPlayerID()
if playerid is not None:
return SendCommand(RPCString("Player.PlayPause", {"playerid":playerid}))
def PlaySkip():
playerid = GetPlayerID()
if playerid is not None:
return SendCommand(RPCString("Player.GoTo", {"playerid":playerid, "to": "next"}))
def PlayPrev():
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 PlayStartOver():
playerid = GetPlayerID()
if playerid is not None:
return SendCommand(RPCString("Player.GoTo", {"playerid":playerid, "to": "previous"}))
def Stop():
playerid = GetPlayerID()
if playerid is not None:
return SendCommand(RPCString("Player.Stop", {"playerid":playerid}))
def Replay():
playerid = GetPlayerID()
if playerid:
return SendCommand(RPCString("Player.Seek", {"playerid":playerid, "value":"smallbackward"}))
def SubtitlesOn():
playerid = GetPlayerID()
if playerid:
return SendCommand(RPCString("Player.SetSubtitle", {"playerid":playerid, "subtitle":"on"}))
def SubtitlesOff():
playerid = GetPlayerID()
if playerid:
return SendCommand(RPCString("Player.SetSubtitle", {"playerid":playerid, "subtitle":"off"}))
def SubtitlesNext():
playerid = GetPlayerID()
if playerid:
return SendCommand(RPCString("Player.SetSubtitle", {"playerid":playerid, "subtitle":"next", "enable":True}))
def SubtitlesPrevious():
playerid = GetPlayerID()
if playerid:
return SendCommand(RPCString("Player.SetSubtitle", {"playerid":playerid, "subtitle":"previous", "enable":True}))
def AudioStreamNext():
playerid = GetPlayerID()
if playerid:
return SendCommand(RPCString("Player.SetAudioStream", {"playerid":playerid, "stream":"next"}))
def AudioStreamPrevious():
playerid = GetPlayerID()
if playerid:
return SendCommand(RPCString("Player.SetAudioStream", {"playerid":playerid, "stream":"previous"}))
# Addons
def CallKodiSearch(name=''):
return SendCommand(RPCString("Addons.ExecuteAddon", {"addonid": "script.globalsearch", "params":{"searchstring":name}}))
def CinemaVision():
return SendCommand(RPCString("Addons.ExecuteAddon", { "addonid": "script.cinemavision", "params": ["experience"]}))
# Library queries
def GetMusicPlaylists():
return SendCommand(RPCString("Files.GetDirectory", {"directory": "special://musicplaylists"}))
def GetMusicArtists():
data = SendCommand(RPCString("AudioLibrary.GetArtists"))
return data
def GetMusicGenres():
data = SendCommand(RPCString("AudioLibrary.GetGenres"))
return data
def GetArtistAlbums(artist_id):
data = SendCommand(RPCString("AudioLibrary.GetAlbums", {"filter": {"artistid": int(artist_id)}}))
return data
def GetAllSongs():
data = SendCommand(RPCString("AudioLibrary.GetSongs"))
return data
def GetArtistSongs(artist_id):
data = SendCommand(RPCString("AudioLibrary.GetSongs", {"filter": {"artistid": int(artist_id)}}))
return data
def GetRecentlyAddedSongs():
data = SendCommand(RPCString("AudioLibrary.GetRecentlyAddedSongs"))
return data
def GetTvShows():
data = SendCommand(RPCString("VideoLibrary.GetTVShows"))
return data
def GetMovies():
data = SendCommand(RPCString("VideoLibrary.GetMovies"))
return data
def GetMovieGenres():
data = SendCommand(RPCString("VideoLibrary.GetGenres", {"type": "movie"}))
return data
def GetUnwatchedMovies():
data = SendCommand(RPCString("VideoLibrary.GetMovies", {"filter":{"field":"playcount", "operator":"lessthan", "value":"1"}}))
return data
def GetEpisodesFromShow(show_id):
data = SendCommand(RPCString("VideoLibrary.GetEpisodes", {"tvshowid": int(show_id)}))
return data
def GetUnwatchedEpisodesFromShow(show_id):
data = SendCommand(RPCString("VideoLibrary.GetEpisodes", {"tvshowid": int(show_id), "filter":{"field":"playcount", "operator":"lessthan", "value":"1"}}))
return data
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"], "sort":{"method":"lastplayed", "order":"descending"}}))
if 'episodes' in data['result']:
episode = data['result']['episodes'][0]
episode_season = episode['season']
episode_number = episode['episode']
next_episode = GetSpecificEpisode(show_id, episode_season, int(episode_number) + 1)
if next_episode:
return next_episode
else:
next_episode = GetSpecificEpisode(show_id, int(episode_season) + 1, 1)
if next_episode:
return next_episode
else:
return None
else:
return None
def GetLastWatchedShow():
data = 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"]}))
return data
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
return correct_id
else:
return None
def GetEpisodesFromShowDetails(show_id):
data = SendCommand(RPCString("VideoLibrary.GetEpisodes", {"tvshowid": int(show_id), "properties": ["season", "episode"]}))
return data
# Returns a list of dictionaries with information about episodes that have been watched.
# May take a long time if you have lots of shows and you set max to a big number
def GetWatchedEpisodes(max=90):
data = SendCommand(RPCString("VideoLibrary.GetEpisodes", {"limits":{"end":max}, "filter":{"field":"playcount", "operator":"greaterthan", "value":"0"}, "properties":["playcount", "showtitle", "season", "episode", "lastplayed" ]}))
return data['result']['episodes']
# Returns a list of dictionaries with information about unwatched episodes. Useful for
# telling/showing users what's ready to be watched. Setting max to very high values
# can take a long time.
def GetUnwatchedEpisodes(max=90):
data = SendCommand(RPCString("VideoLibrary.GetEpisodes", {"limits":{"end":max}, "filter":{"field":"playcount", "operator":"lessthan", "value":"1"}, "sort":{"method":"dateadded", "order":"descending"}, "properties":["title", "playcount", "showtitle", "tvshowid", "dateadded" ]}))
answer = []
shows = set([d['tvshowid'] for d in data['result']['episodes']])
show_info = {}
for show in shows:
show_info[show] = GetShowDetails(show=show)
for d in data['result']['episodes']:
showinfo = show_info[d['tvshowid']]
answer.append({'title':d['title'], 'episodeid':d['episodeid'], 'show':d['showtitle'], 'label':d['label'], 'dateadded':datetime.datetime.strptime(d['dateadded'], "%Y-%m-%d %H:%M:%S")})
return answer
# System commands
def ApplicationQuit():
return SendCommand(RPCString("Application.Quit"))
def SystemHibernate():
return SendCommand(RPCString("System.Hibernate"))
def SystemReboot():
return SendCommand(RPCString("System.Reboot"))
def SystemShutdown():
return SendCommand(RPCString("System.Shutdown"))
def SystemSuspend():
return SendCommand(RPCString("System.Suspend"))
def SystemEjectMedia():
return SendCommand(RPCString("System.EjectOpticalDrive"))
# Misc helpers
# Grabs the artwork for the specified show. Could be modified to return other interesting data.
def GetShowDetails(show=0):
data = SendCommand(RPCString("VideoLibrary.GetTVShowDetails", {'tvshowid':show, 'properties':['art']}))
return data['result']['tvshowdetails']
# Get the first active Audio or Video player, since all we deal with
# currently.
def GetPlayerID(playertype=['audio', 'video']):
info = SendCommand(RPCString("Player.GetActivePlayers"))
result = info.get("result", [])
if len(result) > 0:
for curitem in result:
if curitem.get("type") in playertype:
return curitem.get("playerid")
return None
# Information about the video or audio that's currently playing
def GetActivePlayItem():
playerid = GetPlayerID()
if playerid is not None:
data = SendCommand(RPCString("Player.GetItem", {"playerid":playerid, "properties":["title", "album", "artist", "season", "episode", "showtitle", "tvshowid", "description"]}))
return data['result']['item']
def GetActivePlayProperties():
playerid = GetPlayerID()
if playerid is not None:
data = SendCommand(RPCString("Player.GetProperties", {"playerid":playerid, "properties":["currentaudiostream", "currentsubtitle", "shuffled", "repeat"]}))
return data['result']
# Returns current subtitles as a speakable string
def GetCurrentSubtitles():
subs = ""
curprops = GetActivePlayProperties()
#print curprops
if curprops is not None:
try:
lang = curprops['currentsubtitle']['language']
subs = pycountry.languages.get(bibliographic=lang).name
name = curprops['currentsubtitle']['name']
if name:
subs += " " + name
except:
pass
return subs
# Returns current audio stream as a speakable string
def GetCurrentAudioStream():
stream = ""
curprops = GetActivePlayProperties()
#print curprops
if curprops is not None:
try:
lang = curprops['currentaudiostream']['language']
stream = pycountry.languages.get(bibliographic=lang).name
name = curprops['currentaudiostream']['name']
if name:
stream += " " + name
except:
pass
return stream
# Returns information useful for building a progress bar to show a video's play time
def GetVideoPlayStatus():
playerid = GetPlayerID()
if playerid:
data = SendCommand(RPCString("Player.GetProperties", {"playerid":playerid, "properties":["percentage","speed","time","totaltime"]}))
if 'result' in data:
hours = data['result']['totaltime']['hours']
speed = data['result']['speed']
if hours > 0:
total = '%d:%02d:%02d' % (hours, data['result']['totaltime']['minutes'], data['result']['totaltime']['seconds'])
cur = '%d:%02d:%02d' % (data['result']['time']['hours'], data['result']['time']['minutes'], data['result']['time']['seconds'])
else:
total = '%02d:%02d' % (data['result']['totaltime']['minutes'], data['result']['totaltime']['seconds'])
cur = '%02d:%02d' % (data['result']['time']['minutes'], data['result']['time']['seconds'])
return {'state':'play' if speed > 0 else 'pause', 'time':cur, 'total':total, 'pct':data['result']['percentage']}
return {'state':'stop'}
def GetPVRChannels():
data = SendCommand(RPCString("PVR.GetChannels", {"channelgroupid":"alltv"}))
return data
def GetPVRBroadcasts(channelid):
data = SendCommand(RPCString("PVR.GetBroadcasts", {"channelid": int(channelid), "properties" : ["endtime"]}))
return data
def WatchPVRChannel(channelid):
return SendCommand(RPCString("Player.Open", {"item": {"channelid": int(channelid)}}))