logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

twitch.py (34150B)


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