twitch.py 26 KB

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