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.

400 lines
14 KiB

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_str,
  9. compat_urllib_parse,
  10. compat_urllib_request,
  11. )
  12. from ..utils import (
  13. ExtractorError,
  14. parse_iso8601,
  15. )
  16. class TwitchBaseIE(InfoExtractor):
  17. _VALID_URL_BASE = r'https?://(?:www\.)?twitch\.tv'
  18. _API_BASE = 'https://api.twitch.tv'
  19. _USHER_BASE = 'http://usher.twitch.tv'
  20. _LOGIN_URL = 'https://secure.twitch.tv/user/login'
  21. _NETRC_MACHINE = 'twitch'
  22. def _handle_error(self, response):
  23. if not isinstance(response, dict):
  24. return
  25. error = response.get('error')
  26. if error:
  27. raise ExtractorError(
  28. '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
  29. expected=True)
  30. def _download_json(self, url, video_id, note='Downloading JSON metadata'):
  31. headers = {
  32. 'Referer': 'http://api.twitch.tv/crossdomain/receiver.html?v=2',
  33. 'X-Requested-With': 'XMLHttpRequest',
  34. }
  35. for cookie in self._downloader.cookiejar:
  36. if cookie.name == 'api_token':
  37. headers['Twitch-Api-Token'] = cookie.value
  38. request = compat_urllib_request.Request(url, headers=headers)
  39. response = super(TwitchBaseIE, self)._download_json(request, video_id, note)
  40. self._handle_error(response)
  41. return response
  42. def _real_initialize(self):
  43. self._login()
  44. def _login(self):
  45. (username, password) = self._get_login_info()
  46. if username is None:
  47. return
  48. login_page = self._download_webpage(
  49. self._LOGIN_URL, None, 'Downloading login page')
  50. authenticity_token = self._search_regex(
  51. r'<input name="authenticity_token" type="hidden" value="([^"]+)"',
  52. login_page, 'authenticity token')
  53. login_form = {
  54. 'utf8': ''.encode('utf-8'),
  55. 'authenticity_token': authenticity_token,
  56. 'redirect_on_login': '',
  57. 'embed_form': 'false',
  58. 'mp_source_action': '',
  59. 'follow': '',
  60. 'user[login]': username,
  61. 'user[password]': password,
  62. }
  63. request = compat_urllib_request.Request(
  64. self._LOGIN_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
  65. request.add_header('Referer', self._LOGIN_URL)
  66. response = self._download_webpage(
  67. request, None, 'Logging in as %s' % username)
  68. m = re.search(
  69. r"id=([\"'])login_error_message\1[^>]*>(?P<msg>[^<]+)", response)
  70. if m:
  71. raise ExtractorError(
  72. 'Unable to login: %s' % m.group('msg').strip(), expected=True)
  73. def _prefer_source(self, formats):
  74. try:
  75. source = next(f for f in formats if f['format_id'] == 'Source')
  76. source['preference'] = 10
  77. except StopIteration:
  78. pass # No Source stream present
  79. self._sort_formats(formats)
  80. class TwitchItemBaseIE(TwitchBaseIE):
  81. def _download_info(self, item, item_id):
  82. return self._extract_info(self._download_json(
  83. '%s/kraken/videos/%s%s' % (self._API_BASE, item, item_id), item_id,
  84. 'Downloading %s info JSON' % self._ITEM_TYPE))
  85. def _extract_media(self, item_id):
  86. info = self._download_info(self._ITEM_SHORTCUT, item_id)
  87. response = self._download_json(
  88. '%s/api/videos/%s%s' % (self._API_BASE, self._ITEM_SHORTCUT, item_id), item_id,
  89. 'Downloading %s playlist JSON' % self._ITEM_TYPE)
  90. entries = []
  91. chunks = response['chunks']
  92. qualities = list(chunks.keys())
  93. for num, fragment in enumerate(zip(*chunks.values()), start=1):
  94. formats = []
  95. for fmt_num, fragment_fmt in enumerate(fragment):
  96. format_id = qualities[fmt_num]
  97. fmt = {
  98. 'url': fragment_fmt['url'],
  99. 'format_id': format_id,
  100. 'quality': 1 if format_id == 'live' else 0,
  101. }
  102. m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
  103. if m:
  104. fmt['height'] = int(m.group('height'))
  105. formats.append(fmt)
  106. self._sort_formats(formats)
  107. entry = dict(info)
  108. entry['id'] = '%s_%d' % (entry['id'], num)
  109. entry['title'] = '%s part %d' % (entry['title'], num)
  110. entry['formats'] = formats
  111. entries.append(entry)
  112. return self.playlist_result(entries, info['id'], info['title'])
  113. def _extract_info(self, info):
  114. return {
  115. 'id': info['_id'],
  116. 'title': info['title'],
  117. 'description': info['description'],
  118. 'duration': info['length'],
  119. 'thumbnail': info['preview'],
  120. 'uploader': info['channel']['display_name'],
  121. 'uploader_id': info['channel']['name'],
  122. 'timestamp': parse_iso8601(info['recorded_at']),
  123. 'view_count': info['views'],
  124. }
  125. def _real_extract(self, url):
  126. return self._extract_media(self._match_id(url))
  127. class TwitchVideoIE(TwitchItemBaseIE):
  128. IE_NAME = 'twitch:video'
  129. _VALID_URL = r'%s/[^/]+/b/(?P<id>[^/]+)' % TwitchBaseIE._VALID_URL_BASE
  130. _ITEM_TYPE = 'video'
  131. _ITEM_SHORTCUT = 'a'
  132. _TEST = {
  133. 'url': 'http://www.twitch.tv/riotgames/b/577357806',
  134. 'info_dict': {
  135. 'id': 'a577357806',
  136. 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
  137. },
  138. 'playlist_mincount': 12,
  139. }
  140. class TwitchChapterIE(TwitchItemBaseIE):
  141. IE_NAME = 'twitch:chapter'
  142. _VALID_URL = r'%s/[^/]+/c/(?P<id>[^/]+)' % TwitchBaseIE._VALID_URL_BASE
  143. _ITEM_TYPE = 'chapter'
  144. _ITEM_SHORTCUT = 'c'
  145. _TESTS = [{
  146. 'url': 'http://www.twitch.tv/acracingleague/c/5285812',
  147. 'info_dict': {
  148. 'id': 'c5285812',
  149. 'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
  150. },
  151. 'playlist_mincount': 3,
  152. }, {
  153. 'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361',
  154. 'only_matching': True,
  155. }]
  156. class TwitchVodIE(TwitchItemBaseIE):
  157. IE_NAME = 'twitch:vod'
  158. _VALID_URL = r'%s/[^/]+/v/(?P<id>[^/]+)' % TwitchBaseIE._VALID_URL_BASE
  159. _ITEM_TYPE = 'vod'
  160. _ITEM_SHORTCUT = 'v'
  161. _TEST = {
  162. 'url': 'http://www.twitch.tv/ksptv/v/3622000',
  163. 'info_dict': {
  164. 'id': 'v3622000',
  165. 'ext': 'mp4',
  166. 'title': '''KSPTV: Squadcast: "Everyone's on vacation so here's Dahud" Edition!''',
  167. 'thumbnail': 're:^https?://.*\.jpg$',
  168. 'duration': 6951,
  169. 'timestamp': 1419028564,
  170. 'upload_date': '20141219',
  171. 'uploader': 'KSPTV',
  172. 'uploader_id': 'ksptv',
  173. 'view_count': int,
  174. },
  175. 'params': {
  176. # m3u8 download
  177. 'skip_download': True,
  178. },
  179. }
  180. def _real_extract(self, url):
  181. item_id = self._match_id(url)
  182. info = self._download_info(self._ITEM_SHORTCUT, item_id)
  183. access_token = self._download_json(
  184. '%s/api/vods/%s/access_token' % (self._API_BASE, item_id), item_id,
  185. 'Downloading %s access token' % self._ITEM_TYPE)
  186. formats = self._extract_m3u8_formats(
  187. '%s/vod/%s?nauth=%s&nauthsig=%s'
  188. % (self._USHER_BASE, item_id, access_token['token'], access_token['sig']),
  189. item_id, 'mp4')
  190. self._prefer_source(formats)
  191. info['formats'] = formats
  192. return info
  193. class TwitchPlaylistBaseIE(TwitchBaseIE):
  194. _PLAYLIST_URL = '%s/kraken/channels/%%s/videos/?offset=%%d&limit=%%d' % TwitchBaseIE._API_BASE
  195. _PAGE_LIMIT = 100
  196. def _extract_playlist(self, channel_id):
  197. info = self._download_json(
  198. '%s/kraken/channels/%s' % (self._API_BASE, channel_id),
  199. channel_id, 'Downloading channel info JSON')
  200. channel_name = info.get('display_name') or info.get('name')
  201. entries = []
  202. offset = 0
  203. limit = self._PAGE_LIMIT
  204. for counter in itertools.count(1):
  205. response = self._download_json(
  206. self._PLAYLIST_URL % (channel_id, offset, limit),
  207. channel_id, 'Downloading %s videos JSON page %d' % (self._PLAYLIST_TYPE, counter))
  208. page_entries = self._extract_playlist_page(response)
  209. if not page_entries:
  210. break
  211. entries.extend(page_entries)
  212. offset += limit
  213. return self.playlist_result(
  214. [self.url_result(entry) for entry in set(entries)],
  215. channel_id, channel_name)
  216. def _extract_playlist_page(self, response):
  217. videos = response.get('videos')
  218. return [video['url'] for video in videos] if videos else []
  219. def _real_extract(self, url):
  220. return self._extract_playlist(self._match_id(url))
  221. class TwitchProfileIE(TwitchPlaylistBaseIE):
  222. IE_NAME = 'twitch:profile'
  223. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  224. _PLAYLIST_TYPE = 'profile'
  225. _TEST = {
  226. 'url': 'http://www.twitch.tv/vanillatv/profile',
  227. 'info_dict': {
  228. 'id': 'vanillatv',
  229. 'title': 'VanillaTV',
  230. },
  231. 'playlist_mincount': 412,
  232. }
  233. class TwitchPastBroadcastsIE(TwitchPlaylistBaseIE):
  234. IE_NAME = 'twitch:past_broadcasts'
  235. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/past_broadcasts/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  236. _PLAYLIST_URL = TwitchPlaylistBaseIE._PLAYLIST_URL + '&broadcasts=true'
  237. _PLAYLIST_TYPE = 'past broadcasts'
  238. _TEST = {
  239. 'url': 'http://www.twitch.tv/spamfish/profile/past_broadcasts',
  240. 'info_dict': {
  241. 'id': 'spamfish',
  242. 'title': 'Spamfish',
  243. },
  244. 'playlist_mincount': 54,
  245. }
  246. class TwitchBookmarksIE(TwitchPlaylistBaseIE):
  247. IE_NAME = 'twitch:bookmarks'
  248. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/bookmarks/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  249. _PLAYLIST_URL = '%s/api/bookmark/?user=%%s&offset=%%d&limit=%%d' % TwitchBaseIE._API_BASE
  250. _PLAYLIST_TYPE = 'bookmarks'
  251. _TEST = {
  252. 'url': 'http://www.twitch.tv/ognos/profile/bookmarks',
  253. 'info_dict': {
  254. 'id': 'ognos',
  255. 'title': 'Ognos',
  256. },
  257. 'playlist_mincount': 3,
  258. }
  259. def _extract_playlist_page(self, response):
  260. entries = []
  261. for bookmark in response.get('bookmarks', []):
  262. video = bookmark.get('video')
  263. if not video:
  264. continue
  265. entries.append(video['url'])
  266. return entries
  267. class TwitchStreamIE(TwitchBaseIE):
  268. IE_NAME = 'twitch:stream'
  269. _VALID_URL = r'%s/(?P<id>[^/]+)/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  270. _TEST = {
  271. 'url': 'http://www.twitch.tv/shroomztv',
  272. 'info_dict': {
  273. 'id': '12772022048',
  274. 'display_id': 'shroomztv',
  275. 'ext': 'mp4',
  276. 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  277. 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
  278. 'is_live': True,
  279. 'timestamp': 1421928037,
  280. 'upload_date': '20150122',
  281. 'uploader': 'ShroomzTV',
  282. 'uploader_id': 'shroomztv',
  283. 'view_count': int,
  284. },
  285. 'params': {
  286. # m3u8 download
  287. 'skip_download': True,
  288. },
  289. }
  290. def _real_extract(self, url):
  291. channel_id = self._match_id(url)
  292. stream = self._download_json(
  293. '%s/kraken/streams/%s' % (self._API_BASE, channel_id), channel_id,
  294. 'Downloading stream JSON').get('stream')
  295. # Fallback on profile extraction if stream is offline
  296. if not stream:
  297. return self.url_result(
  298. 'http://www.twitch.tv/%s/profile' % channel_id,
  299. 'TwitchProfile', channel_id)
  300. access_token = self._download_json(
  301. '%s/api/channels/%s/access_token' % (self._API_BASE, channel_id), channel_id,
  302. 'Downloading channel access token')
  303. query = {
  304. 'allow_source': 'true',
  305. 'p': random.randint(1000000, 10000000),
  306. 'player': 'twitchweb',
  307. 'segment_preference': '4',
  308. 'sig': access_token['sig'].encode('utf-8'),
  309. 'token': access_token['token'].encode('utf-8'),
  310. }
  311. formats = self._extract_m3u8_formats(
  312. '%s/api/channel/hls/%s.m3u8?%s'
  313. % (self._USHER_BASE, channel_id, compat_urllib_parse.urlencode(query)),
  314. channel_id, 'mp4')
  315. self._prefer_source(formats)
  316. view_count = stream.get('viewers')
  317. timestamp = parse_iso8601(stream.get('created_at'))
  318. channel = stream['channel']
  319. title = self._live_title(channel.get('display_name') or channel.get('name'))
  320. description = channel.get('status')
  321. thumbnails = []
  322. for thumbnail_key, thumbnail_url in stream['preview'].items():
  323. m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
  324. if not m:
  325. continue
  326. thumbnails.append({
  327. 'url': thumbnail_url,
  328. 'width': int(m.group('width')),
  329. 'height': int(m.group('height')),
  330. })
  331. return {
  332. 'id': compat_str(stream['_id']),
  333. 'display_id': channel_id,
  334. 'title': title,
  335. 'description': description,
  336. 'thumbnails': thumbnails,
  337. 'uploader': channel.get('display_name'),
  338. 'uploader_id': channel.get('name'),
  339. 'timestamp': timestamp,
  340. 'view_count': view_count,
  341. 'formats': formats,
  342. 'is_live': True,
  343. }