twitch.py 34 KB

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