[twitch:vod] Add test for #6585
[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_parse_qs,
11     compat_str,
12     compat_urllib_parse,
13     compat_urllib_parse_urlparse,
14     compat_urllib_request,
15 )
16 from ..utils import (
17     ExtractorError,
18     int_or_none,
19     parse_duration,
20     parse_iso8601,
21 )
22
23
24 class TwitchBaseIE(InfoExtractor):
25     _VALID_URL_BASE = r'https?://(?:www\.)?twitch\.tv'
26
27     _API_BASE = 'https://api.twitch.tv'
28     _USHER_BASE = 'http://usher.twitch.tv'
29     _LOGIN_URL = 'https://secure.twitch.tv/login'
30     _LOGIN_POST_URL = 'https://passport.twitch.tv/authorize'
31     _NETRC_MACHINE = 'twitch'
32
33     def _handle_error(self, response):
34         if not isinstance(response, dict):
35             return
36         error = response.get('error')
37         if error:
38             raise ExtractorError(
39                 '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
40                 expected=True)
41
42     def _download_json(self, url, video_id, note='Downloading JSON metadata'):
43         headers = {
44             'Referer': 'http://api.twitch.tv/crossdomain/receiver.html?v=2',
45             'X-Requested-With': 'XMLHttpRequest',
46         }
47         for cookie in self._downloader.cookiejar:
48             if cookie.name == 'api_token':
49                 headers['Twitch-Api-Token'] = cookie.value
50         request = compat_urllib_request.Request(url, headers=headers)
51         response = super(TwitchBaseIE, self)._download_json(request, video_id, note)
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         login_page = self._download_webpage(
64             self._LOGIN_URL, None, 'Downloading login page')
65
66         login_form = self._hidden_inputs(login_page)
67
68         login_form.update({
69             'login': username.encode('utf-8'),
70             'password': password.encode('utf-8'),
71         })
72
73         request = compat_urllib_request.Request(
74             self._LOGIN_POST_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
75         request.add_header('Referer', self._LOGIN_URL)
76         response = self._download_webpage(
77             request, None, 'Logging in as %s' % username)
78
79         error_message = self._search_regex(
80             r'<div[^>]+class="subwindow_notice"[^>]*>([^<]+)</div>',
81             response, 'error message', default=None)
82         if error_message:
83             raise ExtractorError(
84                 'Unable to login. Twitch said: %s' % error_message, expected=True)
85
86         if '>Reset your password<' in response:
87             self.report_warning('Twitch asks you to reset your password, go to https://secure.twitch.tv/reset/submit')
88
89     def _prefer_source(self, formats):
90         try:
91             source = next(f for f in formats if f['format_id'] == 'Source')
92             source['preference'] = 10
93         except StopIteration:
94             pass  # No Source stream present
95         self._sort_formats(formats)
96
97
98 class TwitchItemBaseIE(TwitchBaseIE):
99     def _download_info(self, item, item_id):
100         return self._extract_info(self._download_json(
101             '%s/kraken/videos/%s%s' % (self._API_BASE, item, item_id), item_id,
102             'Downloading %s info JSON' % self._ITEM_TYPE))
103
104     def _extract_media(self, item_id):
105         info = self._download_info(self._ITEM_SHORTCUT, item_id)
106         response = self._download_json(
107             '%s/api/videos/%s%s' % (self._API_BASE, self._ITEM_SHORTCUT, item_id), item_id,
108             'Downloading %s playlist JSON' % self._ITEM_TYPE)
109         entries = []
110         chunks = response['chunks']
111         qualities = list(chunks.keys())
112         for num, fragment in enumerate(zip(*chunks.values()), start=1):
113             formats = []
114             for fmt_num, fragment_fmt in enumerate(fragment):
115                 format_id = qualities[fmt_num]
116                 fmt = {
117                     'url': fragment_fmt['url'],
118                     'format_id': format_id,
119                     'quality': 1 if format_id == 'live' else 0,
120                 }
121                 m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
122                 if m:
123                     fmt['height'] = int(m.group('height'))
124                 formats.append(fmt)
125             self._sort_formats(formats)
126             entry = dict(info)
127             entry['id'] = '%s_%d' % (entry['id'], num)
128             entry['title'] = '%s part %d' % (entry['title'], num)
129             entry['formats'] = formats
130             entries.append(entry)
131         return self.playlist_result(entries, info['id'], info['title'])
132
133     def _extract_info(self, info):
134         return {
135             'id': info['_id'],
136             'title': info.get('title') or 'Untitled Broadcast',
137             'description': info.get('description'),
138             'duration': int_or_none(info.get('length')),
139             'thumbnail': info.get('preview'),
140             'uploader': info.get('channel', {}).get('display_name'),
141             'uploader_id': info.get('channel', {}).get('name'),
142             'timestamp': parse_iso8601(info.get('recorded_at')),
143             'view_count': int_or_none(info.get('views')),
144         }
145
146     def _real_extract(self, url):
147         return self._extract_media(self._match_id(url))
148
149
150 class TwitchVideoIE(TwitchItemBaseIE):
151     IE_NAME = 'twitch:video'
152     _VALID_URL = r'%s/[^/]+/b/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
153     _ITEM_TYPE = 'video'
154     _ITEM_SHORTCUT = 'a'
155
156     _TEST = {
157         'url': 'http://www.twitch.tv/riotgames/b/577357806',
158         'info_dict': {
159             'id': 'a577357806',
160             'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
161         },
162         'playlist_mincount': 12,
163     }
164
165
166 class TwitchChapterIE(TwitchItemBaseIE):
167     IE_NAME = 'twitch:chapter'
168     _VALID_URL = r'%s/[^/]+/c/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
169     _ITEM_TYPE = 'chapter'
170     _ITEM_SHORTCUT = 'c'
171
172     _TESTS = [{
173         'url': 'http://www.twitch.tv/acracingleague/c/5285812',
174         'info_dict': {
175             'id': 'c5285812',
176             'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
177         },
178         'playlist_mincount': 3,
179     }, {
180         'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361',
181         'only_matching': True,
182     }]
183
184
185 class TwitchVodIE(TwitchItemBaseIE):
186     IE_NAME = 'twitch:vod'
187     _VALID_URL = r'%s/[^/]+/v/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
188     _ITEM_TYPE = 'vod'
189     _ITEM_SHORTCUT = 'v'
190
191     _TESTS = [{
192         'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s',
193         'info_dict': {
194             'id': 'v6528877',
195             'ext': 'mp4',
196             'title': 'LCK Summer Split - Week 6 Day 1',
197             'thumbnail': 're:^https?://.*\.jpg$',
198             'duration': 17208,
199             'timestamp': 1435131709,
200             'upload_date': '20150624',
201             'uploader': 'Riot Games',
202             'uploader_id': 'riotgames',
203             'view_count': int,
204             'start_time': 310,
205         },
206         'params': {
207             # m3u8 download
208             'skip_download': True,
209         },
210     }, {
211         # Untitled broadcast (title is None)
212         'url': 'http://www.twitch.tv/belkao_o/v/11230755',
213         'info_dict': {
214             'id': 'v11230755',
215             'ext': 'mp4',
216             'title': 'Untitled Broadcast',
217             'thumbnail': 're:^https?://.*\.jpg$',
218             'duration': 1638,
219             'timestamp': 1439746708,
220             'upload_date': '20150816',
221             'uploader': 'BelkAO_o',
222             'uploader_id': 'belkao_o',
223             'view_count': int,
224         },
225         'params': {
226             # m3u8 download
227             'skip_download': True,
228         },
229     }]
230
231     def _real_extract(self, url):
232         item_id = self._match_id(url)
233         info = self._download_info(self._ITEM_SHORTCUT, item_id)
234         access_token = self._download_json(
235             '%s/api/vods/%s/access_token' % (self._API_BASE, item_id), item_id,
236             'Downloading %s access token' % self._ITEM_TYPE)
237         formats = self._extract_m3u8_formats(
238             '%s/vod/%s?nauth=%s&nauthsig=%s&allow_source=true'
239             % (self._USHER_BASE, item_id, access_token['token'], access_token['sig']),
240             item_id, 'mp4')
241         self._prefer_source(formats)
242         info['formats'] = formats
243
244         parsed_url = compat_urllib_parse_urlparse(url)
245         query = compat_parse_qs(parsed_url.query)
246         if 't' in query:
247             info['start_time'] = parse_duration(query['t'][0])
248
249         return info
250
251
252 class TwitchPlaylistBaseIE(TwitchBaseIE):
253     _PLAYLIST_URL = '%s/kraken/channels/%%s/videos/?offset=%%d&limit=%%d' % TwitchBaseIE._API_BASE
254     _PAGE_LIMIT = 100
255
256     def _extract_playlist(self, channel_id):
257         info = self._download_json(
258             '%s/kraken/channels/%s' % (self._API_BASE, channel_id),
259             channel_id, 'Downloading channel info JSON')
260         channel_name = info.get('display_name') or info.get('name')
261         entries = []
262         offset = 0
263         limit = self._PAGE_LIMIT
264         for counter in itertools.count(1):
265             response = self._download_json(
266                 self._PLAYLIST_URL % (channel_id, offset, limit),
267                 channel_id, 'Downloading %s videos JSON page %d' % (self._PLAYLIST_TYPE, counter))
268             page_entries = self._extract_playlist_page(response)
269             if not page_entries:
270                 break
271             entries.extend(page_entries)
272             offset += limit
273         return self.playlist_result(
274             [self.url_result(entry) for entry in set(entries)],
275             channel_id, channel_name)
276
277     def _extract_playlist_page(self, response):
278         videos = response.get('videos')
279         return [video['url'] for video in videos] if videos else []
280
281     def _real_extract(self, url):
282         return self._extract_playlist(self._match_id(url))
283
284
285 class TwitchProfileIE(TwitchPlaylistBaseIE):
286     IE_NAME = 'twitch:profile'
287     _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
288     _PLAYLIST_TYPE = 'profile'
289
290     _TEST = {
291         'url': 'http://www.twitch.tv/vanillatv/profile',
292         'info_dict': {
293             'id': 'vanillatv',
294             'title': 'VanillaTV',
295         },
296         'playlist_mincount': 412,
297     }
298
299
300 class TwitchPastBroadcastsIE(TwitchPlaylistBaseIE):
301     IE_NAME = 'twitch:past_broadcasts'
302     _VALID_URL = r'%s/(?P<id>[^/]+)/profile/past_broadcasts/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
303     _PLAYLIST_URL = TwitchPlaylistBaseIE._PLAYLIST_URL + '&broadcasts=true'
304     _PLAYLIST_TYPE = 'past broadcasts'
305
306     _TEST = {
307         'url': 'http://www.twitch.tv/spamfish/profile/past_broadcasts',
308         'info_dict': {
309             'id': 'spamfish',
310             'title': 'Spamfish',
311         },
312         'playlist_mincount': 54,
313     }
314
315
316 class TwitchBookmarksIE(TwitchPlaylistBaseIE):
317     IE_NAME = 'twitch:bookmarks'
318     _VALID_URL = r'%s/(?P<id>[^/]+)/profile/bookmarks/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
319     _PLAYLIST_URL = '%s/api/bookmark/?user=%%s&offset=%%d&limit=%%d' % TwitchBaseIE._API_BASE
320     _PLAYLIST_TYPE = 'bookmarks'
321
322     _TEST = {
323         'url': 'http://www.twitch.tv/ognos/profile/bookmarks',
324         'info_dict': {
325             'id': 'ognos',
326             'title': 'Ognos',
327         },
328         'playlist_mincount': 3,
329     }
330
331     def _extract_playlist_page(self, response):
332         entries = []
333         for bookmark in response.get('bookmarks', []):
334             video = bookmark.get('video')
335             if not video:
336                 continue
337             entries.append(video['url'])
338         return entries
339
340
341 class TwitchStreamIE(TwitchBaseIE):
342     IE_NAME = 'twitch:stream'
343     _VALID_URL = r'%s/(?P<id>[^/#?]+)/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
344
345     _TESTS = [{
346         'url': 'http://www.twitch.tv/shroomztv',
347         'info_dict': {
348             'id': '12772022048',
349             'display_id': 'shroomztv',
350             'ext': 'mp4',
351             'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
352             'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
353             'is_live': True,
354             'timestamp': 1421928037,
355             'upload_date': '20150122',
356             'uploader': 'ShroomzTV',
357             'uploader_id': 'shroomztv',
358             'view_count': int,
359         },
360         'params': {
361             # m3u8 download
362             'skip_download': True,
363         },
364     }, {
365         'url': 'http://www.twitch.tv/miracle_doto#profile-0',
366         'only_matching': True,
367     }]
368
369     def _real_extract(self, url):
370         channel_id = self._match_id(url)
371
372         stream = self._download_json(
373             '%s/kraken/streams/%s' % (self._API_BASE, channel_id), channel_id,
374             'Downloading stream JSON').get('stream')
375
376         # Fallback on profile extraction if stream is offline
377         if not stream:
378             return self.url_result(
379                 'http://www.twitch.tv/%s/profile' % channel_id,
380                 'TwitchProfile', channel_id)
381
382         # Channel name may be typed if different case than the original channel name
383         # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing
384         # an invalid m3u8 URL. Working around by use of original channel name from stream
385         # JSON and fallback to lowercase if it's not available.
386         channel_id = stream.get('channel', {}).get('name') or channel_id.lower()
387
388         access_token = self._download_json(
389             '%s/api/channels/%s/access_token' % (self._API_BASE, channel_id), channel_id,
390             'Downloading channel access token')
391
392         query = {
393             'allow_source': 'true',
394             'p': random.randint(1000000, 10000000),
395             'player': 'twitchweb',
396             'segment_preference': '4',
397             'sig': access_token['sig'].encode('utf-8'),
398             'token': access_token['token'].encode('utf-8'),
399         }
400         formats = self._extract_m3u8_formats(
401             '%s/api/channel/hls/%s.m3u8?%s'
402             % (self._USHER_BASE, channel_id, compat_urllib_parse.urlencode(query)),
403             channel_id, 'mp4')
404         self._prefer_source(formats)
405
406         view_count = stream.get('viewers')
407         timestamp = parse_iso8601(stream.get('created_at'))
408
409         channel = stream['channel']
410         title = self._live_title(channel.get('display_name') or channel.get('name'))
411         description = channel.get('status')
412
413         thumbnails = []
414         for thumbnail_key, thumbnail_url in stream['preview'].items():
415             m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
416             if not m:
417                 continue
418             thumbnails.append({
419                 'url': thumbnail_url,
420                 'width': int(m.group('width')),
421                 'height': int(m.group('height')),
422             })
423
424         return {
425             'id': compat_str(stream['_id']),
426             'display_id': channel_id,
427             'title': title,
428             'description': description,
429             'thumbnails': thumbnails,
430             'uploader': channel.get('display_name'),
431             'uploader_id': channel.get('name'),
432             'timestamp': timestamp,
433             'view_count': view_count,
434             'formats': formats,
435             'is_live': True,
436         }