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.

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