Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 48 additions & 12 deletions resources/lib/twitch/api/usher.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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')
Expand All @@ -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}')
Expand All @@ -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
Expand Down