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.

403 lines
14 KiB

10 years ago
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import itertools
  4. import re
  5. import random
  6. from .common import InfoExtractor
  7. from ..compat import (
  8. compat_str,
  9. compat_urllib_parse,
  10. compat_urllib_request,
  11. )
  12. from ..utils import (
  13. ExtractorError,
  14. parse_iso8601,
  15. )
  16. class TwitchBaseIE(InfoExtractor):
  17. _VALID_URL_BASE = r'https?://(?:www\.)?twitch\.tv'
  18. _API_BASE = 'https://api.twitch.tv'
  19. _USHER_BASE = 'http://usher.twitch.tv'
  20. _LOGIN_URL = 'https://secure.twitch.tv/login'
  21. _LOGIN_POST_URL = 'https://passport.twitch.tv/authorize'
  22. _NETRC_MACHINE = 'twitch'
  23. def _handle_error(self, response):
  24. if not isinstance(response, dict):
  25. return
  26. error = response.get('error')
  27. if error:
  28. raise ExtractorError(
  29. '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
  30. expected=True)
  31. def _download_json(self, url, video_id, note='Downloading JSON metadata'):
  32. headers = {
  33. 'Referer': 'http://api.twitch.tv/crossdomain/receiver.html?v=2',
  34. 'X-Requested-With': 'XMLHttpRequest',
  35. }
  36. for cookie in self._downloader.cookiejar:
  37. if cookie.name == 'api_token':
  38. headers['Twitch-Api-Token'] = cookie.value
  39. request = compat_urllib_request.Request(url, headers=headers)
  40. response = super(TwitchBaseIE, self)._download_json(request, video_id, note)
  41. self._handle_error(response)
  42. return response
  43. def _real_initialize(self):
  44. self._login()
  45. def _login(self):
  46. (username, password) = self._get_login_info()
  47. if username is None:
  48. return
  49. login_page = self._download_webpage(
  50. self._LOGIN_URL, None, 'Downloading login page')
  51. login_form = self._hidden_inputs(login_page)
  52. login_form.update({
  53. 'login': username.encode('utf-8'),
  54. 'password': password.encode('utf-8'),
  55. })
  56. request = compat_urllib_request.Request(
  57. self._LOGIN_POST_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
  58. request.add_header('Referer', self._LOGIN_URL)
  59. response = self._download_webpage(
  60. request, None, 'Logging in as %s' % username)
  61. error_message = self._search_regex(
  62. r'<div[^>]+class="subwindow_notice"[^>]*>([^<]+)</div>',
  63. response, 'error message', default=None)
  64. if error_message:
  65. raise ExtractorError(
  66. 'Unable to login. Twitch said: %s' % error_message, expected=True)
  67. if '>Reset your password<' in response:
  68. self.report_warning('Twitch asks you to reset your password, go to https://secure.twitch.tv/reset/submit')
  69. def _prefer_source(self, formats):
  70. try:
  71. source = next(f for f in formats if f['format_id'] == 'Source')
  72. source['preference'] = 10
  73. except StopIteration:
  74. pass # No Source stream present
  75. self._sort_formats(formats)
  76. class TwitchItemBaseIE(TwitchBaseIE):
  77. def _download_info(self, item, item_id):
  78. return self._extract_info(self._download_json(
  79. '%s/kraken/videos/%s%s' % (self._API_BASE, item, item_id), item_id,
  80. 'Downloading %s info JSON' % self._ITEM_TYPE))
  81. def _extract_media(self, item_id):
  82. info = self._download_info(self._ITEM_SHORTCUT, item_id)
  83. response = self._download_json(
  84. '%s/api/videos/%s%s' % (self._API_BASE, self._ITEM_SHORTCUT, item_id), item_id,
  85. 'Downloading %s playlist JSON' % self._ITEM_TYPE)
  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_extract(self, url):
  122. return self._extract_media(self._match_id(url))
  123. class TwitchVideoIE(TwitchItemBaseIE):
  124. IE_NAME = 'twitch:video'
  125. _VALID_URL = r'%s/[^/]+/b/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
  126. _ITEM_TYPE = 'video'
  127. _ITEM_SHORTCUT = 'a'
  128. _TEST = {
  129. 'url': 'http://www.twitch.tv/riotgames/b/577357806',
  130. 'info_dict': {
  131. 'id': 'a577357806',
  132. 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
  133. },
  134. 'playlist_mincount': 12,
  135. }
  136. class TwitchChapterIE(TwitchItemBaseIE):
  137. IE_NAME = 'twitch:chapter'
  138. _VALID_URL = r'%s/[^/]+/c/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
  139. _ITEM_TYPE = 'chapter'
  140. _ITEM_SHORTCUT = 'c'
  141. _TESTS = [{
  142. 'url': 'http://www.twitch.tv/acracingleague/c/5285812',
  143. 'info_dict': {
  144. 'id': 'c5285812',
  145. 'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
  146. },
  147. 'playlist_mincount': 3,
  148. }, {
  149. 'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361',
  150. 'only_matching': True,
  151. }]
  152. class TwitchVodIE(TwitchItemBaseIE):
  153. IE_NAME = 'twitch:vod'
  154. _VALID_URL = r'%s/[^/]+/v/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
  155. _ITEM_TYPE = 'vod'
  156. _ITEM_SHORTCUT = 'v'
  157. _TEST = {
  158. 'url': 'http://www.twitch.tv/riotgames/v/6528877',
  159. 'info_dict': {
  160. 'id': 'v6528877',
  161. 'ext': 'mp4',
  162. 'title': 'LCK Summer Split - Week 6 Day 1',
  163. 'thumbnail': 're:^https?://.*\.jpg$',
  164. 'duration': 17208,
  165. 'timestamp': 1435131709,
  166. 'upload_date': '20150624',
  167. 'uploader': 'Riot Games',
  168. 'uploader_id': 'riotgames',
  169. 'view_count': int,
  170. },
  171. 'params': {
  172. # m3u8 download
  173. 'skip_download': True,
  174. },
  175. }
  176. def _real_extract(self, url):
  177. item_id = self._match_id(url)
  178. info = self._download_info(self._ITEM_SHORTCUT, item_id)
  179. access_token = self._download_json(
  180. '%s/api/vods/%s/access_token' % (self._API_BASE, item_id), item_id,
  181. 'Downloading %s access token' % self._ITEM_TYPE)
  182. formats = self._extract_m3u8_formats(
  183. '%s/vod/%s?nauth=%s&nauthsig=%s&allow_source=true'
  184. % (self._USHER_BASE, item_id, access_token['token'], access_token['sig']),
  185. item_id, 'mp4')
  186. self._prefer_source(formats)
  187. info['formats'] = formats
  188. return info
  189. class TwitchPlaylistBaseIE(TwitchBaseIE):
  190. _PLAYLIST_URL = '%s/kraken/channels/%%s/videos/?offset=%%d&limit=%%d' % TwitchBaseIE._API_BASE
  191. _PAGE_LIMIT = 100
  192. def _extract_playlist(self, channel_id):
  193. info = self._download_json(
  194. '%s/kraken/channels/%s' % (self._API_BASE, channel_id),
  195. channel_id, 'Downloading channel info JSON')
  196. channel_name = info.get('display_name') or info.get('name')
  197. entries = []
  198. offset = 0
  199. limit = self._PAGE_LIMIT
  200. for counter in itertools.count(1):
  201. response = self._download_json(
  202. self._PLAYLIST_URL % (channel_id, offset, limit),
  203. channel_id, 'Downloading %s videos JSON page %d' % (self._PLAYLIST_TYPE, counter))
  204. page_entries = self._extract_playlist_page(response)
  205. if not page_entries:
  206. break
  207. entries.extend(page_entries)
  208. offset += limit
  209. return self.playlist_result(
  210. [self.url_result(entry) for entry in set(entries)],
  211. channel_id, channel_name)
  212. def _extract_playlist_page(self, response):
  213. videos = response.get('videos')
  214. return [video['url'] for video in videos] if videos else []
  215. def _real_extract(self, url):
  216. return self._extract_playlist(self._match_id(url))
  217. class TwitchProfileIE(TwitchPlaylistBaseIE):
  218. IE_NAME = 'twitch:profile'
  219. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  220. _PLAYLIST_TYPE = 'profile'
  221. _TEST = {
  222. 'url': 'http://www.twitch.tv/vanillatv/profile',
  223. 'info_dict': {
  224. 'id': 'vanillatv',
  225. 'title': 'VanillaTV',
  226. },
  227. 'playlist_mincount': 412,
  228. }
  229. class TwitchPastBroadcastsIE(TwitchPlaylistBaseIE):
  230. IE_NAME = 'twitch:past_broadcasts'
  231. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/past_broadcasts/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  232. _PLAYLIST_URL = TwitchPlaylistBaseIE._PLAYLIST_URL + '&broadcasts=true'
  233. _PLAYLIST_TYPE = 'past broadcasts'
  234. _TEST = {
  235. 'url': 'http://www.twitch.tv/spamfish/profile/past_broadcasts',
  236. 'info_dict': {
  237. 'id': 'spamfish',
  238. 'title': 'Spamfish',
  239. },
  240. 'playlist_mincount': 54,
  241. }
  242. class TwitchBookmarksIE(TwitchPlaylistBaseIE):
  243. IE_NAME = 'twitch:bookmarks'
  244. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/bookmarks/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  245. _PLAYLIST_URL = '%s/api/bookmark/?user=%%s&offset=%%d&limit=%%d' % TwitchBaseIE._API_BASE
  246. _PLAYLIST_TYPE = 'bookmarks'
  247. _TEST = {
  248. 'url': 'http://www.twitch.tv/ognos/profile/bookmarks',
  249. 'info_dict': {
  250. 'id': 'ognos',
  251. 'title': 'Ognos',
  252. },
  253. 'playlist_mincount': 3,
  254. }
  255. def _extract_playlist_page(self, response):
  256. entries = []
  257. for bookmark in response.get('bookmarks', []):
  258. video = bookmark.get('video')
  259. if not video:
  260. continue
  261. entries.append(video['url'])
  262. return entries
  263. class TwitchStreamIE(TwitchBaseIE):
  264. IE_NAME = 'twitch:stream'
  265. _VALID_URL = r'%s/(?P<id>[^/]+)/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  266. _TEST = {
  267. 'url': 'http://www.twitch.tv/shroomztv',
  268. 'info_dict': {
  269. 'id': '12772022048',
  270. 'display_id': 'shroomztv',
  271. 'ext': 'mp4',
  272. 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  273. 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
  274. 'is_live': True,
  275. 'timestamp': 1421928037,
  276. 'upload_date': '20150122',
  277. 'uploader': 'ShroomzTV',
  278. 'uploader_id': 'shroomztv',
  279. 'view_count': int,
  280. },
  281. 'params': {
  282. # m3u8 download
  283. 'skip_download': True,
  284. },
  285. }
  286. def _real_extract(self, url):
  287. channel_id = self._match_id(url)
  288. stream = self._download_json(
  289. '%s/kraken/streams/%s' % (self._API_BASE, channel_id), channel_id,
  290. 'Downloading stream JSON').get('stream')
  291. # Fallback on profile extraction if stream is offline
  292. if not stream:
  293. return self.url_result(
  294. 'http://www.twitch.tv/%s/profile' % channel_id,
  295. 'TwitchProfile', channel_id)
  296. # Channel name may be typed if different case than the original channel name
  297. # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing
  298. # an invalid m3u8 URL. Working around by use of original channel name from stream
  299. # JSON and fallback to lowercase if it's not available.
  300. channel_id = stream.get('channel', {}).get('name') or channel_id.lower()
  301. access_token = self._download_json(
  302. '%s/api/channels/%s/access_token' % (self._API_BASE, channel_id), channel_id,
  303. 'Downloading channel access token')
  304. query = {
  305. 'allow_source': 'true',
  306. 'p': random.randint(1000000, 10000000),
  307. 'player': 'twitchweb',
  308. 'segment_preference': '4',
  309. 'sig': access_token['sig'].encode('utf-8'),
  310. 'token': access_token['token'].encode('utf-8'),
  311. }
  312. formats = self._extract_m3u8_formats(
  313. '%s/api/channel/hls/%s.m3u8?%s'
  314. % (self._USHER_BASE, channel_id, compat_urllib_parse.urlencode(query)),
  315. channel_id, 'mp4')
  316. self._prefer_source(formats)
  317. view_count = stream.get('viewers')
  318. timestamp = parse_iso8601(stream.get('created_at'))
  319. channel = stream['channel']
  320. title = self._live_title(channel.get('display_name') or channel.get('name'))
  321. description = channel.get('status')
  322. thumbnails = []
  323. for thumbnail_key, thumbnail_url in stream['preview'].items():
  324. m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
  325. if not m:
  326. continue
  327. thumbnails.append({
  328. 'url': thumbnail_url,
  329. 'width': int(m.group('width')),
  330. 'height': int(m.group('height')),
  331. })
  332. return {
  333. 'id': compat_str(stream['_id']),
  334. 'display_id': channel_id,
  335. 'title': title,
  336. 'description': description,
  337. 'thumbnails': thumbnails,
  338. 'uploader': channel.get('display_name'),
  339. 'uploader_id': channel.get('name'),
  340. 'timestamp': timestamp,
  341. 'view_count': view_count,
  342. 'formats': formats,
  343. 'is_live': True,
  344. }