justintv.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. from __future__ import unicode_literals
  2. import itertools
  3. import json
  4. import os
  5. import re
  6. from .common import InfoExtractor
  7. from ..utils import (
  8. compat_str,
  9. ExtractorError,
  10. formatSeconds,
  11. parse_iso8601,
  12. )
  13. class JustinTVIE(InfoExtractor):
  14. """Information extractor for justin.tv and twitch.tv"""
  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|justin)\.tv/
  19. (?:
  20. (?P<channelid>[^/]+)|
  21. (?:(?:[^/]+)/b/(?P<videoid>[^/]+))|
  22. (?:(?:[^/]+)/c/(?P<chapterid>[^/]+))
  23. )
  24. /?(?:\#.*)?$
  25. """
  26. _JUSTIN_PAGE_LIMIT = 100
  27. IE_NAME = 'justin.tv'
  28. IE_DESC = 'justin.tv and twitch.tv'
  29. _TEST = {
  30. 'url': 'http://www.twitch.tv/thegamedevhub/b/296128360',
  31. 'md5': 'ecaa8a790c22a40770901460af191c9a',
  32. 'info_dict': {
  33. 'id': '296128360',
  34. 'ext': 'flv',
  35. 'upload_date': '20110927',
  36. 'uploader_id': 25114803,
  37. 'uploader': 'thegamedevhub',
  38. 'title': 'Beginner Series - Scripting With Python Pt.1'
  39. }
  40. }
  41. _API_BASE = 'https://api.twitch.tv'
  42. # Return count of items, list of *valid* items
  43. def _parse_page(self, url, video_id, counter):
  44. info_json = self._download_webpage(
  45. url, video_id,
  46. 'Downloading video info JSON on page %d' % counter,
  47. 'Unable to download video info JSON %d' % counter)
  48. response = json.loads(info_json)
  49. if type(response) != list:
  50. error_text = response.get('error', 'unknown error')
  51. raise ExtractorError('Justin.tv API: %s' % error_text)
  52. info = []
  53. for clip in response:
  54. video_url = clip['video_file_url']
  55. if video_url:
  56. video_extension = os.path.splitext(video_url)[1][1:]
  57. video_date = re.sub('-', '', clip['start_time'][:10])
  58. video_uploader_id = clip.get('user_id', clip.get('channel_id'))
  59. video_id = clip['id']
  60. video_title = clip.get('title', video_id)
  61. info.append({
  62. 'id': compat_str(video_id),
  63. 'url': video_url,
  64. 'title': video_title,
  65. 'uploader': clip.get('channel_name', video_uploader_id),
  66. 'uploader_id': video_uploader_id,
  67. 'upload_date': video_date,
  68. 'ext': video_extension,
  69. })
  70. return (len(response), info)
  71. def _handle_error(self, response):
  72. if not isinstance(response, dict):
  73. return
  74. error = response.get('error')
  75. if error:
  76. raise ExtractorError(
  77. '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
  78. expected=True)
  79. def _download_json(self, url, video_id, note='Downloading JSON metadata'):
  80. response = super(JustinTVIE, self)._download_json(url, video_id, note)
  81. self._handle_error(response)
  82. return response
  83. def _extract_media(self, item, item_id):
  84. ITEMS = {
  85. 'a': 'video',
  86. 'c': 'chapter',
  87. }
  88. info = self._extract_info(self._download_json(
  89. '%s/kraken/videos/%s%s' % (self._API_BASE, item, item_id), item_id,
  90. 'Downloading %s info JSON' % ITEMS[item]))
  91. response = self._download_json(
  92. '%s/api/videos/%s%s' % (self._API_BASE, item, item_id), item_id,
  93. 'Downloading %s playlist JSON' % ITEMS[item])
  94. entries = []
  95. chunks = response['chunks']
  96. qualities = list(chunks.keys())
  97. for num, fragment in enumerate(zip(*chunks.values()), start=1):
  98. formats = []
  99. for fmt_num, fragment_fmt in enumerate(fragment):
  100. format_id = qualities[fmt_num]
  101. fmt = {
  102. 'url': fragment_fmt['url'],
  103. 'format_id': format_id,
  104. 'quality': 1 if format_id == 'live' else 0,
  105. }
  106. m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
  107. if m:
  108. fmt['height'] = int(m.group('height'))
  109. formats.append(fmt)
  110. self._sort_formats(formats)
  111. entry = dict(info)
  112. entry['title'] = '%s part %d' % (entry['title'], num)
  113. entry['formats'] = formats
  114. entries.append(entry)
  115. return entries
  116. def _extract_info(self, info):
  117. return {
  118. 'id': info['_id'],
  119. 'title': info['title'],
  120. 'description': info['description'],
  121. 'duration': info['length'],
  122. 'thumbnail': info['preview'],
  123. 'uploader': info['channel']['display_name'],
  124. 'uploader_id': info['channel']['name'],
  125. 'timestamp': parse_iso8601(info['recorded_at']),
  126. 'view_count': info['views'],
  127. }
  128. def _real_extract(self, url):
  129. mobj = re.match(self._VALID_URL, url)
  130. api_base = 'http://api.twitch.tv'
  131. paged = False
  132. if mobj.group('channelid'):
  133. paged = True
  134. video_id = mobj.group('channelid')
  135. api = api_base + '/channel/archives/%s.json' % video_id
  136. elif mobj.group('chapterid'):
  137. return self._extract_media('c', mobj.group('chapterid'))
  138. """
  139. webpage = self._download_webpage(url, chapter_id)
  140. m = re.search(r'PP\.archive_id = "([0-9]+)";', webpage)
  141. if not m:
  142. raise ExtractorError('Cannot find archive of a chapter')
  143. archive_id = m.group(1)
  144. api = api_base + '/broadcast/by_chapter/%s.xml' % chapter_id
  145. doc = self._download_xml(
  146. api, chapter_id,
  147. note='Downloading chapter information',
  148. errnote='Chapter information download failed')
  149. for a in doc.findall('.//archive'):
  150. if archive_id == a.find('./id').text:
  151. break
  152. else:
  153. raise ExtractorError('Could not find chapter in chapter information')
  154. video_url = a.find('./video_file_url').text
  155. video_ext = video_url.rpartition('.')[2] or 'flv'
  156. chapter_api_url = 'https://api.twitch.tv/kraken/videos/c' + chapter_id
  157. chapter_info = self._download_json(
  158. chapter_api_url, 'c' + chapter_id,
  159. note='Downloading chapter metadata',
  160. errnote='Download of chapter metadata failed')
  161. bracket_start = int(doc.find('.//bracket_start').text)
  162. bracket_end = int(doc.find('.//bracket_end').text)
  163. # TODO determine start (and probably fix up file)
  164. # youtube-dl -v http://www.twitch.tv/firmbelief/c/1757457
  165. #video_url += '?start=' + TODO:start_timestamp
  166. # bracket_start is 13290, but we want 51670615
  167. self._downloader.report_warning('Chapter detected, but we can just download the whole file. '
  168. 'Chapter starts at %s and ends at %s' % (formatSeconds(bracket_start), formatSeconds(bracket_end)))
  169. info = {
  170. 'id': 'c' + chapter_id,
  171. 'url': video_url,
  172. 'ext': video_ext,
  173. 'title': chapter_info['title'],
  174. 'thumbnail': chapter_info['preview'],
  175. 'description': chapter_info['description'],
  176. 'uploader': chapter_info['channel']['display_name'],
  177. 'uploader_id': chapter_info['channel']['name'],
  178. }
  179. return info
  180. """
  181. else:
  182. return self._extract_media('a', mobj.group('videoid'))
  183. entries = []
  184. offset = 0
  185. limit = self._JUSTIN_PAGE_LIMIT
  186. for counter in itertools.count(1):
  187. page_url = api + ('?offset=%d&limit=%d' % (offset, limit))
  188. page_count, page_info = self._parse_page(
  189. page_url, video_id, counter)
  190. entries.extend(page_info)
  191. if not paged or page_count != limit:
  192. break
  193. offset += limit
  194. return {
  195. '_type': 'playlist',
  196. 'id': video_id,
  197. 'entries': entries,
  198. }