niconico.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  1. import datetime
  2. import functools
  3. import itertools
  4. import json
  5. import re
  6. import time
  7. from .common import InfoExtractor, SearchInfoExtractor
  8. from ..compat import (
  9. compat_HTTPError,
  10. )
  11. from ..utils import (
  12. ExtractorError,
  13. OnDemandPagedList,
  14. bug_reports_message,
  15. clean_html,
  16. float_or_none,
  17. int_or_none,
  18. join_nonempty,
  19. parse_duration,
  20. parse_filesize,
  21. parse_iso8601,
  22. parse_resolution,
  23. qualities,
  24. remove_start,
  25. str_or_none,
  26. traverse_obj,
  27. try_get,
  28. unescapeHTML,
  29. update_url_query,
  30. url_or_none,
  31. urlencode_postdata,
  32. urljoin,
  33. )
  34. class NiconicoIE(InfoExtractor):
  35. IE_NAME = 'niconico'
  36. IE_DESC = 'ニコニコ動画'
  37. _TESTS = [{
  38. 'url': 'http://www.nicovideo.jp/watch/sm22312215',
  39. 'md5': 'd1a75c0823e2f629128c43e1212760f9',
  40. 'info_dict': {
  41. 'id': 'sm22312215',
  42. 'ext': 'mp4',
  43. 'title': 'Big Buck Bunny',
  44. 'thumbnail': r're:https?://.*',
  45. 'uploader': 'takuya0301',
  46. 'uploader_id': '2698420',
  47. 'upload_date': '20131123',
  48. 'timestamp': int, # timestamp is unstable
  49. 'description': '(c) copyright 2008, Blender Foundation / www.bigbuckbunny.org',
  50. 'duration': 33,
  51. 'view_count': int,
  52. 'comment_count': int,
  53. },
  54. 'skip': 'Requires an account',
  55. }, {
  56. # File downloaded with and without credentials are different, so omit
  57. # the md5 field
  58. 'url': 'http://www.nicovideo.jp/watch/nm14296458',
  59. 'info_dict': {
  60. 'id': 'nm14296458',
  61. 'ext': 'swf',
  62. 'title': '【鏡音リン】Dance on media【オリジナル】take2!',
  63. 'description': 'md5:689f066d74610b3b22e0f1739add0f58',
  64. 'thumbnail': r're:https?://.*',
  65. 'uploader': 'りょうた',
  66. 'uploader_id': '18822557',
  67. 'upload_date': '20110429',
  68. 'timestamp': 1304065916,
  69. 'duration': 209,
  70. },
  71. 'skip': 'Requires an account',
  72. }, {
  73. # 'video exists but is marked as "deleted"
  74. # md5 is unstable
  75. 'url': 'http://www.nicovideo.jp/watch/sm10000',
  76. 'info_dict': {
  77. 'id': 'sm10000',
  78. 'ext': 'unknown_video',
  79. 'description': 'deleted',
  80. 'title': 'ドラえもんエターナル第3話「決戦第3新東京市」<前編>',
  81. 'thumbnail': r're:https?://.*',
  82. 'upload_date': '20071224',
  83. 'timestamp': int, # timestamp field has different value if logged in
  84. 'duration': 304,
  85. 'view_count': int,
  86. },
  87. 'skip': 'Requires an account',
  88. }, {
  89. 'url': 'http://www.nicovideo.jp/watch/so22543406',
  90. 'info_dict': {
  91. 'id': '1388129933',
  92. 'ext': 'mp4',
  93. 'title': '【第1回】RADIOアニメロミックス ラブライブ!~のぞえりRadio Garden~',
  94. 'description': 'md5:b27d224bb0ff53d3c8269e9f8b561cf1',
  95. 'thumbnail': r're:https?://.*',
  96. 'timestamp': 1388851200,
  97. 'upload_date': '20140104',
  98. 'uploader': 'アニメロチャンネル',
  99. 'uploader_id': '312',
  100. },
  101. 'skip': 'The viewing period of the video you were searching for has expired.',
  102. }, {
  103. # video not available via `getflv`; "old" HTML5 video
  104. 'url': 'http://www.nicovideo.jp/watch/sm1151009',
  105. 'md5': '8fa81c364eb619d4085354eab075598a',
  106. 'info_dict': {
  107. 'id': 'sm1151009',
  108. 'ext': 'mp4',
  109. 'title': 'マスターシステム本体内蔵のスペハリのメインテーマ(PSG版)',
  110. 'description': 'md5:6ee077e0581ff5019773e2e714cdd0b7',
  111. 'thumbnail': r're:https?://.*',
  112. 'duration': 184,
  113. 'timestamp': 1190868283,
  114. 'upload_date': '20070927',
  115. 'uploader': 'denden2',
  116. 'uploader_id': '1392194',
  117. 'view_count': int,
  118. 'comment_count': int,
  119. },
  120. 'skip': 'Requires an account',
  121. }, {
  122. # "New" HTML5 video
  123. # md5 is unstable
  124. 'url': 'http://www.nicovideo.jp/watch/sm31464864',
  125. 'info_dict': {
  126. 'id': 'sm31464864',
  127. 'ext': 'mp4',
  128. 'title': '新作TVアニメ「戦姫絶唱シンフォギアAXZ」PV 最高画質',
  129. 'description': 'md5:e52974af9a96e739196b2c1ca72b5feb',
  130. 'timestamp': 1498514060,
  131. 'upload_date': '20170626',
  132. 'uploader': 'ゲスト',
  133. 'uploader_id': '40826363',
  134. 'thumbnail': r're:https?://.*',
  135. 'duration': 198,
  136. 'view_count': int,
  137. 'comment_count': int,
  138. },
  139. 'skip': 'Requires an account',
  140. }, {
  141. # Video without owner
  142. 'url': 'http://www.nicovideo.jp/watch/sm18238488',
  143. 'md5': 'd265680a1f92bdcbbd2a507fc9e78a9e',
  144. 'info_dict': {
  145. 'id': 'sm18238488',
  146. 'ext': 'mp4',
  147. 'title': '【実写版】ミュータントタートルズ',
  148. 'description': 'md5:15df8988e47a86f9e978af2064bf6d8e',
  149. 'timestamp': 1341160408,
  150. 'upload_date': '20120701',
  151. 'uploader': None,
  152. 'uploader_id': None,
  153. 'thumbnail': r're:https?://.*',
  154. 'duration': 5271,
  155. 'view_count': int,
  156. 'comment_count': int,
  157. },
  158. 'skip': 'Requires an account',
  159. }, {
  160. 'url': 'http://sp.nicovideo.jp/watch/sm28964488?ss_pos=1&cp_in=wt_tg',
  161. 'only_matching': True,
  162. }, {
  163. 'note': 'a video that is only served as an ENCRYPTED HLS.',
  164. 'url': 'https://www.nicovideo.jp/watch/so38016254',
  165. 'only_matching': True,
  166. }]
  167. _VALID_URL = r'https?://(?:(?:www\.|secure\.|sp\.)?nicovideo\.jp/watch|nico\.ms)/(?P<id>(?:[a-z]{2})?[0-9]+)'
  168. _NETRC_MACHINE = 'niconico'
  169. _COMMENT_API_ENDPOINTS = (
  170. 'https://nvcomment.nicovideo.jp/legacy/api.json',
  171. 'https://nmsg.nicovideo.jp/api.json',)
  172. _API_HEADERS = {
  173. 'X-Frontend-ID': '6',
  174. 'X-Frontend-Version': '0',
  175. 'X-Niconico-Language': 'en-us',
  176. 'Referer': 'https://www.nicovideo.jp/',
  177. 'Origin': 'https://www.nicovideo.jp',
  178. }
  179. def _perform_login(self, username, password):
  180. login_ok = True
  181. login_form_strs = {
  182. 'mail_tel': username,
  183. 'password': password,
  184. }
  185. self._request_webpage(
  186. 'https://account.nicovideo.jp/login', None,
  187. note='Acquiring Login session')
  188. page = self._download_webpage(
  189. 'https://account.nicovideo.jp/login/redirector?show_button_twitter=1&site=niconico&show_button_facebook=1', None,
  190. note='Logging in', errnote='Unable to log in',
  191. data=urlencode_postdata(login_form_strs),
  192. headers={
  193. 'Referer': 'https://account.nicovideo.jp/login',
  194. 'Content-Type': 'application/x-www-form-urlencoded',
  195. })
  196. if 'oneTimePw' in page:
  197. post_url = self._search_regex(
  198. r'<form[^>]+action=(["\'])(?P<url>.+?)\1', page, 'post url', group='url')
  199. page = self._download_webpage(
  200. urljoin('https://account.nicovideo.jp', post_url), None,
  201. note='Performing MFA', errnote='Unable to complete MFA',
  202. data=urlencode_postdata({
  203. 'otp': self._get_tfa_info('6 digits code')
  204. }), headers={
  205. 'Content-Type': 'application/x-www-form-urlencoded',
  206. })
  207. if 'oneTimePw' in page or 'formError' in page:
  208. err_msg = self._html_search_regex(
  209. r'formError["\']+>(.*?)</div>', page, 'form_error',
  210. default='There\'s an error but the message can\'t be parsed.',
  211. flags=re.DOTALL)
  212. self.report_warning(f'Unable to log in: MFA challenge failed, "{err_msg}"')
  213. return False
  214. login_ok = 'class="notice error"' not in page
  215. if not login_ok:
  216. self.report_warning('Unable to log in: bad username or password')
  217. return login_ok
  218. def _get_heartbeat_info(self, info_dict):
  219. video_id, video_src_id, audio_src_id = info_dict['url'].split(':')[1].split('/')
  220. dmc_protocol = info_dict['expected_protocol']
  221. api_data = (
  222. info_dict.get('_api_data')
  223. or self._parse_json(
  224. self._html_search_regex(
  225. 'data-api-data="([^"]+)"',
  226. self._download_webpage('https://www.nicovideo.jp/watch/' + video_id, video_id),
  227. 'API data', default='{}'),
  228. video_id))
  229. session_api_data = try_get(api_data, lambda x: x['media']['delivery']['movie']['session'])
  230. session_api_endpoint = try_get(session_api_data, lambda x: x['urls'][0])
  231. def ping():
  232. tracking_id = traverse_obj(api_data, ('media', 'delivery', 'trackingId'))
  233. if tracking_id:
  234. tracking_url = update_url_query('https://nvapi.nicovideo.jp/v1/2ab0cbaa/watch', {'t': tracking_id})
  235. watch_request_response = self._download_json(
  236. tracking_url, video_id,
  237. note='Acquiring permission for downloading video', fatal=False,
  238. headers=self._API_HEADERS)
  239. if traverse_obj(watch_request_response, ('meta', 'status')) != 200:
  240. self.report_warning('Failed to acquire permission for playing video. Video download may fail.')
  241. yesno = lambda x: 'yes' if x else 'no'
  242. if dmc_protocol == 'http':
  243. protocol = 'http'
  244. protocol_parameters = {
  245. 'http_output_download_parameters': {
  246. 'use_ssl': yesno(session_api_data['urls'][0]['isSsl']),
  247. 'use_well_known_port': yesno(session_api_data['urls'][0]['isWellKnownPort']),
  248. }
  249. }
  250. elif dmc_protocol == 'hls':
  251. protocol = 'm3u8'
  252. segment_duration = try_get(self._configuration_arg('segment_duration'), lambda x: int(x[0])) or 6000
  253. parsed_token = self._parse_json(session_api_data['token'], video_id)
  254. encryption = traverse_obj(api_data, ('media', 'delivery', 'encryption'))
  255. protocol_parameters = {
  256. 'hls_parameters': {
  257. 'segment_duration': segment_duration,
  258. 'transfer_preset': '',
  259. 'use_ssl': yesno(session_api_data['urls'][0]['isSsl']),
  260. 'use_well_known_port': yesno(session_api_data['urls'][0]['isWellKnownPort']),
  261. }
  262. }
  263. if 'hls_encryption' in parsed_token and encryption:
  264. protocol_parameters['hls_parameters']['encryption'] = {
  265. parsed_token['hls_encryption']: {
  266. 'encrypted_key': encryption['encryptedKey'],
  267. 'key_uri': encryption['keyUri'],
  268. }
  269. }
  270. else:
  271. protocol = 'm3u8_native'
  272. else:
  273. raise ExtractorError(f'Unsupported DMC protocol: {dmc_protocol}')
  274. session_response = self._download_json(
  275. session_api_endpoint['url'], video_id,
  276. query={'_format': 'json'},
  277. headers={'Content-Type': 'application/json'},
  278. note='Downloading JSON metadata for %s' % info_dict['format_id'],
  279. data=json.dumps({
  280. 'session': {
  281. 'client_info': {
  282. 'player_id': session_api_data.get('playerId'),
  283. },
  284. 'content_auth': {
  285. 'auth_type': try_get(session_api_data, lambda x: x['authTypes'][session_api_data['protocols'][0]]),
  286. 'content_key_timeout': session_api_data.get('contentKeyTimeout'),
  287. 'service_id': 'nicovideo',
  288. 'service_user_id': session_api_data.get('serviceUserId')
  289. },
  290. 'content_id': session_api_data.get('contentId'),
  291. 'content_src_id_sets': [{
  292. 'content_src_ids': [{
  293. 'src_id_to_mux': {
  294. 'audio_src_ids': [audio_src_id],
  295. 'video_src_ids': [video_src_id],
  296. }
  297. }]
  298. }],
  299. 'content_type': 'movie',
  300. 'content_uri': '',
  301. 'keep_method': {
  302. 'heartbeat': {
  303. 'lifetime': session_api_data.get('heartbeatLifetime')
  304. }
  305. },
  306. 'priority': session_api_data['priority'],
  307. 'protocol': {
  308. 'name': 'http',
  309. 'parameters': {
  310. 'http_parameters': {
  311. 'parameters': protocol_parameters
  312. }
  313. }
  314. },
  315. 'recipe_id': session_api_data.get('recipeId'),
  316. 'session_operation_auth': {
  317. 'session_operation_auth_by_signature': {
  318. 'signature': session_api_data.get('signature'),
  319. 'token': session_api_data.get('token'),
  320. }
  321. },
  322. 'timing_constraint': 'unlimited'
  323. }
  324. }).encode())
  325. info_dict['url'] = session_response['data']['session']['content_uri']
  326. info_dict['protocol'] = protocol
  327. # get heartbeat info
  328. heartbeat_info_dict = {
  329. 'url': session_api_endpoint['url'] + '/' + session_response['data']['session']['id'] + '?_format=json&_method=PUT',
  330. 'data': json.dumps(session_response['data']),
  331. # interval, convert milliseconds to seconds, then halve to make a buffer.
  332. 'interval': float_or_none(session_api_data.get('heartbeatLifetime'), scale=3000),
  333. 'ping': ping
  334. }
  335. return info_dict, heartbeat_info_dict
  336. def _extract_format_for_quality(self, video_id, audio_quality, video_quality, dmc_protocol):
  337. if not audio_quality.get('isAvailable') or not video_quality.get('isAvailable'):
  338. return None
  339. def extract_video_quality(video_quality):
  340. return parse_filesize('%sB' % self._search_regex(
  341. r'\| ([0-9]*\.?[0-9]*[MK])', video_quality, 'vbr', default=''))
  342. format_id = '-'.join(
  343. [remove_start(s['id'], 'archive_') for s in (video_quality, audio_quality)] + [dmc_protocol])
  344. vid_qual_label = traverse_obj(video_quality, ('metadata', 'label'))
  345. vid_quality = traverse_obj(video_quality, ('metadata', 'bitrate'))
  346. return {
  347. 'url': 'niconico_dmc:%s/%s/%s' % (video_id, video_quality['id'], audio_quality['id']),
  348. 'format_id': format_id,
  349. 'format_note': join_nonempty('DMC', vid_qual_label, dmc_protocol.upper(), delim=' '),
  350. 'ext': 'mp4', # Session API are used in HTML5, which always serves mp4
  351. 'acodec': 'aac',
  352. 'vcodec': 'h264',
  353. 'abr': float_or_none(traverse_obj(audio_quality, ('metadata', 'bitrate')), 1000),
  354. 'vbr': float_or_none(vid_quality if vid_quality > 0 else extract_video_quality(vid_qual_label), 1000),
  355. 'height': traverse_obj(video_quality, ('metadata', 'resolution', 'height')),
  356. 'width': traverse_obj(video_quality, ('metadata', 'resolution', 'width')),
  357. 'quality': -2 if 'low' in video_quality['id'] else None,
  358. 'protocol': 'niconico_dmc',
  359. 'expected_protocol': dmc_protocol, # XXX: This is not a documented field
  360. 'http_headers': {
  361. 'Origin': 'https://www.nicovideo.jp',
  362. 'Referer': 'https://www.nicovideo.jp/watch/' + video_id,
  363. }
  364. }
  365. def _real_extract(self, url):
  366. video_id = self._match_id(url)
  367. try:
  368. webpage, handle = self._download_webpage_handle(
  369. 'https://www.nicovideo.jp/watch/' + video_id, video_id)
  370. if video_id.startswith('so'):
  371. video_id = self._match_id(handle.geturl())
  372. api_data = self._parse_json(self._html_search_regex(
  373. 'data-api-data="([^"]+)"', webpage,
  374. 'API data', default='{}'), video_id)
  375. except ExtractorError as e:
  376. try:
  377. api_data = self._download_json(
  378. 'https://www.nicovideo.jp/api/watch/v3/%s?_frontendId=6&_frontendVersion=0&actionTrackId=AAAAAAAAAA_%d' % (video_id, round(time.time() * 1000)), video_id,
  379. note='Downloading API JSON', errnote='Unable to fetch data')['data']
  380. except ExtractorError:
  381. if not isinstance(e.cause, compat_HTTPError):
  382. raise
  383. webpage = e.cause.read().decode('utf-8', 'replace')
  384. error_msg = self._html_search_regex(
  385. r'(?s)<section\s+class="(?:(?:ErrorMessage|WatchExceptionPage-message)\s*)+">(.+?)</section>',
  386. webpage, 'error reason', default=None)
  387. if not error_msg:
  388. raise
  389. raise ExtractorError(re.sub(r'\s+', ' ', error_msg), expected=True)
  390. formats = []
  391. def get_video_info(*items, get_first=True, **kwargs):
  392. return traverse_obj(api_data, ('video', *items), get_all=not get_first, **kwargs)
  393. quality_info = api_data['media']['delivery']['movie']
  394. session_api_data = quality_info['session']
  395. for (audio_quality, video_quality, protocol) in itertools.product(quality_info['audios'], quality_info['videos'], session_api_data['protocols']):
  396. fmt = self._extract_format_for_quality(video_id, audio_quality, video_quality, protocol)
  397. if fmt:
  398. formats.append(fmt)
  399. # Start extracting information
  400. tags = None
  401. if webpage:
  402. # use og:video:tag (not logged in)
  403. og_video_tags = re.finditer(r'<meta\s+property="og:video:tag"\s*content="(.*?)">', webpage)
  404. tags = list(filter(None, (clean_html(x.group(1)) for x in og_video_tags)))
  405. if not tags:
  406. # use keywords and split with comma (not logged in)
  407. kwds = self._html_search_meta('keywords', webpage, default=None)
  408. if kwds:
  409. tags = [x for x in kwds.split(',') if x]
  410. if not tags:
  411. # find in json (logged in)
  412. tags = traverse_obj(api_data, ('tag', 'items', ..., 'name'))
  413. thumb_prefs = qualities(['url', 'middleUrl', 'largeUrl', 'player', 'ogp'])
  414. return {
  415. 'id': video_id,
  416. '_api_data': api_data,
  417. 'title': get_video_info(('originalTitle', 'title')) or self._og_search_title(webpage, default=None),
  418. 'formats': formats,
  419. 'thumbnails': [{
  420. 'id': key,
  421. 'url': url,
  422. 'ext': 'jpg',
  423. 'preference': thumb_prefs(key),
  424. **parse_resolution(url, lenient=True),
  425. } for key, url in (get_video_info('thumbnail') or {}).items() if url],
  426. 'description': clean_html(get_video_info('description')),
  427. 'uploader': traverse_obj(api_data, ('owner', 'nickname'), ('channel', 'name'), ('community', 'name')),
  428. 'uploader_id': str_or_none(traverse_obj(api_data, ('owner', 'id'), ('channel', 'id'), ('community', 'id'))),
  429. 'timestamp': parse_iso8601(get_video_info('registeredAt')) or parse_iso8601(
  430. self._html_search_meta('video:release_date', webpage, 'date published', default=None)),
  431. 'channel': traverse_obj(api_data, ('channel', 'name'), ('community', 'name')),
  432. 'channel_id': traverse_obj(api_data, ('channel', 'id'), ('community', 'id')),
  433. 'view_count': int_or_none(get_video_info('count', 'view')),
  434. 'tags': tags,
  435. 'genre': traverse_obj(api_data, ('genre', 'label'), ('genre', 'key')),
  436. 'comment_count': get_video_info('count', 'comment', expected_type=int),
  437. 'duration': (
  438. parse_duration(self._html_search_meta('video:duration', webpage, 'video duration', default=None))
  439. or get_video_info('duration')),
  440. 'webpage_url': url_or_none(url) or f'https://www.nicovideo.jp/watch/{video_id}',
  441. 'subtitles': self.extract_subtitles(video_id, api_data, session_api_data),
  442. }
  443. def _get_subtitles(self, video_id, api_data, session_api_data):
  444. comment_user_key = traverse_obj(api_data, ('comment', 'keys', 'userKey'))
  445. user_id_str = session_api_data.get('serviceUserId')
  446. thread_ids = traverse_obj(api_data, ('comment', 'threads', lambda _, v: v['isActive']))
  447. raw_danmaku = self._extract_all_comments(video_id, thread_ids, user_id_str, comment_user_key)
  448. if not raw_danmaku:
  449. self.report_warning(f'Failed to get comments. {bug_reports_message()}')
  450. return
  451. return {
  452. 'comments': [{
  453. 'ext': 'json',
  454. 'data': json.dumps(raw_danmaku),
  455. }],
  456. }
  457. def _extract_all_comments(self, video_id, threads, user_id, user_key):
  458. auth_data = {
  459. 'user_id': user_id,
  460. 'userkey': user_key,
  461. } if user_id and user_key else {'user_id': ''}
  462. # Request Start
  463. post_data = [{'ping': {'content': 'rs:0'}}]
  464. for i, thread in enumerate(threads):
  465. thread_id = thread['id']
  466. thread_fork = thread['fork']
  467. # Post Start (2N)
  468. post_data.append({'ping': {'content': f'ps:{i * 2}'}})
  469. post_data.append({'thread': {
  470. 'fork': thread_fork,
  471. 'language': 0,
  472. 'nicoru': 3,
  473. 'scores': 1,
  474. 'thread': thread_id,
  475. 'version': '20090904',
  476. 'with_global': 1,
  477. **auth_data,
  478. }})
  479. # Post Final (2N)
  480. post_data.append({'ping': {'content': f'pf:{i * 2}'}})
  481. # Post Start (2N+1)
  482. post_data.append({'ping': {'content': f'ps:{i * 2 + 1}'}})
  483. post_data.append({'thread_leaves': {
  484. # format is '<bottom of minute range>-<top of minute range>:<comments per minute>,<total last comments'
  485. # unfortunately NND limits (deletes?) comment returns this way, so you're only able to grab the last 1000 per language
  486. 'content': '0-999999:999999,999999,nicoru:999999',
  487. 'fork': thread_fork,
  488. 'language': 0,
  489. 'nicoru': 3,
  490. 'scores': 1,
  491. 'thread': thread_id,
  492. **auth_data,
  493. }})
  494. # Post Final (2N+1)
  495. post_data.append({'ping': {'content': f'pf:{i * 2 + 1}'}})
  496. # Request Final
  497. post_data.append({'ping': {'content': 'rf:0'}})
  498. for api_url in self._COMMENT_API_ENDPOINTS:
  499. comments = self._download_json(
  500. api_url, video_id, data=json.dumps(post_data).encode(), fatal=False,
  501. headers={
  502. 'Referer': 'https://www.nicovideo.jp/watch/%s' % video_id,
  503. 'Origin': 'https://www.nicovideo.jp',
  504. 'Content-Type': 'text/plain;charset=UTF-8',
  505. },
  506. note='Downloading comments', errnote=f'Failed to access endpoint {api_url}')
  507. if comments:
  508. return comments
  509. class NiconicoPlaylistBaseIE(InfoExtractor):
  510. _PAGE_SIZE = 100
  511. _API_HEADERS = {
  512. 'X-Frontend-ID': '6',
  513. 'X-Frontend-Version': '0',
  514. 'X-Niconico-Language': 'en-us'
  515. }
  516. def _call_api(self, list_id, resource, query):
  517. raise NotImplementedError('Must be implemented in subclasses')
  518. @staticmethod
  519. def _parse_owner(item):
  520. return {
  521. 'uploader': traverse_obj(item, ('owner', 'name')),
  522. 'uploader_id': traverse_obj(item, ('owner', 'id')),
  523. }
  524. def _fetch_page(self, list_id, page):
  525. page += 1
  526. resp = self._call_api(list_id, 'page %d' % page, {
  527. 'page': page,
  528. 'pageSize': self._PAGE_SIZE,
  529. })
  530. # this is needed to support both mylist and user
  531. for video in traverse_obj(resp, ('items', ..., ('video', None))) or []:
  532. video_id = video.get('id')
  533. if not video_id:
  534. # skip {"video": {"id": "blablabla", ...}}
  535. continue
  536. count = video.get('count') or {}
  537. get_count = lambda x: int_or_none(count.get(x))
  538. yield {
  539. '_type': 'url',
  540. 'id': video_id,
  541. 'title': video.get('title'),
  542. 'url': f'https://www.nicovideo.jp/watch/{video_id}',
  543. 'description': video.get('shortDescription'),
  544. 'duration': int_or_none(video.get('duration')),
  545. 'view_count': get_count('view'),
  546. 'comment_count': get_count('comment'),
  547. 'thumbnail': traverse_obj(video, ('thumbnail', ('nHdUrl', 'largeUrl', 'listingUrl', 'url'))),
  548. 'ie_key': NiconicoIE.ie_key(),
  549. **self._parse_owner(video),
  550. }
  551. def _entries(self, list_id):
  552. return OnDemandPagedList(functools.partial(self._fetch_page, list_id), self._PAGE_SIZE)
  553. class NiconicoPlaylistIE(NiconicoPlaylistBaseIE):
  554. IE_NAME = 'niconico:playlist'
  555. _VALID_URL = r'https?://(?:(?:www\.|sp\.)?nicovideo\.jp|nico\.ms)/(?:user/\d+/)?(?:my/)?mylist/(?:#/)?(?P<id>\d+)'
  556. _TESTS = [{
  557. 'url': 'http://www.nicovideo.jp/mylist/27411728',
  558. 'info_dict': {
  559. 'id': '27411728',
  560. 'title': 'AKB48のオールナイトニッポン',
  561. 'description': 'md5:d89694c5ded4b6c693dea2db6e41aa08',
  562. 'uploader': 'のっく',
  563. 'uploader_id': '805442',
  564. },
  565. 'playlist_mincount': 291,
  566. }, {
  567. 'url': 'https://www.nicovideo.jp/user/805442/mylist/27411728',
  568. 'only_matching': True,
  569. }, {
  570. 'url': 'https://www.nicovideo.jp/my/mylist/#/68048635',
  571. 'only_matching': True,
  572. }]
  573. def _call_api(self, list_id, resource, query):
  574. return self._download_json(
  575. f'https://nvapi.nicovideo.jp/v2/mylists/{list_id}', list_id,
  576. f'Downloading {resource}', query=query,
  577. headers=self._API_HEADERS)['data']['mylist']
  578. def _real_extract(self, url):
  579. list_id = self._match_id(url)
  580. mylist = self._call_api(list_id, 'list', {
  581. 'pageSize': 1,
  582. })
  583. return self.playlist_result(
  584. self._entries(list_id), list_id,
  585. mylist.get('name'), mylist.get('description'), **self._parse_owner(mylist))
  586. class NiconicoSeriesIE(InfoExtractor):
  587. IE_NAME = 'niconico:series'
  588. _VALID_URL = r'https?://(?:(?:www\.|sp\.)?nicovideo\.jp|nico\.ms)/series/(?P<id>\d+)'
  589. _TESTS = [{
  590. 'url': 'https://www.nicovideo.jp/series/110226',
  591. 'info_dict': {
  592. 'id': '110226',
  593. 'title': 'ご立派ァ!のシリーズ',
  594. },
  595. 'playlist_mincount': 10,
  596. }, {
  597. 'url': 'https://www.nicovideo.jp/series/12312/',
  598. 'info_dict': {
  599. 'id': '12312',
  600. 'title': 'バトルスピリッツ お勧めカード紹介(調整中)',
  601. },
  602. 'playlist_mincount': 103,
  603. }, {
  604. 'url': 'https://nico.ms/series/203559',
  605. 'only_matching': True,
  606. }]
  607. def _real_extract(self, url):
  608. list_id = self._match_id(url)
  609. webpage = self._download_webpage(f'https://www.nicovideo.jp/series/{list_id}', list_id)
  610. title = self._search_regex(
  611. (r'<title>「(.+)(全',
  612. r'<div class="TwitterShareButton"\s+data-text="(.+)\s+https:'),
  613. webpage, 'title', fatal=False)
  614. if title:
  615. title = unescapeHTML(title)
  616. playlist = [
  617. self.url_result(f'https://www.nicovideo.jp/watch/{v_id}', video_id=v_id)
  618. for v_id in re.findall(r'data-href=[\'"](?:https://www\.nicovideo\.jp)?/watch/([a-z0-9]+)', webpage)]
  619. return self.playlist_result(playlist, list_id, title)
  620. class NiconicoHistoryIE(NiconicoPlaylistBaseIE):
  621. IE_NAME = 'niconico:history'
  622. IE_DESC = 'NicoNico user history. Requires cookies.'
  623. _VALID_URL = r'https?://(?:www\.|sp\.)?nicovideo\.jp/my/history'
  624. _TESTS = [{
  625. 'note': 'PC page, with /video',
  626. 'url': 'https://www.nicovideo.jp/my/history/video',
  627. 'only_matching': True,
  628. }, {
  629. 'note': 'PC page, without /video',
  630. 'url': 'https://www.nicovideo.jp/my/history',
  631. 'only_matching': True,
  632. }, {
  633. 'note': 'mobile page, with /video',
  634. 'url': 'https://sp.nicovideo.jp/my/history/video',
  635. 'only_matching': True,
  636. }, {
  637. 'note': 'mobile page, without /video',
  638. 'url': 'https://sp.nicovideo.jp/my/history',
  639. 'only_matching': True,
  640. }]
  641. def _call_api(self, list_id, resource, query):
  642. return self._download_json(
  643. 'https://nvapi.nicovideo.jp/v1/users/me/watch/history', 'history',
  644. f'Downloading {resource}', query=query,
  645. headers=self._API_HEADERS)['data']
  646. def _real_extract(self, url):
  647. list_id = 'history'
  648. try:
  649. mylist = self._call_api(list_id, 'list', {
  650. 'pageSize': 1,
  651. })
  652. except ExtractorError as e:
  653. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
  654. self.raise_login_required('You have to be logged in to get your watch history')
  655. raise
  656. return self.playlist_result(self._entries(list_id), list_id, **self._parse_owner(mylist))
  657. class NicovideoSearchBaseIE(InfoExtractor):
  658. _SEARCH_TYPE = 'search'
  659. def _entries(self, url, item_id, query=None, note='Downloading page %(page)s'):
  660. query = query or {}
  661. pages = [query['page']] if 'page' in query else itertools.count(1)
  662. for page_num in pages:
  663. query['page'] = str(page_num)
  664. webpage = self._download_webpage(url, item_id, query=query, note=note % {'page': page_num})
  665. results = re.findall(r'(?<=data-video-id=)["\']?(?P<videoid>.*?)(?=["\'])', webpage)
  666. for item in results:
  667. yield self.url_result(f'https://www.nicovideo.jp/watch/{item}', 'Niconico', item)
  668. if not results:
  669. break
  670. def _search_results(self, query):
  671. return self._entries(
  672. self._proto_relative_url(f'//www.nicovideo.jp/{self._SEARCH_TYPE}/{query}'), query)
  673. class NicovideoSearchIE(NicovideoSearchBaseIE, SearchInfoExtractor):
  674. IE_DESC = 'Nico video search'
  675. IE_NAME = 'nicovideo:search'
  676. _SEARCH_KEY = 'nicosearch'
  677. class NicovideoSearchURLIE(NicovideoSearchBaseIE):
  678. IE_NAME = f'{NicovideoSearchIE.IE_NAME}_url'
  679. IE_DESC = 'Nico video search URLs'
  680. _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/search/(?P<id>[^?#&]+)?'
  681. _TESTS = [{
  682. 'url': 'http://www.nicovideo.jp/search/sm9',
  683. 'info_dict': {
  684. 'id': 'sm9',
  685. 'title': 'sm9'
  686. },
  687. 'playlist_mincount': 40,
  688. }, {
  689. 'url': 'https://www.nicovideo.jp/search/sm9?sort=h&order=d&end=2020-12-31&start=2020-01-01',
  690. 'info_dict': {
  691. 'id': 'sm9',
  692. 'title': 'sm9'
  693. },
  694. 'playlist_count': 31,
  695. }]
  696. def _real_extract(self, url):
  697. query = self._match_id(url)
  698. return self.playlist_result(self._entries(url, query), query, query)
  699. class NicovideoSearchDateIE(NicovideoSearchBaseIE, SearchInfoExtractor):
  700. IE_DESC = 'Nico video search, newest first'
  701. IE_NAME = f'{NicovideoSearchIE.IE_NAME}:date'
  702. _SEARCH_KEY = 'nicosearchdate'
  703. _TESTS = [{
  704. 'url': 'nicosearchdateall:a',
  705. 'info_dict': {
  706. 'id': 'a',
  707. 'title': 'a'
  708. },
  709. 'playlist_mincount': 1610,
  710. }]
  711. _START_DATE = datetime.date(2007, 1, 1)
  712. _RESULTS_PER_PAGE = 32
  713. _MAX_PAGES = 50
  714. def _entries(self, url, item_id, start_date=None, end_date=None):
  715. start_date, end_date = start_date or self._START_DATE, end_date or datetime.datetime.now().date()
  716. # If the last page has a full page of videos, we need to break down the query interval further
  717. last_page_len = len(list(self._get_entries_for_date(
  718. url, item_id, start_date, end_date, self._MAX_PAGES,
  719. note=f'Checking number of videos from {start_date} to {end_date}')))
  720. if (last_page_len == self._RESULTS_PER_PAGE and start_date != end_date):
  721. midpoint = start_date + ((end_date - start_date) // 2)
  722. yield from self._entries(url, item_id, midpoint, end_date)
  723. yield from self._entries(url, item_id, start_date, midpoint)
  724. else:
  725. self.to_screen(f'{item_id}: Downloading results from {start_date} to {end_date}')
  726. yield from self._get_entries_for_date(
  727. url, item_id, start_date, end_date, note=' Downloading page %(page)s')
  728. def _get_entries_for_date(self, url, item_id, start_date, end_date=None, page_num=None, note=None):
  729. query = {
  730. 'start': str(start_date),
  731. 'end': str(end_date or start_date),
  732. 'sort': 'f',
  733. 'order': 'd',
  734. }
  735. if page_num:
  736. query['page'] = str(page_num)
  737. yield from super()._entries(url, item_id, query=query, note=note)
  738. class NicovideoTagURLIE(NicovideoSearchBaseIE):
  739. IE_NAME = 'niconico:tag'
  740. IE_DESC = 'NicoNico video tag URLs'
  741. _SEARCH_TYPE = 'tag'
  742. _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/tag/(?P<id>[^?#&]+)?'
  743. _TESTS = [{
  744. 'url': 'https://www.nicovideo.jp/tag/ドキュメンタリー淫夢',
  745. 'info_dict': {
  746. 'id': 'ドキュメンタリー淫夢',
  747. 'title': 'ドキュメンタリー淫夢'
  748. },
  749. 'playlist_mincount': 400,
  750. }]
  751. def _real_extract(self, url):
  752. query = self._match_id(url)
  753. return self.playlist_result(self._entries(url, query), query, query)
  754. class NiconicoUserIE(InfoExtractor):
  755. _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/user/(?P<id>\d+)/?(?:$|[#?])'
  756. _TEST = {
  757. 'url': 'https://www.nicovideo.jp/user/419948',
  758. 'info_dict': {
  759. 'id': '419948',
  760. },
  761. 'playlist_mincount': 101,
  762. }
  763. _API_URL = "https://nvapi.nicovideo.jp/v1/users/%s/videos?sortKey=registeredAt&sortOrder=desc&pageSize=%s&page=%s"
  764. _PAGE_SIZE = 100
  765. _API_HEADERS = {
  766. 'X-Frontend-ID': '6',
  767. 'X-Frontend-Version': '0'
  768. }
  769. def _entries(self, list_id):
  770. total_count = 1
  771. count = page_num = 0
  772. while count < total_count:
  773. json_parsed = self._download_json(
  774. self._API_URL % (list_id, self._PAGE_SIZE, page_num + 1), list_id,
  775. headers=self._API_HEADERS,
  776. note='Downloading JSON metadata%s' % (' page %d' % page_num if page_num else ''))
  777. if not page_num:
  778. total_count = int_or_none(json_parsed['data'].get('totalCount'))
  779. for entry in json_parsed["data"]["items"]:
  780. count += 1
  781. yield self.url_result('https://www.nicovideo.jp/watch/%s' % entry['id'])
  782. page_num += 1
  783. def _real_extract(self, url):
  784. list_id = self._match_id(url)
  785. return self.playlist_result(self._entries(list_id), list_id, ie=NiconicoIE.ie_key())