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.

351 lines
12 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. 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. videos = response['videos']
  192. if not videos:
  193. break
  194. entries.extend([self.url_result(video['url']) for video in videos])
  195. offset += limit
  196. return self.playlist_result(entries, channel_id, channel_name)
  197. def _real_extract(self, url):
  198. return self._extract_playlist(self._match_id(url))
  199. class TwitchProfileIE(TwitchPlaylistBaseIE):
  200. IE_NAME = 'twitch:profile'
  201. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  202. _PLAYLIST_TYPE = 'profile'
  203. _TEST = {
  204. 'url': 'http://www.twitch.tv/vanillatv/profile',
  205. 'info_dict': {
  206. 'id': 'vanillatv',
  207. 'title': 'VanillaTV',
  208. },
  209. 'playlist_mincount': 412,
  210. }
  211. class TwitchPastBroadcastsIE(TwitchPlaylistBaseIE):
  212. IE_NAME = 'twitch:past_broadcasts'
  213. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/past_broadcasts/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  214. _PLAYLIST_URL = TwitchPlaylistBaseIE._PLAYLIST_URL + '&broadcasts=true'
  215. _PLAYLIST_TYPE = 'past broadcasts'
  216. _TEST = {
  217. 'url': 'http://www.twitch.tv/spamfish/profile/past_broadcasts',
  218. 'info_dict': {
  219. 'id': 'spamfish',
  220. 'title': 'Spamfish',
  221. },
  222. 'playlist_mincount': 54,
  223. }
  224. class TwitchStreamIE(TwitchBaseIE):
  225. IE_NAME = 'twitch:stream'
  226. _VALID_URL = r'%s/(?P<id>[^/]+)/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  227. _TEST = {
  228. 'url': 'http://www.twitch.tv/shroomztv',
  229. 'info_dict': {
  230. 'id': '12772022048',
  231. 'display_id': 'shroomztv',
  232. 'ext': 'mp4',
  233. 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  234. 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
  235. 'is_live': True,
  236. 'timestamp': 1421928037,
  237. 'upload_date': '20150122',
  238. 'uploader': 'ShroomzTV',
  239. 'uploader_id': 'shroomztv',
  240. 'view_count': int,
  241. },
  242. 'params': {
  243. # m3u8 download
  244. 'skip_download': True,
  245. },
  246. }
  247. def _real_extract(self, url):
  248. channel_id = self._match_id(url)
  249. stream = self._download_json(
  250. '%s/kraken/streams/%s' % (self._API_BASE, channel_id), channel_id,
  251. 'Downloading stream JSON').get('stream')
  252. # Fallback on profile extraction if stream is offline
  253. if not stream:
  254. return self.url_result(
  255. 'http://www.twitch.tv/%s/profile' % channel_id,
  256. 'TwitchProfile', channel_id)
  257. access_token = self._download_json(
  258. '%s/api/channels/%s/access_token' % (self._API_BASE, channel_id), channel_id,
  259. 'Downloading channel access token')
  260. query = {
  261. 'allow_source': 'true',
  262. 'p': random.randint(1000000, 10000000),
  263. 'player': 'twitchweb',
  264. 'segment_preference': '4',
  265. 'sig': access_token['sig'],
  266. 'token': access_token['token'],
  267. }
  268. formats = self._extract_m3u8_formats(
  269. '%s/api/channel/hls/%s.m3u8?%s'
  270. % (self._USHER_BASE, channel_id, compat_urllib_parse.urlencode(query).encode('utf-8')),
  271. channel_id, 'mp4')
  272. view_count = stream.get('viewers')
  273. timestamp = parse_iso8601(stream.get('created_at'))
  274. channel = stream['channel']
  275. title = self._live_title(channel.get('display_name') or channel.get('name'))
  276. description = channel.get('status')
  277. thumbnails = []
  278. for thumbnail_key, thumbnail_url in stream['preview'].items():
  279. m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
  280. if not m:
  281. continue
  282. thumbnails.append({
  283. 'url': thumbnail_url,
  284. 'width': int(m.group('width')),
  285. 'height': int(m.group('height')),
  286. })
  287. return {
  288. 'id': compat_str(stream['_id']),
  289. 'display_id': channel_id,
  290. 'title': title,
  291. 'description': description,
  292. 'thumbnails': thumbnails,
  293. 'uploader': channel.get('display_name'),
  294. 'uploader_id': channel.get('name'),
  295. 'timestamp': timestamp,
  296. 'view_count': view_count,
  297. 'formats': formats,
  298. 'is_live': True,
  299. }