twitch.py 7.0 KB

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