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.

256 lines
8.6 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 TwitchBaseIE(InfoExtractor):
  15. _VALID_URL_BASE = r'http://(?:www\.)?twitch\.tv'
  16. _API_BASE = 'https://api.twitch.tv'
  17. _LOGIN_URL = 'https://secure.twitch.tv/user/login'
  18. def _handle_error(self, response):
  19. if not isinstance(response, dict):
  20. return
  21. error = response.get('error')
  22. if error:
  23. raise ExtractorError(
  24. '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
  25. expected=True)
  26. def _download_json(self, url, video_id, note='Downloading JSON metadata'):
  27. response = super(TwitchBaseIE, self)._download_json(url, video_id, note)
  28. self._handle_error(response)
  29. return response
  30. def _real_initialize(self):
  31. self._login()
  32. def _login(self):
  33. (username, password) = self._get_login_info()
  34. if username is None:
  35. return
  36. login_page = self._download_webpage(
  37. self._LOGIN_URL, None, 'Downloading login page')
  38. authenticity_token = self._search_regex(
  39. r'<input name="authenticity_token" type="hidden" value="([^"]+)"',
  40. login_page, 'authenticity token')
  41. login_form = {
  42. 'utf8': ''.encode('utf-8'),
  43. 'authenticity_token': authenticity_token,
  44. 'redirect_on_login': '',
  45. 'embed_form': 'false',
  46. 'mp_source_action': '',
  47. 'follow': '',
  48. 'user[login]': username,
  49. 'user[password]': password,
  50. }
  51. request = compat_urllib_request.Request(
  52. self._LOGIN_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
  53. request.add_header('Referer', self._LOGIN_URL)
  54. response = self._download_webpage(
  55. request, None, 'Logging in as %s' % username)
  56. m = re.search(
  57. r"id=([\"'])login_error_message\1[^>]*>(?P<msg>[^<]+)", response)
  58. if m:
  59. raise ExtractorError(
  60. 'Unable to login: %s' % m.group('msg').strip(), expected=True)
  61. class TwitchItemBaseIE(TwitchBaseIE):
  62. def _download_info(self, item, item_id):
  63. return self._extract_info(self._download_json(
  64. '%s/kraken/videos/%s%s' % (self._API_BASE, item, item_id), item_id,
  65. 'Downloading %s info JSON' % self._ITEM_TYPE))
  66. def _extract_media(self, item_id):
  67. info = self._download_info(self._ITEM_SHORTCUT, item_id)
  68. response = self._download_json(
  69. '%s/api/videos/%s%s' % (self._API_BASE, self._ITEM_SHORTCUT, item_id), item_id,
  70. 'Downloading %s playlist JSON' % self._ITEM_TYPE)
  71. entries = []
  72. chunks = response['chunks']
  73. qualities = list(chunks.keys())
  74. for num, fragment in enumerate(zip(*chunks.values()), start=1):
  75. formats = []
  76. for fmt_num, fragment_fmt in enumerate(fragment):
  77. format_id = qualities[fmt_num]
  78. fmt = {
  79. 'url': fragment_fmt['url'],
  80. 'format_id': format_id,
  81. 'quality': 1 if format_id == 'live' else 0,
  82. }
  83. m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
  84. if m:
  85. fmt['height'] = int(m.group('height'))
  86. formats.append(fmt)
  87. self._sort_formats(formats)
  88. entry = dict(info)
  89. entry['id'] = '%s_%d' % (entry['id'], num)
  90. entry['title'] = '%s part %d' % (entry['title'], num)
  91. entry['formats'] = formats
  92. entries.append(entry)
  93. return self.playlist_result(entries, info['id'], info['title'])
  94. def _extract_info(self, info):
  95. return {
  96. 'id': info['_id'],
  97. 'title': info['title'],
  98. 'description': info['description'],
  99. 'duration': info['length'],
  100. 'thumbnail': info['preview'],
  101. 'uploader': info['channel']['display_name'],
  102. 'uploader_id': info['channel']['name'],
  103. 'timestamp': parse_iso8601(info['recorded_at']),
  104. 'view_count': info['views'],
  105. }
  106. def _real_extract(self, url):
  107. return self._extract_media(self._match_id(url))
  108. class TwitchVideoIE(TwitchItemBaseIE):
  109. IE_NAME = 'twitch:video'
  110. _VALID_URL = r'%s/[^/]+/b/(?P<id>[^/]+)' % TwitchBaseIE._VALID_URL_BASE
  111. _ITEM_TYPE = 'video'
  112. _ITEM_SHORTCUT = 'a'
  113. _TEST = {
  114. 'url': 'http://www.twitch.tv/riotgames/b/577357806',
  115. 'info_dict': {
  116. 'id': 'a577357806',
  117. 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
  118. },
  119. 'playlist_mincount': 12,
  120. }
  121. class TwitchChapterIE(TwitchItemBaseIE):
  122. IE_NAME = 'twitch:chapter'
  123. _VALID_URL = r'%s/[^/]+/c/(?P<id>[^/]+)' % TwitchBaseIE._VALID_URL_BASE
  124. _ITEM_TYPE = 'chapter'
  125. _ITEM_SHORTCUT = 'c'
  126. _TEST = {
  127. 'url': 'http://www.twitch.tv/acracingleague/c/5285812',
  128. 'info_dict': {
  129. 'id': 'c5285812',
  130. 'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
  131. },
  132. 'playlist_mincount': 3,
  133. }
  134. class TwitchVodIE(TwitchItemBaseIE):
  135. IE_NAME = 'twitch:vod'
  136. _VALID_URL = r'%s/[^/]+/v/(?P<id>[^/]+)' % TwitchBaseIE._VALID_URL_BASE
  137. _ITEM_TYPE = 'vod'
  138. _ITEM_SHORTCUT = 'v'
  139. _TEST = {
  140. 'url': 'http://www.twitch.tv/ksptv/v/3622000',
  141. 'info_dict': {
  142. 'id': 'v3622000',
  143. 'ext': 'mp4',
  144. 'title': '''KSPTV: Squadcast: "Everyone's on vacation so here's Dahud" Edition!''',
  145. 'thumbnail': 're:^https?://.*\.jpg$',
  146. 'duration': 6951,
  147. 'timestamp': 1419028564,
  148. 'upload_date': '20141219',
  149. 'uploader': 'KSPTV',
  150. 'uploader_id': 'ksptv',
  151. 'view_count': int,
  152. },
  153. 'params': {
  154. # m3u8 download
  155. 'skip_download': True,
  156. },
  157. }
  158. def _real_extract(self, url):
  159. item_id = self._match_id(url)
  160. info = self._download_info(self._ITEM_SHORTCUT, item_id)
  161. access_token = self._download_json(
  162. '%s/api/vods/%s/access_token' % (self._API_BASE, item_id), item_id,
  163. 'Downloading %s access token' % self._ITEM_TYPE)
  164. formats = self._extract_m3u8_formats(
  165. 'http://usher.twitch.tv/vod/%s?nauth=%s&nauthsig=%s'
  166. % (item_id, access_token['token'], access_token['sig']),
  167. item_id, 'mp4')
  168. info['formats'] = formats
  169. return info
  170. class TwitchPlaylistBaseIE(TwitchBaseIE):
  171. _PLAYLIST_URL = '%s/kraken/channels/%%s/videos/?offset=%%d&limit=%%d' % TwitchBaseIE._API_BASE
  172. _PAGE_LIMIT = 100
  173. def _extract_playlist(self, channel_id):
  174. info = self._download_json(
  175. '%s/kraken/channels/%s' % (self._API_BASE, channel_id),
  176. channel_id, 'Downloading channel info JSON')
  177. channel_name = info.get('display_name') or info.get('name')
  178. entries = []
  179. offset = 0
  180. limit = self._PAGE_LIMIT
  181. for counter in itertools.count(1):
  182. response = self._download_json(
  183. self._PLAYLIST_URL % (channel_id, offset, limit),
  184. channel_id, 'Downloading %s videos JSON page %d' % (self._PLAYLIST_TYPE, counter))
  185. videos = response['videos']
  186. if not videos:
  187. break
  188. entries.extend([self.url_result(video['url']) for video in videos])
  189. offset += limit
  190. return self.playlist_result(entries, channel_id, channel_name)
  191. def _real_extract(self, url):
  192. return self._extract_playlist(self._match_id(url))
  193. class TwitchProfileIE(TwitchPlaylistBaseIE):
  194. IE_NAME = 'twitch:profile'
  195. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  196. _PLAYLIST_TYPE = 'profile'
  197. _TEST = {
  198. 'url': 'http://www.twitch.tv/vanillatv/profile',
  199. 'info_dict': {
  200. 'id': 'vanillatv',
  201. 'title': 'VanillaTV',
  202. },
  203. 'playlist_mincount': 412,
  204. }
  205. class TwitchPastBroadcastsIE(TwitchPlaylistBaseIE):
  206. IE_NAME = 'twitch:past_broadcasts'
  207. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/past_broadcasts/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  208. _PLAYLIST_URL = TwitchPlaylistBaseIE._PLAYLIST_URL + '&broadcasts=true'
  209. _PLAYLIST_TYPE = 'past broadcasts'
  210. _TEST = {
  211. 'url': 'http://www.twitch.tv/spamfish/profile/past_broadcasts',
  212. 'info_dict': {
  213. 'id': 'spamfish',
  214. 'title': 'Spamfish',
  215. },
  216. 'playlist_mincount': 54,
  217. }