diff --git a/resources/lib/twitch/api/usher.py b/resources/lib/twitch/api/usher.py index 28656cc..5116ddb 100644 --- a/resources/lib/twitch/api/usher.py +++ b/resources/lib/twitch/api/usher.py @@ -10,6 +10,16 @@ from twitch.queries import ClipsQuery, HiddenApiQuery, UsherQuery from twitch.queries import query +from six.moves.urllib.parse import urlencode + + +def valid_video_id(video_id): + if video_id.startswith('videos'): + video_id = 'v' + video_id[6:] + if video_id.startswith(('a', 'c', 'v')): + return video_id[1:] + return '' + @query def channel_token(channel): @@ -34,6 +44,22 @@ def _legacy_video(video_id): return q +def live_request(channel): + token = channel_token(channel) + if keys.ERROR in token: + return token + else: + q = UsherQuery('api/channel/hls/{channel}.m3u8') + q.add_urlkw(keys.CHANNEL, channel) + q.add_param(keys.SIG, token[keys.SIG]) + q.add_param(keys.TOKEN, token[keys.TOKEN]) + q.add_param(keys.ALLOW_SOURCE, Boolean.TRUE) + q.add_param(keys.ALLOW_SPECTRE, Boolean.TRUE) + q.add_param(keys.ALLOW_AUDIO_ONLY, Boolean.TRUE) + url = '?'.join([q.url, urlencode(q.params)]) + return {'url': url, 'headers': q.headers} + + @query def _live(channel, token): q = UsherQuery('api/channel/hls/{channel}.m3u8') @@ -55,7 +81,25 @@ def live(channel): return _live(channel, token) -@m3u8 +def video_request(video_id): + video_id = valid_video_id(video_id) + if video_id: + token = vod_token(video_id) + if keys.ERROR in token: + return token + else: + q = UsherQuery('vod/{id}') + q.add_urlkw(keys.ID, video_id) + q.add_param(keys.NAUTHSIG, token[keys.SIG]) + q.add_param(keys.NAUTH, token[keys.TOKEN]) + q.add_param(keys.ALLOW_SOURCE, Boolean.TRUE) + q.add_param(keys.ALLOW_AUDIO_ONLY, Boolean.TRUE) + url = '?'.join([q.url, urlencode(q.params)]) + return {'url': url, 'headers': q.headers} + else: + raise NotImplementedError('Unknown Video Type') + + @query def _vod(video_id, token): q = UsherQuery('vod/{id}') @@ -67,18 +111,10 @@ def _vod(video_id, token): return q +@m3u8 def video(video_id): - if video_id.startswith('videos') or video_id.startswith('v'): - if video_id.startswith('videos'): - video_id = 'v' + video_id[6:] - video_id = video_id[1:] - token = vod_token(video_id) - if keys.ERROR in token: - return token - else: - return _vod(video_id, token) - elif video_id.startswith(('a', 'c')): - video_id = video_id[1:] + video_id = valid_video_id(video_id) + if video_id: token = vod_token(video_id) if keys.ERROR in token: return token