[twitch] Add support for mobile URLs (closes #16146)
[youtube-dl] / youtube_dl / extractor / twitch.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import itertools
5 import re
6 import random
7
8 from .common import InfoExtractor
9 from ..compat import (
10     compat_HTTPError,
11     compat_parse_qs,
12     compat_str,
13     compat_urllib_parse_urlencode,
14     compat_urllib_parse_urlparse,
15 )
16 from ..utils import (
17     clean_html,
18     ExtractorError,
19     int_or_none,
20     js_to_json,
21     orderedSet,
22     parse_duration,
23     parse_iso8601,
24     update_url_query,
25     urlencode_postdata,
26     urljoin,
27 )
28
29
30 class TwitchBaseIE(InfoExtractor):
31     _VALID_URL_BASE = r'https?://(?:(?:www|go|m)\.)?twitch\.tv'
32
33     _API_BASE = 'https://api.twitch.tv'
34     _USHER_BASE = 'https://usher.ttvnw.net'
35     _LOGIN_URL = 'https://www.twitch.tv/login'
36     _CLIENT_ID = 'jzkbprff40iqj646a697cyrvl0zt2m6'
37     _NETRC_MACHINE = 'twitch'
38
39     def _handle_error(self, response):
40         if not isinstance(response, dict):
41             return
42         error = response.get('error')
43         if error:
44             raise ExtractorError(
45                 '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
46                 expected=True)
47
48     def _call_api(self, path, item_id, note):
49         response = self._download_json(
50             '%s/%s' % (self._API_BASE, path), item_id, note,
51             headers={'Client-ID': self._CLIENT_ID})
52         self._handle_error(response)
53         return response
54
55     def _real_initialize(self):
56         self._login()
57
58     def _login(self):
59         (username, password) = self._get_login_info()
60         if username is None:
61             return
62
63         def fail(message):
64             raise ExtractorError(
65                 'Unable to login. Twitch said: %s' % message, expected=True)
66
67         def login_step(page, urlh, note, data):
68             form = self._hidden_inputs(page)
69             form.update(data)
70
71             page_url = urlh.geturl()
72             post_url = self._search_regex(
73                 r'<form[^>]+action=(["\'])(?P<url>.+?)\1', page,
74                 'post url', default=page_url, group='url')
75             post_url = urljoin(page_url, post_url)
76
77             headers = {'Referer': page_url}
78
79             try:
80                 response = self._download_json(
81                     post_url, None, note,
82                     data=urlencode_postdata(form),
83                     headers=headers)
84             except ExtractorError as e:
85                 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 400:
86                     response = self._parse_json(
87                         e.cause.read().decode('utf-8'), None)
88                     fail(response.get('message') or response['errors'][0])
89                 raise
90
91             if 'Authenticated successfully' in response.get('message', ''):
92                 return None, None
93
94             redirect_url = urljoin(
95                 post_url,
96                 response.get('redirect') or response['redirect_path'])
97             return self._download_webpage_handle(
98                 redirect_url, None, 'Downloading login redirect page',
99                 headers=headers)
100
101         login_page, handle = self._download_webpage_handle(
102             self._LOGIN_URL, None, 'Downloading login page')
103
104         # Some TOR nodes and public proxies are blocked completely
105         if 'blacklist_message' in login_page:
106             fail(clean_html(login_page))
107
108         redirect_page, handle = login_step(
109             login_page, handle, 'Logging in', {
110                 'username': username,
111                 'password': password,
112             })
113
114         # Successful login
115         if not redirect_page:
116             return
117
118         if re.search(r'(?i)<form[^>]+id="two-factor-submit"', redirect_page) is not None:
119             # TODO: Add mechanism to request an SMS or phone call
120             tfa_token = self._get_tfa_info('two-factor authentication token')
121             login_step(redirect_page, handle, 'Submitting TFA token', {
122                 'authy_token': tfa_token,
123                 'remember_2fa': 'true',
124             })
125
126     def _prefer_source(self, formats):
127         try:
128             source = next(f for f in formats if f['format_id'] == 'Source')
129             source['preference'] = 10
130         except StopIteration:
131             pass  # No Source stream present
132         self._sort_formats(formats)
133
134
135 class TwitchItemBaseIE(TwitchBaseIE):
136     def _download_info(self, item, item_id):
137         return self._extract_info(self._call_api(
138             'kraken/videos/%s%s' % (item, item_id), item_id,
139             'Downloading %s info JSON' % self._ITEM_TYPE))
140
141     def _extract_media(self, item_id):
142         info = self._download_info(self._ITEM_SHORTCUT, item_id)
143         response = self._call_api(
144             'api/videos/%s%s' % (self._ITEM_SHORTCUT, item_id), item_id,
145             'Downloading %s playlist JSON' % self._ITEM_TYPE)
146         entries = []
147         chunks = response['chunks']
148         qualities = list(chunks.keys())
149         for num, fragment in enumerate(zip(*chunks.values()), start=1):
150             formats = []
151             for fmt_num, fragment_fmt in enumerate(fragment):
152                 format_id = qualities[fmt_num]
153                 fmt = {
154                     'url': fragment_fmt['url'],
155                     'format_id': format_id,
156                     'quality': 1 if format_id == 'live' else 0,
157                 }
158                 m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
159                 if m:
160                     fmt['height'] = int(m.group('height'))
161                 formats.append(fmt)
162             self._sort_formats(formats)
163             entry = dict(info)
164             entry['id'] = '%s_%d' % (entry['id'], num)
165             entry['title'] = '%s part %d' % (entry['title'], num)
166             entry['formats'] = formats
167             entries.append(entry)
168         return self.playlist_result(entries, info['id'], info['title'])
169
170     def _extract_info(self, info):
171         return {
172             'id': info['_id'],
173             'title': info.get('title') or 'Untitled Broadcast',
174             'description': info.get('description'),
175             'duration': int_or_none(info.get('length')),
176             'thumbnail': info.get('preview'),
177             'uploader': info.get('channel', {}).get('display_name'),
178             'uploader_id': info.get('channel', {}).get('name'),
179             'timestamp': parse_iso8601(info.get('recorded_at')),
180             'view_count': int_or_none(info.get('views')),
181         }
182
183     def _real_extract(self, url):
184         return self._extract_media(self._match_id(url))
185
186
187 class TwitchVideoIE(TwitchItemBaseIE):
188     IE_NAME = 'twitch:video'
189     _VALID_URL = r'%s/[^/]+/b/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
190     _ITEM_TYPE = 'video'
191     _ITEM_SHORTCUT = 'a'
192
193     _TEST = {
194         'url': 'http://www.twitch.tv/riotgames/b/577357806',
195         'info_dict': {
196             'id': 'a577357806',
197             'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
198         },
199         'playlist_mincount': 12,
200         'skip': 'HTTP Error 404: Not Found',
201     }
202
203
204 class TwitchChapterIE(TwitchItemBaseIE):
205     IE_NAME = 'twitch:chapter'
206     _VALID_URL = r'%s/[^/]+/c/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
207     _ITEM_TYPE = 'chapter'
208     _ITEM_SHORTCUT = 'c'
209
210     _TESTS = [{
211         'url': 'http://www.twitch.tv/acracingleague/c/5285812',
212         'info_dict': {
213             'id': 'c5285812',
214             'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
215         },
216         'playlist_mincount': 3,
217         'skip': 'HTTP Error 404: Not Found',
218     }, {
219         'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361',
220         'only_matching': True,
221     }]
222
223
224 class TwitchVodIE(TwitchItemBaseIE):
225     IE_NAME = 'twitch:vod'
226     _VALID_URL = r'''(?x)
227                     https?://
228                         (?:
229                             (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/v|videos)/|
230                             player\.twitch\.tv/\?.*?\bvideo=v
231                         )
232                         (?P<id>\d+)
233                     '''
234     _ITEM_TYPE = 'vod'
235     _ITEM_SHORTCUT = 'v'
236
237     _TESTS = [{
238         'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s',
239         'info_dict': {
240             'id': 'v6528877',
241             'ext': 'mp4',
242             'title': 'LCK Summer Split - Week 6 Day 1',
243             'thumbnail': r're:^https?://.*\.jpg$',
244             'duration': 17208,
245             'timestamp': 1435131709,
246             'upload_date': '20150624',
247             'uploader': 'Riot Games',
248             'uploader_id': 'riotgames',
249             'view_count': int,
250             'start_time': 310,
251         },
252         'params': {
253             # m3u8 download
254             'skip_download': True,
255         },
256     }, {
257         # Untitled broadcast (title is None)
258         'url': 'http://www.twitch.tv/belkao_o/v/11230755',
259         'info_dict': {
260             'id': 'v11230755',
261             'ext': 'mp4',
262             'title': 'Untitled Broadcast',
263             'thumbnail': r're:^https?://.*\.jpg$',
264             'duration': 1638,
265             'timestamp': 1439746708,
266             'upload_date': '20150816',
267             'uploader': 'BelkAO_o',
268             'uploader_id': 'belkao_o',
269             'view_count': int,
270         },
271         'params': {
272             # m3u8 download
273             'skip_download': True,
274         },
275         'skip': 'HTTP Error 404: Not Found',
276     }, {
277         'url': 'http://player.twitch.tv/?t=5m10s&video=v6528877',
278         'only_matching': True,
279     }, {
280         'url': 'https://www.twitch.tv/videos/6528877',
281         'only_matching': True,
282     }, {
283         'url': 'https://m.twitch.tv/beagsandjam/v/247478721',
284         'only_matching': True,
285     }]
286
287     def _real_extract(self, url):
288         item_id = self._match_id(url)
289
290         info = self._download_info(self._ITEM_SHORTCUT, item_id)
291         access_token = self._call_api(
292             'api/vods/%s/access_token' % item_id, item_id,
293             'Downloading %s access token' % self._ITEM_TYPE)
294
295         formats = self._extract_m3u8_formats(
296             '%s/vod/%s?%s' % (
297                 self._USHER_BASE, item_id,
298                 compat_urllib_parse_urlencode({
299                     'allow_source': 'true',
300                     'allow_audio_only': 'true',
301                     'allow_spectre': 'true',
302                     'player': 'twitchweb',
303                     'nauth': access_token['token'],
304                     'nauthsig': access_token['sig'],
305                 })),
306             item_id, 'mp4', entry_protocol='m3u8_native')
307
308         self._prefer_source(formats)
309         info['formats'] = formats
310
311         parsed_url = compat_urllib_parse_urlparse(url)
312         query = compat_parse_qs(parsed_url.query)
313         if 't' in query:
314             info['start_time'] = parse_duration(query['t'][0])
315
316         if info.get('timestamp') is not None:
317             info['subtitles'] = {
318                 'rechat': [{
319                     'url': update_url_query(
320                         'https://rechat.twitch.tv/rechat-messages', {
321                             'video_id': 'v%s' % item_id,
322                             'start': info['timestamp'],
323                         }),
324                     'ext': 'json',
325                 }],
326             }
327
328         return info
329
330
331 class TwitchPlaylistBaseIE(TwitchBaseIE):
332     _PLAYLIST_PATH = 'kraken/channels/%s/videos/?offset=%d&limit=%d'
333     _PAGE_LIMIT = 100
334
335     def _extract_playlist(self, channel_id):
336         info = self._call_api(
337             'kraken/channels/%s' % channel_id,
338             channel_id, 'Downloading channel info JSON')
339         channel_name = info.get('display_name') or info.get('name')
340         entries = []
341         offset = 0
342         limit = self._PAGE_LIMIT
343         broken_paging_detected = False
344         counter_override = None
345         for counter in itertools.count(1):
346             response = self._call_api(
347                 self._PLAYLIST_PATH % (channel_id, offset, limit),
348                 channel_id,
349                 'Downloading %s JSON page %s'
350                 % (self._PLAYLIST_TYPE, counter_override or counter))
351             page_entries = self._extract_playlist_page(response)
352             if not page_entries:
353                 break
354             total = int_or_none(response.get('_total'))
355             # Since the beginning of March 2016 twitch's paging mechanism
356             # is completely broken on the twitch side. It simply ignores
357             # a limit and returns the whole offset number of videos.
358             # Working around by just requesting all videos at once.
359             # Upd: pagination bug was fixed by twitch on 15.03.2016.
360             if not broken_paging_detected and total and len(page_entries) > limit:
361                 self.report_warning(
362                     'Twitch pagination is broken on twitch side, requesting all videos at once',
363                     channel_id)
364                 broken_paging_detected = True
365                 offset = total
366                 counter_override = '(all at once)'
367                 continue
368             entries.extend(page_entries)
369             if broken_paging_detected or total and len(page_entries) >= total:
370                 break
371             offset += limit
372         return self.playlist_result(
373             [self._make_url_result(entry) for entry in orderedSet(entries)],
374             channel_id, channel_name)
375
376     def _make_url_result(self, url):
377         try:
378             video_id = 'v%s' % TwitchVodIE._match_id(url)
379             return self.url_result(url, TwitchVodIE.ie_key(), video_id=video_id)
380         except AssertionError:
381             return self.url_result(url)
382
383     def _extract_playlist_page(self, response):
384         videos = response.get('videos')
385         return [video['url'] for video in videos] if videos else []
386
387     def _real_extract(self, url):
388         return self._extract_playlist(self._match_id(url))
389
390
391 class TwitchProfileIE(TwitchPlaylistBaseIE):
392     IE_NAME = 'twitch:profile'
393     _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
394     _PLAYLIST_TYPE = 'profile'
395
396     _TESTS = [{
397         'url': 'http://www.twitch.tv/vanillatv/profile',
398         'info_dict': {
399             'id': 'vanillatv',
400             'title': 'VanillaTV',
401         },
402         'playlist_mincount': 412,
403     }, {
404         'url': 'http://m.twitch.tv/vanillatv/profile',
405         'only_matching': True,
406     }]
407
408
409 class TwitchVideosBaseIE(TwitchPlaylistBaseIE):
410     _VALID_URL_VIDEOS_BASE = r'%s/(?P<id>[^/]+)/videos' % TwitchBaseIE._VALID_URL_BASE
411     _PLAYLIST_PATH = TwitchPlaylistBaseIE._PLAYLIST_PATH + '&broadcast_type='
412
413
414 class TwitchAllVideosIE(TwitchVideosBaseIE):
415     IE_NAME = 'twitch:videos:all'
416     _VALID_URL = r'%s/all' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
417     _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive,upload,highlight'
418     _PLAYLIST_TYPE = 'all videos'
419
420     _TESTS = [{
421         'url': 'https://www.twitch.tv/spamfish/videos/all',
422         'info_dict': {
423             'id': 'spamfish',
424             'title': 'Spamfish',
425         },
426         'playlist_mincount': 869,
427     }, {
428         'url': 'https://m.twitch.tv/spamfish/videos/all',
429         'only_matching': True,
430     }]
431
432
433 class TwitchUploadsIE(TwitchVideosBaseIE):
434     IE_NAME = 'twitch:videos:uploads'
435     _VALID_URL = r'%s/uploads' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
436     _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'upload'
437     _PLAYLIST_TYPE = 'uploads'
438
439     _TESTS = [{
440         'url': 'https://www.twitch.tv/spamfish/videos/uploads',
441         'info_dict': {
442             'id': 'spamfish',
443             'title': 'Spamfish',
444         },
445         'playlist_mincount': 0,
446     }, {
447         'url': 'https://m.twitch.tv/spamfish/videos/uploads',
448         'only_matching': True,
449     }]
450
451
452 class TwitchPastBroadcastsIE(TwitchVideosBaseIE):
453     IE_NAME = 'twitch:videos:past-broadcasts'
454     _VALID_URL = r'%s/past-broadcasts' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
455     _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive'
456     _PLAYLIST_TYPE = 'past broadcasts'
457
458     _TESTS = [{
459         'url': 'https://www.twitch.tv/spamfish/videos/past-broadcasts',
460         'info_dict': {
461             'id': 'spamfish',
462             'title': 'Spamfish',
463         },
464         'playlist_mincount': 0,
465     }, {
466         'url': 'https://m.twitch.tv/spamfish/videos/past-broadcasts',
467         'only_matching': True,
468     }]
469
470
471 class TwitchHighlightsIE(TwitchVideosBaseIE):
472     IE_NAME = 'twitch:videos:highlights'
473     _VALID_URL = r'%s/highlights' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
474     _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'highlight'
475     _PLAYLIST_TYPE = 'highlights'
476
477     _TESTS = [{
478         'url': 'https://www.twitch.tv/spamfish/videos/highlights',
479         'info_dict': {
480             'id': 'spamfish',
481             'title': 'Spamfish',
482         },
483         'playlist_mincount': 805,
484     }, {
485         'url': 'https://m.twitch.tv/spamfish/videos/highlights',
486         'only_matching': True,
487     }]
488
489
490 class TwitchStreamIE(TwitchBaseIE):
491     IE_NAME = 'twitch:stream'
492     _VALID_URL = r'''(?x)
493                     https?://
494                         (?:
495                             (?:(?:www|go|m)\.)?twitch\.tv/|
496                             player\.twitch\.tv/\?.*?\bchannel=
497                         )
498                         (?P<id>[^/#?]+)
499                     '''
500
501     _TESTS = [{
502         'url': 'http://www.twitch.tv/shroomztv',
503         'info_dict': {
504             'id': '12772022048',
505             'display_id': 'shroomztv',
506             'ext': 'mp4',
507             'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
508             'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
509             'is_live': True,
510             'timestamp': 1421928037,
511             'upload_date': '20150122',
512             'uploader': 'ShroomzTV',
513             'uploader_id': 'shroomztv',
514             'view_count': int,
515         },
516         'params': {
517             # m3u8 download
518             'skip_download': True,
519         },
520     }, {
521         'url': 'http://www.twitch.tv/miracle_doto#profile-0',
522         'only_matching': True,
523     }, {
524         'url': 'https://player.twitch.tv/?channel=lotsofs',
525         'only_matching': True,
526     }, {
527         'url': 'https://go.twitch.tv/food',
528         'only_matching': True,
529     }, {
530         'url': 'https://m.twitch.tv/food',
531         'only_matching': True,
532     }]
533
534     @classmethod
535     def suitable(cls, url):
536         return (False
537                 if any(ie.suitable(url) for ie in (
538                     TwitchVideoIE,
539                     TwitchChapterIE,
540                     TwitchVodIE,
541                     TwitchProfileIE,
542                     TwitchAllVideosIE,
543                     TwitchUploadsIE,
544                     TwitchPastBroadcastsIE,
545                     TwitchHighlightsIE))
546                 else super(TwitchStreamIE, cls).suitable(url))
547
548     def _real_extract(self, url):
549         channel_id = self._match_id(url)
550
551         stream = self._call_api(
552             'kraken/streams/%s?stream_type=all' % channel_id, channel_id,
553             'Downloading stream JSON').get('stream')
554
555         if not stream:
556             raise ExtractorError('%s is offline' % channel_id, expected=True)
557
558         # Channel name may be typed if different case than the original channel name
559         # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing
560         # an invalid m3u8 URL. Working around by use of original channel name from stream
561         # JSON and fallback to lowercase if it's not available.
562         channel_id = stream.get('channel', {}).get('name') or channel_id.lower()
563
564         access_token = self._call_api(
565             'api/channels/%s/access_token' % channel_id, channel_id,
566             'Downloading channel access token')
567
568         query = {
569             'allow_source': 'true',
570             'allow_audio_only': 'true',
571             'allow_spectre': 'true',
572             'p': random.randint(1000000, 10000000),
573             'player': 'twitchweb',
574             'segment_preference': '4',
575             'sig': access_token['sig'].encode('utf-8'),
576             'token': access_token['token'].encode('utf-8'),
577         }
578         formats = self._extract_m3u8_formats(
579             '%s/api/channel/hls/%s.m3u8?%s'
580             % (self._USHER_BASE, channel_id, compat_urllib_parse_urlencode(query)),
581             channel_id, 'mp4')
582         self._prefer_source(formats)
583
584         view_count = stream.get('viewers')
585         timestamp = parse_iso8601(stream.get('created_at'))
586
587         channel = stream['channel']
588         title = self._live_title(channel.get('display_name') or channel.get('name'))
589         description = channel.get('status')
590
591         thumbnails = []
592         for thumbnail_key, thumbnail_url in stream['preview'].items():
593             m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
594             if not m:
595                 continue
596             thumbnails.append({
597                 'url': thumbnail_url,
598                 'width': int(m.group('width')),
599                 'height': int(m.group('height')),
600             })
601
602         return {
603             'id': compat_str(stream['_id']),
604             'display_id': channel_id,
605             'title': title,
606             'description': description,
607             'thumbnails': thumbnails,
608             'uploader': channel.get('display_name'),
609             'uploader_id': channel.get('name'),
610             'timestamp': timestamp,
611             'view_count': view_count,
612             'formats': formats,
613             'is_live': True,
614         }
615
616
617 class TwitchClipsIE(InfoExtractor):
618     IE_NAME = 'twitch:clips'
619     _VALID_URL = r'https?://clips\.twitch\.tv/(?:[^/]+/)*(?P<id>[^/?#&]+)'
620
621     _TESTS = [{
622         'url': 'https://clips.twitch.tv/ea/AggressiveCobraPoooound',
623         'md5': '761769e1eafce0ffebfb4089cb3847cd',
624         'info_dict': {
625             'id': 'AggressiveCobraPoooound',
626             'ext': 'mp4',
627             'title': 'EA Play 2016 Live from the Novo Theatre',
628             'thumbnail': r're:^https?://.*\.jpg',
629             'creator': 'EA',
630             'uploader': 'stereotype_',
631             'uploader_id': 'stereotype_',
632         },
633     }, {
634         # multiple formats
635         'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
636         'only_matching': True,
637     }]
638
639     def _real_extract(self, url):
640         video_id = self._match_id(url)
641
642         webpage = self._download_webpage(url, video_id)
643
644         clip = self._parse_json(
645             self._search_regex(
646                 r'(?s)clipInfo\s*=\s*({.+?});', webpage, 'clip info'),
647             video_id, transform_source=js_to_json)
648
649         title = clip.get('title') or clip.get('channel_title') or self._og_search_title(webpage)
650
651         formats = [{
652             'url': option['source'],
653             'format_id': option.get('quality'),
654             'height': int_or_none(option.get('quality')),
655         } for option in clip.get('quality_options', []) if option.get('source')]
656
657         if not formats:
658             formats = [{
659                 'url': clip['clip_video_url'],
660             }]
661
662         self._sort_formats(formats)
663
664         return {
665             'id': video_id,
666             'title': title,
667             'thumbnail': self._og_search_thumbnail(webpage),
668             'creator': clip.get('broadcaster_display_name') or clip.get('broadcaster_login'),
669             'uploader': clip.get('curator_login'),
670             'uploader_id': clip.get('curator_display_name'),
671             'formats': formats,
672         }