[twitch] Rename extractor and support channel videos
[youtube-dl] / youtube_dl / extractor / twitch.py
1 from __future__ import unicode_literals
2
3 import itertools
4 import re
5
6 from .common import InfoExtractor
7 from ..utils import (
8     ExtractorError,
9     parse_iso8601,
10 )
11
12
13 class TwitchIE(InfoExtractor):
14     # TODO: One broadcast may be split into multiple videos. The key
15     # 'broadcast_id' is the same for all parts, and 'broadcast_part'
16     # starts at 1 and increases. Can we treat all parts as one video?
17     _VALID_URL = r"""(?x)^(?:http://)?(?:www\.)?twitch\.tv/
18         (?:
19             (?P<channelid>[^/]+)|
20             (?:(?:[^/]+)/b/(?P<videoid>[^/]+))|
21             (?:(?:[^/]+)/c/(?P<chapterid>[^/]+))
22         )
23         /?(?:\#.*)?$
24         """
25     _PAGE_LIMIT = 100
26     _API_BASE = 'https://api.twitch.tv'
27     _TEST = {
28         'url': 'http://www.twitch.tv/thegamedevhub/b/296128360',
29         'md5': 'ecaa8a790c22a40770901460af191c9a',
30         'info_dict': {
31             'id': '296128360',
32             'ext': 'flv',
33             'upload_date': '20110927',
34             'uploader_id': 25114803,
35             'uploader': 'thegamedevhub',
36             'title': 'Beginner Series - Scripting With Python Pt.1'
37         }
38     }
39
40     def _handle_error(self, response):
41         if not isinstance(response, dict):
42             return
43         error = response.get('error')
44         if error:
45             raise ExtractorError(
46                 '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
47                 expected=True)
48
49     def _download_json(self, url, video_id, note='Downloading JSON metadata'):
50         response = super(TwitchIE, self)._download_json(url, video_id, note)
51         self._handle_error(response)
52         return response
53
54     def _extract_media(self, item, item_id):
55         ITEMS = {
56             'a': 'video',
57             'c': 'chapter',
58         }
59         info = self._extract_info(self._download_json(
60             '%s/kraken/videos/%s%s' % (self._API_BASE, item, item_id), item_id,
61             'Downloading %s info JSON' % ITEMS[item]))
62         response = self._download_json(
63             '%s/api/videos/%s%s' % (self._API_BASE, item, item_id), item_id,
64             'Downloading %s playlist JSON' % ITEMS[item])
65         entries = []
66         chunks = response['chunks']
67         qualities = list(chunks.keys())
68         for num, fragment in enumerate(zip(*chunks.values()), start=1):
69             formats = []
70             for fmt_num, fragment_fmt in enumerate(fragment):
71                 format_id = qualities[fmt_num]
72                 fmt = {
73                     'url': fragment_fmt['url'],
74                     'format_id': format_id,
75                     'quality': 1 if format_id == 'live' else 0,
76                 }
77                 m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
78                 if m:
79                     fmt['height'] = int(m.group('height'))
80                 formats.append(fmt)
81             self._sort_formats(formats)
82             entry = dict(info)
83             entry['title'] = '%s part %d' % (entry['title'], num)
84             entry['formats'] = formats
85             entries.append(entry)
86         return entries
87
88     def _extract_info(self, info):
89         return {
90             'id': info['_id'],
91             'title': info['title'],
92             'description': info['description'],
93             'duration': info['length'],
94             'thumbnail': info['preview'],
95             'uploader': info['channel']['display_name'],
96             'uploader_id': info['channel']['name'],
97             'timestamp': parse_iso8601(info['recorded_at']),
98             'view_count': info['views'],
99         }
100
101     def _real_extract(self, url):
102         mobj = re.match(self._VALID_URL, url)
103         if mobj.group('chapterid'):
104             return self._extract_media('c', mobj.group('chapterid'))
105
106             """
107             webpage = self._download_webpage(url, chapter_id)
108             m = re.search(r'PP\.archive_id = "([0-9]+)";', webpage)
109             if not m:
110                 raise ExtractorError('Cannot find archive of a chapter')
111             archive_id = m.group(1)
112
113             api = api_base + '/broadcast/by_chapter/%s.xml' % chapter_id
114             doc = self._download_xml(
115                 api, chapter_id,
116                 note='Downloading chapter information',
117                 errnote='Chapter information download failed')
118             for a in doc.findall('.//archive'):
119                 if archive_id == a.find('./id').text:
120                     break
121             else:
122                 raise ExtractorError('Could not find chapter in chapter information')
123
124             video_url = a.find('./video_file_url').text
125             video_ext = video_url.rpartition('.')[2] or 'flv'
126
127             chapter_api_url = 'https://api.twitch.tv/kraken/videos/c' + chapter_id
128             chapter_info = self._download_json(
129                 chapter_api_url, 'c' + chapter_id,
130                 note='Downloading chapter metadata',
131                 errnote='Download of chapter metadata failed')
132
133             bracket_start = int(doc.find('.//bracket_start').text)
134             bracket_end = int(doc.find('.//bracket_end').text)
135
136             # TODO determine start (and probably fix up file)
137             #  youtube-dl -v http://www.twitch.tv/firmbelief/c/1757457
138             #video_url += '?start=' + TODO:start_timestamp
139             # bracket_start is 13290, but we want 51670615
140             self._downloader.report_warning('Chapter detected, but we can just download the whole file. '
141                                             'Chapter starts at %s and ends at %s' % (formatSeconds(bracket_start), formatSeconds(bracket_end)))
142
143             info = {
144                 'id': 'c' + chapter_id,
145                 'url': video_url,
146                 'ext': video_ext,
147                 'title': chapter_info['title'],
148                 'thumbnail': chapter_info['preview'],
149                 'description': chapter_info['description'],
150                 'uploader': chapter_info['channel']['display_name'],
151                 'uploader_id': chapter_info['channel']['name'],
152             }
153             return info
154             """
155         elif mobj.group('videoid'):
156             return self._extract_media('a', mobj.group('videoid'))
157         elif mobj.group('channelid'):
158             channel_id = mobj.group('channelid')
159             info = self._download_json(
160                 '%s/kraken/channels/%s' % (self._API_BASE, channel_id),
161                 channel_id, 'Downloading channel info JSON')
162             channel_name = info.get('display_name') or info.get('name')
163             entries = []
164             offset = 0
165             limit = self._PAGE_LIMIT
166             for counter in itertools.count(1):
167                 response = self._download_json(
168                     '%s/kraken/channels/%s/videos/?offset=%d&limit=%d'
169                     % (self._API_BASE, channel_id, offset, limit),
170                     channel_id, 'Downloading channel videos JSON page %d' % counter)
171                 videos = response['videos']
172                 if not videos:
173                     break
174                 entries.extend([self.url_result(video['url'], 'Twitch') for video in videos])
175                 offset += limit
176             return self.playlist_result(entries, channel_id, channel_name)