twitch.py 27 KB

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