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