twitch.py 24 KB

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