twitch.py 25 KB

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