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.

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