You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

499 lines
17 KiB

Switch codebase to use sanitized_Request instead of compat_urllib_request.Request [downloader/dash] Use sanitized_Request [downloader/http] Use sanitized_Request [atresplayer] Use sanitized_Request [bambuser] Use sanitized_Request [bliptv] Use sanitized_Request [brightcove] Use sanitized_Request [cbs] Use sanitized_Request [ceskatelevize] Use sanitized_Request [collegerama] Use sanitized_Request [extractor/common] Use sanitized_Request [crunchyroll] Use sanitized_Request [dailymotion] Use sanitized_Request [dcn] Use sanitized_Request [dramafever] Use sanitized_Request [dumpert] Use sanitized_Request [eitb] Use sanitized_Request [escapist] Use sanitized_Request [everyonesmixtape] Use sanitized_Request [extremetube] Use sanitized_Request [facebook] Use sanitized_Request [fc2] Use sanitized_Request [flickr] Use sanitized_Request [4tube] Use sanitized_Request [gdcvault] Use sanitized_Request [extractor/generic] Use sanitized_Request [hearthisat] Use sanitized_Request [hotnewhiphop] Use sanitized_Request [hypem] Use sanitized_Request [iprima] Use sanitized_Request [ivi] Use sanitized_Request [keezmovies] Use sanitized_Request [letv] Use sanitized_Request [lynda] Use sanitized_Request [metacafe] Use sanitized_Request [minhateca] Use sanitized_Request [miomio] Use sanitized_Request [meovideo] Use sanitized_Request [mofosex] Use sanitized_Request [moniker] Use sanitized_Request [mooshare] Use sanitized_Request [movieclips] Use sanitized_Request [mtv] Use sanitized_Request [myvideo] Use sanitized_Request [neteasemusic] Use sanitized_Request [nfb] Use sanitized_Request [niconico] Use sanitized_Request [noco] Use sanitized_Request [nosvideo] Use sanitized_Request [novamov] Use sanitized_Request [nowness] Use sanitized_Request [nuvid] Use sanitized_Request [played] Use sanitized_Request [pluralsight] Use sanitized_Request [pornhub] Use sanitized_Request [pornotube] Use sanitized_Request [primesharetv] Use sanitized_Request [promptfile] Use sanitized_Request [qqmusic] Use sanitized_Request [rtve] Use sanitized_Request [safari] Use sanitized_Request [sandia] Use sanitized_Request [shared] Use sanitized_Request [sharesix] Use sanitized_Request [sina] Use sanitized_Request [smotri] Use sanitized_Request [sohu] Use sanitized_Request [spankwire] Use sanitized_Request [sportdeutschland] Use sanitized_Request [streamcloud] Use sanitized_Request [streamcz] Use sanitized_Request [tapely] Use sanitized_Request [tube8] Use sanitized_Request [tubitv] Use sanitized_Request [twitch] Use sanitized_Request [twitter] Use sanitized_Request [udemy] Use sanitized_Request [vbox7] Use sanitized_Request [veoh] Use sanitized_Request [vessel] Use sanitized_Request [vevo] Use sanitized_Request [viddler] Use sanitized_Request [videomega] Use sanitized_Request [viewvster] Use sanitized_Request [viki] Use sanitized_Request [vk] Use sanitized_Request [vodlocker] Use sanitized_Request [voicerepublic] Use sanitized_Request [wistia] Use sanitized_Request [xfileshare] Use sanitized_Request [xtube] Use sanitized_Request [xvideos] Use sanitized_Request [yandexmusic] Use sanitized_Request [youku] Use sanitized_Request [youporn] Use sanitized_Request [youtube] Use sanitized_Request [patreon] Use sanitized_Request [extractor/common] Remove unused import [nfb] PEP 8
9 years ago
Switch codebase to use sanitized_Request instead of compat_urllib_request.Request [downloader/dash] Use sanitized_Request [downloader/http] Use sanitized_Request [atresplayer] Use sanitized_Request [bambuser] Use sanitized_Request [bliptv] Use sanitized_Request [brightcove] Use sanitized_Request [cbs] Use sanitized_Request [ceskatelevize] Use sanitized_Request [collegerama] Use sanitized_Request [extractor/common] Use sanitized_Request [crunchyroll] Use sanitized_Request [dailymotion] Use sanitized_Request [dcn] Use sanitized_Request [dramafever] Use sanitized_Request [dumpert] Use sanitized_Request [eitb] Use sanitized_Request [escapist] Use sanitized_Request [everyonesmixtape] Use sanitized_Request [extremetube] Use sanitized_Request [facebook] Use sanitized_Request [fc2] Use sanitized_Request [flickr] Use sanitized_Request [4tube] Use sanitized_Request [gdcvault] Use sanitized_Request [extractor/generic] Use sanitized_Request [hearthisat] Use sanitized_Request [hotnewhiphop] Use sanitized_Request [hypem] Use sanitized_Request [iprima] Use sanitized_Request [ivi] Use sanitized_Request [keezmovies] Use sanitized_Request [letv] Use sanitized_Request [lynda] Use sanitized_Request [metacafe] Use sanitized_Request [minhateca] Use sanitized_Request [miomio] Use sanitized_Request [meovideo] Use sanitized_Request [mofosex] Use sanitized_Request [moniker] Use sanitized_Request [mooshare] Use sanitized_Request [movieclips] Use sanitized_Request [mtv] Use sanitized_Request [myvideo] Use sanitized_Request [neteasemusic] Use sanitized_Request [nfb] Use sanitized_Request [niconico] Use sanitized_Request [noco] Use sanitized_Request [nosvideo] Use sanitized_Request [novamov] Use sanitized_Request [nowness] Use sanitized_Request [nuvid] Use sanitized_Request [played] Use sanitized_Request [pluralsight] Use sanitized_Request [pornhub] Use sanitized_Request [pornotube] Use sanitized_Request [primesharetv] Use sanitized_Request [promptfile] Use sanitized_Request [qqmusic] Use sanitized_Request [rtve] Use sanitized_Request [safari] Use sanitized_Request [sandia] Use sanitized_Request [shared] Use sanitized_Request [sharesix] Use sanitized_Request [sina] Use sanitized_Request [smotri] Use sanitized_Request [sohu] Use sanitized_Request [spankwire] Use sanitized_Request [sportdeutschland] Use sanitized_Request [streamcloud] Use sanitized_Request [streamcz] Use sanitized_Request [tapely] Use sanitized_Request [tube8] Use sanitized_Request [tubitv] Use sanitized_Request [twitch] Use sanitized_Request [twitter] Use sanitized_Request [udemy] Use sanitized_Request [vbox7] Use sanitized_Request [veoh] Use sanitized_Request [vessel] Use sanitized_Request [vevo] Use sanitized_Request [viddler] Use sanitized_Request [videomega] Use sanitized_Request [viewvster] Use sanitized_Request [viki] Use sanitized_Request [vk] Use sanitized_Request [vodlocker] Use sanitized_Request [voicerepublic] Use sanitized_Request [wistia] Use sanitized_Request [xfileshare] Use sanitized_Request [xtube] Use sanitized_Request [xvideos] Use sanitized_Request [yandexmusic] Use sanitized_Request [youku] Use sanitized_Request [youporn] Use sanitized_Request [youtube] Use sanitized_Request [patreon] Use sanitized_Request [extractor/common] Remove unused import [nfb] PEP 8
9 years ago
Switch codebase to use sanitized_Request instead of compat_urllib_request.Request [downloader/dash] Use sanitized_Request [downloader/http] Use sanitized_Request [atresplayer] Use sanitized_Request [bambuser] Use sanitized_Request [bliptv] Use sanitized_Request [brightcove] Use sanitized_Request [cbs] Use sanitized_Request [ceskatelevize] Use sanitized_Request [collegerama] Use sanitized_Request [extractor/common] Use sanitized_Request [crunchyroll] Use sanitized_Request [dailymotion] Use sanitized_Request [dcn] Use sanitized_Request [dramafever] Use sanitized_Request [dumpert] Use sanitized_Request [eitb] Use sanitized_Request [escapist] Use sanitized_Request [everyonesmixtape] Use sanitized_Request [extremetube] Use sanitized_Request [facebook] Use sanitized_Request [fc2] Use sanitized_Request [flickr] Use sanitized_Request [4tube] Use sanitized_Request [gdcvault] Use sanitized_Request [extractor/generic] Use sanitized_Request [hearthisat] Use sanitized_Request [hotnewhiphop] Use sanitized_Request [hypem] Use sanitized_Request [iprima] Use sanitized_Request [ivi] Use sanitized_Request [keezmovies] Use sanitized_Request [letv] Use sanitized_Request [lynda] Use sanitized_Request [metacafe] Use sanitized_Request [minhateca] Use sanitized_Request [miomio] Use sanitized_Request [meovideo] Use sanitized_Request [mofosex] Use sanitized_Request [moniker] Use sanitized_Request [mooshare] Use sanitized_Request [movieclips] Use sanitized_Request [mtv] Use sanitized_Request [myvideo] Use sanitized_Request [neteasemusic] Use sanitized_Request [nfb] Use sanitized_Request [niconico] Use sanitized_Request [noco] Use sanitized_Request [nosvideo] Use sanitized_Request [novamov] Use sanitized_Request [nowness] Use sanitized_Request [nuvid] Use sanitized_Request [played] Use sanitized_Request [pluralsight] Use sanitized_Request [pornhub] Use sanitized_Request [pornotube] Use sanitized_Request [primesharetv] Use sanitized_Request [promptfile] Use sanitized_Request [qqmusic] Use sanitized_Request [rtve] Use sanitized_Request [safari] Use sanitized_Request [sandia] Use sanitized_Request [shared] Use sanitized_Request [sharesix] Use sanitized_Request [sina] Use sanitized_Request [smotri] Use sanitized_Request [sohu] Use sanitized_Request [spankwire] Use sanitized_Request [sportdeutschland] Use sanitized_Request [streamcloud] Use sanitized_Request [streamcz] Use sanitized_Request [tapely] Use sanitized_Request [tube8] Use sanitized_Request [tubitv] Use sanitized_Request [twitch] Use sanitized_Request [twitter] Use sanitized_Request [udemy] Use sanitized_Request [vbox7] Use sanitized_Request [veoh] Use sanitized_Request [vessel] Use sanitized_Request [vevo] Use sanitized_Request [viddler] Use sanitized_Request [videomega] Use sanitized_Request [viewvster] Use sanitized_Request [viki] Use sanitized_Request [vk] Use sanitized_Request [vodlocker] Use sanitized_Request [voicerepublic] Use sanitized_Request [wistia] Use sanitized_Request [xfileshare] Use sanitized_Request [xtube] Use sanitized_Request [xvideos] Use sanitized_Request [yandexmusic] Use sanitized_Request [youku] Use sanitized_Request [youporn] Use sanitized_Request [youtube] Use sanitized_Request [patreon] Use sanitized_Request [extractor/common] Remove unused import [nfb] PEP 8
9 years ago
10 years ago
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import itertools
  4. import re
  5. import random
  6. from .common import InfoExtractor
  7. from ..compat import (
  8. compat_parse_qs,
  9. compat_str,
  10. compat_urllib_parse_urlencode,
  11. compat_urllib_parse_urlparse,
  12. compat_urlparse,
  13. )
  14. from ..utils import (
  15. ExtractorError,
  16. int_or_none,
  17. js_to_json,
  18. orderedSet,
  19. parse_duration,
  20. parse_iso8601,
  21. sanitized_Request,
  22. urlencode_postdata,
  23. )
  24. class TwitchBaseIE(InfoExtractor):
  25. _VALID_URL_BASE = r'https?://(?:www\.)?twitch\.tv'
  26. _API_BASE = 'https://api.twitch.tv'
  27. _USHER_BASE = 'http://usher.twitch.tv'
  28. _LOGIN_URL = 'http://www.twitch.tv/login'
  29. _NETRC_MACHINE = 'twitch'
  30. def _handle_error(self, response):
  31. if not isinstance(response, dict):
  32. return
  33. error = response.get('error')
  34. if error:
  35. raise ExtractorError(
  36. '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
  37. expected=True)
  38. def _download_json(self, url, video_id, note='Downloading JSON metadata'):
  39. headers = {
  40. 'Referer': 'http://api.twitch.tv/crossdomain/receiver.html?v=2',
  41. 'X-Requested-With': 'XMLHttpRequest',
  42. }
  43. for cookie in self._downloader.cookiejar:
  44. if cookie.name == 'api_token':
  45. headers['Twitch-Api-Token'] = cookie.value
  46. request = sanitized_Request(url, headers=headers)
  47. response = super(TwitchBaseIE, self)._download_json(request, video_id, note)
  48. self._handle_error(response)
  49. return response
  50. def _real_initialize(self):
  51. self._login()
  52. def _login(self):
  53. (username, password) = self._get_login_info()
  54. if username is None:
  55. return
  56. login_page, handle = self._download_webpage_handle(
  57. self._LOGIN_URL, None, 'Downloading login page')
  58. login_form = self._hidden_inputs(login_page)
  59. login_form.update({
  60. 'username': username,
  61. 'password': password,
  62. })
  63. redirect_url = handle.geturl()
  64. post_url = self._search_regex(
  65. r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
  66. 'post url', default=redirect_url, group='url')
  67. if not post_url.startswith('http'):
  68. post_url = compat_urlparse.urljoin(redirect_url, post_url)
  69. request = sanitized_Request(
  70. post_url, urlencode_postdata(login_form))
  71. request.add_header('Referer', redirect_url)
  72. response = self._download_webpage(
  73. request, None, 'Logging in as %s' % username)
  74. error_message = self._search_regex(
  75. r'<div[^>]+class="subwindow_notice"[^>]*>([^<]+)</div>',
  76. response, 'error message', default=None)
  77. if error_message:
  78. raise ExtractorError(
  79. 'Unable to login. Twitch said: %s' % error_message, expected=True)
  80. if '>Reset your password<' in response:
  81. self.report_warning('Twitch asks you to reset your password, go to https://secure.twitch.tv/reset/submit')
  82. def _prefer_source(self, formats):
  83. try:
  84. source = next(f for f in formats if f['format_id'] == 'Source')
  85. source['preference'] = 10
  86. except StopIteration:
  87. pass # No Source stream present
  88. self._sort_formats(formats)
  89. class TwitchItemBaseIE(TwitchBaseIE):
  90. def _download_info(self, item, item_id):
  91. return self._extract_info(self._download_json(
  92. '%s/kraken/videos/%s%s' % (self._API_BASE, item, item_id), item_id,
  93. 'Downloading %s info JSON' % self._ITEM_TYPE))
  94. def _extract_media(self, item_id):
  95. info = self._download_info(self._ITEM_SHORTCUT, item_id)
  96. response = self._download_json(
  97. '%s/api/videos/%s%s' % (self._API_BASE, self._ITEM_SHORTCUT, item_id), item_id,
  98. 'Downloading %s playlist JSON' % self._ITEM_TYPE)
  99. entries = []
  100. chunks = response['chunks']
  101. qualities = list(chunks.keys())
  102. for num, fragment in enumerate(zip(*chunks.values()), start=1):
  103. formats = []
  104. for fmt_num, fragment_fmt in enumerate(fragment):
  105. format_id = qualities[fmt_num]
  106. fmt = {
  107. 'url': fragment_fmt['url'],
  108. 'format_id': format_id,
  109. 'quality': 1 if format_id == 'live' else 0,
  110. }
  111. m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
  112. if m:
  113. fmt['height'] = int(m.group('height'))
  114. formats.append(fmt)
  115. self._sort_formats(formats)
  116. entry = dict(info)
  117. entry['id'] = '%s_%d' % (entry['id'], num)
  118. entry['title'] = '%s part %d' % (entry['title'], num)
  119. entry['formats'] = formats
  120. entries.append(entry)
  121. return self.playlist_result(entries, info['id'], info['title'])
  122. def _extract_info(self, info):
  123. return {
  124. 'id': info['_id'],
  125. 'title': info.get('title') or 'Untitled Broadcast',
  126. 'description': info.get('description'),
  127. 'duration': int_or_none(info.get('length')),
  128. 'thumbnail': info.get('preview'),
  129. 'uploader': info.get('channel', {}).get('display_name'),
  130. 'uploader_id': info.get('channel', {}).get('name'),
  131. 'timestamp': parse_iso8601(info.get('recorded_at')),
  132. 'view_count': int_or_none(info.get('views')),
  133. }
  134. def _real_extract(self, url):
  135. return self._extract_media(self._match_id(url))
  136. class TwitchVideoIE(TwitchItemBaseIE):
  137. IE_NAME = 'twitch:video'
  138. _VALID_URL = r'%s/[^/]+/b/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
  139. _ITEM_TYPE = 'video'
  140. _ITEM_SHORTCUT = 'a'
  141. _TEST = {
  142. 'url': 'http://www.twitch.tv/riotgames/b/577357806',
  143. 'info_dict': {
  144. 'id': 'a577357806',
  145. 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
  146. },
  147. 'playlist_mincount': 12,
  148. 'skip': 'HTTP Error 404: Not Found',
  149. }
  150. class TwitchChapterIE(TwitchItemBaseIE):
  151. IE_NAME = 'twitch:chapter'
  152. _VALID_URL = r'%s/[^/]+/c/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
  153. _ITEM_TYPE = 'chapter'
  154. _ITEM_SHORTCUT = 'c'
  155. _TESTS = [{
  156. 'url': 'http://www.twitch.tv/acracingleague/c/5285812',
  157. 'info_dict': {
  158. 'id': 'c5285812',
  159. 'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
  160. },
  161. 'playlist_mincount': 3,
  162. 'skip': 'HTTP Error 404: Not Found',
  163. }, {
  164. 'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361',
  165. 'only_matching': True,
  166. }]
  167. class TwitchVodIE(TwitchItemBaseIE):
  168. IE_NAME = 'twitch:vod'
  169. _VALID_URL = r'%s/[^/]+/v/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
  170. _ITEM_TYPE = 'vod'
  171. _ITEM_SHORTCUT = 'v'
  172. _TESTS = [{
  173. 'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s',
  174. 'info_dict': {
  175. 'id': 'v6528877',
  176. 'ext': 'mp4',
  177. 'title': 'LCK Summer Split - Week 6 Day 1',
  178. 'thumbnail': 're:^https?://.*\.jpg$',
  179. 'duration': 17208,
  180. 'timestamp': 1435131709,
  181. 'upload_date': '20150624',
  182. 'uploader': 'Riot Games',
  183. 'uploader_id': 'riotgames',
  184. 'view_count': int,
  185. 'start_time': 310,
  186. },
  187. 'params': {
  188. # m3u8 download
  189. 'skip_download': True,
  190. },
  191. }, {
  192. # Untitled broadcast (title is None)
  193. 'url': 'http://www.twitch.tv/belkao_o/v/11230755',
  194. 'info_dict': {
  195. 'id': 'v11230755',
  196. 'ext': 'mp4',
  197. 'title': 'Untitled Broadcast',
  198. 'thumbnail': 're:^https?://.*\.jpg$',
  199. 'duration': 1638,
  200. 'timestamp': 1439746708,
  201. 'upload_date': '20150816',
  202. 'uploader': 'BelkAO_o',
  203. 'uploader_id': 'belkao_o',
  204. 'view_count': int,
  205. },
  206. 'params': {
  207. # m3u8 download
  208. 'skip_download': True,
  209. },
  210. }]
  211. def _real_extract(self, url):
  212. item_id = self._match_id(url)
  213. info = self._download_info(self._ITEM_SHORTCUT, item_id)
  214. access_token = self._download_json(
  215. '%s/api/vods/%s/access_token' % (self._API_BASE, item_id), item_id,
  216. 'Downloading %s access token' % self._ITEM_TYPE)
  217. formats = self._extract_m3u8_formats(
  218. '%s/vod/%s?%s' % (
  219. self._USHER_BASE, item_id,
  220. compat_urllib_parse_urlencode({
  221. 'allow_source': 'true',
  222. 'allow_audio_only': 'true',
  223. 'allow_spectre': 'true',
  224. 'player': 'twitchweb',
  225. 'nauth': access_token['token'],
  226. 'nauthsig': access_token['sig'],
  227. })),
  228. item_id, 'mp4', entry_protocol='m3u8_native')
  229. self._prefer_source(formats)
  230. info['formats'] = formats
  231. parsed_url = compat_urllib_parse_urlparse(url)
  232. query = compat_parse_qs(parsed_url.query)
  233. if 't' in query:
  234. info['start_time'] = parse_duration(query['t'][0])
  235. return info
  236. class TwitchPlaylistBaseIE(TwitchBaseIE):
  237. _PLAYLIST_URL = '%s/kraken/channels/%%s/videos/?offset=%%d&limit=%%d' % TwitchBaseIE._API_BASE
  238. _PAGE_LIMIT = 100
  239. def _extract_playlist(self, channel_id):
  240. info = self._download_json(
  241. '%s/kraken/channels/%s' % (self._API_BASE, channel_id),
  242. channel_id, 'Downloading channel info JSON')
  243. channel_name = info.get('display_name') or info.get('name')
  244. entries = []
  245. offset = 0
  246. limit = self._PAGE_LIMIT
  247. broken_paging_detected = False
  248. counter_override = None
  249. for counter in itertools.count(1):
  250. response = self._download_json(
  251. self._PLAYLIST_URL % (channel_id, offset, limit),
  252. channel_id,
  253. 'Downloading %s videos JSON page %s'
  254. % (self._PLAYLIST_TYPE, counter_override or counter))
  255. page_entries = self._extract_playlist_page(response)
  256. if not page_entries:
  257. break
  258. total = int_or_none(response.get('_total'))
  259. # Since the beginning of March 2016 twitch's paging mechanism
  260. # is completely broken on the twitch side. It simply ignores
  261. # a limit and returns the whole offset number of videos.
  262. # Working around by just requesting all videos at once.
  263. # Upd: pagination bug was fixed by twitch on 15.03.2016.
  264. if not broken_paging_detected and total and len(page_entries) > limit:
  265. self.report_warning(
  266. 'Twitch pagination is broken on twitch side, requesting all videos at once',
  267. channel_id)
  268. broken_paging_detected = True
  269. offset = total
  270. counter_override = '(all at once)'
  271. continue
  272. entries.extend(page_entries)
  273. if broken_paging_detected or total and len(page_entries) >= total:
  274. break
  275. offset += limit
  276. return self.playlist_result(
  277. [self.url_result(entry) for entry in orderedSet(entries)],
  278. channel_id, channel_name)
  279. def _extract_playlist_page(self, response):
  280. videos = response.get('videos')
  281. return [video['url'] for video in videos] if videos else []
  282. def _real_extract(self, url):
  283. return self._extract_playlist(self._match_id(url))
  284. class TwitchProfileIE(TwitchPlaylistBaseIE):
  285. IE_NAME = 'twitch:profile'
  286. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  287. _PLAYLIST_TYPE = 'profile'
  288. _TEST = {
  289. 'url': 'http://www.twitch.tv/vanillatv/profile',
  290. 'info_dict': {
  291. 'id': 'vanillatv',
  292. 'title': 'VanillaTV',
  293. },
  294. 'playlist_mincount': 412,
  295. }
  296. class TwitchPastBroadcastsIE(TwitchPlaylistBaseIE):
  297. IE_NAME = 'twitch:past_broadcasts'
  298. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/past_broadcasts/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  299. _PLAYLIST_URL = TwitchPlaylistBaseIE._PLAYLIST_URL + '&broadcasts=true'
  300. _PLAYLIST_TYPE = 'past broadcasts'
  301. _TEST = {
  302. 'url': 'http://www.twitch.tv/spamfish/profile/past_broadcasts',
  303. 'info_dict': {
  304. 'id': 'spamfish',
  305. 'title': 'Spamfish',
  306. },
  307. 'playlist_mincount': 54,
  308. }
  309. class TwitchStreamIE(TwitchBaseIE):
  310. IE_NAME = 'twitch:stream'
  311. _VALID_URL = r'%s/(?P<id>[^/#?]+)/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  312. _TESTS = [{
  313. 'url': 'http://www.twitch.tv/shroomztv',
  314. 'info_dict': {
  315. 'id': '12772022048',
  316. 'display_id': 'shroomztv',
  317. 'ext': 'mp4',
  318. 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  319. 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
  320. 'is_live': True,
  321. 'timestamp': 1421928037,
  322. 'upload_date': '20150122',
  323. 'uploader': 'ShroomzTV',
  324. 'uploader_id': 'shroomztv',
  325. 'view_count': int,
  326. },
  327. 'params': {
  328. # m3u8 download
  329. 'skip_download': True,
  330. },
  331. }, {
  332. 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
  333. 'only_matching': True,
  334. }]
  335. def _real_extract(self, url):
  336. channel_id = self._match_id(url)
  337. stream = self._download_json(
  338. '%s/kraken/streams/%s' % (self._API_BASE, channel_id), channel_id,
  339. 'Downloading stream JSON').get('stream')
  340. # Fallback on profile extraction if stream is offline
  341. if not stream:
  342. return self.url_result(
  343. 'http://www.twitch.tv/%s/profile' % channel_id,
  344. 'TwitchProfile', channel_id)
  345. # Channel name may be typed if different case than the original channel name
  346. # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing
  347. # an invalid m3u8 URL. Working around by use of original channel name from stream
  348. # JSON and fallback to lowercase if it's not available.
  349. channel_id = stream.get('channel', {}).get('name') or channel_id.lower()
  350. access_token = self._download_json(
  351. '%s/api/channels/%s/access_token' % (self._API_BASE, channel_id), channel_id,
  352. 'Downloading channel access token')
  353. query = {
  354. 'allow_source': 'true',
  355. 'allow_audio_only': 'true',
  356. 'p': random.randint(1000000, 10000000),
  357. 'player': 'twitchweb',
  358. 'segment_preference': '4',
  359. 'sig': access_token['sig'].encode('utf-8'),
  360. 'token': access_token['token'].encode('utf-8'),
  361. }
  362. formats = self._extract_m3u8_formats(
  363. '%s/api/channel/hls/%s.m3u8?%s'
  364. % (self._USHER_BASE, channel_id, compat_urllib_parse_urlencode(query)),
  365. channel_id, 'mp4')
  366. self._prefer_source(formats)
  367. view_count = stream.get('viewers')
  368. timestamp = parse_iso8601(stream.get('created_at'))
  369. channel = stream['channel']
  370. title = self._live_title(channel.get('display_name') or channel.get('name'))
  371. description = channel.get('status')
  372. thumbnails = []
  373. for thumbnail_key, thumbnail_url in stream['preview'].items():
  374. m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
  375. if not m:
  376. continue
  377. thumbnails.append({
  378. 'url': thumbnail_url,
  379. 'width': int(m.group('width')),
  380. 'height': int(m.group('height')),
  381. })
  382. return {
  383. 'id': compat_str(stream['_id']),
  384. 'display_id': channel_id,
  385. 'title': title,
  386. 'description': description,
  387. 'thumbnails': thumbnails,
  388. 'uploader': channel.get('display_name'),
  389. 'uploader_id': channel.get('name'),
  390. 'timestamp': timestamp,
  391. 'view_count': view_count,
  392. 'formats': formats,
  393. 'is_live': True,
  394. }
  395. class TwitchClipsIE(InfoExtractor):
  396. IE_NAME = 'twitch:clips'
  397. _VALID_URL = r'https?://clips\.twitch\.tv/(?:[^/]+/)*(?P<id>[^/?#&]+)'
  398. _TEST = {
  399. 'url': 'https://clips.twitch.tv/ea/AggressiveCobraPoooound',
  400. 'md5': '761769e1eafce0ffebfb4089cb3847cd',
  401. 'info_dict': {
  402. 'id': 'AggressiveCobraPoooound',
  403. 'ext': 'mp4',
  404. 'title': 'EA Play 2016 Live from the Novo Theatre',
  405. 'thumbnail': 're:^https?://.*\.jpg',
  406. 'creator': 'EA',
  407. 'uploader': 'stereotype_',
  408. 'uploader_id': 'stereotype_',
  409. },
  410. }
  411. def _real_extract(self, url):
  412. video_id = self._match_id(url)
  413. webpage = self._download_webpage(url, video_id)
  414. clip = self._parse_json(
  415. self._search_regex(
  416. r'(?s)clipInfo\s*=\s*({.+?});', webpage, 'clip info'),
  417. video_id, transform_source=js_to_json)
  418. video_url = clip['clip_video_url']
  419. title = clip['channel_title']
  420. return {
  421. 'id': video_id,
  422. 'url': video_url,
  423. 'title': title,
  424. 'thumbnail': self._og_search_thumbnail(webpage),
  425. 'creator': clip.get('broadcaster_display_name') or clip.get('broadcaster_login'),
  426. 'uploader': clip.get('curator_login'),
  427. 'uploader_id': clip.get('curator_display_name'),
  428. }