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.

522 lines
18 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_HTTPError,
  9. compat_parse_qs,
  10. compat_str,
  11. compat_urllib_parse_urlencode,
  12. compat_urllib_parse_urlparse,
  13. compat_urlparse,
  14. )
  15. from ..utils import (
  16. clean_html,
  17. ExtractorError,
  18. int_or_none,
  19. js_to_json,
  20. orderedSet,
  21. parse_duration,
  22. parse_iso8601,
  23. urlencode_postdata,
  24. )
  25. class TwitchBaseIE(InfoExtractor):
  26. _VALID_URL_BASE = r'https?://(?:www\.)?twitch\.tv'
  27. _API_BASE = 'https://api.twitch.tv'
  28. _USHER_BASE = 'https://usher.ttvnw.net'
  29. _LOGIN_URL = 'http://www.twitch.tv/login'
  30. _CLIENT_ID = 'jzkbprff40iqj646a697cyrvl0zt2m6'
  31. _NETRC_MACHINE = 'twitch'
  32. def _handle_error(self, response):
  33. if not isinstance(response, dict):
  34. return
  35. error = response.get('error')
  36. if error:
  37. raise ExtractorError(
  38. '%s returned error: %s - %s' % (self.IE_NAME, error, response.get('message')),
  39. expected=True)
  40. def _call_api(self, path, item_id, note):
  41. response = self._download_json(
  42. '%s/%s' % (self._API_BASE, path), item_id, note,
  43. headers={'Client-ID': self._CLIENT_ID})
  44. self._handle_error(response)
  45. return response
  46. def _real_initialize(self):
  47. self._login()
  48. def _login(self):
  49. (username, password) = self._get_login_info()
  50. if username is None:
  51. return
  52. def fail(message):
  53. raise ExtractorError(
  54. 'Unable to login. Twitch said: %s' % message, expected=True)
  55. login_page, handle = self._download_webpage_handle(
  56. self._LOGIN_URL, None, 'Downloading login page')
  57. # Some TOR nodes and public proxies are blocked completely
  58. if 'blacklist_message' in login_page:
  59. fail(clean_html(login_page))
  60. login_form = self._hidden_inputs(login_page)
  61. login_form.update({
  62. 'username': username,
  63. 'password': password,
  64. })
  65. redirect_url = handle.geturl()
  66. post_url = self._search_regex(
  67. r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
  68. 'post url', default=redirect_url, group='url')
  69. if not post_url.startswith('http'):
  70. post_url = compat_urlparse.urljoin(redirect_url, post_url)
  71. headers = {'Referer': redirect_url}
  72. try:
  73. response = self._download_json(
  74. post_url, None, 'Logging in as %s' % username,
  75. data=urlencode_postdata(login_form),
  76. headers=headers)
  77. except ExtractorError as e:
  78. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 400:
  79. response = self._parse_json(
  80. e.cause.read().decode('utf-8'), None)
  81. fail(response['message'])
  82. raise
  83. if response.get('redirect'):
  84. self._download_webpage(
  85. response['redirect'], None, 'Downloading login redirect page',
  86. headers=headers)
  87. def _prefer_source(self, formats):
  88. try:
  89. source = next(f for f in formats if f['format_id'] == 'Source')
  90. source['preference'] = 10
  91. except StopIteration:
  92. pass # No Source stream present
  93. self._sort_formats(formats)
  94. class TwitchItemBaseIE(TwitchBaseIE):
  95. def _download_info(self, item, item_id):
  96. return self._extract_info(self._call_api(
  97. 'kraken/videos/%s%s' % (item, item_id), item_id,
  98. 'Downloading %s info JSON' % self._ITEM_TYPE))
  99. def _extract_media(self, item_id):
  100. info = self._download_info(self._ITEM_SHORTCUT, item_id)
  101. response = self._call_api(
  102. 'api/videos/%s%s' % (self._ITEM_SHORTCUT, item_id), item_id,
  103. 'Downloading %s playlist JSON' % self._ITEM_TYPE)
  104. entries = []
  105. chunks = response['chunks']
  106. qualities = list(chunks.keys())
  107. for num, fragment in enumerate(zip(*chunks.values()), start=1):
  108. formats = []
  109. for fmt_num, fragment_fmt in enumerate(fragment):
  110. format_id = qualities[fmt_num]
  111. fmt = {
  112. 'url': fragment_fmt['url'],
  113. 'format_id': format_id,
  114. 'quality': 1 if format_id == 'live' else 0,
  115. }
  116. m = re.search(r'^(?P<height>\d+)[Pp]', format_id)
  117. if m:
  118. fmt['height'] = int(m.group('height'))
  119. formats.append(fmt)
  120. self._sort_formats(formats)
  121. entry = dict(info)
  122. entry['id'] = '%s_%d' % (entry['id'], num)
  123. entry['title'] = '%s part %d' % (entry['title'], num)
  124. entry['formats'] = formats
  125. entries.append(entry)
  126. return self.playlist_result(entries, info['id'], info['title'])
  127. def _extract_info(self, info):
  128. return {
  129. 'id': info['_id'],
  130. 'title': info.get('title') or 'Untitled Broadcast',
  131. 'description': info.get('description'),
  132. 'duration': int_or_none(info.get('length')),
  133. 'thumbnail': info.get('preview'),
  134. 'uploader': info.get('channel', {}).get('display_name'),
  135. 'uploader_id': info.get('channel', {}).get('name'),
  136. 'timestamp': parse_iso8601(info.get('recorded_at')),
  137. 'view_count': int_or_none(info.get('views')),
  138. }
  139. def _real_extract(self, url):
  140. return self._extract_media(self._match_id(url))
  141. class TwitchVideoIE(TwitchItemBaseIE):
  142. IE_NAME = 'twitch:video'
  143. _VALID_URL = r'%s/[^/]+/b/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
  144. _ITEM_TYPE = 'video'
  145. _ITEM_SHORTCUT = 'a'
  146. _TEST = {
  147. 'url': 'http://www.twitch.tv/riotgames/b/577357806',
  148. 'info_dict': {
  149. 'id': 'a577357806',
  150. 'title': 'Worlds Semifinals - Star Horn Royal Club vs. OMG',
  151. },
  152. 'playlist_mincount': 12,
  153. 'skip': 'HTTP Error 404: Not Found',
  154. }
  155. class TwitchChapterIE(TwitchItemBaseIE):
  156. IE_NAME = 'twitch:chapter'
  157. _VALID_URL = r'%s/[^/]+/c/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
  158. _ITEM_TYPE = 'chapter'
  159. _ITEM_SHORTCUT = 'c'
  160. _TESTS = [{
  161. 'url': 'http://www.twitch.tv/acracingleague/c/5285812',
  162. 'info_dict': {
  163. 'id': 'c5285812',
  164. 'title': 'ACRL Off Season - Sports Cars @ Nordschleife',
  165. },
  166. 'playlist_mincount': 3,
  167. 'skip': 'HTTP Error 404: Not Found',
  168. }, {
  169. 'url': 'http://www.twitch.tv/tsm_theoddone/c/2349361',
  170. 'only_matching': True,
  171. }]
  172. class TwitchVodIE(TwitchItemBaseIE):
  173. IE_NAME = 'twitch:vod'
  174. _VALID_URL = r'%s/[^/]+/v/(?P<id>\d+)' % TwitchBaseIE._VALID_URL_BASE
  175. _ITEM_TYPE = 'vod'
  176. _ITEM_SHORTCUT = 'v'
  177. _TESTS = [{
  178. 'url': 'http://www.twitch.tv/riotgames/v/6528877?t=5m10s',
  179. 'info_dict': {
  180. 'id': 'v6528877',
  181. 'ext': 'mp4',
  182. 'title': 'LCK Summer Split - Week 6 Day 1',
  183. 'thumbnail': 're:^https?://.*\.jpg$',
  184. 'duration': 17208,
  185. 'timestamp': 1435131709,
  186. 'upload_date': '20150624',
  187. 'uploader': 'Riot Games',
  188. 'uploader_id': 'riotgames',
  189. 'view_count': int,
  190. 'start_time': 310,
  191. },
  192. 'params': {
  193. # m3u8 download
  194. 'skip_download': True,
  195. },
  196. }, {
  197. # Untitled broadcast (title is None)
  198. 'url': 'http://www.twitch.tv/belkao_o/v/11230755',
  199. 'info_dict': {
  200. 'id': 'v11230755',
  201. 'ext': 'mp4',
  202. 'title': 'Untitled Broadcast',
  203. 'thumbnail': 're:^https?://.*\.jpg$',
  204. 'duration': 1638,
  205. 'timestamp': 1439746708,
  206. 'upload_date': '20150816',
  207. 'uploader': 'BelkAO_o',
  208. 'uploader_id': 'belkao_o',
  209. 'view_count': int,
  210. },
  211. 'params': {
  212. # m3u8 download
  213. 'skip_download': True,
  214. },
  215. }]
  216. def _real_extract(self, url):
  217. item_id = self._match_id(url)
  218. info = self._download_info(self._ITEM_SHORTCUT, item_id)
  219. access_token = self._call_api(
  220. 'api/vods/%s/access_token' % item_id, item_id,
  221. 'Downloading %s access token' % self._ITEM_TYPE)
  222. formats = self._extract_m3u8_formats(
  223. '%s/vod/%s?%s' % (
  224. self._USHER_BASE, item_id,
  225. compat_urllib_parse_urlencode({
  226. 'allow_source': 'true',
  227. 'allow_audio_only': 'true',
  228. 'allow_spectre': 'true',
  229. 'player': 'twitchweb',
  230. 'nauth': access_token['token'],
  231. 'nauthsig': access_token['sig'],
  232. })),
  233. item_id, 'mp4', entry_protocol='m3u8_native')
  234. self._prefer_source(formats)
  235. info['formats'] = formats
  236. parsed_url = compat_urllib_parse_urlparse(url)
  237. query = compat_parse_qs(parsed_url.query)
  238. if 't' in query:
  239. info['start_time'] = parse_duration(query['t'][0])
  240. return info
  241. class TwitchPlaylistBaseIE(TwitchBaseIE):
  242. _PLAYLIST_PATH = 'kraken/channels/%s/videos/?offset=%d&limit=%d'
  243. _PAGE_LIMIT = 100
  244. def _extract_playlist(self, channel_id):
  245. info = self._call_api(
  246. 'kraken/channels/%s' % channel_id,
  247. channel_id, 'Downloading channel info JSON')
  248. channel_name = info.get('display_name') or info.get('name')
  249. entries = []
  250. offset = 0
  251. limit = self._PAGE_LIMIT
  252. broken_paging_detected = False
  253. counter_override = None
  254. for counter in itertools.count(1):
  255. response = self._call_api(
  256. self._PLAYLIST_PATH % (channel_id, offset, limit),
  257. channel_id,
  258. 'Downloading %s videos JSON page %s'
  259. % (self._PLAYLIST_TYPE, counter_override or counter))
  260. page_entries = self._extract_playlist_page(response)
  261. if not page_entries:
  262. break
  263. total = int_or_none(response.get('_total'))
  264. # Since the beginning of March 2016 twitch's paging mechanism
  265. # is completely broken on the twitch side. It simply ignores
  266. # a limit and returns the whole offset number of videos.
  267. # Working around by just requesting all videos at once.
  268. # Upd: pagination bug was fixed by twitch on 15.03.2016.
  269. if not broken_paging_detected and total and len(page_entries) > limit:
  270. self.report_warning(
  271. 'Twitch pagination is broken on twitch side, requesting all videos at once',
  272. channel_id)
  273. broken_paging_detected = True
  274. offset = total
  275. counter_override = '(all at once)'
  276. continue
  277. entries.extend(page_entries)
  278. if broken_paging_detected or total and len(page_entries) >= total:
  279. break
  280. offset += limit
  281. return self.playlist_result(
  282. [self.url_result(entry) for entry in orderedSet(entries)],
  283. channel_id, channel_name)
  284. def _extract_playlist_page(self, response):
  285. videos = response.get('videos')
  286. return [video['url'] for video in videos] if videos else []
  287. def _real_extract(self, url):
  288. return self._extract_playlist(self._match_id(url))
  289. class TwitchProfileIE(TwitchPlaylistBaseIE):
  290. IE_NAME = 'twitch:profile'
  291. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  292. _PLAYLIST_TYPE = 'profile'
  293. _TEST = {
  294. 'url': 'http://www.twitch.tv/vanillatv/profile',
  295. 'info_dict': {
  296. 'id': 'vanillatv',
  297. 'title': 'VanillaTV',
  298. },
  299. 'playlist_mincount': 412,
  300. }
  301. class TwitchPastBroadcastsIE(TwitchPlaylistBaseIE):
  302. IE_NAME = 'twitch:past_broadcasts'
  303. _VALID_URL = r'%s/(?P<id>[^/]+)/profile/past_broadcasts/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  304. _PLAYLIST_PATH = TwitchPlaylistBaseIE._PLAYLIST_PATH + '&broadcasts=true'
  305. _PLAYLIST_TYPE = 'past broadcasts'
  306. _TEST = {
  307. 'url': 'http://www.twitch.tv/spamfish/profile/past_broadcasts',
  308. 'info_dict': {
  309. 'id': 'spamfish',
  310. 'title': 'Spamfish',
  311. },
  312. 'playlist_mincount': 54,
  313. }
  314. class TwitchStreamIE(TwitchBaseIE):
  315. IE_NAME = 'twitch:stream'
  316. _VALID_URL = r'%s/(?P<id>[^/#?]+)/?(?:\#.*)?$' % TwitchBaseIE._VALID_URL_BASE
  317. _TESTS = [{
  318. 'url': 'http://www.twitch.tv/shroomztv',
  319. 'info_dict': {
  320. 'id': '12772022048',
  321. 'display_id': 'shroomztv',
  322. 'ext': 'mp4',
  323. 'title': 're:^ShroomzTV [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
  324. 'description': 'H1Z1 - lonewolfing with ShroomzTV | A3 Battle Royale later - @ShroomzTV',
  325. 'is_live': True,
  326. 'timestamp': 1421928037,
  327. 'upload_date': '20150122',
  328. 'uploader': 'ShroomzTV',
  329. 'uploader_id': 'shroomztv',
  330. 'view_count': int,
  331. },
  332. 'params': {
  333. # m3u8 download
  334. 'skip_download': True,
  335. },
  336. }, {
  337. 'url': 'http://www.twitch.tv/miracle_doto#profile-0',
  338. 'only_matching': True,
  339. }]
  340. def _real_extract(self, url):
  341. channel_id = self._match_id(url)
  342. stream = self._call_api(
  343. 'kraken/streams/%s' % channel_id, channel_id,
  344. 'Downloading stream JSON').get('stream')
  345. # Fallback on profile extraction if stream is offline
  346. if not stream:
  347. return self.url_result(
  348. 'http://www.twitch.tv/%s/profile' % channel_id,
  349. 'TwitchProfile', channel_id)
  350. # Channel name may be typed if different case than the original channel name
  351. # (e.g. http://www.twitch.tv/TWITCHPLAYSPOKEMON) that will lead to constructing
  352. # an invalid m3u8 URL. Working around by use of original channel name from stream
  353. # JSON and fallback to lowercase if it's not available.
  354. channel_id = stream.get('channel', {}).get('name') or channel_id.lower()
  355. access_token = self._call_api(
  356. 'api/channels/%s/access_token' % channel_id, channel_id,
  357. 'Downloading channel access token')
  358. query = {
  359. 'allow_source': 'true',
  360. 'allow_audio_only': 'true',
  361. 'p': random.randint(1000000, 10000000),
  362. 'player': 'twitchweb',
  363. 'segment_preference': '4',
  364. 'sig': access_token['sig'].encode('utf-8'),
  365. 'token': access_token['token'].encode('utf-8'),
  366. }
  367. formats = self._extract_m3u8_formats(
  368. '%s/api/channel/hls/%s.m3u8?%s'
  369. % (self._USHER_BASE, channel_id, compat_urllib_parse_urlencode(query)),
  370. channel_id, 'mp4')
  371. self._prefer_source(formats)
  372. view_count = stream.get('viewers')
  373. timestamp = parse_iso8601(stream.get('created_at'))
  374. channel = stream['channel']
  375. title = self._live_title(channel.get('display_name') or channel.get('name'))
  376. description = channel.get('status')
  377. thumbnails = []
  378. for thumbnail_key, thumbnail_url in stream['preview'].items():
  379. m = re.search(r'(?P<width>\d+)x(?P<height>\d+)\.jpg$', thumbnail_key)
  380. if not m:
  381. continue
  382. thumbnails.append({
  383. 'url': thumbnail_url,
  384. 'width': int(m.group('width')),
  385. 'height': int(m.group('height')),
  386. })
  387. return {
  388. 'id': compat_str(stream['_id']),
  389. 'display_id': channel_id,
  390. 'title': title,
  391. 'description': description,
  392. 'thumbnails': thumbnails,
  393. 'uploader': channel.get('display_name'),
  394. 'uploader_id': channel.get('name'),
  395. 'timestamp': timestamp,
  396. 'view_count': view_count,
  397. 'formats': formats,
  398. 'is_live': True,
  399. }
  400. class TwitchClipsIE(InfoExtractor):
  401. IE_NAME = 'twitch:clips'
  402. _VALID_URL = r'https?://clips\.twitch\.tv/(?:[^/]+/)*(?P<id>[^/?#&]+)'
  403. _TESTS = [{
  404. 'url': 'https://clips.twitch.tv/ea/AggressiveCobraPoooound',
  405. 'md5': '761769e1eafce0ffebfb4089cb3847cd',
  406. 'info_dict': {
  407. 'id': 'AggressiveCobraPoooound',
  408. 'ext': 'mp4',
  409. 'title': 'EA Play 2016 Live from the Novo Theatre',
  410. 'thumbnail': 're:^https?://.*\.jpg',
  411. 'creator': 'EA',
  412. 'uploader': 'stereotype_',
  413. 'uploader_id': 'stereotype_',
  414. },
  415. }, {
  416. # multiple formats
  417. 'url': 'https://clips.twitch.tv/rflegendary/UninterestedBeeDAESuppy',
  418. 'only_matching': True,
  419. }]
  420. def _real_extract(self, url):
  421. video_id = self._match_id(url)
  422. webpage = self._download_webpage(url, video_id)
  423. clip = self._parse_json(
  424. self._search_regex(
  425. r'(?s)clipInfo\s*=\s*({.+?});', webpage, 'clip info'),
  426. video_id, transform_source=js_to_json)
  427. title = clip.get('channel_title') or self._og_search_title(webpage)
  428. formats = [{
  429. 'url': option['source'],
  430. 'format_id': option.get('quality'),
  431. 'height': int_or_none(option.get('quality')),
  432. } for option in clip.get('quality_options', []) if option.get('source')]
  433. if not formats:
  434. formats = [{
  435. 'url': clip['clip_video_url'],
  436. }]
  437. self._sort_formats(formats)
  438. return {
  439. 'id': video_id,
  440. 'title': title,
  441. 'thumbnail': self._og_search_thumbnail(webpage),
  442. 'creator': clip.get('broadcaster_display_name') or clip.get('broadcaster_login'),
  443. 'uploader': clip.get('curator_login'),
  444. 'uploader_id': clip.get('curator_display_name'),
  445. 'formats': formats,
  446. }