-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
1277 lines (1192 loc) · 50.5 KB
/
__init__.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
from os.path import dirname
from adapt.intent import IntentBuilder
from mycroft.skills.core import MycroftSkill, intent_handler, intent_file_handler
from mycroft.util.log import getLogger
from mycroft.util.log import LOG
# from mycroft.skills.context import adds_context, removes_context
'''
also use self.remove_context(s, x)
also use self.set_context(s,x)
Note: the @adds_context / @removes_context can't be used with the Remove / set context options
'''
from mycroft.util.parse import extract_number
from mycroft.audio import wait_while_speaking
import pafy
import pychromecast
from pychromecast.controllers.youtube import YouTubeController
import urllib.error
import urllib.parse
import urllib.request
import requests
import re
import time
import json
import random
_author__ = 'PCWii'
# Release - 20181213
LOGGER = getLogger(__name__)
class KodiSkill(MycroftSkill):
"""
A Skill to control playback on a Kodi instance via the json-rpc interface.
"""
def __init__(self):
super(KodiSkill, self).__init__(name="KodiSkill")
self.kodi_path = ""
self.youtube_id = []
self.youtube_search = ""
self.kodi_payload = ""
self.cv_payload = ""
self.list_payload = ""
self.json_header = {'content-type': 'application/json'}
self.json_response = ""
self.cv_response = ""
self.list_response = ""
self._is_setup = False
self.playing_status = False
self.notifier_bool = False
self.movie_list = []
self.movie_index = 0
self.cv_request = False
self.use_cv = False
def initialize(self):
self.load_data_files(dirname(__file__))
# Check and then monitor for credential changes
#self.settings.set_changed_callback(self.on_websettings_changed)
self.settings_change_callback = self.on_websettings_changed
self.on_websettings_changed()
self.add_event('recognizer_loop:wakeword', self.handle_listen)
self.add_event('recognizer_loop:utterance', self.handle_utterance)
self.add_event('speak', self.handle_speak)
# eg. stop the movie
stop_film_intent = IntentBuilder("StopFilmIntent"). \
require("StopKeyword").one_of("FilmKeyword", "KodiKeyword", "YoutubeKeyword").build()
self.register_intent(stop_film_intent, self.handle_stop_film_intent)
# eg. stop the music
stop_music_intent = IntentBuilder("StopMusicIntent"). \
require("StopKeyword").one_of("MusicKeyword", "KodiKeyword", "YoutubeKeyword").build()
self.register_intent(stop_music_intent, self.handle_stop_music_intent)
# eg. pause the movie
pause_film_intent = IntentBuilder("PauseFilmIntent"). \
require("PauseKeyword").one_of("FilmKeyword", "KodiKeyword").build()
self.register_intent(pause_film_intent, self.handle_pause_film_intent)
# eg. resume the movie
resume_film_intent = IntentBuilder("ResumeFilmIntent"). \
require("ResumeKeyword").require("FilmKeyword").build()
self.register_intent(resume_film_intent, self.handle_resume_film_intent)
# eg. turn kodi notifications on
notification_on_intent = IntentBuilder("NotifyOnIntent"). \
require("NotificationKeyword").require("OnKeyword"). \
require("KodiKeyword").build()
self.register_intent(notification_on_intent, self.handle_notification_on_intent)
# eg. turn kodi notifications off
notification_off_intent = IntentBuilder("NotifyOffIntent"). \
require("NotificationKeyword").require("OffKeyword"). \
require("KodiKeyword").build()
self.register_intent(notification_off_intent, self.handle_notification_off_intent)
def on_websettings_changed(self): # called when updating mycroft home page
# if not self._is_setup:
LOG.info('Websettings have changed! Updating path data')
kodi_ip = self.settings.get("kodi_ip", "192.168.0.32")
kodi_port = self.settings.get("kodi_port", "8080")
kodi_user = self.settings.get("kodi_user", "")
kodi_pass = self.settings.get("kodi_pass", "")
try:
if kodi_ip and kodi_port:
kodi_ip = self.settings["kodi_ip" ]
kodi_port = self.settings["kodi_port"]
kodi_user = self.settings["kodi_user"]
kodi_pass = self.settings["kodi_pass"]
self.kodi_path = "http://" + kodi_user + ":" + kodi_pass + "@" + kodi_ip + ":" + str(kodi_port) + \
"/jsonrpc"
LOG.info(self.kodi_path)
self._is_setup = True
except Exception as e:
LOG.error(e)
def numeric_replace(self, in_words=""):
word_list = in_words.split()
return_list = []
for each_word in word_list:
try:
new_word = w2n.word_to_num(each_word)
except Exception as e:
# print(e)
new_word = each_word
return_list.append(new_word)
return_string = ' '.join(str(e) for e in return_list)
return return_string
# find the movies in the library that match the optional search criteria
def find_movies_with_filter(self, title=""):
title = self.numeric_replace(title)
found_list = [] # this is a dict
movie_list = self.list_all_movies()
title_list = title.replace("-", "").lower().split()
for each_movie in movie_list:
movie_name = each_movie["label"].replace("-", "")
movie_name = self.numeric_replace(movie_name)
LOG.info(movie_name)
if all(words in movie_name.lower() for words in title_list):
LOG.info("Found " + movie_name + " : " + "MovieID: " + str(each_movie["movieid"]))
info = {
"label": each_movie['label'],
"movieid": each_movie['movieid']
}
found_list.append(info)
temp_list = [] # this is a dict
for each_movie in found_list:
movie_title = str(each_movie['label'])
info = {
"label": each_movie['label'],
"movieid": each_movie['movieid']
}
if movie_title not in str(temp_list):
temp_list.append(info)
else:
if len(each_movie['label']) == len(movie_title):
LOG.info('found duplicate')
else:
temp_list.append(info)
found_list = temp_list
return found_list # returns a dictionary of matched movies
# check if kodi is currently playing, required for some functions
def is_kodi_playing(self):
method = "Player.GetActivePlayers"
self.kodi_payload = {
"jsonrpc": "2.0",
"method": method,
"id": 1
}
try:
kodi_response = requests.post(self.kodi_path, data=json.dumps(self.kodi_payload), headers=self.json_header)
LOG.info(kodi_response.text)
parse_response = json.loads(kodi_response.text)["result"]
if not parse_response:
self.playing_status = False
else:
self.playing_status = True
except Exception as e:
LOG.error(e)
LOG.info("Is Kodi Playing?...", str(self.playing_status))
return self.playing_status
def list_all_movies(self):
method = "VideoLibrary.GetMovies"
self.kodi_payload = {
"jsonrpc": "2.0",
"method": method,
"id": 1,
"params": {
"properties": [
],
}
}
try:
kodi_response = requests.post(self.kodi_path, data=json.dumps(self.kodi_payload), headers=self.json_header)
LOG.info(kodi_response.text)
movie_list = json.loads(kodi_response.text)["result"]["movies"]
return movie_list
except Exception as e:
LOG.info(e)
return "NONE"
# activate the kodi root menu system
def show_root(self):
method = "GUI.ActivateWindow"
self.kodi_payload = {
"jsonrpc": "2.0",
"method": method,
"params": {
"window": "videos",
"parameters": [
"library://video/"
]
},
"id": "1"
}
try:
kodi_response = requests.post(self.kodi_path, data=json.dumps(self.kodi_payload), headers=self.json_header)
LOG.info(kodi_response.text)
except Exception as e:
LOG.error(e)
# clear any active playlists
def clear_playlist(self):
method = "Playlist.Clear"
self.kodi_payload = {
"jsonrpc": "2.0",
"method": method,
"id": 1,
"params": {
"playlistid": 1
}
}
try:
kodi_response = requests.post(self.kodi_path, data=json.dumps(self.kodi_payload), headers=self.json_header)
LOG.info(kodi_response.text)
except Exception as e:
LOG.error(e)
# play the movie playlist with cinemavision addon, assumes the playlist is already populated
def play_cinemavision(self):
method = "Addons.ExecuteAddon"
self.cv_payload = {
"jsonrpc": "2.0",
"method": method,
"params": {
"addonid": "script.cinemavision",
"params": [
"experience", "nodialog"
]
},
"id": 1
}
try:
self.cv_response = requests.post(self.kodi_path, data=json.dumps(self.cv_payload),
headers=self.json_header)
LOG.info(self.cv_response.text)
except Exception as e:
LOG.error(e)
# play the movie playlist normally without any addons, assumes there are movies in the playlist
def play_normal(self):
method = "player.open"
self.kodi_payload = {
"jsonrpc": "2.0",
"method": method,
"params": {
"item": {
"playlistid": 1
}
},
"id": 1
}
try:
self.json_response = requests.post(self.kodi_path, data=json.dumps(self.kodi_payload),
headers=self.json_header)
LOG.info(self.json_response.text)
except Exception as e:
LOG.error(e)
# add the movieid to the active playlist movieid is an integer
def add_playlist(self, movieid):
method = "Playlist.Add"
self.kodi_payload = {
"jsonrpc": "2.0",
"id": 1,
"method": method,
"params": {
"playlistid": 1,
"item": {
"movieid": movieid
}
}
}
try:
kodi_response = requests.post(self.kodi_path, data=json.dumps(self.kodi_payload), headers=self.json_header)
LOG.info(kodi_response.text)
except Exception as e:
LOG.error(e)
# pause any playing movie not youtube
def pause_movie(self):
method = "Player.PlayPause"
self.kodi_payload = {
"jsonrpc": "2.0",
"method": method,
"params": {
"playerid": 1,
"play": False},
"id": 1
}
try:
kodi_response = requests.post(self.kodi_path, data=json.dumps(self.kodi_payload), headers=self.json_header)
LOG.info(kodi_response.text)
except Exception as e:
LOG.error(e)
# resume any paused movies not youtube
def resume_movie(self):
method = "Player.PlayPause"
self.kodi_payload = {
"jsonrpc": "2.0",
"method": method,
"params": {
"playerid": 1,
"play": True},
"id": 1
}
try:
kodi_response = requests.post(self.kodi_path, data=json.dumps(self.kodi_payload), headers=self.json_header)
LOG.info(kodi_response.text)
except Exception as e:
LOG.error(e)
# check if the youtube addon exists
def check_youtube_present(self):
method = "Addons.GetAddons"
addon_video = "xbmc.addon.video"
self.kodi_payload = {
"jsonrpc": "2.0",
"method": method,
"id": "1",
"params": {
"type": addon_video
}
}
try:
kodi_response = requests.post(self.kodi_path, data=json.dumps(self.kodi_payload), headers=self.json_header)
except Exception as e:
LOG.info(e)
return False
if "plugin.video.youtube" in kodi_response.text:
return True
else:
return False
# check if the cinemavision addon exists
def check_cinemavision_present(self):
self.list_payload = {
"jsonrpc": "2.0",
"method": "Addons.GetAddons",
"params": {
"type": "xbmc.addon.executable"
},
"id": "1"
}
try:
self.list_response = requests.post(self.kodi_path, data=json.dumps(self.list_payload), headers=self.json_header)
LOG.info(self.list_response.text)
except Exception as e:
LOG.info(e)
return False
if "script.cinemavision" in self.list_response.text:
return True
else:
return False
# use regex to find any movie names found in the utterance
def movie_regex(self, message):
film_regex = r"((movie|film) (?P<Film1>.*))| ((movie|film) (?P<Film2>.*)(with|using) (cinemavision))"
utt_str = message
film_matches = re.finditer(film_regex, utt_str, re.MULTILINE | re.DOTALL)
for film_match_num, film_match in enumerate(film_matches):
group_id = "Film1"
my_movie = "{group}".format(group=film_match.group(group_id))
self.cv_request = False
if my_movie == "None":
group_id = "Film2"
my_movie = "{group}".format(group=film_match.group(group_id))
self.cv_request = True
LOG.info(my_movie)
my_movie = re.sub('\W', ' ', my_movie)
my_movie = re.sub(' +', ' ', my_movie)
return my_movie.strip()
# check the cursor control utterance for repeat commands
def repeat_regex(self, message):
value = extract_number(message)
if value:
repeat_value = value
elif "once" in message:
repeat_value = 1
elif "twice" in message:
repeat_value = 2
else:
repeat_value = 1
return repeat_value
# send a URI to Chromecast and play
def cast_link(self, source_link, device_ip):
cast = pychromecast.Chromecast(device_ip)
cast.wait()
mc = cast.media_controller
LOG.info(source_link)
mc.play_media(source_link, 'video/mp4')
time.sleep(7) #wait for CC to be ready to play
mc.block_until_active()
mc.play()
#mc.stop()
# send a youtube videoID and play
def cast_youtube(self, video_id, device_ip):
cast = pychromecast.Chromecast(device_ip)
cast.wait()
yt = YouTubeController()
cast.register_handler(yt)
yt.play_video(video_id)
# return the id of a movie from the kodi library based on its name
def get_kodi_movie_id(self, movie_name):
found_list = self.find_movies_with_filter(movie_name)
my_id = found_list[0]["movieid"]
return my_id
# returns the full URI of a movie from the kodi library
def get_kodi_movie_path(self, movie_name):
movie_id = self.get_kodi_movie_id(movie_name)
method = "VideoLibrary.GetMovieDetails"
kodi_payload = {
"jsonrpc": "2.0",
"method": method,
"id": 1,
"params": {"movieid": movie_id,
"properties": [
# "art",
# "cast",
# "dateadded",
# "director",
# "fanart",
"file",
# "genre",
# "imdbnumber",
# "lastplayed",
# "mpaa",
# "originaltitle",
# "playcount",
# "plot",
# "plotoutline",
# "premiered",
# "rating",
# "runtime",
# "resume",
# "setid",
# "sorttitle",
# "streamdetails",
# "studio",
# "tagline",
# "thumbnail",
# "title",
# "trailer",
# "userrating",
# "votes",
# "writer"
],
}
}
try:
kodi_response = requests.post(self.kodi_path, data=json.dumps(self.kodi_payload), headers=self.json_header)
movie_path = json.loads(kodi_response.text)["result"]["moviedetails"]["file"]
base_path = 'http://' + self.kodi_ip + ':' + self.kodi_port + '/vfs/'
url_path = base_path + urllib.parse.quote(movie_path, safe='')
LOG.info('Found Kodi Movie Path ' + url_path)
return url_path
except Exception as e:
print(e)
return "NONE"
# play the supplied video_id with the youtube addon
def play_youtube_video(self, video_id):
LOG.info('play youtube ID: ' + str(video_id))
method = "Player.Open"
# Playlist links are longer than individual links
# individual links are 11 characters long
if len(video_id) > 11:
yt_link = "plugin://plugin.video.youtube/play/?playlist_id=" + video_id + "&play=1&order=shuffle"
else:
yt_link = "plugin://plugin.video.youtube/play/?video_id=" + video_id
self.kodi_payload = {
"jsonrpc": "2.0",
"params": {
"item": {
"file": yt_link
}
},
"method": method,
"id": "libPlayer"
}
LOG.info(yt_link)
try:
kodi_response = requests.post(self.kodi_path, data=json.dumps(self.kodi_payload), headers=self.json_header)
LOG.info(kodi_response.text)
except Exception as e:
LOG.error(e)
def get_yt_audio_url(self, youtube_url):
base_url = 'https://www.youtube.com'
abs_url = base_url + youtube_url
LOG.debug('pafy processing: ' + abs_url)
streams = pafy.new(abs_url)
LOG.debug('audiostreams found: ' + str(streams.audiostreams));
bestaudio = streams.getbestaudio()
LOG.debug('audiostream selected: ' + str(bestaudio));
return bestaudio.url
# stop any playing movie not youtube
def stop_movie(self):
method = "Player.Stop"
self.kodi_payload = {
"jsonrpc": "2.0",
"method": method,
"params": {
"playerid": 1
},
"id": 1
}
try:
kodi_response = requests.post(self.kodi_path, data=json.dumps(self.kodi_payload), headers=self.json_header)
LOG.info(kodi_response.text)
except Exception as e:
LOG.error(e)
# stop any playing music not youtube
def stop_music(self):
method = "Player.Stop"
self.kodi_payload = {
"jsonrpc": "2.0",
"method": "Player.Stop",
"params": {
"playerid": 0
},
"id": 1
}
try:
kodi_response = requests.post(self.kodi_path, data=json.dumps(self.kodi_payload), headers=self.json_header)
LOG.info(kodi_response.text)
except Exception as e:
LOG.error(e)
# extract the requested youtube item from the utterance
def youtube_query_regex(self, req_string):
return_list = []
pri_regex = re.search(r'play (?P<item1>.*) from youtube', req_string)
sec_regex = re.search(r'play some (?P<item1>.*) from youtube|play the (?P<item2>.*)from youtube', req_string)
if pri_regex:
if sec_regex: # more items requested
temp_results = sec_regex
else: # single item requested
temp_results = pri_regex
if temp_results:
item_result = temp_results.group(temp_results.lastgroup)
return_list = item_result
LOG.info(return_list)
return return_list
# extract the youtube links from the provided search_list
def get_youtube_links(self, search_list):
# search_text = str(search_list[0])
search_text = str(search_list)
query = urllib.parse.quote(search_text)
url = "https://www.youtube.com/results?search_query=" + query
response = urllib.request.urlopen(url)
html = response.read()
# Get all video links from page
temp_links = []
all_video_links = re.findall(r'href=\"\/watch\?v=(.{11})', html.decode())
for each_video in all_video_links:
if each_video not in temp_links:
temp_links.append(each_video)
video_links = temp_links
# Get all playlist links from page
temp_links = []
all_playlist_results = re.findall(r'href=\"\/playlist\?list\=(.{34})', html.decode())
sep = '"'
for each_playlist in all_playlist_results:
if each_playlist not in temp_links:
cleaned_pl = each_playlist.split(sep, 1)[0] # clean up dirty playlists
temp_links.append(cleaned_pl)
playlist_links = temp_links
yt_links = []
if video_links:
yt_links.append(video_links[0])
LOG.info("Found Single Links: " + str(video_links))
if playlist_links:
yt_links.append(playlist_links[0])
LOG.info("Found Playlist Links: " + str(playlist_links))
return yt_links
# push a message to the kodi notification popup
def post_kodi_notification(self, message):
method = "GUI.ShowNotification"
display_timeout = 5000
self.kodi_payload = {
"jsonrpc": "2.0",
"method": method,
"params": {
"title": "Kelsey.AI",
"message": str(message),
"displaytime": display_timeout,
},
"id": 1
}
try:
kodi_response = requests.post(self.kodi_path, data=json.dumps(self.kodi_payload), headers=self.json_header)
LOG.info(kodi_response.text)
except Exception as e:
LOG.error(e)
# listening event used for kodi notifications
def handle_listen(self, message):
voice_payload = "Listening"
if self.notifier_bool:
try:
self.post_kodi_notification(voice_payload)
except Exception as e:
LOG.error(e)
self.on_websettings_changed()
# utterance event used for kodi notifications
def handle_utterance(self, message):
utterance = message.data.get('utterances')
voice_payload = utterance
if self.notifier_bool:
try:
self.post_kodi_notification(voice_payload)
except Exception as e:
LOG.error(e)
self.on_websettings_changed()
# mycroft speaking event used for kodi notificatons
def handle_speak(self, message):
voice_payload = message.data.get('utterance')
if self.notifier_bool:
try:
self.post_kodi_notification(voice_payload)
except Exception as e:
LOG.error(e)
self.on_websettings_changed()
# Primary Play Movie request
@intent_handler(IntentBuilder('PlayFilmIntent').require("AskKeyword").require("KodiKeyword").
require("PlayKeyword").require("FilmKeyword").
optionally("CinemaVisionKeyword").optionally('RandomKeyword').build())
def handle_play_film_intent(self, message):
LOG.info("Called Play Film Intent")
if message.data.get("CinemaVisionKeyword"):
self.cv_request = True
else:
self.cv_request = False
if message.data.get("RandomKeyword"):
self.handle_random_movie_select_intent()
else:
# Proceed normally
movie_name = self.movie_regex(message.data.get('utterance'))
try:
LOG.info("movie: " + movie_name)
self.speak_dialog("please.wait")
results = self.find_movies_with_filter(movie_name)
self.movie_list = results
self.movie_index = 0
LOG.info("possible movies are: " + str(results))
######
if len(results) == 1:
self.play_film(results[0]['movieid'])
elif len(results):
self.set_context('NavigateContextKeyword', 'NavigateContext')
self.speak_dialog('multiple.results', data={"result": str(len(results))}, expect_response=True)
else:
self.speak_dialog('no.results', data={"result": movie_name}, expect_response=False)
#####
except Exception as e:
LOG.info('an error was detected')
LOG.error(e)
self.on_websettings_changed()
# stop film was requested in the utterance
def handle_stop_film_intent(self, message):
try:
self.stop_movie()
except Exception as e:
LOG.error(e)
self.on_websettings_changed()
# stop music was requested in the utterance
def handle_stop_music_intent(self, message):
try:
self.stop_music()
except Exception as e:
LOG.error(e)
self.on_websettings_changed()
# pause film was requested in the utterance
def handle_pause_film_intent(self, message):
try:
self.pause_movie()
except Exception as e:
LOG.error(e)
self.on_websettings_changed()
# resume the film was requested in the utterance
def handle_resume_film_intent(self, message):
try:
self.resume_movie()
except Exception as e:
LOG.error(e)
self.on_websettings_changed()
# turn notifications on requested in the utterance
def handle_notification_on_intent(self, message):
self.notifier_bool = True
self.speak_dialog("notification", data={"result": "On"})
# turn notifications off requested in the utterance
def handle_notification_off_intent(self, message):
self.notifier_bool = False
self.speak_dialog("notification", data={"result": "Off"})
# move cursor utterance processing
@intent_handler(IntentBuilder('MoveCursorIntent').require('MoveKeyword').require('CursorKeyword').
one_of('UpKeyword', 'DownKeyword', 'LeftKeyword', 'RightKeyword', 'EnterKeyword',
'SelectKeyword', 'BackKeyword').build())
def handle_move_cursor_intent(self, message): # a request was made to move the kodi cursor
self.set_context('MoveKeyword', 'move') # in future the user does not have to say the move keyword
self.set_context('CursorKeyword', 'cursor') # in future the user does not have to say the cursor keyword
if "UpKeyword" in message.data:
direction_kw = "Up" # these english words are required by the kodi api
if "DownKeyword" in message.data:
direction_kw = "Down" # these english words are required by the kodi api
if "LeftKeyword" in message.data:
direction_kw = "Left" # these english words are required by the kodi api
if "RightKeyword" in message.data:
direction_kw = "Right" # these english words are required by the kodi api
if "EnterKeyword" in message.data:
direction_kw = "Enter" # these english words are required by the kodi api
if "SelectKeyword" in message.data:
direction_kw = "Select" # these english words are required by the kodi api
if "BackKeyword" in message.data:
direction_kw = "Back" # these english words are required by the kodi api
repeat_count = self.repeat_regex(message.data.get('utterance'))
LOG.info('utterance: ' + str(message.data.get('utterance')))
LOG.info('repeat_count: ' + str(repeat_count))
if direction_kw:
method = "Input." + direction_kw
for each_count in range(0, int(repeat_count)):
self.kodi_payload = {
"jsonrpc": "2.0",
"method": method,
"id": 1
}
try:
kodi_response = requests.post(self.kodi_path, data=json.dumps(self.kodi_payload),
headers=self.json_header)
LOG.info(kodi_response.text)
except Exception as e:
LOG.error(e)
self.on_websettings_changed()
self.speak_dialog("direction", data={"result": direction_kw},
expect_response=True)
time.sleep(1)
# play the movie based on movie ID
def play_film(self, movieid):
self.clear_playlist()
self.add_playlist(movieid)
if self.check_cinemavision_present(): # Cinemavision is installed
self.set_context('CinemaVisionContextKeyword', 'CinemaVisionContext')
self.speak_dialog('cinema.vision', expect_response=True)
else: # Cinemavision is NOT installed
self.play_normal()
# execute cinemavision addon decision
@intent_handler(IntentBuilder('CinemavisionRequestIntent').require('CinemaVisionContextKeyword')
.one_of('YesKeyword', 'NoKeyword').build())
def handle_cinemavision_request_intent(self, message):
self.set_context('CinemaVisionContextKeyword', '')
if "YesKeyword" in message.data: # Yes was spoken to navigate the list
LOG.info('User responded with: ' + message.data.get("YesKeyword"))
self.play_cinemavision()
else: # No was spoken to navigate the list
LOG.info('User responded with: ' + message.data.get("NoKeyword"))
self.play_normal()
# movie list navigation decision utterance
@intent_handler(IntentBuilder('NavigateDecisionIntent').require('NavigateContextKeyword').
one_of('YesKeyword', 'NoKeyword').build())
def handle_navigate_Decision_intent(self, message):
self.set_context('NavigateContextKeyword', '')
if "YesKeyword" in message.data: # Yes was spoken to navigate the list, reading the first item
LOG.info('User responded with...' + message.data.get('YesKeyword'))
self.set_context('ListContextKeyword', 'ListContext')
msg_payload = str(self.movie_list[self.movie_index]['label'])
self.speak_dialog('navigate', data={"result": msg_payload}, expect_response=True)
else: # No was spoken to navigate the list, reading the first item
LOG.info('User responded with...' + message.data.get('NoKeyword'))
self.speak_dialog('cancel', expect_response=False)
# the currently listed move was selected to play
@intent_handler(IntentBuilder('NavigatePlayIntent').require('ListContextKeyword').require("PlayKeyword").
build())
def handle_navigate_play_intent(self, message):
self.set_context('ListContextKeyword', '')
msg_payload = str(self.movie_list[self.movie_index]['label'])
self.speak_dialog('play.film', data={"result": msg_payload}, expect_response=False)
try:
self.play_film(self.movie_list[self.movie_index]['movieid'])
except Exception as e:
LOG.error(e)
self.on_websettings_changed()
# the user has requested to skip the currently listed movie
@intent_handler(IntentBuilder('ParseNextIntent').require('ListContextKeyword').require('NextKeyword').
build())
def handle_parse_next_intent(self, message):
self.set_context('ListContextKeyword', 'ListContext')
self.movie_index += 1
if self.movie_index < len(self.movie_list):
msg_payload = str(self.movie_list[self.movie_index]['label'])
self.speak_dialog('context', data={"result": msg_payload}, expect_response=True)
else:
self.set_context('ListContextKeyword', '')
self.speak_dialog('list.end', expect_response=False)
# the user has requested to stop navigating the list
@intent_handler(IntentBuilder('NavigateStopIntent').require('NavigateContextKeyword').require('StopKeyword').
build())
def handle_navigate_stop_intent(self, message):
self.set_context('NavigateContextKeyword', '')
self.speak_dialog('cancel', expect_response=False)
# the user has requested to stop parsing the list
@intent_handler(IntentBuilder('ParseCancelIntent').require('ListContextKeyword').require('StopKeyword').
build())
def handle_parse_cancel_intent(self, message):
self.set_context('ListContextKeyword', '')
self.speak_dialog('cancel', expect_response=False)
# Cancel was spoken, Cancel the list navigation
@intent_handler(IntentBuilder('CursorCancelIntent').require('MoveKeyword').require('CursorKeyword').
require('StopKeyword').build())
def handle_cursor_cancel_intent(self, message):
self.set_context('MoveKeyword', '')
self.set_context('CursorKeyword', '')
LOG.info('handle_cursor_cancel_intent')
self.speak_dialog('cancel', expect_response=False)
# An internal conversational context stoppage was issued
def stop_navigation(self, message):
self.speak_dialog('context', data={"result": message}, expect_response=False)
# the movie information dialog was requested in the utterance
@intent_handler(IntentBuilder('SetVolumeIntent').require('SetsKeyword').require('KodiKeyword').
require('VolumeKeyword').build())
def handle_set_volume_intent(self, message):
str_remainder = str(message.utterance_remainder())
volume_level = re.findall('\d+', str_remainder)
if volume_level:
if int(volume_level[0]) < 101:
new_volume = self.set_volume(int(volume_level[0]))
LOG.info("Kodi Volume Now: " + str(new_volume))
self.speak_dialog('volume.set', data={'result': str(new_volume)}, expect_response=False)
else:
self.speak_dialog('volume.error', data={'result': int(volume_level[0])}, expect_response=False)
def set_volume(self, level):
method = "Application.SetVolume"
self.kodi_payload = {
"jsonrpc": "2.0",
"method": method,
"params": {
"volume": level
},
"id": 1
}
try:
kodi_response = requests.post(self.kodi_path, data=json.dumps(self.kodi_payload), headers=self.json_header)
LOG.info(kodi_response.text)
return json.loads(kodi_response.text)["result"]
# return level
except Exception as e:
return e
# the movie information dialog was requested in the utterance
@intent_handler(IntentBuilder('ShowMovieInfoIntent').require('VisibilityKeyword').require('InfoKeyword').
optionally('KodiKeyword').optionally('FilmKeyword').
build())
def handle_show_movie_info_intent(self, message):
method = "Input.Info"
self.kodi_payload = {
"jsonrpc": "2.0",
"method": method,
"id": 1
}
try:
kodi_response = requests.post(self.kodi_path, data=json.dumps(self.kodi_payload), headers=self.json_header)
LOG.info(kodi_response.text)
except Exception as e:
LOG.error(e)
# the user requested to skip the movie timeline forward or backward
@intent_handler(IntentBuilder('SkipMovieIntent').require("NextKeyword").require('FilmKeyword').
one_of('ForwardKeyword', 'BackwardKeyword').
build())
def handle_skip_movie_intent(self, message):
method = "Player.Seek"
backward_kw = message.data.get("BackwardKeyword")
if backward_kw:
dir_skip = "smallbackward"
else:
dir_skip = "smallforward"
self.kodi_payload = {
"jsonrpc": "2.0",
"method": method,
"params": {
"playerid": 1,
"value": dir_skip
},
"id": 1
}
if self.is_kodi_playing():
try:
kodi_response = requests.post(self.kodi_path, data=json.dumps(self.kodi_payload),
headers=self.json_header)
LOG.info(kodi_response.text)
except Exception as e:
LOG.error(e)
else:
LOG.info("There is no movie playing to skip")
# user has requested to turn on the movie subtitles
@intent_handler(IntentBuilder('SubtitlesOnIntent').require("KodiKeyword").require('SubtitlesKeyword').
require('OnKeyword').
build())
def handle_subtitles_on_intent(self, message):
method = "Player.SetSubtitle"
self.kodi_payload = {
"jsonrpc": "2.0",
"id": 1,
"method": method,
"params": {
"playerid": 1,
"subtitle": "on"
}
}
if self.is_kodi_playing():
try:
kodi_response = requests.post(self.kodi_path, data=json.dumps(self.kodi_payload),
headers=self.json_header)
LOG.info(kodi_response)
except Exception as e:
LOG.error(e)
else:
LOG.info("Turning Subtitles On Failed, kodi not playing")
# user has requested to turn off the movie subtitles
@intent_handler(IntentBuilder('SubtitlesOffIntent').require("KodiKeyword").require('SubtitlesKeyword').
require('OffKeyword').
build())
def handle_subtitles_off_intent(self, message):
method = "Player.SetSubtitle"
self.kodi_payload = {
"jsonrpc": "2.0",
"id": 1,
"method": method,
"params": {
"playerid": 1,
"subtitle": "off"
}
}
if self.is_kodi_playing():
try:
kodi_response = requests.post(self.kodi_path, data=json.dumps(self.kodi_payload),
headers=self.json_header)