twitch.py 33 KB

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