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.

470 lines
18 KiB

  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import json
  4. import datetime
  5. from .common import InfoExtractor
  6. from ..compat import (
  7. compat_parse_qs,
  8. compat_urlparse,
  9. )
  10. from ..utils import (
  11. determine_ext,
  12. dict_get,
  13. ExtractorError,
  14. int_or_none,
  15. float_or_none,
  16. parse_duration,
  17. parse_iso8601,
  18. remove_start,
  19. try_get,
  20. unified_timestamp,
  21. urlencode_postdata,
  22. xpath_text,
  23. )
  24. class NiconicoIE(InfoExtractor):
  25. IE_NAME = 'niconico'
  26. IE_DESC = 'ニコニコ動画'
  27. _TESTS = [{
  28. 'url': 'http://www.nicovideo.jp/watch/sm22312215',
  29. 'md5': 'd1a75c0823e2f629128c43e1212760f9',
  30. 'info_dict': {
  31. 'id': 'sm22312215',
  32. 'ext': 'mp4',
  33. 'title': 'Big Buck Bunny',
  34. 'thumbnail': r're:https?://.*',
  35. 'uploader': 'takuya0301',
  36. 'uploader_id': '2698420',
  37. 'upload_date': '20131123',
  38. 'timestamp': int, # timestamp is unstable
  39. 'description': '(c) copyright 2008, Blender Foundation / www.bigbuckbunny.org',
  40. 'duration': 33,
  41. 'view_count': int,
  42. 'comment_count': int,
  43. },
  44. 'skip': 'Requires an account',
  45. }, {
  46. # File downloaded with and without credentials are different, so omit
  47. # the md5 field
  48. 'url': 'http://www.nicovideo.jp/watch/nm14296458',
  49. 'info_dict': {
  50. 'id': 'nm14296458',
  51. 'ext': 'swf',
  52. 'title': '【鏡音リン】Dance on media【オリジナル】take2!',
  53. 'description': 'md5:689f066d74610b3b22e0f1739add0f58',
  54. 'thumbnail': r're:https?://.*',
  55. 'uploader': 'りょうた',
  56. 'uploader_id': '18822557',
  57. 'upload_date': '20110429',
  58. 'timestamp': 1304065916,
  59. 'duration': 209,
  60. },
  61. 'skip': 'Requires an account',
  62. }, {
  63. # 'video exists but is marked as "deleted"
  64. # md5 is unstable
  65. 'url': 'http://www.nicovideo.jp/watch/sm10000',
  66. 'info_dict': {
  67. 'id': 'sm10000',
  68. 'ext': 'unknown_video',
  69. 'description': 'deleted',
  70. 'title': 'ドラえもんエターナル第3話「決戦第3新東京市」<前編>',
  71. 'thumbnail': r're:https?://.*',
  72. 'upload_date': '20071224',
  73. 'timestamp': int, # timestamp field has different value if logged in
  74. 'duration': 304,
  75. 'view_count': int,
  76. },
  77. 'skip': 'Requires an account',
  78. }, {
  79. 'url': 'http://www.nicovideo.jp/watch/so22543406',
  80. 'info_dict': {
  81. 'id': '1388129933',
  82. 'ext': 'mp4',
  83. 'title': '【第1回】RADIOアニメロミックス ラブライブ!~のぞえりRadio Garden~',
  84. 'description': 'md5:b27d224bb0ff53d3c8269e9f8b561cf1',
  85. 'thumbnail': r're:https?://.*',
  86. 'timestamp': 1388851200,
  87. 'upload_date': '20140104',
  88. 'uploader': 'アニメロチャンネル',
  89. 'uploader_id': '312',
  90. },
  91. 'skip': 'The viewing period of the video you were searching for has expired.',
  92. }, {
  93. # video not available via `getflv`; "old" HTML5 video
  94. 'url': 'http://www.nicovideo.jp/watch/sm1151009',
  95. 'md5': '8fa81c364eb619d4085354eab075598a',
  96. 'info_dict': {
  97. 'id': 'sm1151009',
  98. 'ext': 'mp4',
  99. 'title': 'マスターシステム本体内蔵のスペハリのメインテーマ(PSG版)',
  100. 'description': 'md5:6ee077e0581ff5019773e2e714cdd0b7',
  101. 'thumbnail': r're:https?://.*',
  102. 'duration': 184,
  103. 'timestamp': 1190868283,
  104. 'upload_date': '20070927',
  105. 'uploader': 'denden2',
  106. 'uploader_id': '1392194',
  107. 'view_count': int,
  108. 'comment_count': int,
  109. },
  110. 'skip': 'Requires an account',
  111. }, {
  112. # "New" HTML5 video
  113. # md5 is unstable
  114. 'url': 'http://www.nicovideo.jp/watch/sm31464864',
  115. 'info_dict': {
  116. 'id': 'sm31464864',
  117. 'ext': 'mp4',
  118. 'title': '新作TVアニメ「戦姫絶唱シンフォギアAXZ」PV 最高画質',
  119. 'description': 'md5:e52974af9a96e739196b2c1ca72b5feb',
  120. 'timestamp': 1498514060,
  121. 'upload_date': '20170626',
  122. 'uploader': 'ゲスト',
  123. 'uploader_id': '40826363',
  124. 'thumbnail': r're:https?://.*',
  125. 'duration': 198,
  126. 'view_count': int,
  127. 'comment_count': int,
  128. },
  129. 'skip': 'Requires an account',
  130. }, {
  131. # Video without owner
  132. 'url': 'http://www.nicovideo.jp/watch/sm18238488',
  133. 'md5': 'd265680a1f92bdcbbd2a507fc9e78a9e',
  134. 'info_dict': {
  135. 'id': 'sm18238488',
  136. 'ext': 'mp4',
  137. 'title': '【実写版】ミュータントタートルズ',
  138. 'description': 'md5:15df8988e47a86f9e978af2064bf6d8e',
  139. 'timestamp': 1341160408,
  140. 'upload_date': '20120701',
  141. 'uploader': None,
  142. 'uploader_id': None,
  143. 'thumbnail': r're:https?://.*',
  144. 'duration': 5271,
  145. 'view_count': int,
  146. 'comment_count': int,
  147. },
  148. 'skip': 'Requires an account',
  149. }, {
  150. 'url': 'http://sp.nicovideo.jp/watch/sm28964488?ss_pos=1&cp_in=wt_tg',
  151. 'only_matching': True,
  152. }]
  153. _VALID_URL = r'https?://(?:www\.|secure\.|sp\.)?nicovideo\.jp/watch/(?P<id>(?:[a-z]{2})?[0-9]+)'
  154. _NETRC_MACHINE = 'niconico'
  155. def _real_initialize(self):
  156. self._login()
  157. def _login(self):
  158. username, password = self._get_login_info()
  159. # No authentication to be performed
  160. if not username:
  161. return True
  162. # Log in
  163. login_ok = True
  164. login_form_strs = {
  165. 'mail_tel': username,
  166. 'password': password,
  167. }
  168. urlh = self._request_webpage(
  169. 'https://account.nicovideo.jp/api/v1/login', None,
  170. note='Logging in', errnote='Unable to log in',
  171. data=urlencode_postdata(login_form_strs))
  172. if urlh is False:
  173. login_ok = False
  174. else:
  175. parts = compat_urlparse.urlparse(urlh.geturl())
  176. if compat_parse_qs(parts.query).get('message', [None])[0] == 'cant_login':
  177. login_ok = False
  178. if not login_ok:
  179. self._downloader.report_warning('unable to log in: bad username or password')
  180. return login_ok
  181. def _extract_format_for_quality(self, api_data, video_id, audio_quality, video_quality):
  182. def yesno(boolean):
  183. return 'yes' if boolean else 'no'
  184. session_api_data = api_data['video']['dmcInfo']['session_api']
  185. session_api_endpoint = session_api_data['urls'][0]
  186. format_id = '-'.join(map(lambda s: remove_start(s['id'], 'archive_'), [video_quality, audio_quality]))
  187. session_response = self._download_json(
  188. session_api_endpoint['url'], video_id,
  189. query={'_format': 'json'},
  190. headers={'Content-Type': 'application/json'},
  191. note='Downloading JSON metadata for %s' % format_id,
  192. data=json.dumps({
  193. 'session': {
  194. 'client_info': {
  195. 'player_id': session_api_data['player_id'],
  196. },
  197. 'content_auth': {
  198. 'auth_type': session_api_data['auth_types'][session_api_data['protocols'][0]],
  199. 'content_key_timeout': session_api_data['content_key_timeout'],
  200. 'service_id': 'nicovideo',
  201. 'service_user_id': session_api_data['service_user_id']
  202. },
  203. 'content_id': session_api_data['content_id'],
  204. 'content_src_id_sets': [{
  205. 'content_src_ids': [{
  206. 'src_id_to_mux': {
  207. 'audio_src_ids': [audio_quality['id']],
  208. 'video_src_ids': [video_quality['id']],
  209. }
  210. }]
  211. }],
  212. 'content_type': 'movie',
  213. 'content_uri': '',
  214. 'keep_method': {
  215. 'heartbeat': {
  216. 'lifetime': session_api_data['heartbeat_lifetime']
  217. }
  218. },
  219. 'priority': session_api_data['priority'],
  220. 'protocol': {
  221. 'name': 'http',
  222. 'parameters': {
  223. 'http_parameters': {
  224. 'parameters': {
  225. 'http_output_download_parameters': {
  226. 'use_ssl': yesno(session_api_endpoint['is_ssl']),
  227. 'use_well_known_port': yesno(session_api_endpoint['is_well_known_port']),
  228. }
  229. }
  230. }
  231. }
  232. },
  233. 'recipe_id': session_api_data['recipe_id'],
  234. 'session_operation_auth': {
  235. 'session_operation_auth_by_signature': {
  236. 'signature': session_api_data['signature'],
  237. 'token': session_api_data['token'],
  238. }
  239. },
  240. 'timing_constraint': 'unlimited'
  241. }
  242. }).encode())
  243. resolution = video_quality.get('resolution', {})
  244. return {
  245. 'url': session_response['data']['session']['content_uri'],
  246. 'format_id': format_id,
  247. 'ext': 'mp4', # Session API are used in HTML5, which always serves mp4
  248. 'abr': float_or_none(audio_quality.get('bitrate'), 1000),
  249. 'vbr': float_or_none(video_quality.get('bitrate'), 1000),
  250. 'height': resolution.get('height'),
  251. 'width': resolution.get('width'),
  252. }
  253. def _real_extract(self, url):
  254. video_id = self._match_id(url)
  255. # Get video webpage. We are not actually interested in it for normal
  256. # cases, but need the cookies in order to be able to download the
  257. # info webpage
  258. webpage, handle = self._download_webpage_handle(
  259. 'http://www.nicovideo.jp/watch/' + video_id, video_id)
  260. if video_id.startswith('so'):
  261. video_id = self._match_id(handle.geturl())
  262. api_data = self._parse_json(self._html_search_regex(
  263. 'data-api-data="([^"]+)"', webpage,
  264. 'API data', default='{}'), video_id)
  265. def _format_id_from_url(video_url):
  266. return 'economy' if video_real_url.endswith('low') else 'normal'
  267. try:
  268. video_real_url = api_data['video']['smileInfo']['url']
  269. except KeyError: # Flash videos
  270. # Get flv info
  271. flv_info_webpage = self._download_webpage(
  272. 'http://flapi.nicovideo.jp/api/getflv/' + video_id + '?as3=1',
  273. video_id, 'Downloading flv info')
  274. flv_info = compat_urlparse.parse_qs(flv_info_webpage)
  275. if 'url' not in flv_info:
  276. if 'deleted' in flv_info:
  277. raise ExtractorError('The video has been deleted.',
  278. expected=True)
  279. elif 'closed' in flv_info:
  280. raise ExtractorError('Niconico videos now require logging in',
  281. expected=True)
  282. elif 'error' in flv_info:
  283. raise ExtractorError('%s reports error: %s' % (
  284. self.IE_NAME, flv_info['error'][0]), expected=True)
  285. else:
  286. raise ExtractorError('Unable to find video URL')
  287. video_info_xml = self._download_xml(
  288. 'http://ext.nicovideo.jp/api/getthumbinfo/' + video_id,
  289. video_id, note='Downloading video info page')
  290. def get_video_info(items):
  291. if not isinstance(items, list):
  292. items = [items]
  293. for item in items:
  294. ret = xpath_text(video_info_xml, './/' + item)
  295. if ret:
  296. return ret
  297. video_real_url = flv_info['url'][0]
  298. extension = get_video_info('movie_type')
  299. if not extension:
  300. extension = determine_ext(video_real_url)
  301. formats = [{
  302. 'url': video_real_url,
  303. 'ext': extension,
  304. 'format_id': _format_id_from_url(video_real_url),
  305. }]
  306. else:
  307. formats = []
  308. dmc_info = api_data['video'].get('dmcInfo')
  309. if dmc_info: # "New" HTML5 videos
  310. quality_info = dmc_info['quality']
  311. for audio_quality in quality_info['audios']:
  312. for video_quality in quality_info['videos']:
  313. if not audio_quality['available'] or not video_quality['available']:
  314. continue
  315. formats.append(self._extract_format_for_quality(
  316. api_data, video_id, audio_quality, video_quality))
  317. self._sort_formats(formats)
  318. else: # "Old" HTML5 videos
  319. formats = [{
  320. 'url': video_real_url,
  321. 'ext': 'mp4',
  322. 'format_id': _format_id_from_url(video_real_url),
  323. }]
  324. def get_video_info(items):
  325. return dict_get(api_data['video'], items)
  326. # Start extracting information
  327. title = get_video_info('title')
  328. if not title:
  329. title = self._og_search_title(webpage, default=None)
  330. if not title:
  331. title = self._html_search_regex(
  332. r'<span[^>]+class="videoHeaderTitle"[^>]*>([^<]+)</span>',
  333. webpage, 'video title')
  334. watch_api_data_string = self._html_search_regex(
  335. r'<div[^>]+id="watchAPIDataContainer"[^>]+>([^<]+)</div>',
  336. webpage, 'watch api data', default=None)
  337. watch_api_data = self._parse_json(watch_api_data_string, video_id) if watch_api_data_string else {}
  338. video_detail = watch_api_data.get('videoDetail', {})
  339. thumbnail = (
  340. get_video_info(['thumbnail_url', 'thumbnailURL']) or
  341. self._html_search_meta('image', webpage, 'thumbnail', default=None) or
  342. video_detail.get('thumbnail'))
  343. description = get_video_info('description')
  344. timestamp = (parse_iso8601(get_video_info('first_retrieve')) or
  345. unified_timestamp(get_video_info('postedDateTime')))
  346. if not timestamp:
  347. match = self._html_search_meta('datePublished', webpage, 'date published', default=None)
  348. if match:
  349. timestamp = parse_iso8601(match.replace('+', ':00+'))
  350. if not timestamp and video_detail.get('postedAt'):
  351. timestamp = parse_iso8601(
  352. video_detail['postedAt'].replace('/', '-'),
  353. delimiter=' ', timezone=datetime.timedelta(hours=9))
  354. view_count = int_or_none(get_video_info(['view_counter', 'viewCount']))
  355. if not view_count:
  356. match = self._html_search_regex(
  357. r'>Views: <strong[^>]*>([^<]+)</strong>',
  358. webpage, 'view count', default=None)
  359. if match:
  360. view_count = int_or_none(match.replace(',', ''))
  361. view_count = view_count or video_detail.get('viewCount')
  362. comment_count = (int_or_none(get_video_info('comment_num')) or
  363. video_detail.get('commentCount') or
  364. try_get(api_data, lambda x: x['thread']['commentCount']))
  365. if not comment_count:
  366. match = self._html_search_regex(
  367. r'>Comments: <strong[^>]*>([^<]+)</strong>',
  368. webpage, 'comment count', default=None)
  369. if match:
  370. comment_count = int_or_none(match.replace(',', ''))
  371. duration = (parse_duration(
  372. get_video_info('length') or
  373. self._html_search_meta(
  374. 'video:duration', webpage, 'video duration', default=None)) or
  375. video_detail.get('length') or
  376. get_video_info('duration'))
  377. webpage_url = get_video_info('watch_url') or url
  378. # Note: cannot use api_data.get('owner', {}) because owner may be set to "null"
  379. # in the JSON, which will cause None to be returned instead of {}.
  380. owner = try_get(api_data, lambda x: x.get('owner'), dict) or {}
  381. uploader_id = get_video_info(['ch_id', 'user_id']) or owner.get('id')
  382. uploader = get_video_info(['ch_name', 'user_nickname']) or owner.get('nickname')
  383. return {
  384. 'id': video_id,
  385. 'title': title,
  386. 'formats': formats,
  387. 'thumbnail': thumbnail,
  388. 'description': description,
  389. 'uploader': uploader,
  390. 'timestamp': timestamp,
  391. 'uploader_id': uploader_id,
  392. 'view_count': view_count,
  393. 'comment_count': comment_count,
  394. 'duration': duration,
  395. 'webpage_url': webpage_url,
  396. }
  397. class NiconicoPlaylistIE(InfoExtractor):
  398. _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/mylist/(?P<id>\d+)'
  399. _TEST = {
  400. 'url': 'http://www.nicovideo.jp/mylist/27411728',
  401. 'info_dict': {
  402. 'id': '27411728',
  403. 'title': 'AKB48のオールナイトニッポン',
  404. },
  405. 'playlist_mincount': 225,
  406. }
  407. def _real_extract(self, url):
  408. list_id = self._match_id(url)
  409. webpage = self._download_webpage(url, list_id)
  410. entries_json = self._search_regex(r'Mylist\.preload\(\d+, (\[.*\])\);',
  411. webpage, 'entries')
  412. entries = json.loads(entries_json)
  413. entries = [{
  414. '_type': 'url',
  415. 'ie_key': NiconicoIE.ie_key(),
  416. 'url': ('http://www.nicovideo.jp/watch/%s' %
  417. entry['item_data']['video_id']),
  418. } for entry in entries]
  419. return {
  420. '_type': 'playlist',
  421. 'title': self._search_regex(r'\s+name: "(.*?)"', webpage, 'title'),
  422. 'id': list_id,
  423. 'entries': entries,
  424. }