twitch.py 24 KB

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