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.

398 lines
14 KiB

10 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_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. class TwitchItemBaseIE(TwitchBaseIE):
  74. def _download_info(self, item, item_id):
  75. return self._extract_info(self._download_json(
  76. '%s/kraken/videos/%s%s' % (self._API_BASE, item, item_id), item_id,
  77. 'Downloading %s info JSON' % self._ITEM_TYPE))
  78. def _extract_media(self, item_id):
  79. info = self._download_info(self._ITEM_SHORTCUT, item_id)
  80. response = self._download_json(
  81. '%s/api/videos/%s%s' % (self._API_BASE, self._ITEM_SHORTCUT, item_id), item_id,
  82. 'Downloading %s playlist JSON' % self._ITEM_TYPE)
  83. entries = []
  84. chunks = response['chunks']
  85. qualities = list(chunks.keys())
  86. for num, fragment in enumerate(zip(*chunks.values()), start=1):
  87. formats = []
  88. for fmt_num, fragment_fmt in enumerate(fragment):
  89. format_id = qualities[fmt_num]
  90. fmt = {
  91. 'url': fragment_fmt['url'],
  92. 'format_id': format_id,
  93. 'quality': 1 if format_id == 'live' else 0,
  94. }
  95. m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
  96. if m:
  97. fmt['height'] = int(m.group('height'))
  98. formats.append(fmt)
  99. self._sort_formats(formats)
  100. entry = dict(info)
  101. entry['id'] = '%s_%d' % (entry['id'], num)
  102. entry['title'] = '%s part %d' % (entry['title'], num)
  103. entry['formats'] = formats
  104. entries.append(entry)
  105. return self.playlist_result(entries, info['id'], info['title'])
  106. def _extract_info(self, info):
  107. return {
  108. 'id': info['_id'],
  109. 'title': info['title'],
  110. 'description': info['description'],
  111. 'duration': info['length'],
  112. 'thumbnail': info['preview'],
  113. 'uploader': info['channel']['display_name'],
  114. 'uploader_id': info['channel']['name'],
  115. 'timestamp': parse_iso8601(info['recorded_at']),
  116. 'view_count': info['views'],
  117. }
  118. def _real_extract(self, url):
  119. return self._extract_media(self._match_id(url))
  120. class TwitchVideoIE(TwitchItemBaseIE):
  121. IE_NAME = 'twitch:video'
  122. _VALID_URL = r'%s/[^/]+/b/(?P<id>[^/]+)' % TwitchBaseIE._VALID_URL_BASE
  123. _ITEM_TYPE = 'video'
  124. _ITEM_SHORTCUT = 'a'
  125. _TEST = {
  126. 'url': 'http://www.twitch.tv/riotgames/b/577357806',
  127. 'info_dict': {
  128. 'id': 'a577357806',
  129. 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
  130. },
  131. 'playlist_mincount': 12,
  132. }
  133. class TwitchChapterIE(TwitchItemBaseIE):
  134. IE_NAME = 'twitch:chapter'
  135. _VALID_URL = r'%s/[^/]+/c/(?P<id>[^/]+)' % TwitchBaseIE._VALID_URL_BASE
  136. _ITEM_TYPE = 'chapter'
  137. _ITEM_SHORTCUT = 'c'
  138. _TESTS = [{
  139. 'url': 'http://www.twitch.tv/acracingleague/c/5285812',
  140. 'info_dict': {
  141. 'id': 'c5285812',
  142. 'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
  143. },
  144. 'playlist_mincount': 3,
  145. }, {
  146. 'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361',
  147. 'only_matching': True,
  148. }]
  149. class TwitchVodIE(TwitchItemBaseIE):
  150. IE_NAME = 'twitch:vod'
  151. _VALID_URL = r'%s/[^/]+/v/(?P<id>[^/]+)' % TwitchBaseIE._VALID_URL_BASE
  152. _ITEM_TYPE = 'vod'
  153. _ITEM_SHORTCUT = 'v'
  154. _TEST = {
  155. 'url': 'http://www.twitch.tv/ksptv/v/3622000',
  156. 'info_dict': {
  157. 'id': 'v3622000',
  158. 'ext': 'mp4',
  159. 'title': '''KSPTV: Squadcast: "Everyone's on vacation so here's Dahud" Edition!''',
  160. 'thumbnail': 're:^https?://.*\.jpg$',
  161. 'duration': 6951,
  162. 'timestamp': 1419028564,
  163. 'upload_date': '20141219',
  164. 'uploader': 'KSPTV',
  165. 'uploader_id': 'ksptv',
  166. 'view_count': int,
  167. },
  168. 'params': {
  169. # m3u8 download
  170. 'skip_download': True,
  171. },
  172. }
  173. def _real_extract(self, url):
  174. item_id = self._match_id(url)
  175. info = self._download_info(self._ITEM_SHORTCUT, item_id)
  176. access_token = self._download_json(
  177. '%s/api/vods/%s/access_token' % (self._API_BASE, item_id), item_id,
  178. 'Downloading %s access token' % self._ITEM_TYPE)
  179. formats = self._extract_m3u8_formats(
  180. '%s/vod/%s?nauth=%s&nauthsig=%s'
  181. % (self._USHER_BASE, item_id, access_token['token'], access_token['sig']),
  182. item_id, 'mp4')
  183. info['formats'] = formats
  184. return info
  185. class TwitchPlaylistBaseIE(TwitchBaseIE):
  186. _PLAYLIST_URL = '%s/kraken/channels/%%s/videos/?offset=%%d&limit=%%d' % TwitchBaseIE._API_BASE
  187. _PAGE_LIMIT = 100
  188. def _extract_playlist(self, channel_id):
  189. info = self._download_json(
  190. '%s/kraken/channels/%s' % (self._API_BASE, channel_id),
  191. channel_id, 'Downloading channel info JSON')
  192. channel_name = info.get('display_name') or info.get('name')
  193. entries = []
  194. offset = 0
  195. limit = self._PAGE_LIMIT
  196. for counter in itertools.count(1):
  197. response = self._download_json(
  198. self._PLAYLIST_URL % (channel_id, offset, limit),
  199. channel_id, 'Downloading %s videos JSON page %d' % (self._PLAYLIST_TYPE, counter))
  200. page_entries = self._extract_playlist_page(response)
  201. if not page_entries:
  202. break
  203. entries.extend(page_entries)
  204. offset += limit
  205. return self.playlist_result(
  206. [self.url_result(entry) for entry in set(entries)],
  207. channel_id, channel_name)
  208. def _extract_playlist_page(self, response):
  209. videos = response.get('videos')
  210. return [video['url'] for video in videos] if videos else []
  211. def _real_extract(self, url):
  212. return self._extract_playlist(self._match_id(url))
  213. class TwitchProfileIE(TwitchPlaylistBaseIE):
  214. IE_NAME = 'twitch:profile'
  215. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  216. _PLAYLIST_TYPE = 'profile'
  217. _TEST = {
  218. 'url': 'http://www.twitch.tv/vanillatv/profile',
  219. 'info_dict': {
  220. 'id': 'vanillatv',
  221. 'title': 'VanillaTV',
  222. },
  223. 'playlist_mincount': 412,
  224. }
  225. class TwitchPastBroadcastsIE(TwitchPlaylistBaseIE):
  226. IE_NAME = 'twitch:past_broadcasts'
  227. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/past_broadcasts/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  228. _PLAYLIST_URL = TwitchPlaylistBaseIE._PLAYLIST_URL + '&broadcasts=true'
  229. _PLAYLIST_TYPE = 'past broadcasts'
  230. _TEST = {
  231. 'url': 'http://www.twitch.tv/spamfish/profile/past_broadcasts',
  232. 'info_dict': {
  233. 'id': 'spamfish',
  234. 'title': 'Spamfish',
  235. },
  236. 'playlist_mincount': 54,
  237. }
  238. class TwitchBookmarksIE(TwitchPlaylistBaseIE):
  239. IE_NAME = 'twitch:bookmarks'
  240. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/bookmarks/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  241. _PLAYLIST_URL = '%s/api/bookmark/?user=%%s&offset=%%d&limit=%%d' % TwitchBaseIE._API_BASE
  242. _PLAYLIST_TYPE = 'bookmarks'
  243. _TEST = {
  244. 'url': 'http://www.twitch.tv/ognos/profile/bookmarks',
  245. 'info_dict': {
  246. 'id': 'ognos',
  247. 'title': 'Ognos',
  248. },
  249. 'playlist_mincount': 3,
  250. }
  251. def _extract_playlist_page(self, response):
  252. entries = []
  253. for bookmark in response.get('bookmarks', []):
  254. video = bookmark.get('video')
  255. if not video:
  256. continue
  257. entries.append(video['url'])
  258. return entries
  259. class TwitchStreamIE(TwitchBaseIE):
  260. IE_NAME = 'twitch:stream'
  261. _VALID_URL = r'%s/(?P<id>[^/]+)/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  262. _TEST = {
  263. 'url': 'http://www.twitch.tv/shroomztv',
  264. 'info_dict': {
  265. 'id': '12772022048',
  266. 'display_id': 'shroomztv',
  267. 'ext': 'mp4',
  268. 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  269. 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
  270. 'is_live': True,
  271. 'timestamp': 1421928037,
  272. 'upload_date': '20150122',
  273. 'uploader': 'ShroomzTV',
  274. 'uploader_id': 'shroomztv',
  275. 'view_count': int,
  276. },
  277. 'params': {
  278. # m3u8 download
  279. 'skip_download': True,
  280. },
  281. }
  282. def _real_extract(self, url):
  283. channel_id = self._match_id(url)
  284. stream = self._download_json(
  285. '%s/kraken/streams/%s' % (self._API_BASE, channel_id), channel_id,
  286. 'Downloading stream JSON').get('stream')
  287. # Fallback on profile extraction if stream is offline
  288. if not stream:
  289. return self.url_result(
  290. 'http://www.twitch.tv/%s/profile' % channel_id,
  291. 'TwitchProfile', channel_id)
  292. access_token = self._download_json(
  293. '%s/api/channels/%s/access_token' % (self._API_BASE, channel_id), channel_id,
  294. 'Downloading channel access token')
  295. query = {
  296. 'allow_source': 'true',
  297. 'p': random.randint(1000000, 10000000),
  298. 'player': 'twitchweb',
  299. 'segment_preference': '4',
  300. 'sig': access_token['sig'],
  301. 'token': access_token['token'],
  302. }
  303. formats = self._extract_m3u8_formats(
  304. '%s/api/channel/hls/%s.m3u8?%s'
  305. % (self._USHER_BASE, channel_id, compat_urllib_parse.urlencode(query).encode('utf-8')),
  306. channel_id, 'mp4')
  307. # prefer the 'source' stream, the others are limited to 30 fps
  308. def _sort_source(f):
  309. if f.get('m3u8_media') is not None and f['m3u8_media'].get('NAME') == 'Source':
  310. return 1
  311. return 0
  312. formats = sorted(formats, key=_sort_source)
  313. view_count = stream.get('viewers')
  314. timestamp = parse_iso8601(stream.get('created_at'))
  315. channel = stream['channel']
  316. title = self._live_title(channel.get('display_name') or channel.get('name'))
  317. description = channel.get('status')
  318. thumbnails = []
  319. for thumbnail_key, thumbnail_url in stream['preview'].items():
  320. m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
  321. if not m:
  322. continue
  323. thumbnails.append({
  324. 'url': thumbnail_url,
  325. 'width': int(m.group('width')),
  326. 'height': int(m.group('height')),
  327. })
  328. return {
  329. 'id': compat_str(stream['_id']),
  330. 'display_id': channel_id,
  331. 'title': title,
  332. 'description': description,
  333. 'thumbnails': thumbnails,
  334. 'uploader': channel.get('display_name'),
  335. 'uploader_id': channel.get('name'),
  336. 'timestamp': timestamp,
  337. 'view_count': view_count,
  338. 'formats': formats,
  339. 'is_live': True,
  340. }