You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

229 lines
8.8 KiB

  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import itertools
  4. import re
  5. from .common import InfoExtractor
  6. from ..utils import (
  7. compat_urllib_parse,
  8. compat_urllib_request,
  9. ExtractorError,
  10. parse_iso8601,
  11. )
  12. class TwitchIE(InfoExtractor):
  13. # TODO: One broadcast may be split into multiple videos. The key
  14. # 'broadcast_id' is the same for all parts, and 'broadcast_part'
  15. # starts at 1 and increases. Can we treat all parts as one video?
  16. _VALID_URL = r"""(?x)^(?:http://)?(?:www\.)?twitch\.tv/
  17. (?:
  18. (?P<channelid>[^/]+)|
  19. (?:(?:[^/]+)/b/(?P<videoid>[^/]+))|
  20. (?:(?:[^/]+)/c/(?P<chapterid>[^/]+))
  21. )
  22. /?(?:\#.*)?$
  23. """
  24. _PAGE_LIMIT = 100
  25. _API_BASE = 'https://api.twitch.tv'
  26. _LOGIN_URL = 'https://secure.twitch.tv/user/login'
  27. _TESTS = [{
  28. 'url': 'http://www.twitch.tv/riotgames/b/577357806',
  29. 'info_dict': {
  30. 'id': 'a577357806',
  31. 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
  32. },
  33. 'playlist_mincount': 12,
  34. }, {
  35. 'url': 'http://www.twitch.tv/acracingleague/c/5285812',
  36. 'info_dict': {
  37. 'id': 'c5285812',
  38. 'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
  39. },
  40. 'playlist_mincount': 3,
  41. }, {
  42. 'url': 'http://www.twitch.tv/vanillatv',
  43. 'info_dict': {
  44. 'id': 'vanillatv',
  45. 'title': 'VanillaTV',
  46. },
  47. 'playlist_mincount': 412,
  48. }]
  49. def _handle_error(self, response):
  50. if not isinstance(response, dict):
  51. return
  52. error = response.get('error')
  53. if error:
  54. raise ExtractorError(
  55. '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
  56. expected=True)
  57. def _download_json(self, url, video_id, note='Downloading JSON metadata'):
  58. response = super(TwitchIE, self)._download_json(url, video_id, note)
  59. self._handle_error(response)
  60. return response
  61. def _extract_media(self, item, item_id):
  62. ITEMS = {
  63. 'a': 'video',
  64. 'c': 'chapter',
  65. }
  66. info = self._extract_info(self._download_json(
  67. '%s/kraken/videos/%s%s' % (self._API_BASE, item, item_id), item_id,
  68. 'Downloading %s info JSON' % ITEMS[item]))
  69. response = self._download_json(
  70. '%s/api/videos/%s%s' % (self._API_BASE, item, item_id), item_id,
  71. 'Downloading %s playlist JSON' % ITEMS[item])
  72. entries = []
  73. chunks = response['chunks']
  74. qualities = list(chunks.keys())
  75. for num, fragment in enumerate(zip(*chunks.values()), start=1):
  76. formats = []
  77. for fmt_num, fragment_fmt in enumerate(fragment):
  78. format_id = qualities[fmt_num]
  79. fmt = {
  80. 'url': fragment_fmt['url'],
  81. 'format_id': format_id,
  82. 'quality': 1 if format_id == 'live' else 0,
  83. }
  84. m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
  85. if m:
  86. fmt['height'] = int(m.group('height'))
  87. formats.append(fmt)
  88. self._sort_formats(formats)
  89. entry = dict(info)
  90. entry['id'] = '%s_%d' % (entry['id'], num)
  91. entry['title'] = '%s part %d' % (entry['title'], num)
  92. entry['formats'] = formats
  93. entries.append(entry)
  94. return self.playlist_result(entries, info['id'], info['title'])
  95. def _extract_info(self, info):
  96. return {
  97. 'id': info['_id'],
  98. 'title': info['title'],
  99. 'description': info['description'],
  100. 'duration': info['length'],
  101. 'thumbnail': info['preview'],
  102. 'uploader': info['channel']['display_name'],
  103. 'uploader_id': info['channel']['name'],
  104. 'timestamp': parse_iso8601(info['recorded_at']),
  105. 'view_count': info['views'],
  106. }
  107. def _real_initialize(self):
  108. self._login()
  109. def _login(self):
  110. (username, password) = self._get_login_info()
  111. if username is None:
  112. return
  113. login_page = self._download_webpage(
  114. self._LOGIN_URL, None, 'Downloading login page')
  115. authenticity_token = self._search_regex(
  116. r'<input name="authenticity_token" type="hidden" value="([^"]+)"',
  117. login_page, 'authenticity token')
  118. login_form = {
  119. 'utf8': ''.encode('utf-8'),
  120. 'authenticity_token': authenticity_token,
  121. 'redirect_on_login': '',
  122. 'embed_form': 'false',
  123. 'mp_source_action': '',
  124. 'follow': '',
  125. 'user[login]': username,
  126. 'user[password]': password,
  127. }
  128. request = compat_urllib_request.Request(
  129. self._LOGIN_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
  130. request.add_header('Referer', self._LOGIN_URL)
  131. response = self._download_webpage(
  132. request, None, 'Logging in as %s' % username)
  133. m = re.search(
  134. r"id=([\"'])login_error_message\1[^>]*>(?P<msg>[^<]+)", response)
  135. if m:
  136. raise ExtractorError(
  137. 'Unable to login: %s' % m.group('msg').strip(), expected=True)
  138. def _real_extract(self, url):
  139. mobj = re.match(self._VALID_URL, url)
  140. if mobj.group('chapterid'):
  141. return self._extract_media('c', mobj.group('chapterid'))
  142. """
  143. webpage = self._download_webpage(url, chapter_id)
  144. m = re.search(r'PP\.archive_id = "([0-9]+)";', webpage)
  145. if not m:
  146. raise ExtractorError('Cannot find archive of a chapter')
  147. archive_id = m.group(1)
  148. api = api_base + '/broadcast/by_chapter/%s.xml' % chapter_id
  149. doc = self._download_xml(
  150. api, chapter_id,
  151. note='Downloading chapter information',
  152. errnote='Chapter information download failed')
  153. for a in doc.findall('.//archive'):
  154. if archive_id == a.find('./id').text:
  155. break
  156. else:
  157. raise ExtractorError('Could not find chapter in chapter information')
  158. video_url = a.find('./video_file_url').text
  159. video_ext = video_url.rpartition('.')[2] or 'flv'
  160. chapter_api_url = 'https://api.twitch.tv/kraken/videos/c' + chapter_id
  161. chapter_info = self._download_json(
  162. chapter_api_url, 'c' + chapter_id,
  163. note='Downloading chapter metadata',
  164. errnote='Download of chapter metadata failed')
  165. bracket_start = int(doc.find('.//bracket_start').text)
  166. bracket_end = int(doc.find('.//bracket_end').text)
  167. # TODO determine start (and probably fix up file)
  168. # youtube-dl -v http://www.twitch.tv/firmbelief/c/1757457
  169. #video_url += '?start=' + TODO:start_timestamp
  170. # bracket_start is 13290, but we want 51670615
  171. self._downloader.report_warning('Chapter detected, but we can just download the whole file. '
  172. 'Chapter starts at %s and ends at %s' % (formatSeconds(bracket_start), formatSeconds(bracket_end)))
  173. info = {
  174. 'id': 'c' + chapter_id,
  175. 'url': video_url,
  176. 'ext': video_ext,
  177. 'title': chapter_info['title'],
  178. 'thumbnail': chapter_info['preview'],
  179. 'description': chapter_info['description'],
  180. 'uploader': chapter_info['channel']['display_name'],
  181. 'uploader_id': chapter_info['channel']['name'],
  182. }
  183. return info
  184. """
  185. elif mobj.group('videoid'):
  186. return self._extract_media('a', mobj.group('videoid'))
  187. elif mobj.group('channelid'):
  188. channel_id = mobj.group('channelid')
  189. info = self._download_json(
  190. '%s/kraken/channels/%s' % (self._API_BASE, channel_id),
  191. channel_id, 'Downloading channel info JSON')
  192. channel_name = info.get('display_name') or info.get('name')
  193. entries = []
  194. offset = 0
  195. limit = self._PAGE_LIMIT
  196. for counter in itertools.count(1):
  197. response = self._download_json(
  198. '%s/kraken/channels/%s/videos/?offset=%d&limit=%d'
  199. % (self._API_BASE, channel_id, offset, limit),
  200. channel_id, 'Downloading channel videos JSON page %d' % counter)
  201. videos = response['videos']
  202. if not videos:
  203. break
  204. entries.extend([self.url_result(video['url'], 'Twitch') for video in videos])
  205. offset += limit
  206. return self.playlist_result(entries, channel_id, channel_name)