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.

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