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.

624 lines
21 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_HTTPError,
  9. compat_parse_qs,
  10. compat_str,
  11. compat_urllib_parse_urlencode,
  12. compat_urllib_parse_urlparse,
  13. compat_urlparse,
  14. )
  15. from ..utils import (
  16. clean_html,
  17. ExtractorError,
  18. int_or_none,
  19. js_to_json,
  20. orderedSet,
  21. parse_duration,
  22. parse_iso8601,
  23. update_url_query,
  24. urlencode_postdata,
  25. )
  26. class TwitchBaseIE(InfoExtractor):
  27. _VALID_URL_BASE = r'https?://(?:www\.)?twitch\.tv'
  28. _API_BASE = 'https://api.twitch.tv'
  29. _USHER_BASE = 'https://usher.ttvnw.net'
  30. _LOGIN_URL = 'http://www.twitch.tv/login'
  31. _CLIENT_ID = 'jzkbprff40iqj646a697cyrvl0zt2m6'
  32. _NETRC_MACHINE = 'twitch'
  33. def _handle_error(self, response):
  34. if not isinstance(response, dict):
  35. return
  36. error = response.get('error')
  37. if error:
  38. raise ExtractorError(
  39. '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
  40. expected=True)
  41. def _call_api(self, path, item_id, note):
  42. response = self._download_json(
  43. '%s/%s' % (self._API_BASE, path), item_id, note,
  44. headers={'Client-ID': self._CLIENT_ID})
  45. self._handle_error(response)
  46. return response
  47. def _real_initialize(self):
  48. self._login()
  49. def _login(self):
  50. (username, password) = self._get_login_info()
  51. if username is None:
  52. return
  53. def fail(message):
  54. raise ExtractorError(
  55. 'Unable to login. Twitch said: %s' % message, expected=True)
  56. login_page, handle = self._download_webpage_handle(
  57. self._LOGIN_URL, None, 'Downloading login page')
  58. # Some TOR nodes and public proxies are blocked completely
  59. if 'blacklist_message' in login_page:
  60. fail(clean_html(login_page))
  61. login_form = self._hidden_inputs(login_page)
  62. login_form.update({
  63. 'username': username,
  64. 'password': password,
  65. })
  66. redirect_url = handle.geturl()
  67. post_url = self._search_regex(
  68. r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
  69. 'post url', default=redirect_url, group='url')
  70. if not post_url.startswith('http'):
  71. post_url = compat_urlparse.urljoin(redirect_url, post_url)
  72. headers = {'Referer': redirect_url}
  73. try:
  74. response = self._download_json(
  75. post_url, None, 'Logging in as %s' % username,
  76. data=urlencode_postdata(login_form),
  77. headers=headers)
  78. except ExtractorError as e:
  79. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 400:
  80. response = self._parse_json(
  81. e.cause.read().decode('utf-8'), None)
  82. fail(response['message'])
  83. raise
  84. if response.get('redirect'):
  85. self._download_webpage(
  86. response['redirect'], None, 'Downloading login redirect page',
  87. headers=headers)
  88. def _prefer_source(self, formats):
  89. try:
  90. source = next(f for f in formats if f['format_id'] == 'Source')
  91. source['preference'] = 10
  92. except StopIteration:
  93. pass # No Source stream present
  94. self._sort_formats(formats)
  95. class TwitchItemBaseIE(TwitchBaseIE):
  96. def _download_info(self, item, item_id):
  97. return self._extract_info(self._call_api(
  98. 'kraken/videos/%s%s' % (item, item_id), item_id,
  99. 'Downloading %s info JSON' % self._ITEM_TYPE))
  100. def _extract_media(self, item_id):
  101. info = self._download_info(self._ITEM_SHORTCUT, item_id)
  102. response = self._call_api(
  103. 'api/videos/%s%s' % (self._ITEM_SHORTCUT, item_id), item_id,
  104. 'Downloading %s playlist JSON' % self._ITEM_TYPE)
  105. entries = []
  106. chunks = response['chunks']
  107. qualities = list(chunks.keys())
  108. for num, fragment in enumerate(zip(*chunks.values()), start=1):
  109. formats = []
  110. for fmt_num, fragment_fmt in enumerate(fragment):
  111. format_id = qualities[fmt_num]
  112. fmt = {
  113. 'url': fragment_fmt['url'],
  114. 'format_id': format_id,
  115. 'quality': 1 if format_id == 'live' else 0,
  116. }
  117. m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
  118. if m:
  119. fmt['height'] = int(m.group('height'))
  120. formats.append(fmt)
  121. self._sort_formats(formats)
  122. entry = dict(info)
  123. entry['id'] = '%s_%d' % (entry['id'], num)
  124. entry['title'] = '%s part %d' % (entry['title'], num)
  125. entry['formats'] = formats
  126. entries.append(entry)
  127. return self.playlist_result(entries, info['id'], info['title'])
  128. def _extract_info(self, info):
  129. return {
  130. 'id': info['_id'],
  131. 'title': info.get('title') or 'Untitled Broadcast',
  132. 'description': info.get('description'),
  133. 'duration': int_or_none(info.get('length')),
  134. 'thumbnail': info.get('preview'),
  135. 'uploader': info.get('channel', {}).get('display_name'),
  136. 'uploader_id': info.get('channel', {}).get('name'),
  137. 'timestamp': parse_iso8601(info.get('recorded_at')),
  138. 'view_count': int_or_none(info.get('views')),
  139. }
  140. def _real_extract(self, url):
  141. return self._extract_media(self._match_id(url))
  142. class TwitchVideoIE(TwitchItemBaseIE):
  143. IE_NAME = 'twitch:video'
  144. _VALID_URL = r'%s/[^/]+/b/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
  145. _ITEM_TYPE = 'video'
  146. _ITEM_SHORTCUT = 'a'
  147. _TEST = {
  148. 'url': 'http://www.twitch.tv/riotgames/b/577357806',
  149. 'info_dict': {
  150. 'id': 'a577357806',
  151. 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
  152. },
  153. 'playlist_mincount': 12,
  154. 'skip': 'HTTP Error 404: Not Found',
  155. }
  156. class TwitchChapterIE(TwitchItemBaseIE):
  157. IE_NAME = 'twitch:chapter'
  158. _VALID_URL = r'%s/[^/]+/c/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
  159. _ITEM_TYPE = 'chapter'
  160. _ITEM_SHORTCUT = 'c'
  161. _TESTS = [{
  162. 'url': 'http://www.twitch.tv/acracingleague/c/5285812',
  163. 'info_dict': {
  164. 'id': 'c5285812',
  165. 'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
  166. },
  167. 'playlist_mincount': 3,
  168. 'skip': 'HTTP Error 404: Not Found',
  169. }, {
  170. 'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361',
  171. 'only_matching': True,
  172. }]
  173. class TwitchVodIE(TwitchItemBaseIE):
  174. IE_NAME = 'twitch:vod'
  175. _VALID_URL = r'''(?x)
  176. https?://
  177. (?:
  178. (?:www\.)?twitch\.tv/(?:[^/]+/v|videos)/|
  179. player\.twitch\.tv/\?.*?\bvideo=v
  180. )
  181. (?P<id>\d+)
  182. '''
  183. _ITEM_TYPE = 'vod'
  184. _ITEM_SHORTCUT = 'v'
  185. _TESTS = [{
  186. 'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s',
  187. 'info_dict': {
  188. 'id': 'v6528877',
  189. 'ext': 'mp4',
  190. 'title': 'LCK Summer Split - Week 6 Day 1',
  191. 'thumbnail': r're:^https?://.*\.jpg$',
  192. 'duration': 17208,
  193. 'timestamp': 1435131709,
  194. 'upload_date': '20150624',
  195. 'uploader': 'Riot Games',
  196. 'uploader_id': 'riotgames',
  197. 'view_count': int,
  198. 'start_time': 310,
  199. },
  200. 'params': {
  201. # m3u8 download
  202. 'skip_download': True,
  203. },
  204. }, {
  205. # Untitled broadcast (title is None)
  206. 'url': 'http://www.twitch.tv/belkao_o/v/11230755',
  207. 'info_dict': {
  208. 'id': 'v11230755',
  209. 'ext': 'mp4',
  210. 'title': 'Untitled Broadcast',
  211. 'thumbnail': r're:^https?://.*\.jpg$',
  212. 'duration': 1638,
  213. 'timestamp': 1439746708,
  214. 'upload_date': '20150816',
  215. 'uploader': 'BelkAO_o',
  216. 'uploader_id': 'belkao_o',
  217. 'view_count': int,
  218. },
  219. 'params': {
  220. # m3u8 download
  221. 'skip_download': True,
  222. },
  223. 'skip': 'HTTP Error 404: Not Found',
  224. }, {
  225. 'url': 'http://player.twitch.tv/?t=5m10s&video=v6528877',
  226. 'only_matching': True,
  227. }, {
  228. 'url': 'https://www.twitch.tv/videos/6528877',
  229. 'only_matching': True,
  230. }]
  231. def _real_extract(self, url):
  232. item_id = self._match_id(url)
  233. info = self._download_info(self._ITEM_SHORTCUT, item_id)
  234. access_token = self._call_api(
  235. 'api/vods/%s/access_token' % item_id, item_id,
  236. 'Downloading %s access token' % self._ITEM_TYPE)
  237. formats = self._extract_m3u8_formats(
  238. '%s/vod/%s?%s' % (
  239. self._USHER_BASE, item_id,
  240. compat_urllib_parse_urlencode({
  241. 'allow_source': 'true',
  242. 'allow_audio_only': 'true',
  243. 'allow_spectre': 'true',
  244. 'player': 'twitchweb',
  245. 'nauth': access_token['token'],
  246. 'nauthsig': access_token['sig'],
  247. })),
  248. item_id, 'mp4', entry_protocol='m3u8_native')
  249. self._prefer_source(formats)
  250. info['formats'] = formats
  251. parsed_url = compat_urllib_parse_urlparse(url)
  252. query = compat_parse_qs(parsed_url.query)
  253. if 't' in query:
  254. info['start_time'] = parse_duration(query['t'][0])
  255. if info.get('timestamp') is not None:
  256. info['subtitles'] = {
  257. 'rechat': [{
  258. 'url': update_url_query(
  259. 'https://rechat.twitch.tv/rechat-messages', {
  260. 'video_id': 'v%s' % item_id,
  261. 'start': info['timestamp'],
  262. }),
  263. 'ext': 'json',
  264. }],
  265. }
  266. return info
  267. class TwitchPlaylistBaseIE(TwitchBaseIE):
  268. _PLAYLIST_PATH = 'kraken/channels/%s/videos/?offset=%d&limit=%d'
  269. _PAGE_LIMIT = 100
  270. def _extract_playlist(self, channel_id):
  271. info = self._call_api(
  272. 'kraken/channels/%s' % channel_id,
  273. channel_id, 'Downloading channel info JSON')
  274. channel_name = info.get('display_name') or info.get('name')
  275. entries = []
  276. offset = 0
  277. limit = self._PAGE_LIMIT
  278. broken_paging_detected = False
  279. counter_override = None
  280. for counter in itertools.count(1):
  281. response = self._call_api(
  282. self._PLAYLIST_PATH % (channel_id, offset, limit),
  283. channel_id,
  284. 'Downloading %s JSON page %s'
  285. % (self._PLAYLIST_TYPE, counter_override or counter))
  286. page_entries = self._extract_playlist_page(response)
  287. if not page_entries:
  288. break
  289. total = int_or_none(response.get('_total'))
  290. # Since the beginning of March 2016 twitch's paging mechanism
  291. # is completely broken on the twitch side. It simply ignores
  292. # a limit and returns the whole offset number of videos.
  293. # Working around by just requesting all videos at once.
  294. # Upd: pagination bug was fixed by twitch on 15.03.2016.
  295. if not broken_paging_detected and total and len(page_entries) > limit:
  296. self.report_warning(
  297. 'Twitch pagination is broken on twitch side, requesting all videos at once',
  298. channel_id)
  299. broken_paging_detected = True
  300. offset = total
  301. counter_override = '(all at once)'
  302. continue
  303. entries.extend(page_entries)
  304. if broken_paging_detected or total and len(page_entries) >= total:
  305. break
  306. offset += limit
  307. return self.playlist_result(
  308. [self.url_result(entry) for entry in orderedSet(entries)],
  309. channel_id, channel_name)
  310. def _extract_playlist_page(self, response):
  311. videos = response.get('videos')
  312. return [video['url'] for video in videos] if videos else []
  313. def _real_extract(self, url):
  314. return self._extract_playlist(self._match_id(url))
  315. class TwitchProfileIE(TwitchPlaylistBaseIE):
  316. IE_NAME = 'twitch:profile'
  317. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  318. _PLAYLIST_TYPE = 'profile'
  319. _TEST = {
  320. 'url': 'http://www.twitch.tv/vanillatv/profile',
  321. 'info_dict': {
  322. 'id': 'vanillatv',
  323. 'title': 'VanillaTV',
  324. },
  325. 'playlist_mincount': 412,
  326. }
  327. class TwitchVideosBaseIE(TwitchPlaylistBaseIE):
  328. _VALID_URL_VIDEOS_BASE = r'%s/(?P<id>[^/]+)/videos' % TwitchBaseIE._VALID_URL_BASE
  329. _PLAYLIST_PATH = TwitchPlaylistBaseIE._PLAYLIST_PATH + '&broadcast_type='
  330. class TwitchAllVideosIE(TwitchVideosBaseIE):
  331. IE_NAME = 'twitch:videos:all'
  332. _VALID_URL = r'%s/all' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
  333. _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive,upload,highlight'
  334. _PLAYLIST_TYPE = 'all videos'
  335. _TEST = {
  336. 'url': 'https://www.twitch.tv/spamfish/videos/all',
  337. 'info_dict': {
  338. 'id': 'spamfish',
  339. 'title': 'Spamfish',
  340. },
  341. 'playlist_mincount': 869,
  342. }
  343. class TwitchUploadsIE(TwitchVideosBaseIE):
  344. IE_NAME = 'twitch:videos:uploads'
  345. _VALID_URL = r'%s/uploads' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
  346. _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'upload'
  347. _PLAYLIST_TYPE = 'uploads'
  348. _TEST = {
  349. 'url': 'https://www.twitch.tv/spamfish/videos/uploads',
  350. 'info_dict': {
  351. 'id': 'spamfish',
  352. 'title': 'Spamfish',
  353. },
  354. 'playlist_mincount': 0,
  355. }
  356. class TwitchPastBroadcastsIE(TwitchVideosBaseIE):
  357. IE_NAME = 'twitch:videos:past-broadcasts'
  358. _VALID_URL = r'%s/past-broadcasts' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
  359. _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive'
  360. _PLAYLIST_TYPE = 'past broadcasts'
  361. _TEST = {
  362. 'url': 'https://www.twitch.tv/spamfish/videos/past-broadcasts',
  363. 'info_dict': {
  364. 'id': 'spamfish',
  365. 'title': 'Spamfish',
  366. },
  367. 'playlist_mincount': 0,
  368. }
  369. class TwitchHighlightsIE(TwitchVideosBaseIE):
  370. IE_NAME = 'twitch:videos:highlights'
  371. _VALID_URL = r'%s/highlights' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
  372. _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'highlight'
  373. _PLAYLIST_TYPE = 'highlights'
  374. _TEST = {
  375. 'url': 'https://www.twitch.tv/spamfish/videos/highlights',
  376. 'info_dict': {
  377. 'id': 'spamfish',
  378. 'title': 'Spamfish',
  379. },
  380. 'playlist_mincount': 805,
  381. }
  382. class TwitchStreamIE(TwitchBaseIE):
  383. IE_NAME = 'twitch:stream'
  384. _VALID_URL = r'''(?x)
  385. https?://
  386. (?:
  387. (?:www\.)?twitch\.tv/|
  388. player\.twitch\.tv/\?.*?\bchannel=
  389. )
  390. (?P<id>[^/#?]+)
  391. '''
  392. _TESTS = [{
  393. 'url': 'http://www.twitch.tv/shroomztv',
  394. 'info_dict': {
  395. 'id': '12772022048',
  396. 'display_id': 'shroomztv',
  397. 'ext': 'mp4',
  398. 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  399. 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
  400. 'is_live': True,
  401. 'timestamp': 1421928037,
  402. 'upload_date': '20150122',
  403. 'uploader': 'ShroomzTV',
  404. 'uploader_id': 'shroomztv',
  405. 'view_count': int,
  406. },
  407. 'params': {
  408. # m3u8 download
  409. 'skip_download': True,
  410. },
  411. }, {
  412. 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
  413. 'only_matching': True,
  414. }, {
  415. 'url': 'https://player.twitch.tv/?channel=lotsofs',
  416. 'only_matching': True,
  417. }]
  418. @classmethod
  419. def suitable(cls, url):
  420. return (False
  421. if any(ie.suitable(url) for ie in (
  422. TwitchVideoIE,
  423. TwitchChapterIE,
  424. TwitchVodIE,
  425. TwitchProfileIE,
  426. TwitchAllVideosIE,
  427. TwitchUploadsIE,
  428. TwitchPastBroadcastsIE,
  429. TwitchHighlightsIE))
  430. else super(TwitchStreamIE, cls).suitable(url))
  431. def _real_extract(self, url):
  432. channel_id = self._match_id(url)
  433. stream = self._call_api(
  434. 'kraken/streams/%s?stream_type=all' % channel_id, channel_id,
  435. 'Downloading stream JSON').get('stream')
  436. if not stream:
  437. raise ExtractorError('%s is offline' % channel_id, expected=True)
  438. # Channel name may be typed if different case than the original channel name
  439. # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing
  440. # an invalid m3u8 URL. Working around by use of original channel name from stream
  441. # JSON and fallback to lowercase if it's not available.
  442. channel_id = stream.get('channel', {}).get('name') or channel_id.lower()
  443. access_token = self._call_api(
  444. 'api/channels/%s/access_token' % channel_id, channel_id,
  445. 'Downloading channel access token')
  446. query = {
  447. 'allow_source': 'true',
  448. 'allow_audio_only': 'true',
  449. 'allow_spectre': 'true',
  450. 'p': random.randint(1000000, 10000000),
  451. 'player': 'twitchweb',
  452. 'segment_preference': '4',
  453. 'sig': access_token['sig'].encode('utf-8'),
  454. 'token': access_token['token'].encode('utf-8'),
  455. }
  456. formats = self._extract_m3u8_formats(
  457. '%s/api/channel/hls/%s.m3u8?%s'
  458. % (self._USHER_BASE, channel_id, compat_urllib_parse_urlencode(query)),
  459. channel_id, 'mp4')
  460. self._prefer_source(formats)
  461. view_count = stream.get('viewers')
  462. timestamp = parse_iso8601(stream.get('created_at'))
  463. channel = stream['channel']
  464. title = self._live_title(channel.get('display_name') or channel.get('name'))
  465. description = channel.get('status')
  466. thumbnails = []
  467. for thumbnail_key, thumbnail_url in stream['preview'].items():
  468. m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
  469. if not m:
  470. continue
  471. thumbnails.append({
  472. 'url': thumbnail_url,
  473. 'width': int(m.group('width')),
  474. 'height': int(m.group('height')),
  475. })
  476. return {
  477. 'id': compat_str(stream['_id']),
  478. 'display_id': channel_id,
  479. 'title': title,
  480. 'description': description,
  481. 'thumbnails': thumbnails,
  482. 'uploader': channel.get('display_name'),
  483. 'uploader_id': channel.get('name'),
  484. 'timestamp': timestamp,
  485. 'view_count': view_count,
  486. 'formats': formats,
  487. 'is_live': True,
  488. }
  489. class TwitchClipsIE(InfoExtractor):
  490. IE_NAME = 'twitch:clips'
  491. _VALID_URL = r'https?://clips\.twitch\.tv/(?:[^/]+/)*(?P<id>[^/?#&]+)'
  492. _TESTS = [{
  493. 'url': 'https://clips.twitch.tv/ea/AggressiveCobraPoooound',
  494. 'md5': '761769e1eafce0ffebfb4089cb3847cd',
  495. 'info_dict': {
  496. 'id': 'AggressiveCobraPoooound',
  497. 'ext': 'mp4',
  498. 'title': 'EA Play 2016 Live from the Novo Theatre',
  499. 'thumbnail': r're:^https?://.*\.jpg',
  500. 'creator': 'EA',
  501. 'uploader': 'stereotype_',
  502. 'uploader_id': 'stereotype_',
  503. },
  504. }, {
  505. # multiple formats
  506. 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
  507. 'only_matching': True,
  508. }]
  509. def _real_extract(self, url):
  510. video_id = self._match_id(url)
  511. webpage = self._download_webpage(url, video_id)
  512. clip = self._parse_json(
  513. self._search_regex(
  514. r'(?s)clipInfo\s*=\s*({.+?});', webpage, 'clip info'),
  515. video_id, transform_source=js_to_json)
  516. title = clip.get('channel_title') or self._og_search_title(webpage)
  517. formats = [{
  518. 'url': option['source'],
  519. 'format_id': option.get('quality'),
  520. 'height': int_or_none(option.get('quality')),
  521. } for option in clip.get('quality_options', []) if option.get('source')]
  522. if not formats:
  523. formats = [{
  524. 'url': clip['clip_video_url'],
  525. }]
  526. self._sort_formats(formats)
  527. return {
  528. 'id': video_id,
  529. 'title': title,
  530. 'thumbnail': self._og_search_thumbnail(webpage),
  531. 'creator': clip.get('broadcaster_display_name') or clip.get('broadcaster_login'),
  532. 'uploader': clip.get('curator_login'),
  533. 'uploader_id': clip.get('curator_display_name'),
  534. 'formats': formats,
  535. }