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.

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