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