twitch.py 23 KB

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