twitch.py 34 KB

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