forked from ndg63276/alexa-youtube
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlambda_function.py
759 lines (706 loc) · 28.2 KB
/
lambda_function.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
# -*- coding: utf-8 -*-
from __future__ import print_function
from os import environ
from googleapiclient.discovery import build
from pytube import YouTube
import logging
from random import shuffle, randint
from botocore.vendored import requests
import json
import urllib
from time import time
logging.getLogger('googleapiclient.discovery_cache').setLevel(logging.ERROR)
logger = logging.getLogger()
logger.setLevel(logging.INFO)
DEVELOPER_KEY=environ['DEVELOPER_KEY']
YOUTUBE_API_SERVICE_NAME = 'youtube'
YOUTUBE_API_VERSION = 'v3'
strings_en = {
'welcome1':"Welcome to Youtube. Say, for example, play videos by The Beatles.",
'welcome2':"Or you can say, shuffle songs by Michael Jackson.",
'help':"For example say, play videos by Fall Out Boy",
'illegal':"You can't do that with this skill.",
'gonewrong':"Sorry, something's gone wrong",
'playlist':"The playlist",
'channel':"The channel",
'video':"The video",
'notworked':"hasn't worked, shall I try the next one?",
'playing':"Playing",
'pausing':"Pausing",
'nomoreitems':"There are no more items in the playlist.",
'resuming':"Resuming",
'noresume':"I wasn't able to resume playing.",
'novideo':"I wasn't able to play a video.",
'notitle':"I can't find out the name of the current video.",
'nowplaying':"Now playing",
'nothingplaying':"Nothing is currently playing.",
'sorryskipby':"Sorry, I didn't hear how much to skip by",
'sorryskipto':"Sorry, I didn't hear where to skip to",
'ok':"OK"
}
strings_fr = {
'welcome1':"Bienvenue sur Youtube. Dite, par exemple, jouer une vidéo de Madonna.",
'welcome2':"Ou vous pouvez dire, chanson aléatoire de Michael Jackson.",
'help':"Par exemple dite, joue une vidéo de Michael Jackson",
'illegal':"Vous ne pouvez pas faire ça avec cette skill.",
'gonewrong':"Désolé, quelque chose n'a pas fonctionné",
'playlist':"La playlist",
'channel':"La chaîne",
'video':"The vidéo",
'notworked':"ne fonctionne pas, dois je essayer la suivante ?",
'playing':"Lecture de",
'pausing':"En pause",
'nomoreitems':"Il n'y a plus rien à lire dans cette playlist.",
'resuming':"Reprise",
'noresume':"Je n'ai pas pu reprendre la lecture.",
'novideo':"Je ne peux pas lire la vidéo.",
'notitle':"Je ne retrouve pas le nom de cette vidéo.",
'nowplaying':"Vous écoutez ",
'nothingplaying':"Il n'y a aucune lecture en cours.",
'sorryskipby':"Désolé, je n'ai pas compris de combien je devais avancer ou reculer.",
'sorryskipto':"Désolé, je n'ai pas compris de combien je devais avancer ou reculer.",
'ok':"OK"
}
strings_it = {
'welcome1':"Benvenuto su YouTube. Dici, per esempio, riproduci i video dei Beatles.",
'welcome2':"Oppure puoi dire, canzoni casuali di Michael Jackson.",
'help':"Per esempio dici, riproduci i videi dei Fall out Boy",
'illegal':"Non puoi fare questo con questa skill.",
'gonewrong':"Spiacente, qualcosa è andato storto",
'playlist':"La playlist",
'channel':"Il canale",
'video':"Il video",
'notworked':"non ha funzionato, dovrei provare la prossima?",
'playing':"Riproduco",
'pausing':"Ciao da Youtube",
'nomoreitems':"Non ci sono più elementi nella playlist.",
'resuming':"Riprendo",
'noresume':"Non ero in grado di riprendere la riproduzione.",
'novideo':"Non ero in grado di riprodurre un video",
'notitle':"Non riesco a trovare il nome del video corrente.",
'nowplaying':"Ora riproduco",
'nothingplaying':"Al momento non sto riproducendo nulla.",
'sorryskipby':"Spiacente, non ho capito di quanto saltare",
'sorryskipto':"Spiacente, non ho capito dove saltare",
'ok':"OK"
}
strings_de = {
'welcome1':"Willkommen bei Youtube. Sagen Sie zum Beispiel, spiel Videos von The Beatles.",
'welcome2':"Oder Sie können sagen, misch Songs von Michael Jackson.",
'help':"Sie können sagen zum Beispiel, spiel Videos von Fall Out Boy ab.",
'illegal':"Sie können dies mit dieses Skill nicht tun.",
'gonewrong':"Es tut mir Leid, etwas ist schief gelaufen",
'playlist':"Die Wiedergabeliste",
'channel':"Der Kanal",
'video':"Das Video",
'notworked':"hat nicht funktioniert, soll ich das nächste versuchen?",
'playing':"Spielen",
'pausing':"Pausieren",
'nomoreitems':"Die Wiedergabeliste enthält keine weiteren Elemente.",
'resuming':"Fortfahren",
'noresume':"Ich konnte nicht weiter spielen.",
'novideo':"Ich konnte dieses Video nicht abspielen.",
'notitle':"Ich kann den Namen des aktuellen Videos nicht herausfinden.",
'nowplaying':"Jetzt spielt",
'nothingplaying':"Es wird momentan nichts abgespielt.",
'sorryskipby':"Entschuldigung, ich habe nicht gehört, wie viel ich überspringen soll",
'sorryskipto':"Entschuldigung, ich habe nicht gehört, wo ich überspringen soll",
'ok':"OK"
}
strings_es = {
'welcome1':"Bienvenido a Youtube. Di, por ejemplo, pon videos de los Beatles.",
'welcome2':"O puedes decir, aleatorio canciones de Michael Jackson.",
'help':"por ejemplo di, pon videos de Fall Out Boy",
'illegal':"Tu no puedes hacer esto con esta skill .",
'gonewrong':"Lo sentimos, ocurrio un error",
'playlist':"la playlist",
'channel':"el canal",
'video':"el video",
'notworked':"no ha funcionado desea la siguiente?",
'playing':"sonando",
'pausing':"para",
'nomoreitems':"No hay items en la playlist",
'resuming':"resumiendo",
'noresume':"No hay resumen del video",
'novideo':"No se puede reproducir el video",
'notitle':"No puedo encontrar el titulo del video",
'nowplaying':"ahora sonando",
'nothingplaying':"Nada esta sonando",
'sorryskipby':"Lo siento no escuche cuando adelantar",
'sorryskipto':"Lo siento no escuche a donde adelantar",
'ok':"OK"
}
strings = strings_en
# --------------- Helpers that build all of the responses ----------------------
def build_speechlet_response(title, output, reprompt_text, should_end_session):
return {
'outputSpeech': {
'type': 'PlainText',
'text': output
},
'card': {
'type': 'Simple',
'title': title,
'content': output
},
'reprompt': {
'outputSpeech': {
'type': 'PlainText',
'text': reprompt_text
}
},
'shouldEndSession': should_end_session
}
def build_cardless_speechlet_response(output, reprompt_text, should_end_session):
return {
'outputSpeech': {
'type': 'PlainText',
'text': output
},
'reprompt': {
'outputSpeech': {
'type': 'PlainText',
'text': reprompt_text
}
},
'shouldEndSession': should_end_session
}
def build_audio_speechlet_response(title, output, should_end_session, url, token, offsetInMilliseconds=0):
return {
'outputSpeech': {
'type': 'PlainText',
'text': output
},
'card': {
'type': 'Simple',
'title': title,
'content': output
},
'directives': [{
'type': 'AudioPlayer.Play',
'playBehavior': 'REPLACE_ALL',
'audioItem': {
'stream': {
'token': str(token),
'url': url,
'offsetInMilliseconds': offsetInMilliseconds
}
}
}],
'shouldEndSession': should_end_session
}
def build_cardless_audio_speechlet_response(output, should_end_session, url, token, offsetInMilliseconds=0):
return {
'outputSpeech': {
'type': 'PlainText',
'text': output
},
'directives': [{
'type': 'AudioPlayer.Play',
'playBehavior': 'REPLACE_ALL',
'audioItem': {
'stream': {
'token': str(token),
'url': url,
'offsetInMilliseconds': offsetInMilliseconds
}
}
}],
'shouldEndSession': should_end_session
}
def build_audio_enqueue_response(should_end_session, url, previous_token, next_token, playBehavior='ENQUEUE'):
to_return = {
'directives': [{
'type': 'AudioPlayer.Play',
'playBehavior': playBehavior,
'audioItem': {
'stream': {
'token': str(next_token),
'url': url,
'offsetInMilliseconds': 0
}
}
}],
'shouldEndSession': should_end_session
}
if playBehavior == 'ENQUEUE':
to_return['directives'][0]['audioItem']['stream']['expectedPreviousToken'] = str(previous_token)
return to_return
def build_cancel_speechlet_response(title, output, should_end_session):
return {
'outputSpeech': {
'type': 'PlainText',
'text': output
},
'card': {
'type': 'Simple',
'title': title,
'content': output
},
'directives': [{
'type': 'AudioPlayer.ClearQueue',
'clearBehavior' : "CLEAR_ALL"
}],
'shouldEndSession': should_end_session
}
def build_stop_speechlet_response(output, should_end_session):
return {
'outputSpeech': {
'type': 'PlainText',
'text': output
},
'directives': [{
'type': 'AudioPlayer.Stop'
}],
'shouldEndSession': should_end_session
}
def build_short_speechlet_response(output, should_end_session):
return {
'outputSpeech': {
'type': 'PlainText',
'text': output
},
'shouldEndSession': should_end_session
}
def build_response(speechlet_response, sessionAttributes={}):
return {
'version': '1.0',
'sessionAttributes': sessionAttributes,
'response': speechlet_response
}
# --------------- Main handler ------------------
def lambda_handler(event, context):
global strings
if event['request']['locale'][0:2] == 'fr':
strings = strings_fr
elif event['request']['locale'][0:2] == 'it':
strings = strings_it
elif event['request']['locale'][0:2] == 'de':
strings = strings_de
elif event['request']['locale'][0:2] == 'es':
strings = strings_es
else:
strings = strings_en
if event['request']['type'] == "LaunchRequest":
return get_welcome_response()
elif event['request']['type'] == "IntentRequest":
return on_intent(event)
elif event['request']['type'] == "SessionEndedRequest":
logger.info("on_session_ended")
elif event['request']['type'].startswith('AudioPlayer'):
return handle_playback(event)
# --------------- Events ------------------
def on_intent(event):
intent_request = event['request']
session = event['session']
intent = intent_request['intent']
intent_name = intent_request['intent']['name']
# Dispatch to your skill's intent handlers
if intent_name == "SearchIntent":
return search(intent, session)
elif intent_name == "PlaylistIntent":
return search(intent, session)
elif intent_name == "ChannelIntent":
return search(intent, session)
elif intent_name == "ShuffleIntent":
return search(intent, session)
elif intent_name == "ShufflePlaylistIntent":
return search(intent, session)
elif intent_name == "ShuffleChannelIntent":
return search(intent, session)
elif intent_name == 'SkipForwardIntent':
return skip_by(event, 1)
elif intent_name == 'SkipBackwardIntent':
return skip_by(event, -1)
elif intent_name == 'SkipToIntent':
return skip_to(event)
elif intent_name == "AMAZON.YesIntent":
return yes_intent(session)
elif intent_name == "AMAZON.NoIntent":
return do_nothing()
elif intent_name == "AMAZON.HelpIntent":
return get_help()
elif intent_name == "AMAZON.CancelIntent":
return do_nothing()
elif intent_name == "AMAZON.PreviousIntent":
return skip_action(event, -1)
elif intent_name == "AMAZON.NextIntent":
return skip_action(event, 1)
elif intent_name == "AMAZON.ShuffleOnIntent":
return change_mode(event, 's', 1)
elif intent_name == "AMAZON.ShuffleOffIntent":
return change_mode(event, 's', 0)
elif intent_name == "AMAZON.ResumeIntent":
return resume(event)
elif intent_name == "AMAZON.RepeatIntent" or intent_name == "NowPlayingIntent":
return say_video_title(event)
elif intent_name == "AMAZON.LoopOnIntent":
return change_mode(event, 'l', 1)
elif intent_name == "AMAZON.LoopOffIntent":
return change_mode(event, 'l', 0)
elif intent_name == "AMAZON.StartOverIntent":
return start_over(event)
elif intent_name == "AMAZON.StopIntent" or intent_name == "AMAZON.PauseIntent":
return stop(intent, session)
else:
raise ValueError("Invalid intent")
def handle_playback(event):
request = event['request']
if request['type'] == 'AudioPlayer.PlaybackStarted':
return started(event)
elif request['type'] == 'AudioPlayer.PlaybackFinished':
return finished(event)
elif request['type'] == 'AudioPlayer.PlaybackStopped':
return stopped(event)
elif request['type'] == 'AudioPlayer.PlaybackNearlyFinished':
return nearly_finished(event)
elif request['type'] == 'AudioPlayer.PlaybackFailed':
return failed(event)
# --------------- Functions that control the skill's behavior ------------------
def get_welcome_response():
speech_output = strings['welcome1']
reprompt_text = strings['welcome2']
should_end_session = False
return build_response(build_cardless_speechlet_response(speech_output, reprompt_text, should_end_session))
def get_help():
speech_output = strings['help']
card_title = 'Youtube Help'
should_end_session = False
return build_response(build_speechlet_response(card_title, speech_output, None, should_end_session))
def illegal_action():
speech_output = strings['illegal']
should_end_session = True
return build_response(build_short_speechlet_response(speech_output, should_end_session))
def do_nothing():
return build_response({})
def video_search(query):
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY)
search_response = youtube.search().list(
q=query,
part='id,snippet',
maxResults=50,
type='video'
).execute()
videos = []
for search_result in search_response.get('items', []):
if 'videoId' in search_result['id']:
videos.append(search_result['id']['videoId'])
return videos
def playlist_search(query, sr):
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY)
search_response = youtube.search().list(
q=query,
part='id,snippet',
maxResults=10,
type='playlist'
).execute()
playlist_id = search_response.get('items')[sr]['id']['playlistId']
logger.info('Playlist info: https://www.youtube.com/playlist?list='+playlist_id)
playlist_title = search_response.get('items')[sr]['snippet']['title']
videos = []
data={'nextPageToken':''}
while 'nextPageToken' in data and len(videos) < 25:
next_page_token = data['nextPageToken']
data = json.loads(requests.get('https://www.googleapis.com/youtube/v3/playlistItems?pageToken={}&part=snippet&playlistId={}&key={}'.format(next_page_token,playlist_id,DEVELOPER_KEY)).text)
for item in data['items']:
try:
videos.append(item['snippet']['resourceId']['videoId'])
except:
pass
return videos, playlist_title
def channel_search(query, sr):
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY)
search_response = youtube.search().list(
q=query,
part='id,snippet',
maxResults=10,
type='channel'
).execute()
playlist_id = search_response.get('items')[sr]['id']['channelId']
playlist_title = search_response.get('items')[sr]['snippet']['title']
data={'nextPageToken':''}
videos = []
while 'nextPageToken' in data and len(videos) < 25:
next_page_token = data['nextPageToken']
data = json.loads(requests.get('https://www.googleapis.com/youtube/v3/search?pageToken={}&part=snippet&channelId={}&key={}'.format(next_page_token,playlist_id,DEVELOPER_KEY)).text)
for item in data['items']:
try:
videos.append(item['id']['videoId'])
except:
pass
return videos, playlist_title
def get_url_and_title(id):
logger.info('Getting url for https://www.youtube.com/watch?v='+id)
try:
yt=YouTube('https://www.youtube.com/watch?v='+id)
first_stream = yt.streams.filter(only_audio=True, subtype='mp4').first()
logger.info(first_stream.url)
return first_stream.url, yt.title
except:
logger.info('Unable to get URL for '+id)
return get_live_video_url_and_title(id)
def get_live_video_url_and_title(id):
logger.info('Live video?')
info_url = 'https://www.youtube.com/get_video_info?&video_id='+id
r = requests.get(info_url)
info = convert_token_to_dict(r.text)
try:
raw_url = info['hlsvp']
url = urllib.unquote(raw_url)
return url, 'live video'
except:
logger.info('Unable to get hlsvp')
return None, None
def yes_intent(session):
sessionAttributes = session.get('attributes')
if not sessionAttributes or 'intent' not in sessionAttributes or 'sr' not in sessionAttributes:
return build_response(build_cardless_speechlet_response(strings['gonewrong'], None, True))
intent = sessionAttributes['intent']
session['attributes']['sr'] = sessionAttributes['sr'] + 1
return search(intent, session)
def search(intent, session):
startTime = time()
query = intent['slots']['query']['value']
should_end_session = True
logger.info('Looking for: ' + query)
intent_name = intent['name']
playlist_title = None
sessionAttributes = session.get('attributes')
if not sessionAttributes:
sessionAttributes={'sr':0, 'intent':intent}
sr = sessionAttributes['sr']
if intent_name == "PlaylistIntent" or intent_name == "ShufflePlaylistIntent":
videos, playlist_title = playlist_search(query, sr)
playlist_channel_video = strings['playlist']
elif intent_name == "ChannelIntent" or intent_name == "ShuffleChannelIntent":
videos, playlist_title = channel_search(query, sr)
playlist_channel_video = strings['channel']
else:
videos = video_search(query)
playlist_channel_video = strings['video']
next_url = None
playlist = {}
playlist['s'] = '0'
if intent_name == "ShuffleIntent" or intent_name == "ShufflePlaylistIntent" or intent_name == "ShuffleChannelIntent":
shuffle(videos)
playlist['s'] = '1'
playlist['l'] = '0'
for i,id in enumerate(videos):
if playlist_channel_video != 'video' and time() - startTime > 8:
return build_response(build_cardless_speechlet_response(playlist_channel_video+" "+playlist_title+" " + strings['notworked'], None, False), sessionAttributes)
playlist['v'+str(i)]=id
if next_url is None:
playlist['p'] = i
next_url, title = get_url_and_title(id)
next_token = convert_dict_to_token(playlist)
if playlist_title is None:
speech_output = strings['playing'] + ' ' + title
else:
speech_output = strings['playing'] + ' ' + playlist_title
card_title = "Youtube"
return build_response(build_audio_speechlet_response(card_title, speech_output, should_end_session, next_url, next_token))
def stop(intent, session):
should_end_session = True
speech_output = strings['pausing']
return build_response(build_stop_speechlet_response(speech_output, should_end_session))
def nearly_finished(event):
should_end_session = True
current_token = event['request']['token']
skip = 1
next_url, next_token, title = get_next_url_and_token(current_token, skip)
if title is None:
return do_nothing()
return build_response(build_audio_enqueue_response(should_end_session, next_url, current_token, next_token))
def skip_action(event, skip):
logger.info("event:")
logger.info(event)
logger.info("context:")
logger.info(event['context'])
should_end_session = True
current_token = event['context']['AudioPlayer']['token']
next_url, next_token, title = get_next_url_and_token(current_token, skip)
if title is None:
speech_output = strings['nomoreitems']
return build_response(build_short_speechlet_response(speech_output, should_end_session))
speech_output = strings['playing']+' '+title
return build_response(build_cardless_audio_speechlet_response(speech_output, should_end_session, next_url, next_token))
def skip_by(event, direction):
intent = event['request']['intent']
logger.info(intent)
if 'token' not in event['context']['AudioPlayer']:
speech_output = strings['nothingplaying']
return build_response(build_short_speechlet_response(speech_output, True))
if 'slots' not in intent:
speech_output = strings['sorryskipby']
return build_response(build_short_speechlet_response(speech_output, True))
if 'hours' in intent['slots'] and 'value' in intent['slots']['hours']:
try:
hours = int(intent['slots']['hours']['value'])
except:
hours = 0
else:
hours = 0
if 'minutes' in intent['slots'] and 'value' in intent['slots']['minutes']:
try:
minutes = int(intent['slots']['minutes']['value'])
except:
minutes = 0
else:
minutes = 0
if 'seconds' in intent['slots'] and 'value' in intent['slots']['seconds']:
try:
seconds = int(intent['slots']['seconds']['value'])
except:
seconds = 0
else:
seconds = 0
if hours == 0 and minutes == 0 and seconds == 0:
speech_output = strings['sorryskipby']
return build_response(build_short_speechlet_response(speech_output, True))
current_offsetInMilliseconds = event['context']['AudioPlayer']['offsetInMilliseconds']
skip_by_offsetInMilliseconds = direction * (hours * 3600000 + minutes * 60000 + seconds * 1000)
return resume(event, offsetInMilliseconds = current_offsetInMilliseconds + skip_by_offsetInMilliseconds)
def skip_to(event):
intent = event['request']['intent']
logger.info(intent)
if 'token' not in event['context']['AudioPlayer']:
speech_output = strings['nothingplaying']
return build_response(build_short_speechlet_response(speech_output, True))
if 'slots' not in intent:
speech_output = strings['sorryskipto']
return build_response(build_short_speechlet_response(speech_output, True))
if 'hours' in intent['slots'] and 'value' in intent['slots']['hours']:
try:
hours = int(intent['slots']['hours']['value'])
except:
hours = 0
else:
hours = 0
if 'minutes' in intent['slots'] and 'value' in intent['slots']['minutes']:
try:
minutes = int(intent['slots']['minutes']['value'])
except:
minutes = 0
else:
minutes = 0
if 'seconds' in intent['slots'] and 'value' in intent['slots']['seconds']:
try:
seconds = int(intent['slots']['seconds']['value'])
except:
seconds = 0
else:
seconds = 0
if hours == 0 and minutes == 0 and seconds == 0:
speech_output = strings['sorryskipto']
return build_response(build_short_speechlet_response(speech_output, True))
offsetInMilliseconds = hours * 3600000 + minutes * 60000 + seconds * 1000
return resume(event, offsetInMilliseconds = offsetInMilliseconds)
def resume(event, say_title = False, offsetInMilliseconds = None):
if 'token' not in event['context']['AudioPlayer']:
return get_welcome_response()
current_token = event['context']['AudioPlayer']['token']
should_end_session = True
speech_output = strings['ok']
if offsetInMilliseconds is None:
speech_output = strings['resuming']
offsetInMilliseconds = event['context']['AudioPlayer']['offsetInMilliseconds']
next_url, next_token, title = get_next_url_and_token(current_token, 0)
if title is None:
speech_output = strings['noresume']
return build_response(build_short_speechlet_response(speech_output, should_end_session))
return build_response(build_cardless_audio_speechlet_response(speech_output, should_end_session, next_url, current_token, offsetInMilliseconds))
def change_mode(event, mode, value):
current_token = event['context']['AudioPlayer']['token']
should_end_session = True
playlist = convert_token_to_dict(current_token)
playlist[mode] = str(value)
current_token = convert_dict_to_token(playlist)
speech_output = strings['ok']
offsetInMilliseconds = event['context']['AudioPlayer']['offsetInMilliseconds']
next_url, next_token, title = get_next_url_and_token(current_token, 0)
return build_response(build_cardless_audio_speechlet_response(speech_output, should_end_session, next_url, current_token, offsetInMilliseconds))
def start_over(event):
current_token = event['context']['AudioPlayer']['token']
should_end_session = True
next_url, next_token, title = get_next_url_and_token(current_token, 0)
if title is None:
speech_output = strings['novideo']
return build_response(build_short_speechlet_response(speech_output, should_end_session))
speech_output = strings['playing']+" " + title
return build_response(build_cardless_audio_speechlet_response(speech_output, should_end_session, next_url, next_token))
def say_video_title(event):
should_end_session = True
if 'token' in event['context']['AudioPlayer']:
current_token = event['context']['AudioPlayer']['token']
next_url, next_token, title = get_next_url_and_token(current_token, 0)
if title is None:
speech_output = strings['notitle']
else:
speech_output = strings['nowplaying']+" "+title
else:
speech_output = strings['nothingplaying']
return build_response(build_short_speechlet_response(speech_output, should_end_session))
def convert_token_to_dict(token):
pi=token.split('&')
playlist={}
for i in pi:
key=i.split('=')[0]
val=i.split('=')[1]
playlist[key]=val
return playlist
def convert_dict_to_token(playlist):
token = "&".join(["=".join([key, str(val)]) for key, val in playlist.items()])
return token
def get_next_url_and_token(current_token, skip):
should_end_session = True
speech_output = ''
playlist = convert_token_to_dict(current_token)
next_url = None
title = None
shuffle_mode = int(playlist['s'])
loop_mode = int(playlist['l'])
next_playing = int(playlist['p'])
number_of_videos = sum('v' in i for i in playlist.keys())
while next_url is None:
next_playing = next_playing + skip
if shuffle_mode and skip != 0:
next_playing = randint(0,number_of_videos-1)
if next_playing < 0:
if loop_mode:
next_playing = number_of_videos - 1
else:
next_playing = 0
if next_playing >= number_of_videos and loop_mode:
next_playing = 0
next_key = 'v'+str(next_playing)
if next_key not in playlist:
break
next_id = playlist[next_key]
next_url, title = get_url_and_title(next_id)
if skip == 0:
break
playlist['p'] = str(next_playing)
next_token = convert_dict_to_token(playlist)
return next_url, next_token, title
def stopped(event):
offsetInMilliseconds = event['request']['offsetInMilliseconds']
logger.info("Stopped at %s" % offsetInMilliseconds)
def started(event):
logger.info("Started")
token = event['request']['token']
def finished(event):
logger.info('finished')
token = event['request']['token']
def failed(event):
logger.info("Playback failed")
logger.info(event)
if 'error' in event['request']:
logger.info(event['request']['error'])
should_end_session = True
playBehavior = 'REPLACE_ALL'
current_token = event['request']['token']
skip = 1
next_url, next_token, title = get_next_url_and_token(current_token, skip)
if title is None:
return do_nothing()
return build_response(build_audio_enqueue_response(should_end_session, next_url, current_token, next_token, playBehavior))