twitch.py 25 KB

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