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.

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