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.

154 lines
5.9 KiB

  1. from __future__ import unicode_literals
  2. import json
  3. import os
  4. import re
  5. from .common import InfoExtractor
  6. from ..utils import (
  7. compat_str,
  8. ExtractorError,
  9. formatSeconds,
  10. )
  11. class JustinTVIE(InfoExtractor):
  12. """Information extractor for justin.tv and twitch.tv"""
  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|justin)\.tv/
  17. (?:
  18. (?P<channelid>[^/]+)|
  19. (?:(?:[^/]+)/b/(?P<videoid>[^/]+))|
  20. (?:(?:[^/]+)/c/(?P<chapterid>[^/]+))
  21. )
  22. /?(?:\#.*)?$
  23. """
  24. _JUSTIN_PAGE_LIMIT = 100
  25. IE_NAME = 'justin.tv'
  26. IE_DESC = 'justin.tv and twitch.tv'
  27. _TEST = {
  28. 'url': 'http://www.twitch.tv/thegamedevhub/b/296128360',
  29. 'md5': 'ecaa8a790c22a40770901460af191c9a',
  30. 'info_dict': {
  31. 'id': '296128360',
  32. 'ext': 'flv',
  33. 'upload_date': '20110927',
  34. 'uploader_id': 25114803,
  35. 'uploader': 'thegamedevhub',
  36. 'title': 'Beginner Series - Scripting With Python Pt.1'
  37. }
  38. }
  39. # Return count of items, list of *valid* items
  40. def _parse_page(self, url, video_id):
  41. info_json = self._download_webpage(url, video_id,
  42. 'Downloading video info JSON',
  43. 'unable to download video info JSON')
  44. response = json.loads(info_json)
  45. if type(response) != list:
  46. error_text = response.get('error', 'unknown error')
  47. raise ExtractorError('Justin.tv API: %s' % error_text)
  48. info = []
  49. for clip in response:
  50. video_url = clip['video_file_url']
  51. if video_url:
  52. video_extension = os.path.splitext(video_url)[1][1:]
  53. video_date = re.sub('-', '', clip['start_time'][:10])
  54. video_uploader_id = clip.get('user_id', clip.get('channel_id'))
  55. video_id = clip['id']
  56. video_title = clip.get('title', video_id)
  57. info.append({
  58. 'id': compat_str(video_id),
  59. 'url': video_url,
  60. 'title': video_title,
  61. 'uploader': clip.get('channel_name', video_uploader_id),
  62. 'uploader_id': video_uploader_id,
  63. 'upload_date': video_date,
  64. 'ext': video_extension,
  65. })
  66. return (len(response), info)
  67. def _real_extract(self, url):
  68. mobj = re.match(self._VALID_URL, url)
  69. api_base = 'http://api.justin.tv'
  70. paged = False
  71. if mobj.group('channelid'):
  72. paged = True
  73. video_id = mobj.group('channelid')
  74. api = api_base + '/channel/archives/%s.json' % video_id
  75. elif mobj.group('chapterid'):
  76. chapter_id = mobj.group('chapterid')
  77. webpage = self._download_webpage(url, chapter_id)
  78. m = re.search(r'PP\.archive_id = "([0-9]+)";', webpage)
  79. if not m:
  80. raise ExtractorError('Cannot find archive of a chapter')
  81. archive_id = m.group(1)
  82. api = api_base + '/broadcast/by_chapter/%s.xml' % chapter_id
  83. doc = self._download_xml(
  84. api, chapter_id,
  85. note='Downloading chapter information',
  86. errnote='Chapter information download failed')
  87. for a in doc.findall('.//archive'):
  88. if archive_id == a.find('./id').text:
  89. break
  90. else:
  91. raise ExtractorError('Could not find chapter in chapter information')
  92. video_url = a.find('./video_file_url').text
  93. video_ext = video_url.rpartition('.')[2] or 'flv'
  94. chapter_api_url = 'https://api.twitch.tv/kraken/videos/c' + chapter_id
  95. chapter_info = self._download_json(
  96. chapter_api_url, 'c' + chapter_id,
  97. note='Downloading chapter metadata',
  98. errnote='Download of chapter metadata failed')
  99. bracket_start = int(doc.find('.//bracket_start').text)
  100. bracket_end = int(doc.find('.//bracket_end').text)
  101. # TODO determine start (and probably fix up file)
  102. # youtube-dl -v http://www.twitch.tv/firmbelief/c/1757457
  103. #video_url += '?start=' + TODO:start_timestamp
  104. # bracket_start is 13290, but we want 51670615
  105. self._downloader.report_warning('Chapter detected, but we can just download the whole file. '
  106. 'Chapter starts at %s and ends at %s' % (formatSeconds(bracket_start), formatSeconds(bracket_end)))
  107. info = {
  108. 'id': 'c' + chapter_id,
  109. 'url': video_url,
  110. 'ext': video_ext,
  111. 'title': chapter_info['title'],
  112. 'thumbnail': chapter_info['preview'],
  113. 'description': chapter_info['description'],
  114. 'uploader': chapter_info['channel']['display_name'],
  115. 'uploader_id': chapter_info['channel']['name'],
  116. }
  117. return info
  118. else:
  119. video_id = mobj.group('videoid')
  120. api = api_base + '/broadcast/by_archive/%s.json' % video_id
  121. entries = []
  122. offset = 0
  123. limit = self._JUSTIN_PAGE_LIMIT
  124. while True:
  125. if paged:
  126. self.report_download_page(video_id, offset)
  127. page_url = api + ('?offset=%d&limit=%d' % (offset, limit))
  128. page_count, page_info = self._parse_page(page_url, video_id)
  129. entries.extend(page_info)
  130. if not paged or page_count != limit:
  131. break
  132. offset += limit
  133. return {
  134. '_type': 'playlist',
  135. 'id': video_id,
  136. 'entries': entries,
  137. }