twitch.py 33 KB

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