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.

597 lines
20 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/|
  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': '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': '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. def _real_extract(self, url):
  229. item_id = self._match_id(url)
  230. info = self._download_info(self._ITEM_SHORTCUT, item_id)
  231. access_token = self._call_api(
  232. 'api/vods/%s/access_token' % item_id, item_id,
  233. 'Downloading %s access token' % self._ITEM_TYPE)
  234. formats = self._extract_m3u8_formats(
  235. '%s/vod/%s?%s' % (
  236. self._USHER_BASE, item_id,
  237. compat_urllib_parse_urlencode({
  238. 'allow_source': 'true',
  239. 'allow_audio_only': 'true',
  240. 'allow_spectre': 'true',
  241. 'player': 'twitchweb',
  242. 'nauth': access_token['token'],
  243. 'nauthsig': access_token['sig'],
  244. })),
  245. item_id, 'mp4', entry_protocol='m3u8_native')
  246. self._prefer_source(formats)
  247. info['formats'] = formats
  248. parsed_url = compat_urllib_parse_urlparse(url)
  249. query = compat_parse_qs(parsed_url.query)
  250. if 't' in query:
  251. info['start_time'] = parse_duration(query['t'][0])
  252. if info.get('timestamp') is not None:
  253. info['subtitles'] = {
  254. 'rechat': [{
  255. 'url': update_url_query(
  256. 'https://rechat.twitch.tv/rechat-messages', {
  257. 'video_id': 'v%s' % item_id,
  258. 'start': info['timestamp'],
  259. }),
  260. 'ext': 'json',
  261. }],
  262. }
  263. return info
  264. class TwitchPlaylistBaseIE(TwitchBaseIE):
  265. _PLAYLIST_PATH = 'kraken/channels/%s/videos/?offset=%d&limit=%d'
  266. _PAGE_LIMIT = 100
  267. def _extract_playlist(self, channel_id):
  268. info = self._call_api(
  269. 'kraken/channels/%s' % channel_id,
  270. channel_id, 'Downloading channel info JSON')
  271. channel_name = info.get('display_name') or info.get('name')
  272. entries = []
  273. offset = 0
  274. limit = self._PAGE_LIMIT
  275. broken_paging_detected = False
  276. counter_override = None
  277. for counter in itertools.count(1):
  278. response = self._call_api(
  279. self._PLAYLIST_PATH % (channel_id, offset, limit),
  280. channel_id,
  281. 'Downloading %s JSON page %s'
  282. % (self._PLAYLIST_TYPE, counter_override or counter))
  283. page_entries = self._extract_playlist_page(response)
  284. if not page_entries:
  285. break
  286. total = int_or_none(response.get('_total'))
  287. # Since the beginning of March 2016 twitch's paging mechanism
  288. # is completely broken on the twitch side. It simply ignores
  289. # a limit and returns the whole offset number of videos.
  290. # Working around by just requesting all videos at once.
  291. # Upd: pagination bug was fixed by twitch on 15.03.2016.
  292. if not broken_paging_detected and total and len(page_entries) > limit:
  293. self.report_warning(
  294. 'Twitch pagination is broken on twitch side, requesting all videos at once',
  295. channel_id)
  296. broken_paging_detected = True
  297. offset = total
  298. counter_override = '(all at once)'
  299. continue
  300. entries.extend(page_entries)
  301. if broken_paging_detected or total and len(page_entries) >= total:
  302. break
  303. offset += limit
  304. return self.playlist_result(
  305. [self.url_result(entry) for entry in orderedSet(entries)],
  306. channel_id, channel_name)
  307. def _extract_playlist_page(self, response):
  308. videos = response.get('videos')
  309. return [video['url'] for video in videos] if videos else []
  310. def _real_extract(self, url):
  311. return self._extract_playlist(self._match_id(url))
  312. class TwitchProfileIE(TwitchPlaylistBaseIE):
  313. IE_NAME = 'twitch:profile'
  314. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  315. _PLAYLIST_TYPE = 'profile'
  316. _TEST = {
  317. 'url': 'http://www.twitch.tv/vanillatv/profile',
  318. 'info_dict': {
  319. 'id': 'vanillatv',
  320. 'title': 'VanillaTV',
  321. },
  322. 'playlist_mincount': 412,
  323. }
  324. class TwitchVideosBaseIE(TwitchPlaylistBaseIE):
  325. _VALID_URL_VIDEOS_BASE = r'%s/(?P<id>[^/]+)/videos' % TwitchBaseIE._VALID_URL_BASE
  326. _PLAYLIST_PATH = TwitchPlaylistBaseIE._PLAYLIST_PATH + '&broadcast_type='
  327. class TwitchAllVideosIE(TwitchVideosBaseIE):
  328. IE_NAME = 'twitch:videos:all'
  329. _VALID_URL = r'%s/all' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
  330. _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive,upload,highlight'
  331. _PLAYLIST_TYPE = 'all videos'
  332. _TEST = {
  333. 'url': 'https://www.twitch.tv/spamfish/videos/all',
  334. 'info_dict': {
  335. 'id': 'spamfish',
  336. 'title': 'Spamfish',
  337. },
  338. 'playlist_mincount': 869,
  339. }
  340. class TwitchUploadsIE(TwitchVideosBaseIE):
  341. IE_NAME = 'twitch:videos:uploads'
  342. _VALID_URL = r'%s/uploads' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
  343. _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'upload'
  344. _PLAYLIST_TYPE = 'uploads'
  345. _TEST = {
  346. 'url': 'https://www.twitch.tv/spamfish/videos/uploads',
  347. 'info_dict': {
  348. 'id': 'spamfish',
  349. 'title': 'Spamfish',
  350. },
  351. 'playlist_mincount': 0,
  352. }
  353. class TwitchPastBroadcastsIE(TwitchVideosBaseIE):
  354. IE_NAME = 'twitch:videos:past-broadcasts'
  355. _VALID_URL = r'%s/past-broadcasts' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
  356. _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'archive'
  357. _PLAYLIST_TYPE = 'past broadcasts'
  358. _TEST = {
  359. 'url': 'https://www.twitch.tv/spamfish/videos/past-broadcasts',
  360. 'info_dict': {
  361. 'id': 'spamfish',
  362. 'title': 'Spamfish',
  363. },
  364. 'playlist_mincount': 0,
  365. }
  366. class TwitchHighlightsIE(TwitchVideosBaseIE):
  367. IE_NAME = 'twitch:videos:highlights'
  368. _VALID_URL = r'%s/highlights' % TwitchVideosBaseIE._VALID_URL_VIDEOS_BASE
  369. _PLAYLIST_PATH = TwitchVideosBaseIE._PLAYLIST_PATH + 'highlight'
  370. _PLAYLIST_TYPE = 'highlights'
  371. _TEST = {
  372. 'url': 'https://www.twitch.tv/spamfish/videos/highlights',
  373. 'info_dict': {
  374. 'id': 'spamfish',
  375. 'title': 'Spamfish',
  376. },
  377. 'playlist_mincount': 805,
  378. }
  379. class TwitchStreamIE(TwitchBaseIE):
  380. IE_NAME = 'twitch:stream'
  381. _VALID_URL = r'%s/(?P<id>[^/#?]+)/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  382. _TESTS = [{
  383. 'url': 'http://www.twitch.tv/shroomztv',
  384. 'info_dict': {
  385. 'id': '12772022048',
  386. 'display_id': 'shroomztv',
  387. 'ext': 'mp4',
  388. 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  389. 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
  390. 'is_live': True,
  391. 'timestamp': 1421928037,
  392. 'upload_date': '20150122',
  393. 'uploader': 'ShroomzTV',
  394. 'uploader_id': 'shroomztv',
  395. 'view_count': int,
  396. },
  397. 'params': {
  398. # m3u8 download
  399. 'skip_download': True,
  400. },
  401. }, {
  402. 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
  403. 'only_matching': True,
  404. }]
  405. def _real_extract(self, url):
  406. channel_id = self._match_id(url)
  407. stream = self._call_api(
  408. 'kraken/streams/%s?stream_type=all' % channel_id, channel_id,
  409. 'Downloading stream JSON').get('stream')
  410. if not stream:
  411. raise ExtractorError('%s is offline' % channel_id, expected=True)
  412. # Channel name may be typed if different case than the original channel name
  413. # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing
  414. # an invalid m3u8 URL. Working around by use of original channel name from stream
  415. # JSON and fallback to lowercase if it's not available.
  416. channel_id = stream.get('channel', {}).get('name') or channel_id.lower()
  417. access_token = self._call_api(
  418. 'api/channels/%s/access_token' % channel_id, channel_id,
  419. 'Downloading channel access token')
  420. query = {
  421. 'allow_source': 'true',
  422. 'allow_audio_only': 'true',
  423. 'allow_spectre': 'true',
  424. 'p': random.randint(1000000, 10000000),
  425. 'player': 'twitchweb',
  426. 'segment_preference': '4',
  427. 'sig': access_token['sig'].encode('utf-8'),
  428. 'token': access_token['token'].encode('utf-8'),
  429. }
  430. formats = self._extract_m3u8_formats(
  431. '%s/api/channel/hls/%s.m3u8?%s'
  432. % (self._USHER_BASE, channel_id, compat_urllib_parse_urlencode(query)),
  433. channel_id, 'mp4')
  434. self._prefer_source(formats)
  435. view_count = stream.get('viewers')
  436. timestamp = parse_iso8601(stream.get('created_at'))
  437. channel = stream['channel']
  438. title = self._live_title(channel.get('display_name') or channel.get('name'))
  439. description = channel.get('status')
  440. thumbnails = []
  441. for thumbnail_key, thumbnail_url in stream['preview'].items():
  442. m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
  443. if not m:
  444. continue
  445. thumbnails.append({
  446. 'url': thumbnail_url,
  447. 'width': int(m.group('width')),
  448. 'height': int(m.group('height')),
  449. })
  450. return {
  451. 'id': compat_str(stream['_id']),
  452. 'display_id': channel_id,
  453. 'title': title,
  454. 'description': description,
  455. 'thumbnails': thumbnails,
  456. 'uploader': channel.get('display_name'),
  457. 'uploader_id': channel.get('name'),
  458. 'timestamp': timestamp,
  459. 'view_count': view_count,
  460. 'formats': formats,
  461. 'is_live': True,
  462. }
  463. class TwitchClipsIE(InfoExtractor):
  464. IE_NAME = 'twitch:clips'
  465. _VALID_URL = r'https?://clips\.twitch\.tv/(?:[^/]+/)*(?P<id>[^/?#&]+)'
  466. _TESTS = [{
  467. 'url': 'https://clips.twitch.tv/ea/AggressiveCobraPoooound',
  468. 'md5': '761769e1eafce0ffebfb4089cb3847cd',
  469. 'info_dict': {
  470. 'id': 'AggressiveCobraPoooound',
  471. 'ext': 'mp4',
  472. 'title': 'EA Play 2016 Live from the Novo Theatre',
  473. 'thumbnail': 're:^https?://.*\.jpg',
  474. 'creator': 'EA',
  475. 'uploader': 'stereotype_',
  476. 'uploader_id': 'stereotype_',
  477. },
  478. }, {
  479. # multiple formats
  480. 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
  481. 'only_matching': True,
  482. }]
  483. def _real_extract(self, url):
  484. video_id = self._match_id(url)
  485. webpage = self._download_webpage(url, video_id)
  486. clip = self._parse_json(
  487. self._search_regex(
  488. r'(?s)clipInfo\s*=\s*({.+?});', webpage, 'clip info'),
  489. video_id, transform_source=js_to_json)
  490. title = clip.get('channel_title') or self._og_search_title(webpage)
  491. formats = [{
  492. 'url': option['source'],
  493. 'format_id': option.get('quality'),
  494. 'height': int_or_none(option.get('quality')),
  495. } for option in clip.get('quality_options', []) if option.get('source')]
  496. if not formats:
  497. formats = [{
  498. 'url': clip['clip_video_url'],
  499. }]
  500. self._sort_formats(formats)
  501. return {
  502. 'id': video_id,
  503. 'title': title,
  504. 'thumbnail': self._og_search_thumbnail(webpage),
  505. 'creator': clip.get('broadcaster_display_name') or clip.get('broadcaster_login'),
  506. 'uploader': clip.get('curator_login'),
  507. 'uploader_id': clip.get('curator_display_name'),
  508. 'formats': formats,
  509. }