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.

187 lines
7.4 KiB

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