twitch.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import collections
  4. import itertools
  5. import json
  6. import random
  7. import re
  8. from .common import InfoExtractor
  9. from ..compat import (
  10. compat_kwargs,
  11. compat_parse_qs,
  12. compat_str,
  13. compat_urlparse,
  14. compat_urllib_parse_urlencode,
  15. compat_urllib_parse_urlparse,
  16. )
  17. from ..utils import (
  18. clean_html,
  19. ExtractorError,
  20. float_or_none,
  21. int_or_none,
  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 = 'kimne78kx3ncx6brgo4mv6wki5h1ko'
  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. headers = kwargs.get('headers', {}).copy()
  49. headers.update({
  50. 'Accept': 'application/vnd.twitchtv.v5+json; charset=UTF-8',
  51. 'Client-ID': self._CLIENT_ID,
  52. })
  53. kwargs.update({
  54. 'headers': headers,
  55. 'expected_status': (400, 410),
  56. })
  57. response = self._download_json(
  58. '%s/%s' % (self._API_BASE, path), item_id,
  59. *args, **compat_kwargs(kwargs))
  60. self._handle_error(response)
  61. return response
  62. def _real_initialize(self):
  63. self._login()
  64. def _login(self):
  65. username, password = self._get_login_info()
  66. if username is None:
  67. return
  68. def fail(message):
  69. raise ExtractorError(
  70. 'Unable to login. Twitch said: %s' % message, expected=True)
  71. def login_step(page, urlh, note, data):
  72. form = self._hidden_inputs(page)
  73. form.update(data)
  74. page_url = urlh.geturl()
  75. post_url = self._search_regex(
  76. r'<form[^>]+action=(["\'])(?P<url>.+?)\1', page,
  77. 'post url', default=self._LOGIN_POST_URL, group='url')
  78. post_url = urljoin(page_url, post_url)
  79. headers = {
  80. 'Referer': page_url,
  81. 'Origin': page_url,
  82. 'Content-Type': 'text/plain;charset=UTF-8',
  83. }
  84. response = self._download_json(
  85. post_url, None, note, data=json.dumps(form).encode(),
  86. headers=headers, expected_status=400)
  87. error = response.get('error_description') or response.get('error_code')
  88. if error:
  89. fail(error)
  90. if 'Authenticated successfully' in response.get('message', ''):
  91. return None, None
  92. redirect_url = urljoin(
  93. post_url,
  94. response.get('redirect') or response['redirect_path'])
  95. return self._download_webpage_handle(
  96. redirect_url, None, 'Downloading login redirect page',
  97. headers=headers)
  98. login_page, handle = self._download_webpage_handle(
  99. self._LOGIN_FORM_URL, None, 'Downloading login page')
  100. # Some TOR nodes and public proxies are blocked completely
  101. if 'blacklist_message' in login_page:
  102. fail(clean_html(login_page))
  103. redirect_page, handle = login_step(
  104. login_page, handle, 'Logging in', {
  105. 'username': username,
  106. 'password': password,
  107. 'client_id': self._CLIENT_ID,
  108. })
  109. # Successful login
  110. if not redirect_page:
  111. return
  112. if re.search(r'(?i)<form[^>]+id="two-factor-submit"', redirect_page) is not None:
  113. # TODO: Add mechanism to request an SMS or phone call
  114. tfa_token = self._get_tfa_info('two-factor authentication token')
  115. login_step(redirect_page, handle, 'Submitting TFA token', {
  116. 'authy_token': tfa_token,
  117. 'remember_2fa': 'true',
  118. })
  119. def _prefer_source(self, formats):
  120. try:
  121. source = next(f for f in formats if f['format_id'] == 'Source')
  122. source['quality'] = 10
  123. except StopIteration:
  124. for f in formats:
  125. if '/chunked/' in f['url']:
  126. f.update({
  127. 'quality': 10,
  128. 'format_note': 'Source',
  129. })
  130. self._sort_formats(formats)
  131. def _download_access_token(self, channel_name):
  132. return self._call_api(
  133. 'api/channels/%s/access_token' % channel_name, channel_name,
  134. 'Downloading access token JSON')
  135. def _extract_channel_id(self, token, channel_name):
  136. return compat_str(self._parse_json(token, channel_name)['channel_id'])
  137. class TwitchGraphQLBaseIE(TwitchBaseIE):
  138. _PAGE_LIMIT = 100
  139. _OPERATION_HASHES = {
  140. 'CollectionSideBar': '27111f1b382effad0b6def325caef1909c733fe6a4fbabf54f8d491ef2cf2f14',
  141. 'FilterableVideoTower_Videos': 'a937f1d22e269e39a03b509f65a7490f9fc247d7f83d6ac1421523e3b68042cb',
  142. 'ClipsCards__User': 'b73ad2bfaecfd30a9e6c28fada15bd97032c83ec77a0440766a56fe0bd632777',
  143. 'ChannelCollectionsContent': '07e3691a1bad77a36aba590c351180439a40baefc1c275356f40fc7082419a84',
  144. 'StreamMetadata': '1c719a40e481453e5c48d9bb585d971b8b372f8ebb105b17076722264dfa5b3e',
  145. 'ComscoreStreamingQuery': 'e1edae8122517d013405f237ffcc124515dc6ded82480a88daef69c83b53ac01',
  146. 'VideoPreviewOverlay': '3006e77e51b128d838fa4e835723ca4dc9a05c5efd4466c1085215c6e437e65c',
  147. 'VideoMetadata': '226edb3e692509f727fd56821f5653c05740242c82b0388883e0c0e75dcbf687',
  148. }
  149. def _download_base_gql(self, video_id, ops, note, fatal=True):
  150. return self._download_json(
  151. 'https://gql.twitch.tv/gql', video_id, note,
  152. data=json.dumps(ops).encode(),
  153. headers={
  154. 'Content-Type': 'text/plain;charset=UTF-8',
  155. 'Client-ID': self._CLIENT_ID,
  156. }, fatal=fatal)
  157. def _download_gql(self, video_id, ops, note, fatal=True):
  158. for op in ops:
  159. op['extensions'] = {
  160. 'persistedQuery': {
  161. 'version': 1,
  162. 'sha256Hash': self._OPERATION_HASHES[op['operationName']],
  163. }
  164. }
  165. return self._download_base_gql(video_id, ops, note)
  166. def _download_access_token_gql(self, video_id, token_kind, param_name):
  167. method = '%sPlaybackAccessToken' % token_kind
  168. ops = {
  169. 'query': '''{
  170. %s(
  171. %s: "%s",
  172. params: {
  173. platform: "web",
  174. playerBackend: "mediaplayer",
  175. playerType: "site"
  176. }
  177. )
  178. {
  179. value
  180. signature
  181. }
  182. }''' % (method, param_name, video_id),
  183. }
  184. return self._download_base_gql(
  185. video_id, ops,
  186. 'Downloading %s access token GraphQL' % token_kind)['data'][method]
  187. class TwitchVodIE(TwitchGraphQLBaseIE):
  188. IE_NAME = 'twitch:vod'
  189. _VALID_URL = r'''(?x)
  190. https?://
  191. (?:
  192. (?:(?:www|go|m)\.)?twitch\.tv/(?:[^/]+/v(?:ideo)?|videos)/|
  193. player\.twitch\.tv/\?.*?\bvideo=v?
  194. )
  195. (?P<id>\d+)
  196. '''
  197. _TESTS = [{
  198. 'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s',
  199. 'info_dict': {
  200. 'id': 'v6528877',
  201. 'ext': 'mp4',
  202. 'title': 'LCK Summer Split - Week 6 Day 1',
  203. 'thumbnail': r're:^https?://.*\.jpg$',
  204. 'duration': 17208,
  205. 'timestamp': 1435131734,
  206. 'upload_date': '20150624',
  207. 'uploader': 'Riot Games',
  208. 'uploader_id': 'riotgames',
  209. 'view_count': int,
  210. 'start_time': 310,
  211. },
  212. 'params': {
  213. # m3u8 download
  214. 'skip_download': True,
  215. },
  216. }, {
  217. # Untitled broadcast (title is None)
  218. 'url': 'http://www.twitch.tv/belkao_o/v/11230755',
  219. 'info_dict': {
  220. 'id': 'v11230755',
  221. 'ext': 'mp4',
  222. 'title': 'Untitled Broadcast',
  223. 'thumbnail': r're:^https?://.*\.jpg$',
  224. 'duration': 1638,
  225. 'timestamp': 1439746708,
  226. 'upload_date': '20150816',
  227. 'uploader': 'BelkAO_o',
  228. 'uploader_id': 'belkao_o',
  229. 'view_count': int,
  230. },
  231. 'params': {
  232. # m3u8 download
  233. 'skip_download': True,
  234. },
  235. 'skip': 'HTTP Error 404: Not Found',
  236. }, {
  237. 'url': 'http://player.twitch.tv/?t=5m10s&video=v6528877',
  238. 'only_matching': True,
  239. }, {
  240. 'url': 'https://www.twitch.tv/videos/6528877',
  241. 'only_matching': True,
  242. }, {
  243. 'url': 'https://m.twitch.tv/beagsandjam/v/247478721',
  244. 'only_matching': True,
  245. }, {
  246. 'url': 'https://www.twitch.tv/northernlion/video/291940395',
  247. 'only_matching': True,
  248. }, {
  249. 'url': 'https://player.twitch.tv/?video=480452374',
  250. 'only_matching': True,
  251. }]
  252. def _download_info(self, item_id):
  253. return self._extract_info(
  254. self._call_api(
  255. 'kraken/videos/%s' % item_id, item_id,
  256. 'Downloading video info JSON'))
  257. def _download_info_gql(self, item_id):
  258. data = self._download_gql(
  259. item_id, [{
  260. 'operationName': 'VideoMetadata',
  261. 'variables': {
  262. 'channelLogin': '',
  263. 'videoID': item_id,
  264. },
  265. }],
  266. 'Downloading stream metadata GraphQL')[0]['data']
  267. video = data.get('video')
  268. if video is None:
  269. raise ExtractorError(
  270. 'Video %s does not exist' % item_id, expected=True)
  271. return self._extract_info_gql(video, item_id)
  272. @staticmethod
  273. def _extract_info(info):
  274. status = info.get('status')
  275. if status == 'recording':
  276. is_live = True
  277. elif status == 'recorded':
  278. is_live = False
  279. else:
  280. is_live = None
  281. _QUALITIES = ('small', 'medium', 'large')
  282. quality_key = qualities(_QUALITIES)
  283. thumbnails = []
  284. preview = info.get('preview')
  285. if isinstance(preview, dict):
  286. for thumbnail_id, thumbnail_url in preview.items():
  287. thumbnail_url = url_or_none(thumbnail_url)
  288. if not thumbnail_url:
  289. continue
  290. if thumbnail_id not in _QUALITIES:
  291. continue
  292. thumbnails.append({
  293. 'url': thumbnail_url,
  294. 'preference': quality_key(thumbnail_id),
  295. })
  296. return {
  297. 'id': info['_id'],
  298. 'title': info.get('title') or 'Untitled Broadcast',
  299. 'description': info.get('description'),
  300. 'duration': int_or_none(info.get('length')),
  301. 'thumbnails': thumbnails,
  302. 'uploader': info.get('channel', {}).get('display_name'),
  303. 'uploader_id': info.get('channel', {}).get('name'),
  304. 'timestamp': parse_iso8601(info.get('recorded_at')),
  305. 'view_count': int_or_none(info.get('views')),
  306. 'is_live': is_live,
  307. }
  308. @staticmethod
  309. def _extract_info_gql(info, item_id):
  310. vod_id = info.get('id') or item_id
  311. # id backward compatibility for download archives
  312. if vod_id[0] != 'v':
  313. vod_id = 'v%s' % vod_id
  314. thumbnail = url_or_none(info.get('previewThumbnailURL'))
  315. if thumbnail:
  316. for p in ('width', 'height'):
  317. thumbnail = thumbnail.replace('{%s}' % p, '0')
  318. return {
  319. 'id': vod_id,
  320. 'title': info.get('title') or 'Untitled Broadcast',
  321. 'description': info.get('description'),
  322. 'duration': int_or_none(info.get('lengthSeconds')),
  323. 'thumbnail': thumbnail,
  324. 'uploader': try_get(info, lambda x: x['owner']['displayName'], compat_str),
  325. 'uploader_id': try_get(info, lambda x: x['owner']['login'], compat_str),
  326. 'timestamp': unified_timestamp(info.get('publishedAt')),
  327. 'view_count': int_or_none(info.get('viewCount')),
  328. }
  329. def _real_extract(self, url):
  330. vod_id = self._match_id(url)
  331. info = self._download_info_gql(vod_id)
  332. access_token = self._download_access_token_gql(vod_id, 'video', 'id')
  333. formats = self._extract_m3u8_formats(
  334. '%s/vod/%s.m3u8?%s' % (
  335. self._USHER_BASE, vod_id,
  336. compat_urllib_parse_urlencode({
  337. 'allow_source': 'true',
  338. 'allow_audio_only': 'true',
  339. 'allow_spectre': 'true',
  340. 'player': 'twitchweb',
  341. 'playlist_include_framerate': 'true',
  342. 'nauth': access_token['value'],
  343. 'nauthsig': access_token['signature'],
  344. })),
  345. vod_id, 'mp4', entry_protocol='m3u8_native')
  346. self._prefer_source(formats)
  347. info['formats'] = formats
  348. parsed_url = compat_urllib_parse_urlparse(url)
  349. query = compat_parse_qs(parsed_url.query)
  350. if 't' in query:
  351. info['start_time'] = parse_duration(query['t'][0])
  352. if info.get('timestamp') is not None:
  353. info['subtitles'] = {
  354. 'rechat': [{
  355. 'url': update_url_query(
  356. 'https://api.twitch.tv/v5/videos/%s/comments' % vod_id, {
  357. 'client_id': self._CLIENT_ID,
  358. }),
  359. 'ext': 'json',
  360. }],
  361. }
  362. return info
  363. def _make_video_result(node):
  364. assert isinstance(node, dict)
  365. video_id = node.get('id')
  366. if not video_id:
  367. return
  368. return {
  369. '_type': 'url_transparent',
  370. 'ie_key': TwitchVodIE.ie_key(),
  371. 'id': video_id,
  372. 'url': 'https://www.twitch.tv/videos/%s' % video_id,
  373. 'title': node.get('title'),
  374. 'thumbnail': node.get('previewThumbnailURL'),
  375. 'duration': float_or_none(node.get('lengthSeconds')),
  376. 'view_count': int_or_none(node.get('viewCount')),
  377. }
  378. class TwitchCollectionIE(TwitchGraphQLBaseIE):
  379. _VALID_URL = r'https?://(?:(?:www|go|m)\.)?twitch\.tv/collections/(?P<id>[^/]+)'
  380. _TESTS = [{
  381. 'url': 'https://www.twitch.tv/collections/wlDCoH0zEBZZbQ',
  382. 'info_dict': {
  383. 'id': 'wlDCoH0zEBZZbQ',
  384. 'title': 'Overthrow Nook, capitalism for children',
  385. },
  386. 'playlist_mincount': 13,
  387. }]
  388. _OPERATION_NAME = 'CollectionSideBar'
  389. def _real_extract(self, url):
  390. collection_id = self._match_id(url)
  391. collection = self._download_gql(
  392. collection_id, [{
  393. 'operationName': self._OPERATION_NAME,
  394. 'variables': {'collectionID': collection_id},
  395. }],
  396. 'Downloading collection GraphQL')[0]['data']['collection']
  397. title = collection.get('title')
  398. entries = []
  399. for edge in collection['items']['edges']:
  400. if not isinstance(edge, dict):
  401. continue
  402. node = edge.get('node')
  403. if not isinstance(node, dict):
  404. continue
  405. video = _make_video_result(node)
  406. if video:
  407. entries.append(video)
  408. return self.playlist_result(
  409. entries, playlist_id=collection_id, playlist_title=title)
  410. class TwitchPlaylistBaseIE(TwitchGraphQLBaseIE):
  411. def _entries(self, channel_name, *args):
  412. cursor = None
  413. variables_common = self._make_variables(channel_name, *args)
  414. entries_key = '%ss' % self._ENTRY_KIND
  415. for page_num in itertools.count(1):
  416. variables = variables_common.copy()
  417. variables['limit'] = self._PAGE_LIMIT
  418. if cursor:
  419. variables['cursor'] = cursor
  420. page = self._download_gql(
  421. channel_name, [{
  422. 'operationName': self._OPERATION_NAME,
  423. 'variables': variables,
  424. }],
  425. 'Downloading %ss GraphQL page %s' % (self._NODE_KIND, page_num),
  426. fatal=False)
  427. if not page:
  428. break
  429. edges = try_get(
  430. page, lambda x: x[0]['data']['user'][entries_key]['edges'], list)
  431. if not edges:
  432. break
  433. for edge in edges:
  434. if not isinstance(edge, dict):
  435. continue
  436. if edge.get('__typename') != self._EDGE_KIND:
  437. continue
  438. node = edge.get('node')
  439. if not isinstance(node, dict):
  440. continue
  441. if node.get('__typename') != self._NODE_KIND:
  442. continue
  443. entry = self._extract_entry(node)
  444. if entry:
  445. cursor = edge.get('cursor')
  446. yield entry
  447. if not cursor or not isinstance(cursor, compat_str):
  448. break
  449. # Deprecated kraken v5 API
  450. def _entries_kraken(self, channel_name, broadcast_type, sort):
  451. access_token = self._download_access_token(channel_name)
  452. channel_id = self._extract_channel_id(access_token['token'], channel_name)
  453. offset = 0
  454. counter_override = None
  455. for counter in itertools.count(1):
  456. response = self._call_api(
  457. 'kraken/channels/%s/videos/' % channel_id,
  458. channel_id,
  459. 'Downloading video JSON page %s' % (counter_override or counter),
  460. query={
  461. 'offset': offset,
  462. 'limit': self._PAGE_LIMIT,
  463. 'broadcast_type': broadcast_type,
  464. 'sort': sort,
  465. })
  466. videos = response.get('videos')
  467. if not isinstance(videos, list):
  468. break
  469. for video in videos:
  470. if not isinstance(video, dict):
  471. continue
  472. video_url = url_or_none(video.get('url'))
  473. if not video_url:
  474. continue
  475. yield {
  476. '_type': 'url_transparent',
  477. 'ie_key': TwitchVodIE.ie_key(),
  478. 'id': video.get('_id'),
  479. 'url': video_url,
  480. 'title': video.get('title'),
  481. 'description': video.get('description'),
  482. 'timestamp': unified_timestamp(video.get('published_at')),
  483. 'duration': float_or_none(video.get('length')),
  484. 'view_count': int_or_none(video.get('views')),
  485. 'language': video.get('language'),
  486. }
  487. offset += self._PAGE_LIMIT
  488. total = int_or_none(response.get('_total'))
  489. if total and offset >= total:
  490. break
  491. class TwitchVideosIE(TwitchPlaylistBaseIE):
  492. _VALID_URL = r'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/(?:videos|profile)'
  493. _TESTS = [{
  494. # All Videos sorted by Date
  495. 'url': 'https://www.twitch.tv/spamfish/videos?filter=all',
  496. 'info_dict': {
  497. 'id': 'spamfish',
  498. 'title': 'spamfish - All Videos sorted by Date',
  499. },
  500. 'playlist_mincount': 924,
  501. }, {
  502. # All Videos sorted by Popular
  503. 'url': 'https://www.twitch.tv/spamfish/videos?filter=all&sort=views',
  504. 'info_dict': {
  505. 'id': 'spamfish',
  506. 'title': 'spamfish - All Videos sorted by Popular',
  507. },
  508. 'playlist_mincount': 931,
  509. }, {
  510. # Past Broadcasts sorted by Date
  511. 'url': 'https://www.twitch.tv/spamfish/videos?filter=archives',
  512. 'info_dict': {
  513. 'id': 'spamfish',
  514. 'title': 'spamfish - Past Broadcasts sorted by Date',
  515. },
  516. 'playlist_mincount': 27,
  517. }, {
  518. # Highlights sorted by Date
  519. 'url': 'https://www.twitch.tv/spamfish/videos?filter=highlights',
  520. 'info_dict': {
  521. 'id': 'spamfish',
  522. 'title': 'spamfish - Highlights sorted by Date',
  523. },
  524. 'playlist_mincount': 901,
  525. }, {
  526. # Uploads sorted by Date
  527. 'url': 'https://www.twitch.tv/esl_csgo/videos?filter=uploads&sort=time',
  528. 'info_dict': {
  529. 'id': 'esl_csgo',
  530. 'title': 'esl_csgo - Uploads sorted by Date',
  531. },
  532. 'playlist_mincount': 5,
  533. }, {
  534. # Past Premieres sorted by Date
  535. 'url': 'https://www.twitch.tv/spamfish/videos?filter=past_premieres',
  536. 'info_dict': {
  537. 'id': 'spamfish',
  538. 'title': 'spamfish - Past Premieres sorted by Date',
  539. },
  540. 'playlist_mincount': 1,
  541. }, {
  542. 'url': 'https://www.twitch.tv/spamfish/videos/all',
  543. 'only_matching': True,
  544. }, {
  545. 'url': 'https://m.twitch.tv/spamfish/videos/all',
  546. 'only_matching': True,
  547. }, {
  548. 'url': 'https://www.twitch.tv/spamfish/videos',
  549. 'only_matching': True,
  550. }]
  551. Broadcast = collections.namedtuple('Broadcast', ['type', 'label'])
  552. _DEFAULT_BROADCAST = Broadcast(None, 'All Videos')
  553. _BROADCASTS = {
  554. 'archives': Broadcast('ARCHIVE', 'Past Broadcasts'),
  555. 'highlights': Broadcast('HIGHLIGHT', 'Highlights'),
  556. 'uploads': Broadcast('UPLOAD', 'Uploads'),
  557. 'past_premieres': Broadcast('PAST_PREMIERE', 'Past Premieres'),
  558. 'all': _DEFAULT_BROADCAST,
  559. }
  560. _DEFAULT_SORTED_BY = 'Date'
  561. _SORTED_BY = {
  562. 'time': _DEFAULT_SORTED_BY,
  563. 'views': 'Popular',
  564. }
  565. _OPERATION_NAME = 'FilterableVideoTower_Videos'
  566. _ENTRY_KIND = 'video'
  567. _EDGE_KIND = 'VideoEdge'
  568. _NODE_KIND = 'Video'
  569. @classmethod
  570. def suitable(cls, url):
  571. return (False
  572. if any(ie.suitable(url) for ie in (
  573. TwitchVideosClipsIE,
  574. TwitchVideosCollectionsIE))
  575. else super(TwitchVideosIE, cls).suitable(url))
  576. @staticmethod
  577. def _make_variables(channel_name, broadcast_type, sort):
  578. return {
  579. 'channelOwnerLogin': channel_name,
  580. 'broadcastType': broadcast_type,
  581. 'videoSort': sort.upper(),
  582. }
  583. @staticmethod
  584. def _extract_entry(node):
  585. return _make_video_result(node)
  586. def _real_extract(self, url):
  587. channel_name = self._match_id(url)
  588. qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  589. filter = qs.get('filter', ['all'])[0]
  590. sort = qs.get('sort', ['time'])[0]
  591. broadcast = self._BROADCASTS.get(filter, self._DEFAULT_BROADCAST)
  592. return self.playlist_result(
  593. self._entries(channel_name, broadcast.type, sort),
  594. playlist_id=channel_name,
  595. playlist_title='%s - %s sorted by %s'
  596. % (channel_name, broadcast.label,
  597. self._SORTED_BY.get(sort, self._DEFAULT_SORTED_BY)))
  598. class TwitchVideosClipsIE(TwitchPlaylistBaseIE):
  599. _VALID_URL = r'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/(?:clips|videos/*?\?.*?\bfilter=clips)'
  600. _TESTS = [{
  601. # Clips
  602. 'url': 'https://www.twitch.tv/vanillatv/clips?filter=clips&range=all',
  603. 'info_dict': {
  604. 'id': 'vanillatv',
  605. 'title': 'vanillatv - Clips Top All',
  606. },
  607. 'playlist_mincount': 1,
  608. }, {
  609. 'url': 'https://www.twitch.tv/dota2ruhub/videos?filter=clips&range=7d',
  610. 'only_matching': True,
  611. }]
  612. Clip = collections.namedtuple('Clip', ['filter', 'label'])
  613. _DEFAULT_CLIP = Clip('LAST_WEEK', 'Top 7D')
  614. _RANGE = {
  615. '24hr': Clip('LAST_DAY', 'Top 24H'),
  616. '7d': _DEFAULT_CLIP,
  617. '30d': Clip('LAST_MONTH', 'Top 30D'),
  618. 'all': Clip('ALL_TIME', 'Top All'),
  619. }
  620. # NB: values other than 20 result in skipped videos
  621. _PAGE_LIMIT = 20
  622. _OPERATION_NAME = 'ClipsCards__User'
  623. _ENTRY_KIND = 'clip'
  624. _EDGE_KIND = 'ClipEdge'
  625. _NODE_KIND = 'Clip'
  626. @staticmethod
  627. def _make_variables(channel_name, filter):
  628. return {
  629. 'login': channel_name,
  630. 'criteria': {
  631. 'filter': filter,
  632. },
  633. }
  634. @staticmethod
  635. def _extract_entry(node):
  636. assert isinstance(node, dict)
  637. clip_url = url_or_none(node.get('url'))
  638. if not clip_url:
  639. return
  640. return {
  641. '_type': 'url_transparent',
  642. 'ie_key': TwitchClipsIE.ie_key(),
  643. 'id': node.get('id'),
  644. 'url': clip_url,
  645. 'title': node.get('title'),
  646. 'thumbnail': node.get('thumbnailURL'),
  647. 'duration': float_or_none(node.get('durationSeconds')),
  648. 'timestamp': unified_timestamp(node.get('createdAt')),
  649. 'view_count': int_or_none(node.get('viewCount')),
  650. 'language': node.get('language'),
  651. }
  652. def _real_extract(self, url):
  653. channel_name = self._match_id(url)
  654. qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  655. range = qs.get('range', ['7d'])[0]
  656. clip = self._RANGE.get(range, self._DEFAULT_CLIP)
  657. return self.playlist_result(
  658. self._entries(channel_name, clip.filter),
  659. playlist_id=channel_name,
  660. playlist_title='%s - Clips %s' % (channel_name, clip.label))
  661. class TwitchVideosCollectionsIE(TwitchPlaylistBaseIE):
  662. _VALID_URL = r'https?://(?:(?:www|go|m)\.)?twitch\.tv/(?P<id>[^/]+)/videos/*?\?.*?\bfilter=collections'
  663. _TESTS = [{
  664. # Collections
  665. 'url': 'https://www.twitch.tv/spamfish/videos?filter=collections',
  666. 'info_dict': {
  667. 'id': 'spamfish',
  668. 'title': 'spamfish - Collections',
  669. },
  670. 'playlist_mincount': 3,
  671. }]
  672. _OPERATION_NAME = 'ChannelCollectionsContent'
  673. _ENTRY_KIND = 'collection'
  674. _EDGE_KIND = 'CollectionsItemEdge'
  675. _NODE_KIND = 'Collection'
  676. @staticmethod
  677. def _make_variables(channel_name):
  678. return {
  679. 'ownerLogin': channel_name,
  680. }
  681. @staticmethod
  682. def _extract_entry(node):
  683. assert isinstance(node, dict)
  684. collection_id = node.get('id')
  685. if not collection_id:
  686. return
  687. return {
  688. '_type': 'url_transparent',
  689. 'ie_key': TwitchCollectionIE.ie_key(),
  690. 'id': collection_id,
  691. 'url': 'https://www.twitch.tv/collections/%s' % collection_id,
  692. 'title': node.get('title'),
  693. 'thumbnail': node.get('thumbnailURL'),
  694. 'duration': float_or_none(node.get('lengthSeconds')),
  695. 'timestamp': unified_timestamp(node.get('updatedAt')),
  696. 'view_count': int_or_none(node.get('viewCount')),
  697. }
  698. def _real_extract(self, url):
  699. channel_name = self._match_id(url)
  700. return self.playlist_result(
  701. self._entries(channel_name), playlist_id=channel_name,
  702. playlist_title='%s - Collections' % channel_name)
  703. class TwitchStreamIE(TwitchGraphQLBaseIE):
  704. IE_NAME = 'twitch:stream'
  705. _VALID_URL = r'''(?x)
  706. https?://
  707. (?:
  708. (?:(?:www|go|m)\.)?twitch\.tv/|
  709. player\.twitch\.tv/\?.*?\bchannel=
  710. )
  711. (?P<id>[^/#?]+)
  712. '''
  713. _TESTS = [{
  714. 'url': 'http://www.twitch.tv/shroomztv',
  715. 'info_dict': {
  716. 'id': '12772022048',
  717. 'display_id': 'shroomztv',
  718. 'ext': 'mp4',
  719. 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  720. 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
  721. 'is_live': True,
  722. 'timestamp': 1421928037,
  723. 'upload_date': '20150122',
  724. 'uploader': 'ShroomzTV',
  725. 'uploader_id': 'shroomztv',
  726. 'view_count': int,
  727. },
  728. 'params': {
  729. # m3u8 download
  730. 'skip_download': True,
  731. },
  732. }, {
  733. 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
  734. 'only_matching': True,
  735. }, {
  736. 'url': 'https://player.twitch.tv/?channel=lotsofs',
  737. 'only_matching': True,
  738. }, {
  739. 'url': 'https://go.twitch.tv/food',
  740. 'only_matching': True,
  741. }, {
  742. 'url': 'https://m.twitch.tv/food',
  743. 'only_matching': True,
  744. }]
  745. @classmethod
  746. def suitable(cls, url):
  747. return (False
  748. if any(ie.suitable(url) for ie in (
  749. TwitchVodIE,
  750. TwitchCollectionIE,
  751. TwitchVideosIE,
  752. TwitchVideosClipsIE,
  753. TwitchVideosCollectionsIE,
  754. TwitchClipsIE))
  755. else super(TwitchStreamIE, cls).suitable(url))
  756. def _real_extract(self, url):
  757. channel_name = self._match_id(url).lower()
  758. gql = self._download_gql(
  759. channel_name, [{
  760. 'operationName': 'StreamMetadata',
  761. 'variables': {'channelLogin': channel_name},
  762. }, {
  763. 'operationName': 'ComscoreStreamingQuery',
  764. 'variables': {
  765. 'channel': channel_name,
  766. 'clipSlug': '',
  767. 'isClip': False,
  768. 'isLive': True,
  769. 'isVodOrCollection': False,
  770. 'vodID': '',
  771. },
  772. }, {
  773. 'operationName': 'VideoPreviewOverlay',
  774. 'variables': {'login': channel_name},
  775. }],
  776. 'Downloading stream GraphQL')
  777. user = gql[0]['data']['user']
  778. if not user:
  779. raise ExtractorError(
  780. '%s does not exist' % channel_name, expected=True)
  781. stream = user['stream']
  782. if not stream:
  783. raise ExtractorError('%s is offline' % channel_name, expected=True)
  784. access_token = self._download_access_token_gql(
  785. channel_name, 'stream', 'channelName')
  786. token = access_token['value']
  787. stream_id = stream.get('id') or channel_name
  788. query = {
  789. 'allow_source': 'true',
  790. 'allow_audio_only': 'true',
  791. 'allow_spectre': 'true',
  792. 'p': random.randint(1000000, 10000000),
  793. 'player': 'twitchweb',
  794. 'playlist_include_framerate': 'true',
  795. 'segment_preference': '4',
  796. 'sig': access_token['signature'].encode('utf-8'),
  797. 'token': token.encode('utf-8'),
  798. }
  799. formats = self._extract_m3u8_formats(
  800. '%s/api/channel/hls/%s.m3u8' % (self._USHER_BASE, channel_name),
  801. stream_id, 'mp4', query=query)
  802. self._prefer_source(formats)
  803. view_count = stream.get('viewers')
  804. timestamp = unified_timestamp(stream.get('createdAt'))
  805. sq_user = try_get(gql, lambda x: x[1]['data']['user'], dict) or {}
  806. uploader = sq_user.get('displayName')
  807. description = try_get(
  808. sq_user, lambda x: x['broadcastSettings']['title'], compat_str)
  809. thumbnail = url_or_none(try_get(
  810. gql, lambda x: x[2]['data']['user']['stream']['previewImageURL'],
  811. compat_str))
  812. title = uploader or channel_name
  813. stream_type = stream.get('type')
  814. if stream_type in ['rerun', 'live']:
  815. title += ' (%s)' % stream_type
  816. return {
  817. 'id': stream_id,
  818. 'display_id': channel_name,
  819. 'title': self._live_title(title),
  820. 'description': description,
  821. 'thumbnail': thumbnail,
  822. 'uploader': uploader,
  823. 'uploader_id': channel_name,
  824. 'timestamp': timestamp,
  825. 'view_count': view_count,
  826. 'formats': formats,
  827. 'is_live': stream_type == 'live',
  828. }
  829. class TwitchClipsIE(TwitchGraphQLBaseIE):
  830. IE_NAME = 'twitch:clips'
  831. _VALID_URL = r'''(?x)
  832. https?://
  833. (?:
  834. clips\.twitch\.tv/(?:embed\?.*?\bclip=|(?:[^/]+/)*)|
  835. (?:(?:www|go|m)\.)?twitch\.tv/[^/]+/clip/
  836. )
  837. (?P<id>[^/?#&]+)
  838. '''
  839. _TESTS = [{
  840. 'url': 'https://clips.twitch.tv/FaintLightGullWholeWheat',
  841. 'md5': '761769e1eafce0ffebfb4089cb3847cd',
  842. 'info_dict': {
  843. 'id': '42850523',
  844. 'ext': 'mp4',
  845. 'title': 'EA Play 2016 Live from the Novo Theatre',
  846. 'thumbnail': r're:^https?://.*\.jpg',
  847. 'timestamp': 1465767393,
  848. 'upload_date': '20160612',
  849. 'creator': 'EA',
  850. 'uploader': 'stereotype_',
  851. 'uploader_id': '43566419',
  852. },
  853. }, {
  854. # multiple formats
  855. 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
  856. 'only_matching': True,
  857. }, {
  858. 'url': 'https://www.twitch.tv/sergeynixon/clip/StormyThankfulSproutFutureMan',
  859. 'only_matching': True,
  860. }, {
  861. 'url': 'https://clips.twitch.tv/embed?clip=InquisitiveBreakableYogurtJebaited',
  862. 'only_matching': True,
  863. }, {
  864. 'url': 'https://m.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
  865. 'only_matching': True,
  866. }, {
  867. 'url': 'https://go.twitch.tv/rossbroadcast/clip/ConfidentBraveHumanChefFrank',
  868. 'only_matching': True,
  869. }]
  870. def _real_extract(self, url):
  871. video_id = self._match_id(url)
  872. clip = self._download_base_gql(
  873. video_id, {
  874. 'query': '''{
  875. clip(slug: "%s") {
  876. broadcaster {
  877. displayName
  878. }
  879. createdAt
  880. curator {
  881. displayName
  882. id
  883. }
  884. durationSeconds
  885. id
  886. tiny: thumbnailURL(width: 86, height: 45)
  887. small: thumbnailURL(width: 260, height: 147)
  888. medium: thumbnailURL(width: 480, height: 272)
  889. title
  890. videoQualities {
  891. frameRate
  892. quality
  893. sourceURL
  894. }
  895. viewCount
  896. }
  897. }''' % video_id}, 'Downloading clip GraphQL')['data']['clip']
  898. if not clip:
  899. raise ExtractorError(
  900. 'This clip is no longer available', expected=True)
  901. formats = []
  902. for option in clip.get('videoQualities', []):
  903. if not isinstance(option, dict):
  904. continue
  905. source = url_or_none(option.get('sourceURL'))
  906. if not source:
  907. continue
  908. formats.append({
  909. 'url': source,
  910. 'format_id': option.get('quality'),
  911. 'height': int_or_none(option.get('quality')),
  912. 'fps': int_or_none(option.get('frameRate')),
  913. })
  914. self._sort_formats(formats)
  915. thumbnails = []
  916. for thumbnail_id in ('tiny', 'small', 'medium'):
  917. thumbnail_url = clip.get(thumbnail_id)
  918. if not thumbnail_url:
  919. continue
  920. thumb = {
  921. 'id': thumbnail_id,
  922. 'url': thumbnail_url,
  923. }
  924. mobj = re.search(r'-(\d+)x(\d+)\.', thumbnail_url)
  925. if mobj:
  926. thumb.update({
  927. 'height': int(mobj.group(2)),
  928. 'width': int(mobj.group(1)),
  929. })
  930. thumbnails.append(thumb)
  931. return {
  932. 'id': clip.get('id') or video_id,
  933. 'title': clip.get('title') or video_id,
  934. 'formats': formats,
  935. 'duration': int_or_none(clip.get('durationSeconds')),
  936. 'views': int_or_none(clip.get('viewCount')),
  937. 'timestamp': unified_timestamp(clip.get('createdAt')),
  938. 'thumbnails': thumbnails,
  939. 'creator': try_get(clip, lambda x: x['broadcaster']['displayName'], compat_str),
  940. 'uploader': try_get(clip, lambda x: x['curator']['displayName'], compat_str),
  941. 'uploader_id': try_get(clip, lambda x: x['curator']['id'], compat_str),
  942. }