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.

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