twitch.py 33 KB

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