-
Notifications
You must be signed in to change notification settings - Fork 116
/
youtube.py
1179 lines (980 loc) · 49.2 KB
/
youtube.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
# -*- coding: utf-8 -*-
"""
Copyright (C) 2014-2016 bromix (plugin.video.youtube)
Copyright (C) 2016-2018 plugin.video.youtube
SPDX-License-Identifier: GPL-2.0-only
See LICENSES/GPL-2.0-only for more information.
"""
import copy
import traceback
import requests
from .login_client import LoginClient
from ..helper.video_info import VideoInfo
from ..helper.utils import get_shelf_index_by_title
from ...kodion import constants
from ...kodion import Context
_context = Context(plugin_id='plugin.video.youtube')
class YouTube(LoginClient):
def __init__(self, config=None, language='en-US', region='US', items_per_page=50, access_token='', access_token_tv=''):
if config is None:
config = {}
LoginClient.__init__(self, config=config, language=language, region=region, access_token=access_token,
access_token_tv=access_token_tv)
self._max_results = items_per_page
def get_max_results(self):
return self._max_results
def get_language(self):
return self._language
def get_region(self):
return self._region
@staticmethod
def calculate_next_page_token(page, max_result):
page -= 1
low = 'AEIMQUYcgkosw048'
high = 'ABCDEFGHIJKLMNOP'
len_low = len(low)
len_high = len(high)
position = page * max_result
overflow_token = 'Q'
if position >= 128:
overflow_token_iteration = position // 128
overflow_token = '%sE' % high[overflow_token_iteration]
low_iteration = position % len_low
# at this position the iteration starts with 'I' again (after 'P')
if position >= 256:
multiplier = (position // 128) - 1
position -= 128 * multiplier
high_iteration = (position // len_low) % len_high
return 'C%s%s%sAA' % (high[high_iteration], low[low_iteration], overflow_token)
def update_watch_history(self, video_id, url):
headers = {'Host': 'www.youtube.com',
'Connection': 'keep-alive',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.36 Safari/537.36',
'Accept': 'image/webp,*/*;q=0.8',
'DNT': '1',
'Referer': 'https://www.youtube.com/tv',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'en-US,en;q=0.8,de;q=0.6'}
params = {'noflv': '1',
'html5': '1',
'video_id': video_id,
'referrer': '',
'eurl': 'https://www.youtube.com/tv#/watch?v=%s' % video_id,
'skl': 'false',
'ns': 'yt',
'el': 'leanback',
'ps': 'leanback'}
if self._access_token:
params['access_token'] = self._access_token
try:
_ = requests.get(url, params=params, headers=headers, verify=self._verify, allow_redirects=True)
except:
_context.log_error('Failed to update watch history |%s|' % traceback.print_exc())
def get_video_streams(self, context, video_id=None, player_config=None, cookies=None):
video_info = VideoInfo(context, access_token=self._access_token, language=self._language)
video_streams = video_info.load_stream_infos(video_id, player_config, cookies)
# update title
for video_stream in video_streams:
title = '%s (%s)' % (context.get_ui().bold(video_stream['title']), video_stream['container'])
if 'audio' in video_stream and 'video' in video_stream:
if video_stream['audio']['bitrate'] > 0 and video_stream['video']['encoding'] and \
video_stream['audio']['encoding']:
title = '%s (%s; %s / %s@%d)' % (context.get_ui().bold(video_stream['title']),
video_stream['container'],
video_stream['video']['encoding'],
video_stream['audio']['encoding'],
video_stream['audio']['bitrate'])
elif video_stream['video']['encoding'] and video_stream['audio']['encoding']:
title = '%s (%s; %s / %s)' % (context.get_ui().bold(video_stream['title']),
video_stream['container'],
video_stream['video']['encoding'],
video_stream['audio']['encoding'])
elif 'audio' in video_stream and 'video' not in video_stream:
if video_stream['audio']['encoding'] and video_stream['audio']['bitrate'] > 0:
title = '%s (%s; %s@%d)' % (context.get_ui().bold(video_stream['title']),
video_stream['container'],
video_stream['audio']['encoding'],
video_stream['audio']['bitrate'])
elif 'audio' in video_stream or 'video' in video_stream:
encoding = video_stream.get('audio', dict()).get('encoding')
if not encoding:
encoding = video_stream.get('video', dict()).get('encoding')
if encoding:
title = '%s (%s; %s)' % (context.get_ui().bold(video_stream['title']),
video_stream['container'],
encoding)
video_stream['title'] = title
return video_streams
def remove_playlist(self, playlist_id):
params = {'id': playlist_id,
'mine': 'true'}
return self.perform_v3_request(method='DELETE', path='playlists', params=params)
def get_supported_languages(self, language=None):
_language = language
if not _language:
_language = self._language
_language = _language.replace('-', '_')
params = {'part': 'snippet',
'hl': _language}
return self.perform_v3_request(method='GET', path='i18nLanguages', params=params)
def get_supported_regions(self, language=None):
_language = language
if not _language:
_language = self._language
_language = _language.replace('-', '_')
params = {'part': 'snippet',
'hl': _language}
return self.perform_v3_request(method='GET', path='i18nRegions', params=params)
def rename_playlist(self, playlist_id, new_title, privacy_status='private'):
params = {'part': 'snippet,id,status'}
post_data = {'kind': 'youtube#playlist',
'id': playlist_id,
'snippet': {'title': new_title},
'status': {'privacyStatus': privacy_status}}
return self.perform_v3_request(method='PUT', path='playlists', params=params, post_data=post_data)
def create_playlist(self, title, privacy_status='private'):
params = {'part': 'snippet,status'}
post_data = {'kind': 'youtube#playlist',
'snippet': {'title': title},
'status': {'privacyStatus': privacy_status}}
return self.perform_v3_request(method='POST', path='playlists', params=params, post_data=post_data)
def get_video_rating(self, video_id):
if isinstance(video_id, list):
video_id = ','.join(video_id)
params = {'id': video_id}
return self.perform_v3_request(method='GET', path='videos/getRating', params=params)
def rate_video(self, video_id, rating='like'):
"""
Rate a video
:param video_id: if of the video
:param rating: [like|dislike|none]
:return:
"""
params = {'id': video_id,
'rating': rating}
return self.perform_v3_request(method='POST', path='videos/rate', params=params)
def add_video_to_playlist(self, playlist_id, video_id):
params = {'part': 'snippet',
'mine': 'true'}
post_data = {'kind': 'youtube#playlistItem',
'snippet': {'playlistId': playlist_id,
'resourceId': {'kind': 'youtube#video',
'videoId': video_id}}}
return self.perform_v3_request(method='POST', path='playlistItems', params=params, post_data=post_data)
# noinspection PyUnusedLocal
def remove_video_from_playlist(self, playlist_id, playlist_item_id):
params = {'id': playlist_item_id}
return self.perform_v3_request(method='DELETE', path='playlistItems', params=params)
def unsubscribe(self, subscription_id):
params = {'id': subscription_id}
return self.perform_v3_request(method='DELETE', path='subscriptions', params=params)
def subscribe(self, channel_id):
params = {'part': 'snippet'}
post_data = {'kind': 'youtube#subscription',
'snippet': {'resourceId': {'kind': 'youtube#channel',
'channelId': channel_id}}}
return self.perform_v3_request(method='POST', path='subscriptions', params=params, post_data=post_data)
def get_subscription(self, channel_id, order='alphabetical', page_token=''):
"""
:param channel_id: [channel-id|'mine']
:param order: ['alphabetical'|'relevance'|'unread']
:param page_token:
:return:
"""
params = {'part': 'snippet',
'maxResults': str(self._max_results),
'order': order}
if channel_id == 'mine':
params['mine'] = 'true'
else:
params['channelId'] = channel_id
if page_token:
params['pageToken'] = page_token
return self.perform_v3_request(method='GET', path='subscriptions', params=params)
def get_guide_category(self, guide_category_id, page_token=''):
params = {'part': 'snippet,contentDetails,brandingSettings',
'maxResults': str(self._max_results),
'categoryId': guide_category_id,
'regionCode': self._region,
'hl': self._language}
if page_token:
params['pageToken'] = page_token
return self.perform_v3_request(method='GET', path='channels', params=params)
def get_guide_categories(self, page_token=''):
params = {'part': 'snippet',
'maxResults': str(self._max_results),
'regionCode': self._region,
'hl': self._language}
if page_token:
params['pageToken'] = page_token
return self.perform_v3_request(method='GET', path='guideCategories', params=params)
def get_popular_videos(self, page_token=''):
params = {'part': 'snippet,status',
'maxResults': str(self._max_results),
'regionCode': self._region,
'hl': self._language,
'chart': 'mostPopular'}
if page_token:
params['pageToken'] = page_token
return self.perform_v3_request(method='GET', path='videos', params=params)
def get_video_category(self, video_category_id, page_token=''):
params = {'part': 'snippet,contentDetails,status',
'maxResults': str(self._max_results),
'videoCategoryId': video_category_id,
'chart': 'mostPopular',
'regionCode': self._region,
'hl': self._language}
if page_token:
params['pageToken'] = page_token
return self.perform_v3_request(method='GET', path='videos', params=params)
def get_video_categories(self, page_token=''):
params = {'part': 'snippet',
'maxResults': str(self._max_results),
'regionCode': self._region,
'hl': self._language}
if page_token:
params['pageToken'] = page_token
return self.perform_v3_request(method='GET', path='videoCategories', params=params)
def get_activities(self, channel_id, page_token=''):
params = {'part': 'snippet,contentDetails',
'maxResults': str(self._max_results),
'regionCode': self._region,
'hl': self._language}
if channel_id == 'home':
params['home'] = 'true'
elif channel_id == 'mine':
params['mine'] = 'true'
else:
params['channelId'] = channel_id
if page_token:
params['pageToken'] = page_token
return self.perform_v3_request(method='GET', path='activities', params=params)
def get_channel_sections(self, channel_id):
params = {'part': 'snippet,contentDetails',
'regionCode': self._region,
'hl': self._language}
if channel_id == 'mine':
params['mine'] = 'true'
else:
params['channelId'] = channel_id
return self.perform_v3_request(method='GET', path='channelSections', params=params)
def get_playlists_of_channel(self, channel_id, page_token=''):
params = {'part': 'snippet',
'maxResults': str(self._max_results)}
if channel_id != 'mine':
params['channelId'] = channel_id
else:
params['mine'] = 'true'
if page_token:
params['pageToken'] = page_token
return self.perform_v3_request(method='GET', path='playlists', params=params)
def get_playlist_item_id_of_video_id(self, playlist_id, video_id, page_token=''):
old_max_results = self._max_results
self._max_results = 50
json_data = self.get_playlist_items(playlist_id=playlist_id, page_token=page_token)
self._max_results = old_max_results
items = json_data.get('items', [])
for item in items:
playlist_item_id = item['id']
playlist_video_id = item.get('snippet', {}).get('resourceId', {}).get('videoId', '')
if playlist_video_id and playlist_video_id == video_id:
return playlist_item_id
next_page_token = json_data.get('nextPageToken', '')
if next_page_token:
return self.get_playlist_item_id_of_video_id(playlist_id=playlist_id, video_id=video_id,
page_token=next_page_token)
return None
def get_playlist_items(self, playlist_id, page_token='', max_results=None):
# prepare params
max_results = str(self._max_results) if max_results is None else str(max_results)
params = {'part': 'snippet',
'maxResults': max_results,
'playlistId': playlist_id}
if page_token:
params['pageToken'] = page_token
return self.perform_v3_request(method='GET', path='playlistItems', params=params)
def get_channel_by_username(self, username):
"""
Returns a collection of zero or more channel resources that match the request criteria.
:param username: retrieve channel_id for username
:return:
"""
params = {'part': 'id'}
if username == 'mine':
params.update({'mine': 'true'})
else:
params.update({'forUsername': username})
return self.perform_v3_request(method='GET', path='channels', params=params)
def get_channels(self, channel_id):
"""
Returns a collection of zero or more channel resources that match the request criteria.
:param channel_id: list or comma-separated list of the YouTube channel ID(s)
:return:
"""
if isinstance(channel_id, list):
channel_id = ','.join(channel_id)
params = {'part': 'snippet,contentDetails,brandingSettings'}
if channel_id != 'mine':
params['id'] = channel_id
else:
params['mine'] = 'true'
return self.perform_v3_request(method='GET', path='channels', params=params)
def get_disliked_videos(self, page_token=''):
# prepare page token
if not page_token:
page_token = ''
# prepare params
params = {'part': 'snippet,status',
'myRating': 'dislike',
'maxResults': str(self._max_results)}
if page_token:
params['pageToken'] = page_token
return self.perform_v3_request(method='GET', path='videos', params=params)
def get_videos(self, video_id, live_details=False):
"""
Returns a list of videos that match the API request parameters
:param video_id: list of video ids
:param live_details: also retrieve liveStreamingDetails
:return:
"""
if isinstance(video_id, list):
video_id = ','.join(video_id)
parts = ['snippet,contentDetails,status']
if live_details:
parts.append(',liveStreamingDetails')
params = {'part': ''.join(parts),
'id': video_id}
return self.perform_v3_request(method='GET', path='videos', params=params)
def get_playlists(self, playlist_id):
if isinstance(playlist_id, list):
playlist_id = ','.join(playlist_id)
params = {'part': 'snippet,contentDetails',
'id': playlist_id}
return self.perform_v3_request(method='GET', path='playlists', params=params)
def get_live_events(self, event_type='live', order='relevance', page_token='', location=False):
"""
:param event_type: one of: 'live', 'completed', 'upcoming'
:param order: one of: 'date', 'rating', 'relevance', 'title', 'videoCount', 'viewCount'
:param page_token:
:param location: bool, use geolocation
:return:
"""
# prepare page token
if not page_token:
page_token = ''
# prepare params
params = {'part': 'snippet',
'type': 'video',
'order': order,
'eventType': event_type,
'regionCode': self._region,
'hl': self._language,
'relevanceLanguage': self._language,
'maxResults': str(self._max_results)}
if location:
location = _context.get_settings().get_location()
if location:
params['location'] = location
params['locationRadius'] = _context.get_settings().get_location_radius()
if page_token:
params['pageToken'] = page_token
return self.perform_v3_request(method='GET', path='search', params=params)
def get_related_videos(self, video_id, page_token='', max_results=0):
# prepare page token
if not page_token:
page_token = ''
max_results = self._max_results if max_results <= 0 else max_results
# prepare params
params = {'relatedToVideoId': video_id,
'part': 'snippet',
'type': 'video',
'regionCode': self._region,
'hl': self._language,
'maxResults': str(max_results)}
if page_token:
params['pageToken'] = page_token
return self.perform_v3_request(method='GET', path='search', params=params)
def get_channel_videos(self, channel_id, page_token=''):
"""
Returns a collection of video search results for the specified channel_id
"""
params = {'part': 'snippet',
'hl': self._language,
'maxResults': str(self._max_results),
'type': 'video',
'safeSearch': 'none',
'order': 'date'}
if channel_id == 'mine':
params['forMine'] = 'true'
else:
params['channelId'] = channel_id
if page_token:
params['pageToken'] = page_token
return self.perform_v3_request(method='GET', path='search', params=params)
def search(self, q, search_type=None, event_type='', channel_id='',
order='relevance', safe_search='moderate', page_token='', location=False):
"""
Returns a collection of search results that match the query parameters specified in the API request. By default,
a search result set identifies matching video, channel, and playlist resources, but you can also configure
queries to only retrieve a specific type of resource.
:param q:
:param search_type: acceptable values are: 'video' | 'channel' | 'playlist'
:param event_type: 'live', 'completed', 'upcoming'
:param channel_id: limit search to channel id
:param order: one of: 'date', 'rating', 'relevance', 'title', 'videoCount', 'viewCount'
:param safe_search: one of: 'moderate', 'none', 'strict'
:param page_token: can be ''
:param location: bool, use geolocation
:return:
"""
if search_type is None:
search_type = ['video', 'channel', 'playlist']
# prepare search type
if not search_type:
search_type = ''
if isinstance(search_type, list):
search_type = ','.join(search_type)
# prepare page token
if not page_token:
page_token = ''
# prepare params
params = {'q': q,
'part': 'snippet',
'regionCode': self._region,
'hl': self._language,
'relevanceLanguage': self._language,
'maxResults': str(self._max_results)}
if event_type and event_type in ['live', 'upcoming', 'completed']:
params['eventType'] = event_type
if search_type:
params['type'] = search_type
if channel_id:
params['channelId'] = channel_id
if order:
params['order'] = order
if safe_search:
params['safeSearch'] = safe_search
if page_token:
params['pageToken'] = page_token
video_only_params = ['eventType', 'videoCaption', 'videoCategoryId', 'videoDefinition',
'videoDimension', 'videoDuration', 'videoEmbeddable', 'videoLicense',
'videoSyndicated', 'videoType', 'relatedToVideoId', 'forMine']
for key in video_only_params:
if params.get(key) is not None:
params['type'] = 'video'
break
if params['type'] == 'video' and location:
location = _context.get_settings().get_location()
if location:
params['location'] = location
params['locationRadius'] = _context.get_settings().get_location_radius()
return self.perform_v3_request(method='GET', path='search', params=params)
def get_my_subscriptions(self, page_token=None, offset=0):
if not page_token:
page_token = ''
result = {'items': [],
'next_page_token': page_token,
'offset': offset}
def _perform(_page_token, _offset, _result):
_post_data = {
'context': {
'client': {
'clientName': 'TVHTML5',
'clientVersion': '5.20150304',
'theme': 'CLASSIC',
'acceptRegion': '%s' % self._region,
'acceptLanguage': '%s' % self._language.replace('_', '-')
},
'user': {
'enableSafetyMode': False
}
},
'browseId': 'FEsubscriptions'
}
if _page_token:
_post_data['continuation'] = _page_token
_json_data = self.perform_v1_tv_request(method='POST', path='browse', post_data=_post_data)
_data = _json_data.get('contents', {}).get('sectionListRenderer', {}).get('contents', [{}])[0].get(
'shelfRenderer', {}).get('content', {}).get('horizontalListRenderer', {})
if not _data:
_data = _json_data.get('continuationContents', {}).get('horizontalListContinuation', {})
_items = _data.get('items', [])
if not _result:
_result = {'items': []}
_new_offset = self._max_results - len(_result['items']) + _offset
if _offset > 0:
_items = _items[_offset:]
_result['offset'] = _new_offset
for _item in _items:
_item = _item.get('gridVideoRenderer', {})
if _item:
_video_item = {'id': _item['videoId'],
'title': _item.get('title', {}).get('runs', [{}])[0].get('text', ''),
'channel': _item.get('shortBylineText', {}).get('runs', [{}])[0].get('text', '')}
_result['items'].append(_video_item)
_continuations = _data.get('continuations', [{}])[0].get('nextContinuationData', {}).get('continuation', '')
if _continuations and len(_result['items']) <= self._max_results:
_result['next_page_token'] = _continuations
if len(_result['items']) < self._max_results:
_result = _perform(_page_token=_continuations, _offset=0, _result=_result)
# trim result
if len(_result['items']) > self._max_results:
_items = _result['items']
_items = _items[:self._max_results]
_result['items'] = _items
_result['continue'] = True
if 'offset' in _result and _result['offset'] >= 100:
_result['offset'] -= 100
if len(_result['items']) < self._max_results:
if 'continue' in _result:
del _result['continue']
if 'next_page_token' in _result:
del _result['next_page_token']
if 'offset' in _result:
del _result['offset']
return _result
return _perform(_page_token=page_token, _offset=offset, _result=result)
def get_purchases(self, page_token, offset):
if not page_token:
page_token = ''
shelf_title = 'Purchases'
result = {'items': [],
'next_page_token': page_token,
'offset': offset}
def _perform(_page_token, _offset, _result, _shelf_index=None):
_post_data = {
'context': {
'client': {
'clientName': 'TVHTML5',
'clientVersion': '5.20150304',
'theme': 'CLASSIC',
'acceptRegion': '%s' % self._region,
'acceptLanguage': '%s' % self._language.replace('_', '-')
},
'user': {
'enableSafetyMode': False
}
}
}
if _page_token:
_post_data['continuation'] = _page_token
else:
_post_data['browseId'] = 'FEmy_youtube'
_json_data = self.perform_v1_tv_request(method='POST', path='browse', post_data=_post_data)
_data = {}
if 'continuationContents' in _json_data:
_data = _json_data.get('continuationContents', {}).get('horizontalListContinuation', {})
elif 'contents' in _json_data:
_contents = _json_data.get('contents', {}).get('sectionListRenderer', {}).get('contents', [{}])
if _shelf_index is None:
_shelf_index = get_shelf_index_by_title(_context, _json_data, shelf_title)
if _shelf_index is not None:
_data = _contents[_shelf_index].get('shelfRenderer', {}).get('content', {}).get('horizontalListRenderer', {})
_items = _data.get('items', [])
if not _result:
_result = {'items': []}
_new_offset = self._max_results - len(_result['items']) + _offset
if _offset > 0:
_items = _items[_offset:]
_result['offset'] = _new_offset
for _listItem in _items:
_item = _listItem.get('gridVideoRenderer', {})
if _item:
_video_item = {'id': _item['videoId'],
'title': _item.get('title', {}).get('runs', [{}])[0].get('text', ''),
'channel': _item.get('shortBylineText', {}).get('runs', [{}])[0].get('text', '')}
_result['items'].append(_video_item)
_item = _listItem.get('gridPlaylistRenderer', {})
if _item:
play_next_page_token = ''
while True:
json_playlist_data = self.get_playlist_items(_item['playlistId'], page_token=play_next_page_token)
_playListItems = json_playlist_data.get('items', {})
for _playListItem in _playListItems:
_playListItem = _playListItem.get('snippet', {})
if _playListItem:
_video_item = {'id': _playListItem.get('resourceId', {}).get('videoId', ''),
'title': _playListItem['title'],
'channel': _item.get('shortBylineText', {}).get('runs', [{}])[0].get('text', '')}
_result['items'].append(_video_item)
play_next_page_token = json_playlist_data.get('nextPageToken', '')
if not play_next_page_token or _context.abort_requested():
break
_continuations = _data.get('continuations', [{}])[0].get('nextContinuationData', {}).get('continuation', '')
if _continuations and len(_result['items']) <= self._max_results:
_result['next_page_token'] = _continuations
if len(_result['items']) < self._max_results:
_result = _perform(_page_token=_continuations, _offset=0, _result=_result, _shelf_index=shelf_index)
# trim result
if len(_result['items']) > self._max_results:
_items = _result['items']
_items = _items[:self._max_results]
_result['items'] = _items
_result['continue'] = True
if len(_result['items']) < self._max_results:
if 'continue' in _result:
del _result['continue']
if 'next_page_token' in _result:
del _result['next_page_token']
if 'offset' in _result:
del _result['offset']
return _result
shelf_index = None
if self._language != 'en' and not self._language.startswith('en-') and not page_token:
# shelf index is a moving target, make a request in english first to find the correct index by title
_en_post_data = {
'context': {
'client': {
'clientName': 'TVHTML5',
'clientVersion': '5.20150304',
'theme': 'CLASSIC',
'acceptRegion': 'US',
'acceptLanguage': 'en-US'
},
'user': {
'enableSafetyMode': False
}
},
'browseId': 'FEmy_youtube'
}
json_data = self.perform_v1_tv_request(method='POST', path='browse', post_data=_en_post_data)
shelf_index = get_shelf_index_by_title(_context, json_data, shelf_title)
result = _perform(_page_token=page_token, _offset=offset, _result=result, _shelf_index=shelf_index)
return result
def get_saved_playlists(self, page_token, offset):
if not page_token:
page_token = ''
shelf_title = 'Saved Playlists'
result = {'items': [],
'next_page_token': page_token,
'offset': offset}
def _perform(_page_token, _offset, _result, _shelf_index=None):
_post_data = {
'context': {
'client': {
'clientName': 'TVHTML5',
'clientVersion': '5.20150304',
'theme': 'CLASSIC',
'acceptRegion': '%s' % self._region,
'acceptLanguage': '%s' % self._language.replace('_', '-')
},
'user': {
'enableSafetyMode': False
}
}
}
if _page_token:
_post_data['continuation'] = _page_token
else:
_post_data['browseId'] = 'FEmy_youtube'
_json_data = self.perform_v1_tv_request(method='POST', path='browse', post_data=_post_data)
_data = {}
if 'continuationContents' in _json_data:
_data = _json_data.get('continuationContents', {}).get('horizontalListContinuation', {})
elif 'contents' in _json_data:
_contents = _json_data.get('contents', {}).get('sectionListRenderer', {}).get('contents', [{}])
if _shelf_index is None:
_shelf_index = get_shelf_index_by_title(_context, _json_data, shelf_title)
if _shelf_index is not None:
_data = _contents[_shelf_index].get('shelfRenderer', {}).get('content', {}).get('horizontalListRenderer', {})
_items = _data.get('items', [])
if not _result:
_result = {'items': []}
_new_offset = self._max_results - len(_result['items']) + _offset
if _offset > 0:
_items = _items[_offset:]
_result['offset'] = _new_offset
for _item in _items:
_item = _item.get('gridPlaylistRenderer', {})
if _item:
_video_item = {'id': _item['playlistId'],
'title': _item.get('title', {}).get('runs', [{}])[0].get('text', ''),
'channel': _item.get('shortBylineText', {}).get('runs', [{}])[0].get('text', ''),
'channel_id': _item.get('shortBylineText', {}).get('runs', [{}])[0].get('navigationEndpoint', {}).get('browseEndpoint', {}).get('browseId', ''),
'thumbnails': {'default': {'url': ''}, 'medium': {'url': ''}, 'high': {'url': ''}}}
_thumbs = _item.get('thumbnail', {}).get('thumbnails', [{}])
for _thumb in _thumbs:
_thumb_url = _thumb.get('url', '')
if _thumb_url.startswith('//'):
_thumb_url = ''.join(['https:', _thumb_url])
if _thumb_url.endswith('/default.jpg'):
_video_item['thumbnails']['default']['url'] = _thumb_url
elif _thumb_url.endswith('/mqdefault.jpg'):
_video_item['thumbnails']['medium']['url'] = _thumb_url
elif _thumb_url.endswith('/hqdefault.jpg'):
_video_item['thumbnails']['high']['url'] = _thumb_url
_result['items'].append(_video_item)
_continuations = _data.get('continuations', [{}])[0].get('nextContinuationData', {}).get('continuation', '')
if _continuations and len(_result['items']) <= self._max_results:
_result['next_page_token'] = _continuations
if len(_result['items']) < self._max_results:
_result = _perform(_page_token=_continuations, _offset=0, _result=_result, _shelf_index=_shelf_index)
# trim result
if len(_result['items']) > self._max_results:
_items = _result['items']
_items = _items[:self._max_results]
_result['items'] = _items
_result['continue'] = True
if len(_result['items']) < self._max_results:
if 'continue' in _result:
del _result['continue']
if 'next_page_token' in _result:
del _result['next_page_token']
if 'offset' in _result:
del _result['offset']
return _result
shelf_index = None
if self._language != 'en' and not self._language.startswith('en-') and not page_token:
# shelf index is a moving target, make a request in english first to find the correct index by title
_en_post_data = {
'context': {
'client': {
'clientName': 'TVHTML5',
'clientVersion': '5.20150304',
'theme': 'CLASSIC',
'acceptRegion': 'US',
'acceptLanguage': 'en-US'
},
'user': {
'enableSafetyMode': False
}
},
'browseId': 'FEmy_youtube'
}
json_data = self.perform_v1_tv_request(method='POST', path='browse', post_data=_en_post_data)
shelf_index = get_shelf_index_by_title(_context, json_data, shelf_title)
result = _perform(_page_token=page_token, _offset=offset, _result=result, _shelf_index=shelf_index)
return result
def clear_watch_history(self):
_post_data = {
'context': {
'client': {
'clientName': 'TVHTML5',
'clientVersion': '5.20150304',
'theme': 'CLASSIC',
'acceptRegion': '%s' % self._region,
'acceptLanguage': '%s' % self._language.replace('_', '-')
},
'user': {
'enableSafetyMode': False
}
}
}
_json_data = self.perform_v1_tv_request(method='POST', path='history/clear_watch_history', post_data=_post_data)
return _json_data
def get_watch_history(self, page_token=None, offset=0):
if not page_token:
page_token = ''
result = {'items': [],
'next_page_token': page_token,
'offset': offset}
def _perform(_page_token, _offset, _result):
_post_data = {
'context': {
'client': {
'clientName': 'TVHTML5',
'clientVersion': '5.20150304',
'theme': 'CLASSIC',
'acceptRegion': '%s' % self._region,
'acceptLanguage': '%s' % self._language.replace('_', '-')
},
'user': {
'enableSafetyMode': False
}
},
'browseId': 'FEhistory'
}
if _page_token:
_post_data['continuation'] = _page_token
_json_data = self.perform_v1_tv_request(method='POST', path='browse', post_data=_post_data)
_data = _json_data.get('contents', {}).get('sectionListRenderer', {}).get('contents', [{}])[0].get(
'shelfRenderer', {}).get('content', {}).get('horizontalListRenderer', {})
if not _data:
_data = _json_data.get('continuationContents', {}).get('horizontalListContinuation', {})
_items = _data.get('items', [])
if not _result:
_result = {'items': []}
_new_offset = self._max_results - len(_result['items']) + _offset
if _offset > 0:
_items = _items[_offset:]
_result['offset'] = _new_offset
for _item in _items:
_item = _item.get('gridVideoRenderer', {})
if _item:
_video_item = {'id': _item['videoId'],
'title': _item.get('title', {}).get('runs', [{}])[0].get('text', ''),
'channel': _item.get('shortBylineText', {}).get('runs', [{}])[0].get('text', '')}
_result['items'].append(_video_item)
_continuations = _data.get('continuations', [{}])[0].get('nextContinuationData', {}).get('continuation', '')
if _continuations and len(_result['items']) <= self._max_results:
_result['next_page_token'] = _continuations
if len(_result['items']) < self._max_results:
_result = _perform(_page_token=_continuations, _offset=0, _result=_result)
# trim result
if len(_result['items']) > self._max_results:
_items = _result['items']
_items = _items[:self._max_results]
_result['items'] = _items
_result['continue'] = True
if len(_result['items']) < self._max_results:
if 'continue' in _result:
del _result['continue']
if 'next_page_token' in _result:
del _result['next_page_token']
if 'offset' in _result:
del _result['offset']
return _result
return _perform(_page_token=page_token, _offset=offset, _result=result)
def get_watch_later_id(self):
watch_later_id = ''