twitch.py 27 KB

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