twitch.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  1. import collections
  2. import itertools
  3. import json
  4. import random
  5. import re
  6. import urllib.parse
  7. from .common import InfoExtractor
  8. from ..utils import (
  9. ExtractorError,
  10. UserNotLive,
  11. base_url,
  12. clean_html,
  13. dict_get,
  14. float_or_none,
  15. int_or_none,
  16. make_archive_id,
  17. parse_duration,
  18. parse_iso8601,
  19. parse_qs,
  20. qualities,
  21. str_or_none,
  22. traverse_obj,
  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. _NETRC_MACHINE = 'twitch'
  36. _OPERATION_HASHES = {
  37. 'CollectionSideBar': '27111f1b382effad0b6def325caef1909c733fe6a4fbabf54f8d491ef2cf2f14',
  38. 'FilterableVideoTower_Videos': 'a937f1d22e269e39a03b509f65a7490f9fc247d7f83d6ac1421523e3b68042cb',
  39. 'ClipsCards__User': 'b73ad2bfaecfd30a9e6c28fada15bd97032c83ec77a0440766a56fe0bd632777',
  40. 'ChannelCollectionsContent': '447aec6a0cc1e8d0a8d7732d47eb0762c336a2294fdb009e9c9d854e49d484b9',
  41. 'StreamMetadata': 'a647c2a13599e5991e175155f798ca7f1ecddde73f7f341f39009c14dbf59962',
  42. 'ComscoreStreamingQuery': 'e1edae8122517d013405f237ffcc124515dc6ded82480a88daef69c83b53ac01',
  43. 'VideoAccessToken_Clip': '36b89d2507fce29e5ca551df756d27c1cfe079e2609642b4390aa4c35796eb11',
  44. 'VideoPreviewOverlay': '3006e77e51b128d838fa4e835723ca4dc9a05c5efd4466c1085215c6e437e65c',
  45. 'VideoMetadata': '49b5b8f268cdeb259d75b58dcb0c1a748e3b575003448a2333dc5cdafd49adad',
  46. 'VideoPlayer_ChapterSelectButtonVideo': '8d2793384aac3773beab5e59bd5d6f585aedb923d292800119e03d40cd0f9b41',
  47. 'VideoPlayer_VODSeekbarPreviewVideo': '07e99e4d56c5a7c67117a154777b0baf85a5ffefa393b213f4bc712ccaf85dd6',
  48. }
  49. @property
  50. def _CLIENT_ID(self):
  51. return self._configuration_arg(
  52. 'client_id', ['ue6666qo983tsx6so1t0vnawi233wa'], ie_key='Twitch', casesense=True)[0]
  53. def _perform_login(self, username, password):
  54. def fail(message):
  55. raise ExtractorError(
  56. f'Unable to login. Twitch said: {message}', expected=True)
  57. def login_step(page, urlh, note, data):
  58. form = self._hidden_inputs(page)
  59. form.update(data)
  60. page_url = urlh.url
  61. post_url = self._search_regex(
  62. r'<form[^>]+action=(["\'])(?P<url>.+?)\1', page,
  63. 'post url', default=self._LOGIN_POST_URL, group='url')
  64. post_url = urljoin(page_url, post_url)
  65. headers = {
  66. 'Referer': page_url,
  67. 'Origin': 'https://www.twitch.tv',
  68. 'Content-Type': 'text/plain;charset=UTF-8',
  69. }
  70. response = self._download_json(
  71. post_url, None, note, data=json.dumps(form).encode(),
  72. headers=headers, expected_status=400)
  73. error = dict_get(response, ('error', 'error_description', 'error_code'))
  74. if error:
  75. fail(error)
  76. if 'Authenticated successfully' in response.get('message', ''):
  77. return None, None
  78. redirect_url = urljoin(
  79. post_url,
  80. response.get('redirect') or response['redirect_path'])
  81. return self._download_webpage_handle(
  82. redirect_url, None, 'Downloading login redirect page',
  83. headers=headers)
  84. login_page, handle = self._download_webpage_handle(
  85. self._LOGIN_FORM_URL, None, 'Downloading login page')
  86. # Some TOR nodes and public proxies are blocked completely
  87. if 'blacklist_message' in login_page:
  88. fail(clean_html(login_page))
  89. redirect_page, handle = login_step(
  90. login_page, handle, 'Logging in', {
  91. 'username': username,
  92. 'password': password,
  93. 'client_id': self._CLIENT_ID,
  94. })
  95. # Successful login
  96. if not redirect_page:
  97. return
  98. if re.search(r'(?i)<form[^>]+id="two-factor-submit"', redirect_page) is not None:
  99. # TODO: Add mechanism to request an SMS or phone call
  100. tfa_token = self._get_tfa_info('two-factor authentication token')
  101. login_step(redirect_page, handle, 'Submitting TFA token', {
  102. 'authy_token': tfa_token,
  103. 'remember_2fa': 'true',
  104. })
  105. def _prefer_source(self, formats):
  106. try:
  107. source = next(f for f in formats if f['format_id'] == 'Source')
  108. source['quality'] = 10
  109. except StopIteration:
  110. for f in formats:
  111. if '/chunked/' in f['url']:
  112. f.update({
  113. 'quality': 10,
  114. 'format_note': 'Source',
  115. })
  116. def _download_base_gql(self, video_id, ops, note, fatal=True):
  117. headers = {
  118. 'Content-Type': 'text/plain;charset=UTF-8',
  119. 'Client-ID': self._CLIENT_ID,
  120. }
  121. gql_auth = self._get_cookies('https://gql.twitch.tv').get('auth-token')
  122. if gql_auth:
  123. headers['Authorization'] = 'OAuth ' + gql_auth.value
  124. return self._download_json(
  125. 'https://gql.twitch.tv/gql', video_id, note,
  126. data=json.dumps(ops).encode(),
  127. headers=headers, fatal=fatal)
  128. def _download_gql(self, video_id, ops, note, fatal=True):
  129. for op in ops:
  130. op['extensions'] = {
  131. 'persistedQuery': {
  132. 'version': 1,
  133. 'sha256Hash': self._OPERATION_HASHES[op['operationName']],
  134. },
  135. }
  136. return self._download_base_gql(video_id, ops, note)
  137. def _download_access_token(self, video_id, token_kind, param_name):
  138. method = f'{token_kind}PlaybackAccessToken'
  139. ops = {
  140. 'query': '''{
  141. %s(
  142. %s: "%s",
  143. params: {
  144. platform: "web",
  145. playerBackend: "mediaplayer",
  146. playerType: "site"
  147. }
  148. )
  149. {
  150. value
  151. signature
  152. }
  153. }''' % (method, param_name, video_id), # noqa: UP031
  154. }
  155. return self._download_base_gql(
  156. video_id, ops,
  157. f'Downloading {token_kind} access token GraphQL')['data'][method]
  158. def _get_thumbnails(self, thumbnail):
  159. return [{
  160. 'url': re.sub(r'\d+x\d+(\.\w+)($|(?=[?#]))', r'0x0\g<1>', thumbnail),
  161. 'preference': 1,
  162. }, {
  163. 'url': thumbnail,
  164. }] if thumbnail else None
  165. def _extract_twitch_m3u8_formats(self, path, video_id, token, signature):
  166. formats = self._extract_m3u8_formats(
  167. f'{self._USHER_BASE}/{path}/{video_id}.m3u8', video_id, 'mp4', query={
  168. 'allow_source': 'true',
  169. 'allow_audio_only': 'true',
  170. 'allow_spectre': 'true',
  171. 'p': random.randint(1000000, 10000000),
  172. 'platform': 'web',
  173. 'player': 'twitchweb',
  174. 'supported_codecs': 'av1,h265,h264',
  175. 'playlist_include_framerate': 'true',
  176. 'sig': signature,
  177. 'token': token,
  178. })
  179. for fmt in formats:
  180. if fmt.get('vcodec') and fmt['vcodec'].startswith('av01'):
  181. # mpegts does not yet have proper support for av1
  182. fmt['downloader_options'] = {'ffmpeg_args_out': ['-f', 'mp4']}
  183. return formats
  184. class TwitchVodIE(TwitchBaseIE):
  185. IE_NAME = 'twitch:vod'
  186. _VALID_URL = r'''(?x)
  187. https?://
  188. (?:
  189. (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/v(?:ideo)?|videos)/|
  190. player\.twitch\.tv/\?.*?\bvideo=v?|
  191. www\.twitch\.tv/[^/]+/schedule\?vodID=
  192. )
  193. (?P<id>\d+)
  194. '''
  195. _TESTS = [{
  196. 'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s',
  197. 'info_dict': {
  198. 'id': 'v6528877',
  199. 'ext': 'mp4',
  200. 'title': 'LCK Summer Split - Week 6 Day 1',
  201. 'thumbnail': r're:^https?://.*\.jpg$',
  202. 'duration': 17208,
  203. 'timestamp': 1435131734,
  204. 'upload_date': '20150624',
  205. 'uploader': 'Riot Games',
  206. 'uploader_id': 'riotgames',
  207. 'view_count': int,
  208. 'start_time': 310,
  209. 'chapters': [
  210. {
  211. 'start_time': 0,
  212. 'end_time': 17208,
  213. 'title': 'League of Legends',
  214. },
  215. ],
  216. 'live_status': 'was_live',
  217. },
  218. 'params': {
  219. # m3u8 download
  220. 'skip_download': True,
  221. },
  222. }, {
  223. # Untitled broadcast (title is None)
  224. 'url': 'http://www.twitch.tv/belkao_o/v/11230755',
  225. 'info_dict': {
  226. 'id': 'v11230755',
  227. 'ext': 'mp4',
  228. 'title': 'Untitled Broadcast',
  229. 'thumbnail': r're:^https?://.*\.jpg$',
  230. 'duration': 1638,
  231. 'timestamp': 1439746708,
  232. 'upload_date': '20150816',
  233. 'uploader': 'BelkAO_o',
  234. 'uploader_id': 'belkao_o',
  235. 'view_count': int,
  236. },
  237. 'params': {
  238. # m3u8 download
  239. 'skip_download': True,
  240. },
  241. 'skip': 'HTTP Error 404: Not Found',
  242. }, {
  243. 'url': 'http://player.twitch.tv/?t=5m10s&video=v6528877',
  244. 'only_matching': True,
  245. }, {
  246. 'url': 'https://www.twitch.tv/videos/6528877',
  247. 'only_matching': True,
  248. }, {
  249. 'url': 'https://m.twitch.tv/beagsandjam/v/247478721',
  250. 'only_matching': True,
  251. }, {
  252. 'url': 'https://www.twitch.tv/northernlion/video/291940395',
  253. 'only_matching': True,
  254. }, {
  255. 'url': 'https://player.twitch.tv/?video=480452374',
  256. 'only_matching': True,
  257. }, {
  258. 'url': 'https://www.twitch.tv/videos/635475444',
  259. 'info_dict': {
  260. 'id': 'v635475444',
  261. 'ext': 'mp4',
  262. 'title': 'Riot Games',
  263. 'duration': 11643,
  264. 'uploader': 'Riot Games',
  265. 'uploader_id': 'riotgames',
  266. 'timestamp': 1590770569,
  267. 'upload_date': '20200529',
  268. 'chapters': [
  269. {
  270. 'start_time': 0,
  271. 'end_time': 573,
  272. 'title': 'League of Legends',
  273. },
  274. {
  275. 'start_time': 573,
  276. 'end_time': 3922,
  277. 'title': 'Legends of Runeterra',
  278. },
  279. {
  280. 'start_time': 3922,
  281. 'end_time': 11643,
  282. 'title': 'Art',
  283. },
  284. ],
  285. 'live_status': 'was_live',
  286. 'thumbnail': r're:^https?://.*\.jpg$',
  287. 'view_count': int,
  288. },
  289. 'params': {
  290. 'skip_download': True,
  291. },
  292. }, {
  293. 'note': 'Storyboards',
  294. 'url': 'https://www.twitch.tv/videos/635475444',
  295. 'info_dict': {
  296. 'id': 'v635475444',
  297. 'format_id': 'sb0',
  298. 'ext': 'mhtml',
  299. 'title': 'Riot Games',
  300. 'duration': 11643,
  301. 'uploader': 'Riot Games',
  302. 'uploader_id': 'riotgames',
  303. 'timestamp': 1590770569,
  304. 'upload_date': '20200529',
  305. 'chapters': [
  306. {
  307. 'start_time': 0,
  308. 'end_time': 573,
  309. 'title': 'League of Legends',
  310. },
  311. {
  312. 'start_time': 573,
  313. 'end_time': 3922,
  314. 'title': 'Legends of Runeterra',
  315. },
  316. {
  317. 'start_time': 3922,
  318. 'end_time': 11643,
  319. 'title': 'Art',
  320. },
  321. ],
  322. 'live_status': 'was_live',
  323. 'thumbnail': r're:^https?://.*\.jpg$',
  324. 'view_count': int,
  325. 'columns': int,
  326. 'rows': int,
  327. },
  328. 'params': {
  329. 'format': 'mhtml',
  330. 'skip_download': True,
  331. },
  332. }, {
  333. 'note': 'VOD with single chapter',
  334. 'url': 'https://www.twitch.tv/videos/1536751224',
  335. 'info_dict': {
  336. 'id': 'v1536751224',
  337. 'ext': 'mp4',
  338. 'title': 'Porter Robinson Star Guardian Stream Tour with LilyPichu',
  339. 'duration': 8353,
  340. 'uploader': 'Riot Games',
  341. 'uploader_id': 'riotgames',
  342. 'timestamp': 1658267731,
  343. 'upload_date': '20220719',
  344. 'chapters': [
  345. {
  346. 'start_time': 0,
  347. 'end_time': 8353,
  348. 'title': 'League of Legends',
  349. },
  350. ],
  351. 'live_status': 'was_live',
  352. 'thumbnail': r're:^https?://.*\.jpg$',
  353. 'view_count': int,
  354. },
  355. 'params': {
  356. 'skip_download': True,
  357. },
  358. 'expected_warnings': ['Unable to download JSON metadata: HTTP Error 403: Forbidden'],
  359. }, {
  360. 'url': 'https://www.twitch.tv/tangotek/schedule?vodID=1822395420',
  361. 'only_matching': True,
  362. }]
  363. def _download_info(self, item_id):
  364. data = self._download_gql(
  365. item_id, [{
  366. 'operationName': 'VideoMetadata',
  367. 'variables': {
  368. 'channelLogin': '',
  369. 'videoID': item_id,
  370. },
  371. }, {
  372. 'operationName': 'VideoPlayer_ChapterSelectButtonVideo',
  373. 'variables': {
  374. 'includePrivate': False,
  375. 'videoID': item_id,
  376. },
  377. }, {
  378. 'operationName': 'VideoPlayer_VODSeekbarPreviewVideo',
  379. 'variables': {
  380. 'includePrivate': False,
  381. 'videoID': item_id,
  382. },
  383. }],
  384. 'Downloading stream metadata GraphQL')
  385. video = traverse_obj(data, (..., 'data', 'video'), get_all=False)
  386. if video is None:
  387. raise ExtractorError(f'Video {item_id} does not exist', expected=True)
  388. video['moments'] = traverse_obj(data, (..., 'data', 'video', 'moments', 'edges', ..., 'node'))
  389. video['storyboard'] = traverse_obj(
  390. data, (..., 'data', 'video', 'seekPreviewsURL', {url_or_none}), get_all=False)
  391. return video
  392. def _extract_info(self, info):
  393. status = info.get('status')
  394. if status == 'recording':
  395. is_live = True
  396. elif status == 'recorded':
  397. is_live = False
  398. else:
  399. is_live = None
  400. _QUALITIES = ('small', 'medium', 'large')
  401. quality_key = qualities(_QUALITIES)
  402. thumbnails = []
  403. preview = info.get('preview')
  404. if isinstance(preview, dict):
  405. for thumbnail_id, thumbnail_url in preview.items():
  406. thumbnail_url = url_or_none(thumbnail_url)
  407. if not thumbnail_url:
  408. continue
  409. if thumbnail_id not in _QUALITIES:
  410. continue
  411. thumbnails.append({
  412. 'url': thumbnail_url,
  413. 'preference': quality_key(thumbnail_id),
  414. })
  415. return {
  416. 'id': info['_id'],
  417. 'title': info.get('title') or 'Untitled Broadcast',
  418. 'description': info.get('description'),
  419. 'duration': int_or_none(info.get('length')),
  420. 'thumbnails': thumbnails,
  421. 'uploader': info.get('channel', {}).get('display_name'),
  422. 'uploader_id': info.get('channel', {}).get('name'),
  423. 'timestamp': parse_iso8601(info.get('recorded_at')),
  424. 'view_count': int_or_none(info.get('views')),
  425. 'is_live': is_live,
  426. 'was_live': True,
  427. }
  428. def _extract_chapters(self, info, item_id):
  429. if not info.get('moments'):
  430. game = traverse_obj(info, ('game', 'displayName'))
  431. if game:
  432. yield {'title': game}
  433. return
  434. for moment in info['moments']:
  435. start_time = int_or_none(moment.get('positionMilliseconds'), 1000)
  436. duration = int_or_none(moment.get('durationMilliseconds'), 1000)
  437. name = str_or_none(moment.get('description'))
  438. if start_time is None or duration is None:
  439. self.report_warning(f'Important chapter information missing for chapter {name}', item_id)
  440. continue
  441. yield {
  442. 'start_time': start_time,
  443. 'end_time': start_time + duration,
  444. 'title': name,
  445. }
  446. def _extract_info_gql(self, info, item_id):
  447. vod_id = info.get('id') or item_id
  448. # id backward compatibility for download archives
  449. if vod_id[0] != 'v':
  450. vod_id = f'v{vod_id}'
  451. thumbnail = url_or_none(info.get('previewThumbnailURL'))
  452. is_live = None
  453. if thumbnail:
  454. if re.findall(r'/404_processing_[^.?#]+\.png', thumbnail):
  455. is_live, thumbnail = True, None
  456. else:
  457. is_live = False
  458. return {
  459. 'id': vod_id,
  460. 'title': info.get('title') or 'Untitled Broadcast',
  461. 'description': info.get('description'),
  462. 'duration': int_or_none(info.get('lengthSeconds')),
  463. 'thumbnails': self._get_thumbnails(thumbnail),
  464. 'uploader': try_get(info, lambda x: x['owner']['displayName'], str),
  465. 'uploader_id': try_get(info, lambda x: x['owner']['login'], str),
  466. 'timestamp': unified_timestamp(info.get('publishedAt')),
  467. 'view_count': int_or_none(info.get('viewCount')),
  468. 'chapters': list(self._extract_chapters(info, item_id)),
  469. 'is_live': is_live,
  470. 'was_live': True,
  471. }
  472. def _extract_storyboard(self, item_id, storyboard_json_url, duration):
  473. if not duration or not storyboard_json_url:
  474. return
  475. spec = self._download_json(storyboard_json_url, item_id, 'Downloading storyboard metadata JSON', fatal=False) or []
  476. # sort from highest quality to lowest
  477. # This makes sb0 the highest-quality format, sb1 - lower, etc which is consistent with youtube sb ordering
  478. spec.sort(key=lambda x: int_or_none(x.get('width')) or 0, reverse=True)
  479. base = base_url(storyboard_json_url)
  480. for i, s in enumerate(spec):
  481. count = int_or_none(s.get('count'))
  482. images = s.get('images')
  483. if not (images and count):
  484. continue
  485. fragment_duration = duration / len(images)
  486. yield {
  487. 'format_id': f'sb{i}',
  488. 'format_note': 'storyboard',
  489. 'ext': 'mhtml',
  490. 'protocol': 'mhtml',
  491. 'acodec': 'none',
  492. 'vcodec': 'none',
  493. 'url': urljoin(base, images[0]),
  494. 'width': int_or_none(s.get('width')),
  495. 'height': int_or_none(s.get('height')),
  496. 'fps': count / duration,
  497. 'rows': int_or_none(s.get('rows')),
  498. 'columns': int_or_none(s.get('cols')),
  499. 'fragments': [{
  500. 'url': urljoin(base, path),
  501. 'duration': fragment_duration,
  502. } for path in images],
  503. }
  504. def _real_extract(self, url):
  505. vod_id = self._match_id(url)
  506. video = self._download_info(vod_id)
  507. info = self._extract_info_gql(video, vod_id)
  508. access_token = self._download_access_token(vod_id, 'video', 'id')
  509. formats = self._extract_twitch_m3u8_formats(
  510. 'vod', vod_id, access_token['value'], access_token['signature'])
  511. formats.extend(self._extract_storyboard(vod_id, video.get('storyboard'), info.get('duration')))
  512. self._prefer_source(formats)
  513. info['formats'] = formats
  514. parsed_url = urllib.parse.urlparse(url)
  515. query = urllib.parse.parse_qs(parsed_url.query)
  516. if 't' in query:
  517. info['start_time'] = parse_duration(query['t'][0])
  518. if info.get('timestamp') is not None:
  519. info['subtitles'] = {
  520. 'rechat': [{
  521. 'url': update_url_query(
  522. f'https://api.twitch.tv/v5/videos/{vod_id}/comments', {
  523. 'client_id': self._CLIENT_ID,
  524. }),
  525. 'ext': 'json',
  526. }],
  527. }
  528. return info
  529. def _make_video_result(node):
  530. assert isinstance(node, dict)
  531. video_id = node.get('id')
  532. if not video_id:
  533. return
  534. return {
  535. '_type': 'url_transparent',
  536. 'ie_key': TwitchVodIE.ie_key(),
  537. 'id': 'v' + video_id,
  538. 'url': f'https://www.twitch.tv/videos/{video_id}',
  539. 'title': node.get('title'),
  540. 'thumbnail': node.get('previewThumbnailURL'),
  541. 'duration': float_or_none(node.get('lengthSeconds')),
  542. 'view_count': int_or_none(node.get('viewCount')),
  543. }
  544. class TwitchCollectionIE(TwitchBaseIE):
  545. _VALID_URL = r'https?://(?:(?:www|go|m)\.)?twitch\.tv/collections/(?P<id>[^/]+)'
  546. _TESTS = [{
  547. 'url': 'https://www.twitch.tv/collections/wlDCoH0zEBZZbQ',
  548. 'info_dict': {
  549. 'id': 'wlDCoH0zEBZZbQ',
  550. 'title': 'Overthrow Nook, capitalism for children',
  551. },
  552. 'playlist_mincount': 13,
  553. }]
  554. _OPERATION_NAME = 'CollectionSideBar'
  555. def _real_extract(self, url):
  556. collection_id = self._match_id(url)
  557. collection = self._download_gql(
  558. collection_id, [{
  559. 'operationName': self._OPERATION_NAME,
  560. 'variables': {'collectionID': collection_id},
  561. }],
  562. 'Downloading collection GraphQL')[0]['data']['collection']
  563. title = collection.get('title')
  564. entries = []
  565. for edge in collection['items']['edges']:
  566. if not isinstance(edge, dict):
  567. continue
  568. node = edge.get('node')
  569. if not isinstance(node, dict):
  570. continue
  571. video = _make_video_result(node)
  572. if video:
  573. entries.append(video)
  574. return self.playlist_result(
  575. entries, playlist_id=collection_id, playlist_title=title)
  576. class TwitchPlaylistBaseIE(TwitchBaseIE):
  577. _PAGE_LIMIT = 100
  578. def _entries(self, channel_name, *args):
  579. cursor = None
  580. variables_common = self._make_variables(channel_name, *args)
  581. entries_key = f'{self._ENTRY_KIND}s'
  582. for page_num in itertools.count(1):
  583. variables = variables_common.copy()
  584. variables['limit'] = self._PAGE_LIMIT
  585. if cursor:
  586. variables['cursor'] = cursor
  587. page = self._download_gql(
  588. channel_name, [{
  589. 'operationName': self._OPERATION_NAME,
  590. 'variables': variables,
  591. }],
  592. f'Downloading {self._NODE_KIND}s GraphQL page {page_num}',
  593. fatal=False)
  594. if not page:
  595. break
  596. edges = try_get(
  597. page, lambda x: x[0]['data']['user'][entries_key]['edges'], list)
  598. if not edges:
  599. break
  600. for edge in edges:
  601. if not isinstance(edge, dict):
  602. continue
  603. if edge.get('__typename') != self._EDGE_KIND:
  604. continue
  605. node = edge.get('node')
  606. if not isinstance(node, dict):
  607. continue
  608. if node.get('__typename') != self._NODE_KIND:
  609. continue
  610. entry = self._extract_entry(node)
  611. if entry:
  612. cursor = edge.get('cursor')
  613. yield entry
  614. if not cursor or not isinstance(cursor, str):
  615. break
  616. class TwitchVideosIE(TwitchPlaylistBaseIE):
  617. _VALID_URL = r'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/(?:videos|profile)'
  618. _TESTS = [{
  619. # All Videos sorted by Date
  620. 'url': 'https://www.twitch.tv/spamfish/videos?filter=all',
  621. 'info_dict': {
  622. 'id': 'spamfish',
  623. 'title': 'spamfish - All Videos sorted by Date',
  624. },
  625. 'playlist_mincount': 924,
  626. }, {
  627. # All Videos sorted by Popular
  628. 'url': 'https://www.twitch.tv/spamfish/videos?filter=all&sort=views',
  629. 'info_dict': {
  630. 'id': 'spamfish',
  631. 'title': 'spamfish - All Videos sorted by Popular',
  632. },
  633. 'playlist_mincount': 931,
  634. }, {
  635. # Past Broadcasts sorted by Date
  636. 'url': 'https://www.twitch.tv/spamfish/videos?filter=archives',
  637. 'info_dict': {
  638. 'id': 'spamfish',
  639. 'title': 'spamfish - Past Broadcasts sorted by Date',
  640. },
  641. 'playlist_mincount': 27,
  642. }, {
  643. # Highlights sorted by Date
  644. 'url': 'https://www.twitch.tv/spamfish/videos?filter=highlights',
  645. 'info_dict': {
  646. 'id': 'spamfish',
  647. 'title': 'spamfish - Highlights sorted by Date',
  648. },
  649. 'playlist_mincount': 901,
  650. }, {
  651. # Uploads sorted by Date
  652. 'url': 'https://www.twitch.tv/esl_csgo/videos?filter=uploads&sort=time',
  653. 'info_dict': {
  654. 'id': 'esl_csgo',
  655. 'title': 'esl_csgo - Uploads sorted by Date',
  656. },
  657. 'playlist_mincount': 5,
  658. }, {
  659. # Past Premieres sorted by Date
  660. 'url': 'https://www.twitch.tv/spamfish/videos?filter=past_premieres',
  661. 'info_dict': {
  662. 'id': 'spamfish',
  663. 'title': 'spamfish - Past Premieres sorted by Date',
  664. },
  665. 'playlist_mincount': 1,
  666. }, {
  667. 'url': 'https://www.twitch.tv/spamfish/videos/all',
  668. 'only_matching': True,
  669. }, {
  670. 'url': 'https://m.twitch.tv/spamfish/videos/all',
  671. 'only_matching': True,
  672. }, {
  673. 'url': 'https://www.twitch.tv/spamfish/videos',
  674. 'only_matching': True,
  675. }]
  676. Broadcast = collections.namedtuple('Broadcast', ['type', 'label'])
  677. _DEFAULT_BROADCAST = Broadcast(None, 'All Videos')
  678. _BROADCASTS = {
  679. 'archives': Broadcast('ARCHIVE', 'Past Broadcasts'),
  680. 'highlights': Broadcast('HIGHLIGHT', 'Highlights'),
  681. 'uploads': Broadcast('UPLOAD', 'Uploads'),
  682. 'past_premieres': Broadcast('PAST_PREMIERE', 'Past Premieres'),
  683. 'all': _DEFAULT_BROADCAST,
  684. }
  685. _DEFAULT_SORTED_BY = 'Date'
  686. _SORTED_BY = {
  687. 'time': _DEFAULT_SORTED_BY,
  688. 'views': 'Popular',
  689. }
  690. _OPERATION_NAME = 'FilterableVideoTower_Videos'
  691. _ENTRY_KIND = 'video'
  692. _EDGE_KIND = 'VideoEdge'
  693. _NODE_KIND = 'Video'
  694. @classmethod
  695. def suitable(cls, url):
  696. return (False
  697. if any(ie.suitable(url) for ie in (
  698. TwitchVideosClipsIE,
  699. TwitchVideosCollectionsIE))
  700. else super().suitable(url))
  701. @staticmethod
  702. def _make_variables(channel_name, broadcast_type, sort):
  703. return {
  704. 'channelOwnerLogin': channel_name,
  705. 'broadcastType': broadcast_type,
  706. 'videoSort': sort.upper(),
  707. }
  708. @staticmethod
  709. def _extract_entry(node):
  710. return _make_video_result(node)
  711. def _real_extract(self, url):
  712. channel_name = self._match_id(url)
  713. qs = parse_qs(url)
  714. video_filter = qs.get('filter', ['all'])[0]
  715. sort = qs.get('sort', ['time'])[0]
  716. broadcast = self._BROADCASTS.get(video_filter, self._DEFAULT_BROADCAST)
  717. return self.playlist_result(
  718. self._entries(channel_name, broadcast.type, sort),
  719. playlist_id=channel_name,
  720. playlist_title=(
  721. f'{channel_name} - {broadcast.label} '
  722. f'sorted by {self._SORTED_BY.get(sort, self._DEFAULT_SORTED_BY)}'))
  723. class TwitchVideosClipsIE(TwitchPlaylistBaseIE):
  724. _VALID_URL = r'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/(?:clips|videos/*?\?.*?\bfilter=clips)'
  725. _TESTS = [{
  726. # Clips
  727. 'url': 'https://www.twitch.tv/vanillatv/clips?filter=clips&range=all',
  728. 'info_dict': {
  729. 'id': 'vanillatv',
  730. 'title': 'vanillatv - Clips Top All',
  731. },
  732. 'playlist_mincount': 1,
  733. }, {
  734. 'url': 'https://www.twitch.tv/dota2ruhub/videos?filter=clips&range=7d',
  735. 'only_matching': True,
  736. }]
  737. Clip = collections.namedtuple('Clip', ['filter', 'label'])
  738. _DEFAULT_CLIP = Clip('LAST_WEEK', 'Top 7D')
  739. _RANGE = {
  740. '24hr': Clip('LAST_DAY', 'Top 24H'),
  741. '7d': _DEFAULT_CLIP,
  742. '30d': Clip('LAST_MONTH', 'Top 30D'),
  743. 'all': Clip('ALL_TIME', 'Top All'),
  744. }
  745. # NB: values other than 20 result in skipped videos
  746. _PAGE_LIMIT = 20
  747. _OPERATION_NAME = 'ClipsCards__User'
  748. _ENTRY_KIND = 'clip'
  749. _EDGE_KIND = 'ClipEdge'
  750. _NODE_KIND = 'Clip'
  751. @staticmethod
  752. def _make_variables(channel_name, channel_filter):
  753. return {
  754. 'login': channel_name,
  755. 'criteria': {
  756. 'filter': channel_filter,
  757. },
  758. }
  759. @staticmethod
  760. def _extract_entry(node):
  761. assert isinstance(node, dict)
  762. clip_url = url_or_none(node.get('url'))
  763. if not clip_url:
  764. return
  765. return {
  766. '_type': 'url_transparent',
  767. 'ie_key': TwitchClipsIE.ie_key(),
  768. 'id': node.get('id'),
  769. 'url': clip_url,
  770. 'title': node.get('title'),
  771. 'thumbnail': node.get('thumbnailURL'),
  772. 'duration': float_or_none(node.get('durationSeconds')),
  773. 'timestamp': unified_timestamp(node.get('createdAt')),
  774. 'view_count': int_or_none(node.get('viewCount')),
  775. 'language': node.get('language'),
  776. }
  777. def _real_extract(self, url):
  778. channel_name = self._match_id(url)
  779. qs = parse_qs(url)
  780. date_range = qs.get('range', ['7d'])[0]
  781. clip = self._RANGE.get(date_range, self._DEFAULT_CLIP)
  782. return self.playlist_result(
  783. self._entries(channel_name, clip.filter),
  784. playlist_id=channel_name,
  785. playlist_title=f'{channel_name} - Clips {clip.label}')
  786. class TwitchVideosCollectionsIE(TwitchPlaylistBaseIE):
  787. _VALID_URL = r'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/videos/*?\?.*?\bfilter=collections'
  788. _TESTS = [{
  789. # Collections
  790. 'url': 'https://www.twitch.tv/spamfish/videos?filter=collections',
  791. 'info_dict': {
  792. 'id': 'spamfish',
  793. 'title': 'spamfish - Collections',
  794. },
  795. 'playlist_mincount': 3,
  796. }, {
  797. 'url': 'https://www.twitch.tv/monstercat/videos?filter=collections',
  798. 'info_dict': {
  799. 'id': 'monstercat',
  800. 'title': 'monstercat - Collections',
  801. },
  802. 'playlist_mincount': 13,
  803. }]
  804. _OPERATION_NAME = 'ChannelCollectionsContent'
  805. _ENTRY_KIND = 'collection'
  806. _EDGE_KIND = 'CollectionsItemEdge'
  807. _NODE_KIND = 'Collection'
  808. @staticmethod
  809. def _make_variables(channel_name):
  810. return {
  811. 'ownerLogin': channel_name,
  812. }
  813. @staticmethod
  814. def _extract_entry(node):
  815. assert isinstance(node, dict)
  816. collection_id = node.get('id')
  817. if not collection_id:
  818. return
  819. return {
  820. '_type': 'url_transparent',
  821. 'ie_key': TwitchCollectionIE.ie_key(),
  822. 'id': collection_id,
  823. 'url': f'https://www.twitch.tv/collections/{collection_id}',
  824. 'title': node.get('title'),
  825. 'thumbnail': node.get('thumbnailURL'),
  826. 'duration': float_or_none(node.get('lengthSeconds')),
  827. 'timestamp': unified_timestamp(node.get('updatedAt')),
  828. 'view_count': int_or_none(node.get('viewCount')),
  829. }
  830. def _real_extract(self, url):
  831. channel_name = self._match_id(url)
  832. return self.playlist_result(
  833. self._entries(channel_name), playlist_id=channel_name,
  834. playlist_title=f'{channel_name} - Collections')
  835. class TwitchStreamIE(TwitchBaseIE):
  836. IE_NAME = 'twitch:stream'
  837. _VALID_URL = r'''(?x)
  838. https?://
  839. (?:
  840. (?:(?:www|go|m)\.)?twitch\.tv/|
  841. player\.twitch\.tv/\?.*?\bchannel=
  842. )
  843. (?P<id>[^/#?]+)
  844. '''
  845. _TESTS = [{
  846. 'url': 'http://www.twitch.tv/shroomztv',
  847. 'info_dict': {
  848. 'id': '12772022048',
  849. 'display_id': 'shroomztv',
  850. 'ext': 'mp4',
  851. 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  852. 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
  853. 'is_live': True,
  854. 'timestamp': 1421928037,
  855. 'upload_date': '20150122',
  856. 'uploader': 'ShroomzTV',
  857. 'uploader_id': 'shroomztv',
  858. 'view_count': int,
  859. },
  860. 'params': {
  861. # m3u8 download
  862. 'skip_download': True,
  863. },
  864. 'skip': 'User does not exist',
  865. }, {
  866. 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
  867. 'only_matching': True,
  868. }, {
  869. 'url': 'https://player.twitch.tv/?channel=lotsofs',
  870. 'only_matching': True,
  871. }, {
  872. 'url': 'https://go.twitch.tv/food',
  873. 'only_matching': True,
  874. }, {
  875. 'url': 'https://m.twitch.tv/food',
  876. 'only_matching': True,
  877. }, {
  878. 'url': 'https://www.twitch.tv/monstercat',
  879. 'info_dict': {
  880. 'id': '40500071752',
  881. 'display_id': 'monstercat',
  882. 'title': 're:Monstercat',
  883. 'description': 'md5:0945ad625e615bc8f0469396537d87d9',
  884. 'is_live': True,
  885. 'timestamp': 1677107190,
  886. 'upload_date': '20230222',
  887. 'uploader': 'Monstercat',
  888. 'uploader_id': 'monstercat',
  889. 'live_status': 'is_live',
  890. 'thumbnail': 're:https://.*.jpg',
  891. 'ext': 'mp4',
  892. },
  893. 'params': {
  894. 'skip_download': 'Livestream',
  895. },
  896. }]
  897. @classmethod
  898. def suitable(cls, url):
  899. return (False
  900. if any(ie.suitable(url) for ie in (
  901. TwitchVodIE,
  902. TwitchCollectionIE,
  903. TwitchVideosIE,
  904. TwitchVideosClipsIE,
  905. TwitchVideosCollectionsIE,
  906. TwitchClipsIE))
  907. else super().suitable(url))
  908. def _real_extract(self, url):
  909. channel_name = self._match_id(url).lower()
  910. gql = self._download_gql(
  911. channel_name, [{
  912. 'operationName': 'StreamMetadata',
  913. 'variables': {'channelLogin': channel_name},
  914. }, {
  915. 'operationName': 'ComscoreStreamingQuery',
  916. 'variables': {
  917. 'channel': channel_name,
  918. 'clipSlug': '',
  919. 'isClip': False,
  920. 'isLive': True,
  921. 'isVodOrCollection': False,
  922. 'vodID': '',
  923. },
  924. }, {
  925. 'operationName': 'VideoPreviewOverlay',
  926. 'variables': {'login': channel_name},
  927. }],
  928. 'Downloading stream GraphQL')
  929. user = gql[0]['data']['user']
  930. if not user:
  931. raise ExtractorError(
  932. f'{channel_name} does not exist', expected=True)
  933. stream = user['stream']
  934. if not stream:
  935. raise UserNotLive(video_id=channel_name)
  936. access_token = self._download_access_token(
  937. channel_name, 'stream', 'channelName')
  938. stream_id = stream.get('id') or channel_name
  939. formats = self._extract_twitch_m3u8_formats(
  940. 'api/channel/hls', channel_name, access_token['value'], access_token['signature'])
  941. self._prefer_source(formats)
  942. view_count = stream.get('viewers')
  943. timestamp = unified_timestamp(stream.get('createdAt'))
  944. sq_user = try_get(gql, lambda x: x[1]['data']['user'], dict) or {}
  945. uploader = sq_user.get('displayName')
  946. description = try_get(
  947. sq_user, lambda x: x['broadcastSettings']['title'], str)
  948. thumbnail = url_or_none(try_get(
  949. gql, lambda x: x[2]['data']['user']['stream']['previewImageURL'],
  950. str))
  951. title = uploader or channel_name
  952. stream_type = stream.get('type')
  953. if stream_type in ['rerun', 'live']:
  954. title += f' ({stream_type})'
  955. return {
  956. 'id': stream_id,
  957. 'display_id': channel_name,
  958. 'title': title,
  959. 'description': description,
  960. 'thumbnails': self._get_thumbnails(thumbnail),
  961. 'uploader': uploader,
  962. 'uploader_id': channel_name,
  963. 'timestamp': timestamp,
  964. 'view_count': view_count,
  965. 'formats': formats,
  966. 'is_live': stream_type == 'live',
  967. }
  968. class TwitchClipsIE(TwitchBaseIE):
  969. IE_NAME = 'twitch:clips'
  970. _VALID_URL = r'''(?x)
  971. https?://
  972. (?:
  973. clips\.twitch\.tv/(?:embed\?.*?\bclip=|(?:[^/]+/)*)|
  974. (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/)?clip/
  975. )
  976. (?P<id>[^/?#&]+)
  977. '''
  978. _TESTS = [{
  979. 'url': 'https://clips.twitch.tv/FaintLightGullWholeWheat',
  980. 'md5': '761769e1eafce0ffebfb4089cb3847cd',
  981. 'info_dict': {
  982. 'id': '42850523',
  983. 'display_id': 'FaintLightGullWholeWheat',
  984. 'ext': 'mp4',
  985. 'title': 'EA Play 2016 Live from the Novo Theatre',
  986. 'thumbnail': r're:^https?://.*\.jpg',
  987. 'timestamp': 1465767393,
  988. 'upload_date': '20160612',
  989. 'creator': 'EA',
  990. 'uploader': 'stereotype_',
  991. 'uploader_id': '43566419',
  992. },
  993. }, {
  994. # multiple formats
  995. 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
  996. 'only_matching': True,
  997. }, {
  998. 'url': 'https://www.twitch.tv/sergeynixon/clip/StormyThankfulSproutFutureMan',
  999. 'only_matching': True,
  1000. }, {
  1001. 'url': 'https://clips.twitch.tv/embed?clip=InquisitiveBreakableYogurtJebaited',
  1002. 'only_matching': True,
  1003. }, {
  1004. 'url': 'https://m.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
  1005. 'only_matching': True,
  1006. }, {
  1007. 'url': 'https://go.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
  1008. 'only_matching': True,
  1009. }, {
  1010. 'url': 'https://m.twitch.tv/clip/FaintLightGullWholeWheat',
  1011. 'only_matching': True,
  1012. }]
  1013. def _real_extract(self, url):
  1014. video_id = self._match_id(url)
  1015. clip = self._download_gql(
  1016. video_id, [{
  1017. 'operationName': 'VideoAccessToken_Clip',
  1018. 'variables': {
  1019. 'slug': video_id,
  1020. },
  1021. }],
  1022. 'Downloading clip access token GraphQL')[0]['data']['clip']
  1023. if not clip:
  1024. raise ExtractorError(
  1025. 'This clip is no longer available', expected=True)
  1026. access_query = {
  1027. 'sig': clip['playbackAccessToken']['signature'],
  1028. 'token': clip['playbackAccessToken']['value'],
  1029. }
  1030. data = self._download_base_gql(
  1031. video_id, {
  1032. 'query': '''{
  1033. clip(slug: "%s") {
  1034. broadcaster {
  1035. displayName
  1036. }
  1037. createdAt
  1038. curator {
  1039. displayName
  1040. id
  1041. }
  1042. durationSeconds
  1043. id
  1044. tiny: thumbnailURL(width: 86, height: 45)
  1045. small: thumbnailURL(width: 260, height: 147)
  1046. medium: thumbnailURL(width: 480, height: 272)
  1047. title
  1048. videoQualities {
  1049. frameRate
  1050. quality
  1051. sourceURL
  1052. }
  1053. viewCount
  1054. }
  1055. }''' % video_id}, 'Downloading clip GraphQL', fatal=False) # noqa: UP031
  1056. if data:
  1057. clip = try_get(data, lambda x: x['data']['clip'], dict) or clip
  1058. formats = []
  1059. for option in clip.get('videoQualities', []):
  1060. if not isinstance(option, dict):
  1061. continue
  1062. source = url_or_none(option.get('sourceURL'))
  1063. if not source:
  1064. continue
  1065. formats.append({
  1066. 'url': update_url_query(source, access_query),
  1067. 'format_id': option.get('quality'),
  1068. 'height': int_or_none(option.get('quality')),
  1069. 'fps': int_or_none(option.get('frameRate')),
  1070. })
  1071. thumbnails = []
  1072. for thumbnail_id in ('tiny', 'small', 'medium'):
  1073. thumbnail_url = clip.get(thumbnail_id)
  1074. if not thumbnail_url:
  1075. continue
  1076. thumb = {
  1077. 'id': thumbnail_id,
  1078. 'url': thumbnail_url,
  1079. }
  1080. mobj = re.search(r'-(\d+)x(\d+)\.', thumbnail_url)
  1081. if mobj:
  1082. thumb.update({
  1083. 'height': int(mobj.group(2)),
  1084. 'width': int(mobj.group(1)),
  1085. })
  1086. thumbnails.append(thumb)
  1087. old_id = self._search_regex(r'%7C(\d+)(?:-\d+)?.mp4', formats[-1]['url'], 'old id', default=None)
  1088. return {
  1089. 'id': clip.get('id') or video_id,
  1090. '_old_archive_ids': [make_archive_id(self, old_id)] if old_id else None,
  1091. 'display_id': video_id,
  1092. 'title': clip.get('title'),
  1093. 'formats': formats,
  1094. 'duration': int_or_none(clip.get('durationSeconds')),
  1095. 'view_count': int_or_none(clip.get('viewCount')),
  1096. 'timestamp': unified_timestamp(clip.get('createdAt')),
  1097. 'thumbnails': thumbnails,
  1098. 'creator': try_get(clip, lambda x: x['broadcaster']['displayName'], str),
  1099. 'uploader': try_get(clip, lambda x: x['curator']['displayName'], str),
  1100. 'uploader_id': try_get(clip, lambda x: x['curator']['id'], str),
  1101. }