twitch.py 32 KB

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