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