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.

247 lines
9.5 KiB

  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import itertools
  4. import re
  5. from .common import InfoExtractor
  6. from ..compat import (
  7. compat_urllib_parse,
  8. compat_urllib_request,
  9. )
  10. from ..utils import (
  11. ExtractorError,
  12. parse_iso8601,
  13. )
  14. class TwitchIE(InfoExtractor):
  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\.tv/
  19. (?:
  20. (?P<channelid>[^/]+)|
  21. (?:(?:[^/]+)/v/(?P<vodid>[^/]+))|
  22. (?:(?:[^/]+)/b/(?P<videoid>[^/]+))|
  23. (?:(?:[^/]+)/c/(?P<chapterid>[^/]+))
  24. )
  25. /?(?:\#.*)?$
  26. """
  27. _PAGE_LIMIT = 100
  28. _API_BASE = 'https://api.twitch.tv'
  29. _LOGIN_URL = 'https://secure.twitch.tv/user/login'
  30. _TESTS = [{
  31. 'url': 'http://www.twitch.tv/riotgames/b/577357806',
  32. 'info_dict': {
  33. 'id': 'a577357806',
  34. 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
  35. },
  36. 'playlist_mincount': 12,
  37. }, {
  38. 'url': 'http://www.twitch.tv/acracingleague/c/5285812',
  39. 'info_dict': {
  40. 'id': 'c5285812',
  41. 'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
  42. },
  43. 'playlist_mincount': 3,
  44. }, {
  45. 'url': 'http://www.twitch.tv/vanillatv',
  46. 'info_dict': {
  47. 'id': 'vanillatv',
  48. 'title': 'VanillaTV',
  49. },
  50. 'playlist_mincount': 412,
  51. }]
  52. def _handle_error(self, response):
  53. if not isinstance(response, dict):
  54. return
  55. error = response.get('error')
  56. if error:
  57. raise ExtractorError(
  58. '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
  59. expected=True)
  60. def _download_json(self, url, video_id, note='Downloading JSON metadata'):
  61. response = super(TwitchIE, self)._download_json(url, video_id, note)
  62. self._handle_error(response)
  63. return response
  64. def _extract_media(self, item, item_id):
  65. ITEMS = {
  66. 'a': 'video',
  67. 'v': 'vod',
  68. 'c': 'chapter',
  69. }
  70. info = self._extract_info(self._download_json(
  71. '%s/kraken/videos/%s%s' % (self._API_BASE, item, item_id), item_id,
  72. 'Downloading %s info JSON' % ITEMS[item]))
  73. if item == 'v':
  74. access_token = self._download_json(
  75. '%s/api/vods/%s/access_token' % (self._API_BASE, item_id), item_id,
  76. 'Downloading %s access token' % ITEMS[item])
  77. formats = self._extract_m3u8_formats(
  78. 'http://usher.twitch.tv/vod/%s?nauth=%s&nauthsig=%s'
  79. % (item_id, access_token['token'], access_token['sig']),
  80. item_id, 'mp4')
  81. info['formats'] = formats
  82. return info
  83. response = self._download_json(
  84. '%s/api/videos/%s%s' % (self._API_BASE, item, item_id), item_id,
  85. 'Downloading %s playlist JSON' % ITEMS[item])
  86. entries = []
  87. chunks = response['chunks']
  88. qualities = list(chunks.keys())
  89. for num, fragment in enumerate(zip(*chunks.values()), start=1):
  90. formats = []
  91. for fmt_num, fragment_fmt in enumerate(fragment):
  92. format_id = qualities[fmt_num]
  93. fmt = {
  94. 'url': fragment_fmt['url'],
  95. 'format_id': format_id,
  96. 'quality': 1 if format_id == 'live' else 0,
  97. }
  98. m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
  99. if m:
  100. fmt['height'] = int(m.group('height'))
  101. formats.append(fmt)
  102. self._sort_formats(formats)
  103. entry = dict(info)
  104. entry['id'] = '%s_%d' % (entry['id'], num)
  105. entry['title'] = '%s part %d' % (entry['title'], num)
  106. entry['formats'] = formats
  107. entries.append(entry)
  108. return self.playlist_result(entries, info['id'], info['title'])
  109. def _extract_info(self, info):
  110. return {
  111. 'id': info['_id'],
  112. 'title': info['title'],
  113. 'description': info['description'],
  114. 'duration': info['length'],
  115. 'thumbnail': info['preview'],
  116. 'uploader': info['channel']['display_name'],
  117. 'uploader_id': info['channel']['name'],
  118. 'timestamp': parse_iso8601(info['recorded_at']),
  119. 'view_count': info['views'],
  120. }
  121. def _real_initialize(self):
  122. self._login()
  123. def _login(self):
  124. (username, password) = self._get_login_info()
  125. if username is None:
  126. return
  127. login_page = self._download_webpage(
  128. self._LOGIN_URL, None, 'Downloading login page')
  129. authenticity_token = self._search_regex(
  130. r'<input name="authenticity_token" type="hidden" value="([^"]+)"',
  131. login_page, 'authenticity token')
  132. login_form = {
  133. 'utf8': ''.encode('utf-8'),
  134. 'authenticity_token': authenticity_token,
  135. 'redirect_on_login': '',
  136. 'embed_form': 'false',
  137. 'mp_source_action': '',
  138. 'follow': '',
  139. 'user[login]': username,
  140. 'user[password]': password,
  141. }
  142. request = compat_urllib_request.Request(
  143. self._LOGIN_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
  144. request.add_header('Referer', self._LOGIN_URL)
  145. response = self._download_webpage(
  146. request, None, 'Logging in as %s' % username)
  147. m = re.search(
  148. r"id=([\"'])login_error_message\1[^>]*>(?P<msg>[^<]+)", response)
  149. if m:
  150. raise ExtractorError(
  151. 'Unable to login: %s' % m.group('msg').strip(), expected=True)
  152. def _real_extract(self, url):
  153. mobj = re.match(self._VALID_URL, url)
  154. if mobj.group('chapterid'):
  155. return self._extract_media('c', mobj.group('chapterid'))
  156. """
  157. webpage = self._download_webpage(url, chapter_id)
  158. m = re.search(r'PP\.archive_id = "([0-9]+)";', webpage)
  159. if not m:
  160. raise ExtractorError('Cannot find archive of a chapter')
  161. archive_id = m.group(1)
  162. api = api_base + '/broadcast/by_chapter/%s.xml' % chapter_id
  163. doc = self._download_xml(
  164. api, chapter_id,
  165. note='Downloading chapter information',
  166. errnote='Chapter information download failed')
  167. for a in doc.findall('.//archive'):
  168. if archive_id == a.find('./id').text:
  169. break
  170. else:
  171. raise ExtractorError('Could not find chapter in chapter information')
  172. video_url = a.find('./video_file_url').text
  173. video_ext = video_url.rpartition('.')[2] or 'flv'
  174. chapter_api_url = 'https://api.twitch.tv/kraken/videos/c' + chapter_id
  175. chapter_info = self._download_json(
  176. chapter_api_url, 'c' + chapter_id,
  177. note='Downloading chapter metadata',
  178. errnote='Download of chapter metadata failed')
  179. bracket_start = int(doc.find('.//bracket_start').text)
  180. bracket_end = int(doc.find('.//bracket_end').text)
  181. # TODO determine start (and probably fix up file)
  182. # youtube-dl -v http://www.twitch.tv/firmbelief/c/1757457
  183. #video_url += '?start=' + TODO:start_timestamp
  184. # bracket_start is 13290, but we want 51670615
  185. self._downloader.report_warning('Chapter detected, but we can just download the whole file. '
  186. 'Chapter starts at %s and ends at %s' % (formatSeconds(bracket_start), formatSeconds(bracket_end)))
  187. info = {
  188. 'id': 'c' + chapter_id,
  189. 'url': video_url,
  190. 'ext': video_ext,
  191. 'title': chapter_info['title'],
  192. 'thumbnail': chapter_info['preview'],
  193. 'description': chapter_info['description'],
  194. 'uploader': chapter_info['channel']['display_name'],
  195. 'uploader_id': chapter_info['channel']['name'],
  196. }
  197. return info
  198. """
  199. elif mobj.group('videoid'):
  200. return self._extract_media('a', mobj.group('videoid'))
  201. elif mobj.group('vodid'):
  202. return self._extract_media('v', mobj.group('vodid'))
  203. elif mobj.group('channelid'):
  204. channel_id = mobj.group('channelid')
  205. info = self._download_json(
  206. '%s/kraken/channels/%s' % (self._API_BASE, channel_id),
  207. channel_id, 'Downloading channel info JSON')
  208. channel_name = info.get('display_name') or info.get('name')
  209. entries = []
  210. offset = 0
  211. limit = self._PAGE_LIMIT
  212. for counter in itertools.count(1):
  213. response = self._download_json(
  214. '%s/kraken/channels/%s/videos/?offset=%d&limit=%d'
  215. % (self._API_BASE, channel_id, offset, limit),
  216. channel_id, 'Downloading channel videos JSON page %d' % counter)
  217. videos = response['videos']
  218. if not videos:
  219. break
  220. entries.extend([self.url_result(video['url'], 'Twitch') for video in videos])
  221. offset += limit
  222. return self.playlist_result(entries, channel_id, channel_name)