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.

350 lines
12 KiB

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