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