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.

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