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.

736 lines
25 KiB

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