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.

153 lines
6.2 KiB

  1. import json
  2. import os
  3. import re
  4. from .common import InfoExtractor
  5. from ..utils import (
  6. ExtractorError,
  7. formatSeconds,
  8. )
  9. class JustinTVIE(InfoExtractor):
  10. """Information extractor for justin.tv and twitch.tv"""
  11. # TODO: One broadcast may be split into multiple videos. The key
  12. # 'broadcast_id' is the same for all parts, and 'broadcast_part'
  13. # starts at 1 and increases. Can we treat all parts as one video?
  14. _VALID_URL = r"""(?x)^(?:http://)?(?:www\.)?(?:twitch|justin)\.tv/
  15. (?:
  16. (?P<channelid>[^/]+)|
  17. (?:(?:[^/]+)/b/(?P<videoid>[^/]+))|
  18. (?:(?:[^/]+)/c/(?P<chapterid>[^/]+))
  19. )
  20. /?(?:\#.*)?$
  21. """
  22. _JUSTIN_PAGE_LIMIT = 100
  23. IE_NAME = u'justin.tv'
  24. _TEST = {
  25. u'url': u'http://www.twitch.tv/thegamedevhub/b/296128360',
  26. u'file': u'296128360.flv',
  27. u'md5': u'ecaa8a790c22a40770901460af191c9a',
  28. u'info_dict': {
  29. u"upload_date": u"20110927",
  30. u"uploader_id": 25114803,
  31. u"uploader": u"thegamedevhub",
  32. u"title": u"Beginner Series - Scripting With Python Pt.1"
  33. }
  34. }
  35. def report_download_page(self, channel, offset):
  36. """Report attempt to download a single page of videos."""
  37. self.to_screen(u'%s: Downloading video information from %d to %d' %
  38. (channel, offset, offset + self._JUSTIN_PAGE_LIMIT))
  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. u'Downloading video info JSON',
  43. u'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(u'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': 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. if mobj is None:
  70. raise ExtractorError(u'invalid URL: %s' % url)
  71. api_base = 'http://api.justin.tv'
  72. paged = False
  73. if mobj.group('channelid'):
  74. paged = True
  75. video_id = mobj.group('channelid')
  76. api = api_base + '/channel/archives/%s.json' % video_id
  77. elif mobj.group('chapterid'):
  78. chapter_id = mobj.group('chapterid')
  79. webpage = self._download_webpage(url, chapter_id)
  80. m = re.search(r'PP\.archive_id = "([0-9]+)";', webpage)
  81. if not m:
  82. raise ExtractorError(u'Cannot find archive of a chapter')
  83. archive_id = m.group(1)
  84. api = api_base + '/broadcast/by_chapter/%s.xml' % chapter_id
  85. doc = self._download_xml(api, chapter_id,
  86. note=u'Downloading chapter information',
  87. errnote=u'Chapter information download failed')
  88. for a in doc.findall('.//archive'):
  89. if archive_id == a.find('./id').text:
  90. break
  91. else:
  92. raise ExtractorError(u'Could not find chapter in chapter information')
  93. video_url = a.find('./video_file_url').text
  94. video_ext = video_url.rpartition('.')[2] or u'flv'
  95. chapter_api_url = u'https://api.twitch.tv/kraken/videos/c' + chapter_id
  96. chapter_info_json = self._download_webpage(chapter_api_url, u'c' + chapter_id,
  97. note='Downloading chapter metadata',
  98. errnote='Download of chapter metadata failed')
  99. chapter_info = json.loads(chapter_info_json)
  100. bracket_start = int(doc.find('.//bracket_start').text)
  101. bracket_end = int(doc.find('.//bracket_end').text)
  102. # TODO determine start (and probably fix up file)
  103. # youtube-dl -v http://www.twitch.tv/firmbelief/c/1757457
  104. #video_url += u'?start=' + TODO:start_timestamp
  105. # bracket_start is 13290, but we want 51670615
  106. self._downloader.report_warning(u'Chapter detected, but we can just download the whole file. '
  107. u'Chapter starts at %s and ends at %s' % (formatSeconds(bracket_start), formatSeconds(bracket_end)))
  108. info = {
  109. 'id': u'c' + chapter_id,
  110. 'url': video_url,
  111. 'ext': video_ext,
  112. 'title': chapter_info['title'],
  113. 'thumbnail': chapter_info['preview'],
  114. 'description': chapter_info['description'],
  115. 'uploader': chapter_info['channel']['display_name'],
  116. 'uploader_id': chapter_info['channel']['name'],
  117. }
  118. return [info]
  119. else:
  120. video_id = mobj.group('videoid')
  121. api = api_base + '/broadcast/by_archive/%s.json' % video_id
  122. self.report_extraction(video_id)
  123. info = []
  124. offset = 0
  125. limit = self._JUSTIN_PAGE_LIMIT
  126. while True:
  127. if paged:
  128. self.report_download_page(video_id, offset)
  129. page_url = api + ('?offset=%d&limit=%d' % (offset, limit))
  130. page_count, page_info = self._parse_page(page_url, video_id)
  131. info.extend(page_info)
  132. if not paged or page_count != limit:
  133. break
  134. offset += limit
  135. return info