1 from __future__ import unicode_literals
6 from .common import InfoExtractor
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/
20 (?:(?:[^/]+)/b/(?P<videoid>[^/]+))|
21 (?:(?:[^/]+)/c/(?P<chapterid>[^/]+))
26 _API_BASE = 'https://api.twitch.tv'
28 'url': 'http://www.twitch.tv/thegamedevhub/b/296128360',
29 'md5': 'ecaa8a790c22a40770901460af191c9a',
33 'upload_date': '20110927',
34 'uploader_id': 25114803,
35 'uploader': 'thegamedevhub',
36 'title': 'Beginner Series - Scripting With Python Pt.1'
40 def _handle_error(self, response):
41 if not isinstance(response, dict):
43 error = response.get('error')
46 '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
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)
54 def _extract_media(self, item, item_id):
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])
66 chunks = response['chunks']
67 qualities = list(chunks.keys())
68 for num, fragment in enumerate(zip(*chunks.values()), start=1):
70 for fmt_num, fragment_fmt in enumerate(fragment):
71 format_id = qualities[fmt_num]
73 'url': fragment_fmt['url'],
74 'format_id': format_id,
75 'quality': 1 if format_id == 'live' else 0,
77 m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
79 fmt['height'] = int(m.group('height'))
81 self._sort_formats(formats)
83 entry['title'] = '%s part %d' % (entry['title'], num)
84 entry['formats'] = formats
88 def _extract_info(self, info):
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'],
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'))
107 webpage = self._download_webpage(url, chapter_id)
108 m = re.search(r'PP\.archive_id = "([0-9]+)";', webpage)
110 raise ExtractorError('Cannot find archive of a chapter')
111 archive_id = m.group(1)
113 api = api_base + '/broadcast/by_chapter/%s.xml' % chapter_id
114 doc = self._download_xml(
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:
122 raise ExtractorError('Could not find chapter in chapter information')
124 video_url = a.find('./video_file_url').text
125 video_ext = video_url.rpartition('.')[2] or 'flv'
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')
133 bracket_start = int(doc.find('.//bracket_start').text)
134 bracket_end = int(doc.find('.//bracket_end').text)
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)))
144 'id': 'c' + chapter_id,
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'],
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')
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']
174 entries.extend([self.url_result(video['url'], 'Twitch') for video in videos])
176 return self.playlist_result(entries, channel_id, channel_name)