]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/niconico.py
[cleanup] Fix infodict returned fields (#8906)
[yt-dlp.git] / yt_dlp / extractor / niconico.py
1 import datetime
2 import functools
3 import itertools
4 import json
5 import re
6 import time
7
8 from urllib.parse import urlparse
9
10 from .common import InfoExtractor, SearchInfoExtractor
11 from ..networking import Request
12 from ..networking.exceptions import HTTPError
13 from ..utils import (
14 ExtractorError,
15 OnDemandPagedList,
16 clean_html,
17 float_or_none,
18 int_or_none,
19 join_nonempty,
20 parse_duration,
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
35
36 class NiconicoIE(InfoExtractor):
37 IE_NAME = 'niconico'
38 IE_DESC = 'ニコニコ動画'
39 _GEO_COUNTRIES = ['JP']
40 _GEO_BYPASS = False
41
42 _TESTS = [{
43 'url': 'http://www.nicovideo.jp/watch/sm22312215',
44 'md5': 'd1a75c0823e2f629128c43e1212760f9',
45 'info_dict': {
46 'id': 'sm22312215',
47 'ext': 'mp4',
48 'title': 'Big Buck Bunny',
49 'thumbnail': r're:https?://.*',
50 'uploader': 'takuya0301',
51 'uploader_id': '2698420',
52 'upload_date': '20131123',
53 'timestamp': int, # timestamp is unstable
54 'description': '(c) copyright 2008, Blender Foundation / www.bigbuckbunny.org',
55 'duration': 33,
56 'view_count': int,
57 'comment_count': int,
58 'genres': ['未設定'],
59 'tags': [],
60 'expected_protocol': str,
61 },
62 }, {
63 # File downloaded with and without credentials are different, so omit
64 # the md5 field
65 'url': 'http://www.nicovideo.jp/watch/nm14296458',
66 'info_dict': {
67 'id': 'nm14296458',
68 'ext': 'mp4',
69 'title': '【Kagamine Rin】Dance on media【Original】take2!',
70 'description': 'md5:9368f2b1f4178de64f2602c2f3d6cbf5',
71 'thumbnail': r're:https?://.*',
72 'uploader': 'りょうた',
73 'uploader_id': '18822557',
74 'upload_date': '20110429',
75 'timestamp': 1304065916,
76 'duration': 208.0,
77 'comment_count': int,
78 'view_count': int,
79 'genres': ['音楽・サウンド'],
80 'tags': ['Translation_Request', 'Kagamine_Rin', 'Rin_Original'],
81 'expected_protocol': str,
82 },
83 }, {
84 # 'video exists but is marked as "deleted"
85 # md5 is unstable
86 'url': 'http://www.nicovideo.jp/watch/sm10000',
87 'info_dict': {
88 'id': 'sm10000',
89 'ext': 'unknown_video',
90 'description': 'deleted',
91 'title': 'ドラえもんエターナル第3話「決戦第3新東京市」<前編>',
92 'thumbnail': r're:https?://.*',
93 'upload_date': '20071224',
94 'timestamp': int, # timestamp field has different value if logged in
95 'duration': 304,
96 'view_count': int,
97 },
98 'skip': 'Requires an account',
99 }, {
100 'url': 'http://www.nicovideo.jp/watch/so22543406',
101 'info_dict': {
102 'id': '1388129933',
103 'ext': 'mp4',
104 'title': '【第1回】RADIOアニメロミックス ラブライブ!~のぞえりRadio Garden~',
105 'description': 'md5:b27d224bb0ff53d3c8269e9f8b561cf1',
106 'thumbnail': r're:https?://.*',
107 'timestamp': 1388851200,
108 'upload_date': '20140104',
109 'uploader': 'アニメロチャンネル',
110 'uploader_id': '312',
111 },
112 'skip': 'The viewing period of the video you were searching for has expired.',
113 }, {
114 # video not available via `getflv`; "old" HTML5 video
115 'url': 'http://www.nicovideo.jp/watch/sm1151009',
116 'md5': 'f95a3d259172667b293530cc2e41ebda',
117 'info_dict': {
118 'id': 'sm1151009',
119 'ext': 'mp4',
120 'title': 'マスターシステム本体内蔵のスペハリのメインテーマ(PSG版)',
121 'description': 'md5:f95a3d259172667b293530cc2e41ebda',
122 'thumbnail': r're:https?://.*',
123 'duration': 184,
124 'timestamp': 1190835883,
125 'upload_date': '20070926',
126 'uploader': 'denden2',
127 'uploader_id': '1392194',
128 'view_count': int,
129 'comment_count': int,
130 'genres': ['ゲーム'],
131 'tags': [],
132 'expected_protocol': str,
133 },
134 }, {
135 # "New" HTML5 video
136 # md5 is unstable
137 'url': 'http://www.nicovideo.jp/watch/sm31464864',
138 'info_dict': {
139 'id': 'sm31464864',
140 'ext': 'mp4',
141 'title': '新作TVアニメ「戦姫絶唱シンフォギアAXZ」PV 最高画質',
142 'description': 'md5:e52974af9a96e739196b2c1ca72b5feb',
143 'timestamp': 1498481660,
144 'upload_date': '20170626',
145 'uploader': 'no-namamae',
146 'uploader_id': '40826363',
147 'thumbnail': r're:https?://.*',
148 'duration': 198,
149 'view_count': int,
150 'comment_count': int,
151 'genres': ['アニメ'],
152 'tags': [],
153 'expected_protocol': str,
154 },
155 }, {
156 # Video without owner
157 'url': 'http://www.nicovideo.jp/watch/sm18238488',
158 'md5': 'd265680a1f92bdcbbd2a507fc9e78a9e',
159 'info_dict': {
160 'id': 'sm18238488',
161 'ext': 'mp4',
162 'title': '【実写版】ミュータントタートルズ',
163 'description': 'md5:15df8988e47a86f9e978af2064bf6d8e',
164 'timestamp': 1341128008,
165 'upload_date': '20120701',
166 'thumbnail': r're:https?://.*',
167 'duration': 5271,
168 'view_count': int,
169 'comment_count': int,
170 'genres': ['エンターテイメント'],
171 'tags': [],
172 'expected_protocol': str,
173 },
174 }, {
175 'url': 'http://sp.nicovideo.jp/watch/sm28964488?ss_pos=1&cp_in=wt_tg',
176 'only_matching': True,
177 }, {
178 'note': 'a video that is only served as an ENCRYPTED HLS.',
179 'url': 'https://www.nicovideo.jp/watch/so38016254',
180 'only_matching': True,
181 }]
182
183 _VALID_URL = r'https?://(?:(?:www\.|secure\.|sp\.)?nicovideo\.jp/watch|nico\.ms)/(?P<id>(?:[a-z]{2})?[0-9]+)'
184 _NETRC_MACHINE = 'niconico'
185 _API_HEADERS = {
186 'X-Frontend-ID': '6',
187 'X-Frontend-Version': '0',
188 'X-Niconico-Language': 'en-us',
189 'Referer': 'https://www.nicovideo.jp/',
190 'Origin': 'https://www.nicovideo.jp',
191 }
192
193 def _perform_login(self, username, password):
194 login_ok = True
195 login_form_strs = {
196 'mail_tel': username,
197 'password': password,
198 }
199 self._request_webpage(
200 'https://account.nicovideo.jp/login', None,
201 note='Acquiring Login session')
202 page = self._download_webpage(
203 'https://account.nicovideo.jp/login/redirector?show_button_twitter=1&site=niconico&show_button_facebook=1', None,
204 note='Logging in', errnote='Unable to log in',
205 data=urlencode_postdata(login_form_strs),
206 headers={
207 'Referer': 'https://account.nicovideo.jp/login',
208 'Content-Type': 'application/x-www-form-urlencoded',
209 })
210 if 'oneTimePw' in page:
211 post_url = self._search_regex(
212 r'<form[^>]+action=(["\'])(?P<url>.+?)\1', page, 'post url', group='url')
213 page = self._download_webpage(
214 urljoin('https://account.nicovideo.jp', post_url), None,
215 note='Performing MFA', errnote='Unable to complete MFA',
216 data=urlencode_postdata({
217 'otp': self._get_tfa_info('6 digits code')
218 }), headers={
219 'Content-Type': 'application/x-www-form-urlencoded',
220 })
221 if 'oneTimePw' in page or 'formError' in page:
222 err_msg = self._html_search_regex(
223 r'formError["\']+>(.*?)</div>', page, 'form_error',
224 default='There\'s an error but the message can\'t be parsed.',
225 flags=re.DOTALL)
226 self.report_warning(f'Unable to log in: MFA challenge failed, "{err_msg}"')
227 return False
228 login_ok = 'class="notice error"' not in page
229 if not login_ok:
230 self.report_warning('Unable to log in: bad username or password')
231 return login_ok
232
233 def _get_heartbeat_info(self, info_dict):
234 video_id, video_src_id, audio_src_id = info_dict['url'].split(':')[1].split('/')
235 dmc_protocol = info_dict['expected_protocol']
236
237 api_data = (
238 info_dict.get('_api_data')
239 or self._parse_json(
240 self._html_search_regex(
241 'data-api-data="([^"]+)"',
242 self._download_webpage('https://www.nicovideo.jp/watch/' + video_id, video_id),
243 'API data', default='{}'),
244 video_id))
245
246 session_api_data = try_get(api_data, lambda x: x['media']['delivery']['movie']['session'])
247 session_api_endpoint = try_get(session_api_data, lambda x: x['urls'][0])
248
249 def ping():
250 tracking_id = traverse_obj(api_data, ('media', 'delivery', 'trackingId'))
251 if tracking_id:
252 tracking_url = update_url_query('https://nvapi.nicovideo.jp/v1/2ab0cbaa/watch', {'t': tracking_id})
253 watch_request_response = self._download_json(
254 tracking_url, video_id,
255 note='Acquiring permission for downloading video', fatal=False,
256 headers=self._API_HEADERS)
257 if traverse_obj(watch_request_response, ('meta', 'status')) != 200:
258 self.report_warning('Failed to acquire permission for playing video. Video download may fail.')
259
260 yesno = lambda x: 'yes' if x else 'no'
261
262 if dmc_protocol == 'http':
263 protocol = 'http'
264 protocol_parameters = {
265 'http_output_download_parameters': {
266 'use_ssl': yesno(session_api_data['urls'][0]['isSsl']),
267 'use_well_known_port': yesno(session_api_data['urls'][0]['isWellKnownPort']),
268 }
269 }
270 elif dmc_protocol == 'hls':
271 protocol = 'm3u8'
272 segment_duration = try_get(self._configuration_arg('segment_duration'), lambda x: int(x[0])) or 6000
273 parsed_token = self._parse_json(session_api_data['token'], video_id)
274 encryption = traverse_obj(api_data, ('media', 'delivery', 'encryption'))
275 protocol_parameters = {
276 'hls_parameters': {
277 'segment_duration': segment_duration,
278 'transfer_preset': '',
279 'use_ssl': yesno(session_api_data['urls'][0]['isSsl']),
280 'use_well_known_port': yesno(session_api_data['urls'][0]['isWellKnownPort']),
281 }
282 }
283 if 'hls_encryption' in parsed_token and encryption:
284 protocol_parameters['hls_parameters']['encryption'] = {
285 parsed_token['hls_encryption']: {
286 'encrypted_key': encryption['encryptedKey'],
287 'key_uri': encryption['keyUri'],
288 }
289 }
290 else:
291 protocol = 'm3u8_native'
292 else:
293 raise ExtractorError(f'Unsupported DMC protocol: {dmc_protocol}')
294
295 session_response = self._download_json(
296 session_api_endpoint['url'], video_id,
297 query={'_format': 'json'},
298 headers={'Content-Type': 'application/json'},
299 note='Downloading JSON metadata for %s' % info_dict['format_id'],
300 data=json.dumps({
301 'session': {
302 'client_info': {
303 'player_id': session_api_data.get('playerId'),
304 },
305 'content_auth': {
306 'auth_type': try_get(session_api_data, lambda x: x['authTypes'][session_api_data['protocols'][0]]),
307 'content_key_timeout': session_api_data.get('contentKeyTimeout'),
308 'service_id': 'nicovideo',
309 'service_user_id': session_api_data.get('serviceUserId')
310 },
311 'content_id': session_api_data.get('contentId'),
312 'content_src_id_sets': [{
313 'content_src_ids': [{
314 'src_id_to_mux': {
315 'audio_src_ids': [audio_src_id],
316 'video_src_ids': [video_src_id],
317 }
318 }]
319 }],
320 'content_type': 'movie',
321 'content_uri': '',
322 'keep_method': {
323 'heartbeat': {
324 'lifetime': session_api_data.get('heartbeatLifetime')
325 }
326 },
327 'priority': session_api_data['priority'],
328 'protocol': {
329 'name': 'http',
330 'parameters': {
331 'http_parameters': {
332 'parameters': protocol_parameters
333 }
334 }
335 },
336 'recipe_id': session_api_data.get('recipeId'),
337 'session_operation_auth': {
338 'session_operation_auth_by_signature': {
339 'signature': session_api_data.get('signature'),
340 'token': session_api_data.get('token'),
341 }
342 },
343 'timing_constraint': 'unlimited'
344 }
345 }).encode())
346
347 info_dict['url'] = session_response['data']['session']['content_uri']
348 info_dict['protocol'] = protocol
349
350 # get heartbeat info
351 heartbeat_info_dict = {
352 'url': session_api_endpoint['url'] + '/' + session_response['data']['session']['id'] + '?_format=json&_method=PUT',
353 'data': json.dumps(session_response['data']),
354 # interval, convert milliseconds to seconds, then halve to make a buffer.
355 'interval': float_or_none(session_api_data.get('heartbeatLifetime'), scale=3000),
356 'ping': ping
357 }
358
359 return info_dict, heartbeat_info_dict
360
361 def _extract_format_for_quality(self, video_id, audio_quality, video_quality, dmc_protocol):
362
363 if not audio_quality.get('isAvailable') or not video_quality.get('isAvailable'):
364 return None
365
366 format_id = '-'.join(
367 [remove_start(s['id'], 'archive_') for s in (video_quality, audio_quality)] + [dmc_protocol])
368
369 vid_qual_label = traverse_obj(video_quality, ('metadata', 'label'))
370
371 return {
372 'url': 'niconico_dmc:%s/%s/%s' % (video_id, video_quality['id'], audio_quality['id']),
373 'format_id': format_id,
374 'format_note': join_nonempty('DMC', vid_qual_label, dmc_protocol.upper(), delim=' '),
375 'ext': 'mp4', # Session API are used in HTML5, which always serves mp4
376 'acodec': 'aac',
377 'vcodec': 'h264',
378 **traverse_obj(audio_quality, ('metadata', {
379 'abr': ('bitrate', {functools.partial(float_or_none, scale=1000)}),
380 'asr': ('samplingRate', {int_or_none}),
381 })),
382 **traverse_obj(video_quality, ('metadata', {
383 'vbr': ('bitrate', {functools.partial(float_or_none, scale=1000)}),
384 'height': ('resolution', 'height', {int_or_none}),
385 'width': ('resolution', 'width', {int_or_none}),
386 })),
387 'quality': -2 if 'low' in video_quality['id'] else None,
388 'protocol': 'niconico_dmc',
389 'expected_protocol': dmc_protocol, # XXX: This is not a documented field
390 'http_headers': {
391 'Origin': 'https://www.nicovideo.jp',
392 'Referer': 'https://www.nicovideo.jp/watch/' + video_id,
393 }
394 }
395
396 def _yield_dmc_formats(self, api_data, video_id):
397 dmc_data = traverse_obj(api_data, ('media', 'delivery', 'movie'))
398 audios = traverse_obj(dmc_data, ('audios', ..., {dict}))
399 videos = traverse_obj(dmc_data, ('videos', ..., {dict}))
400 protocols = traverse_obj(dmc_data, ('session', 'protocols', ..., {str}))
401 if not all((audios, videos, protocols)):
402 return
403
404 for audio_quality, video_quality, protocol in itertools.product(audios, videos, protocols):
405 if fmt := self._extract_format_for_quality(video_id, audio_quality, video_quality, protocol):
406 yield fmt
407
408 def _yield_dms_formats(self, api_data, video_id):
409 fmt_filter = lambda _, v: v['isAvailable'] and v['id']
410 videos = traverse_obj(api_data, ('media', 'domand', 'videos', fmt_filter))
411 audios = traverse_obj(api_data, ('media', 'domand', 'audios', fmt_filter))
412 access_key = traverse_obj(api_data, ('media', 'domand', 'accessRightKey', {str}))
413 track_id = traverse_obj(api_data, ('client', 'watchTrackId', {str}))
414 if not all((videos, audios, access_key, track_id)):
415 return
416
417 dms_m3u8_url = self._download_json(
418 f'https://nvapi.nicovideo.jp/v1/watch/{video_id}/access-rights/hls', video_id,
419 data=json.dumps({
420 'outputs': list(itertools.product((v['id'] for v in videos), (a['id'] for a in audios)))
421 }).encode(), query={'actionTrackId': track_id}, headers={
422 'x-access-right-key': access_key,
423 'x-frontend-id': 6,
424 'x-frontend-version': 0,
425 'x-request-with': 'https://www.nicovideo.jp',
426 })['data']['contentUrl']
427 # Getting all audio formats results in duplicate video formats which we filter out later
428 dms_fmts = self._extract_m3u8_formats(dms_m3u8_url, video_id)
429
430 # m3u8 extraction does not provide audio bitrates, so extract from the API data and fix
431 for audio_fmt in traverse_obj(dms_fmts, lambda _, v: v['vcodec'] == 'none'):
432 yield {
433 **audio_fmt,
434 **traverse_obj(audios, (lambda _, v: audio_fmt['format_id'].startswith(v['id']), {
435 'format_id': ('id', {str}),
436 'abr': ('bitRate', {functools.partial(float_or_none, scale=1000)}),
437 'asr': ('samplingRate', {int_or_none}),
438 }), get_all=False),
439 'acodec': 'aac',
440 'ext': 'm4a',
441 }
442
443 # Sort before removing dupes to keep the format dicts with the lowest tbr
444 video_fmts = sorted((fmt for fmt in dms_fmts if fmt['vcodec'] != 'none'), key=lambda f: f['tbr'])
445 self._remove_duplicate_formats(video_fmts)
446 # Calculate the true vbr/tbr by subtracting the lowest abr
447 min_abr = min(traverse_obj(audios, (..., 'bitRate', {float_or_none})), default=0) / 1000
448 for video_fmt in video_fmts:
449 video_fmt['tbr'] -= min_abr
450 video_fmt['format_id'] = f'video-{video_fmt["tbr"]:.0f}'
451 yield video_fmt
452
453 def _real_extract(self, url):
454 video_id = self._match_id(url)
455
456 try:
457 webpage, handle = self._download_webpage_handle(
458 'https://www.nicovideo.jp/watch/' + video_id, video_id)
459 if video_id.startswith('so'):
460 video_id = self._match_id(handle.url)
461
462 api_data = self._parse_json(self._html_search_regex(
463 'data-api-data="([^"]+)"', webpage,
464 'API data', default='{}'), video_id)
465 except ExtractorError as e:
466 try:
467 api_data = self._download_json(
468 'https://www.nicovideo.jp/api/watch/v3/%s?_frontendId=6&_frontendVersion=0&actionTrackId=AAAAAAAAAA_%d' % (video_id, round(time.time() * 1000)), video_id,
469 note='Downloading API JSON', errnote='Unable to fetch data')['data']
470 except ExtractorError:
471 if not isinstance(e.cause, HTTPError):
472 raise
473 webpage = e.cause.response.read().decode('utf-8', 'replace')
474 error_msg = self._html_search_regex(
475 r'(?s)<section\s+class="(?:(?:ErrorMessage|WatchExceptionPage-message)\s*)+">(.+?)</section>',
476 webpage, 'error reason', default=None)
477 if not error_msg:
478 raise
479 raise ExtractorError(clean_html(error_msg), expected=True)
480
481 availability = self._availability(**(traverse_obj(api_data, ('payment', 'video', {
482 'needs_premium': ('isPremium', {bool}),
483 'needs_subscription': ('isAdmission', {bool}),
484 })) or {'needs_auth': True}))
485 formats = [*self._yield_dmc_formats(api_data, video_id),
486 *self._yield_dms_formats(api_data, video_id)]
487 if not formats:
488 fail_msg = clean_html(self._html_search_regex(
489 r'<p[^>]+\bclass="fail-message"[^>]*>(?P<msg>.+?)</p>',
490 webpage, 'fail message', default=None, group='msg'))
491 if fail_msg:
492 self.to_screen(f'Niconico said: {fail_msg}')
493 if fail_msg and 'された地域と同じ地域からのみ視聴できます。' in fail_msg:
494 availability = None
495 self.raise_geo_restricted(countries=self._GEO_COUNTRIES, metadata_available=True)
496 elif availability == 'premium_only':
497 self.raise_login_required('This video requires premium', metadata_available=True)
498 elif availability == 'subscriber_only':
499 self.raise_login_required('This video is for members only', metadata_available=True)
500 elif availability == 'needs_auth':
501 self.raise_login_required(metadata_available=False)
502
503 # Start extracting information
504 tags = None
505 if webpage:
506 # use og:video:tag (not logged in)
507 og_video_tags = re.finditer(r'<meta\s+property="og:video:tag"\s*content="(.*?)">', webpage)
508 tags = list(filter(None, (clean_html(x.group(1)) for x in og_video_tags)))
509 if not tags:
510 # use keywords and split with comma (not logged in)
511 kwds = self._html_search_meta('keywords', webpage, default=None)
512 if kwds:
513 tags = [x for x in kwds.split(',') if x]
514 if not tags:
515 # find in json (logged in)
516 tags = traverse_obj(api_data, ('tag', 'items', ..., 'name'))
517
518 thumb_prefs = qualities(['url', 'middleUrl', 'largeUrl', 'player', 'ogp'])
519
520 def get_video_info(*items, get_first=True, **kwargs):
521 return traverse_obj(api_data, ('video', *items), get_all=not get_first, **kwargs)
522
523 return {
524 'id': video_id,
525 '_api_data': api_data,
526 'title': get_video_info(('originalTitle', 'title')) or self._og_search_title(webpage, default=None),
527 'formats': formats,
528 'availability': availability,
529 'thumbnails': [{
530 'id': key,
531 'url': url,
532 'ext': 'jpg',
533 'preference': thumb_prefs(key),
534 **parse_resolution(url, lenient=True),
535 } for key, url in (get_video_info('thumbnail') or {}).items() if url],
536 'description': clean_html(get_video_info('description')),
537 'uploader': traverse_obj(api_data, ('owner', 'nickname'), ('channel', 'name'), ('community', 'name')),
538 'uploader_id': str_or_none(traverse_obj(api_data, ('owner', 'id'), ('channel', 'id'), ('community', 'id'))),
539 'timestamp': parse_iso8601(get_video_info('registeredAt')) or parse_iso8601(
540 self._html_search_meta('video:release_date', webpage, 'date published', default=None)),
541 'channel': traverse_obj(api_data, ('channel', 'name'), ('community', 'name')),
542 'channel_id': traverse_obj(api_data, ('channel', 'id'), ('community', 'id')),
543 'view_count': int_or_none(get_video_info('count', 'view')),
544 'tags': tags,
545 'genre': traverse_obj(api_data, ('genre', 'label'), ('genre', 'key')),
546 'comment_count': get_video_info('count', 'comment', expected_type=int),
547 'duration': (
548 parse_duration(self._html_search_meta('video:duration', webpage, 'video duration', default=None))
549 or get_video_info('duration')),
550 'webpage_url': url_or_none(url) or f'https://www.nicovideo.jp/watch/{video_id}',
551 'subtitles': self.extract_subtitles(video_id, api_data),
552 }
553
554 def _get_subtitles(self, video_id, api_data):
555 comments_info = traverse_obj(api_data, ('comment', 'nvComment', {dict})) or {}
556 if not comments_info.get('server'):
557 return
558
559 danmaku = traverse_obj(self._download_json(
560 f'{comments_info["server"]}/v1/threads', video_id, data=json.dumps({
561 'additionals': {},
562 'params': comments_info.get('params'),
563 'threadKey': comments_info.get('threadKey'),
564 }).encode(), fatal=False,
565 headers={
566 'Referer': 'https://www.nicovideo.jp/',
567 'Origin': 'https://www.nicovideo.jp',
568 'Content-Type': 'text/plain;charset=UTF-8',
569 'x-client-os-type': 'others',
570 'x-frontend-id': '6',
571 'x-frontend-version': '0',
572 },
573 note='Downloading comments', errnote='Failed to download comments'),
574 ('data', 'threads', ..., 'comments', ...))
575
576 return {
577 'comments': [{
578 'ext': 'json',
579 'data': json.dumps(danmaku),
580 }],
581 }
582
583
584 class NiconicoPlaylistBaseIE(InfoExtractor):
585 _PAGE_SIZE = 100
586
587 _API_HEADERS = {
588 'X-Frontend-ID': '6',
589 'X-Frontend-Version': '0',
590 'X-Niconico-Language': 'en-us'
591 }
592
593 def _call_api(self, list_id, resource, query):
594 raise NotImplementedError('Must be implemented in subclasses')
595
596 @staticmethod
597 def _parse_owner(item):
598 return {
599 'uploader': traverse_obj(item, ('owner', 'name')),
600 'uploader_id': traverse_obj(item, ('owner', 'id')),
601 }
602
603 def _fetch_page(self, list_id, page):
604 page += 1
605 resp = self._call_api(list_id, 'page %d' % page, {
606 'page': page,
607 'pageSize': self._PAGE_SIZE,
608 })
609 # this is needed to support both mylist and user
610 for video in traverse_obj(resp, ('items', ..., ('video', None))) or []:
611 video_id = video.get('id')
612 if not video_id:
613 # skip {"video": {"id": "blablabla", ...}}
614 continue
615 count = video.get('count') or {}
616 get_count = lambda x: int_or_none(count.get(x))
617 yield {
618 '_type': 'url',
619 'id': video_id,
620 'title': video.get('title'),
621 'url': f'https://www.nicovideo.jp/watch/{video_id}',
622 'description': video.get('shortDescription'),
623 'duration': int_or_none(video.get('duration')),
624 'view_count': get_count('view'),
625 'comment_count': get_count('comment'),
626 'thumbnail': traverse_obj(video, ('thumbnail', ('nHdUrl', 'largeUrl', 'listingUrl', 'url'))),
627 'ie_key': NiconicoIE.ie_key(),
628 **self._parse_owner(video),
629 }
630
631 def _entries(self, list_id):
632 return OnDemandPagedList(functools.partial(self._fetch_page, list_id), self._PAGE_SIZE)
633
634
635 class NiconicoPlaylistIE(NiconicoPlaylistBaseIE):
636 IE_NAME = 'niconico:playlist'
637 _VALID_URL = r'https?://(?:(?:www\.|sp\.)?nicovideo\.jp|nico\.ms)/(?:user/\d+/)?(?:my/)?mylist/(?:#/)?(?P<id>\d+)'
638
639 _TESTS = [{
640 'url': 'http://www.nicovideo.jp/mylist/27411728',
641 'info_dict': {
642 'id': '27411728',
643 'title': 'AKB48のオールナイトニッポン',
644 'description': 'md5:d89694c5ded4b6c693dea2db6e41aa08',
645 'uploader': 'のっく',
646 'uploader_id': '805442',
647 },
648 'playlist_mincount': 291,
649 }, {
650 'url': 'https://www.nicovideo.jp/user/805442/mylist/27411728',
651 'only_matching': True,
652 }, {
653 'url': 'https://www.nicovideo.jp/my/mylist/#/68048635',
654 'only_matching': True,
655 }]
656
657 def _call_api(self, list_id, resource, query):
658 return self._download_json(
659 f'https://nvapi.nicovideo.jp/v2/mylists/{list_id}', list_id,
660 f'Downloading {resource}', query=query,
661 headers=self._API_HEADERS)['data']['mylist']
662
663 def _real_extract(self, url):
664 list_id = self._match_id(url)
665 mylist = self._call_api(list_id, 'list', {
666 'pageSize': 1,
667 })
668 return self.playlist_result(
669 self._entries(list_id), list_id,
670 mylist.get('name'), mylist.get('description'), **self._parse_owner(mylist))
671
672
673 class NiconicoSeriesIE(InfoExtractor):
674 IE_NAME = 'niconico:series'
675 _VALID_URL = r'https?://(?:(?:www\.|sp\.)?nicovideo\.jp(?:/user/\d+)?|nico\.ms)/series/(?P<id>\d+)'
676
677 _TESTS = [{
678 'url': 'https://www.nicovideo.jp/user/44113208/series/110226',
679 'info_dict': {
680 'id': '110226',
681 'title': 'ご立派ァ!のシリーズ',
682 },
683 'playlist_mincount': 10,
684 }, {
685 'url': 'https://www.nicovideo.jp/series/12312/',
686 'info_dict': {
687 'id': '12312',
688 'title': 'バトルスピリッツ お勧めカード紹介(調整中)',
689 },
690 'playlist_mincount': 103,
691 }, {
692 'url': 'https://nico.ms/series/203559',
693 'only_matching': True,
694 }]
695
696 def _real_extract(self, url):
697 list_id = self._match_id(url)
698 webpage = self._download_webpage(url, list_id)
699
700 title = self._search_regex(
701 (r'<title>「(.+)(全',
702 r'<div class="TwitterShareButton"\s+data-text="(.+)\s+https:'),
703 webpage, 'title', fatal=False)
704 if title:
705 title = unescapeHTML(title)
706 json_data = next(self._yield_json_ld(webpage, None, fatal=False))
707 return self.playlist_from_matches(
708 traverse_obj(json_data, ('itemListElement', ..., 'url')), list_id, title, ie=NiconicoIE)
709
710
711 class NiconicoHistoryIE(NiconicoPlaylistBaseIE):
712 IE_NAME = 'niconico:history'
713 IE_DESC = 'NicoNico user history or likes. Requires cookies.'
714 _VALID_URL = r'https?://(?:www\.|sp\.)?nicovideo\.jp/my/(?P<id>history(?:/like)?)'
715
716 _TESTS = [{
717 'note': 'PC page, with /video',
718 'url': 'https://www.nicovideo.jp/my/history/video',
719 'only_matching': True,
720 }, {
721 'note': 'PC page, without /video',
722 'url': 'https://www.nicovideo.jp/my/history',
723 'only_matching': True,
724 }, {
725 'note': 'mobile page, with /video',
726 'url': 'https://sp.nicovideo.jp/my/history/video',
727 'only_matching': True,
728 }, {
729 'note': 'mobile page, without /video',
730 'url': 'https://sp.nicovideo.jp/my/history',
731 'only_matching': True,
732 }, {
733 'note': 'PC page',
734 'url': 'https://www.nicovideo.jp/my/history/like',
735 'only_matching': True,
736 }, {
737 'note': 'Mobile page',
738 'url': 'https://sp.nicovideo.jp/my/history/like',
739 'only_matching': True,
740 }]
741
742 def _call_api(self, list_id, resource, query):
743 path = 'likes' if list_id == 'history/like' else 'watch/history'
744 return self._download_json(
745 f'https://nvapi.nicovideo.jp/v1/users/me/{path}', list_id,
746 f'Downloading {resource}', query=query, headers=self._API_HEADERS)['data']
747
748 def _real_extract(self, url):
749 list_id = self._match_id(url)
750 try:
751 mylist = self._call_api(list_id, 'list', {'pageSize': 1})
752 except ExtractorError as e:
753 if isinstance(e.cause, HTTPError) and e.cause.status == 401:
754 self.raise_login_required('You have to be logged in to get your history')
755 raise
756 return self.playlist_result(self._entries(list_id), list_id, **self._parse_owner(mylist))
757
758
759 class NicovideoSearchBaseIE(InfoExtractor):
760 _SEARCH_TYPE = 'search'
761
762 def _entries(self, url, item_id, query=None, note='Downloading page %(page)s'):
763 query = query or {}
764 pages = [query['page']] if 'page' in query else itertools.count(1)
765 for page_num in pages:
766 query['page'] = str(page_num)
767 webpage = self._download_webpage(url, item_id, query=query, note=note % {'page': page_num})
768 results = re.findall(r'(?<=data-video-id=)["\']?(?P<videoid>.*?)(?=["\'])', webpage)
769 for item in results:
770 yield self.url_result(f'https://www.nicovideo.jp/watch/{item}', 'Niconico', item)
771 if not results:
772 break
773
774 def _search_results(self, query):
775 return self._entries(
776 self._proto_relative_url(f'//www.nicovideo.jp/{self._SEARCH_TYPE}/{query}'), query)
777
778
779 class NicovideoSearchIE(NicovideoSearchBaseIE, SearchInfoExtractor):
780 IE_DESC = 'Nico video search'
781 IE_NAME = 'nicovideo:search'
782 _SEARCH_KEY = 'nicosearch'
783
784
785 class NicovideoSearchURLIE(NicovideoSearchBaseIE):
786 IE_NAME = f'{NicovideoSearchIE.IE_NAME}_url'
787 IE_DESC = 'Nico video search URLs'
788 _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/search/(?P<id>[^?#&]+)?'
789 _TESTS = [{
790 'url': 'http://www.nicovideo.jp/search/sm9',
791 'info_dict': {
792 'id': 'sm9',
793 'title': 'sm9'
794 },
795 'playlist_mincount': 40,
796 }, {
797 'url': 'https://www.nicovideo.jp/search/sm9?sort=h&order=d&end=2020-12-31&start=2020-01-01',
798 'info_dict': {
799 'id': 'sm9',
800 'title': 'sm9'
801 },
802 'playlist_count': 31,
803 }]
804
805 def _real_extract(self, url):
806 query = self._match_id(url)
807 return self.playlist_result(self._entries(url, query), query, query)
808
809
810 class NicovideoSearchDateIE(NicovideoSearchBaseIE, SearchInfoExtractor):
811 IE_DESC = 'Nico video search, newest first'
812 IE_NAME = f'{NicovideoSearchIE.IE_NAME}:date'
813 _SEARCH_KEY = 'nicosearchdate'
814 _TESTS = [{
815 'url': 'nicosearchdateall:a',
816 'info_dict': {
817 'id': 'a',
818 'title': 'a'
819 },
820 'playlist_mincount': 1610,
821 }]
822
823 _START_DATE = datetime.date(2007, 1, 1)
824 _RESULTS_PER_PAGE = 32
825 _MAX_PAGES = 50
826
827 def _entries(self, url, item_id, start_date=None, end_date=None):
828 start_date, end_date = start_date or self._START_DATE, end_date or datetime.datetime.now().date()
829
830 # If the last page has a full page of videos, we need to break down the query interval further
831 last_page_len = len(list(self._get_entries_for_date(
832 url, item_id, start_date, end_date, self._MAX_PAGES,
833 note=f'Checking number of videos from {start_date} to {end_date}')))
834 if (last_page_len == self._RESULTS_PER_PAGE and start_date != end_date):
835 midpoint = start_date + ((end_date - start_date) // 2)
836 yield from self._entries(url, item_id, midpoint, end_date)
837 yield from self._entries(url, item_id, start_date, midpoint)
838 else:
839 self.to_screen(f'{item_id}: Downloading results from {start_date} to {end_date}')
840 yield from self._get_entries_for_date(
841 url, item_id, start_date, end_date, note=' Downloading page %(page)s')
842
843 def _get_entries_for_date(self, url, item_id, start_date, end_date=None, page_num=None, note=None):
844 query = {
845 'start': str(start_date),
846 'end': str(end_date or start_date),
847 'sort': 'f',
848 'order': 'd',
849 }
850 if page_num:
851 query['page'] = str(page_num)
852
853 yield from super()._entries(url, item_id, query=query, note=note)
854
855
856 class NicovideoTagURLIE(NicovideoSearchBaseIE):
857 IE_NAME = 'niconico:tag'
858 IE_DESC = 'NicoNico video tag URLs'
859 _SEARCH_TYPE = 'tag'
860 _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/tag/(?P<id>[^?#&]+)?'
861 _TESTS = [{
862 'url': 'https://www.nicovideo.jp/tag/ドキュメンタリー淫夢',
863 'info_dict': {
864 'id': 'ドキュメンタリー淫夢',
865 'title': 'ドキュメンタリー淫夢'
866 },
867 'playlist_mincount': 400,
868 }]
869
870 def _real_extract(self, url):
871 query = self._match_id(url)
872 return self.playlist_result(self._entries(url, query), query, query)
873
874
875 class NiconicoUserIE(InfoExtractor):
876 _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/user/(?P<id>\d+)/?(?:$|[#?])'
877 _TEST = {
878 'url': 'https://www.nicovideo.jp/user/419948',
879 'info_dict': {
880 'id': '419948',
881 },
882 'playlist_mincount': 101,
883 }
884 _API_URL = "https://nvapi.nicovideo.jp/v1/users/%s/videos?sortKey=registeredAt&sortOrder=desc&pageSize=%s&page=%s"
885 _PAGE_SIZE = 100
886
887 _API_HEADERS = {
888 'X-Frontend-ID': '6',
889 'X-Frontend-Version': '0'
890 }
891
892 def _entries(self, list_id):
893 total_count = 1
894 count = page_num = 0
895 while count < total_count:
896 json_parsed = self._download_json(
897 self._API_URL % (list_id, self._PAGE_SIZE, page_num + 1), list_id,
898 headers=self._API_HEADERS,
899 note='Downloading JSON metadata%s' % (' page %d' % page_num if page_num else ''))
900 if not page_num:
901 total_count = int_or_none(json_parsed['data'].get('totalCount'))
902 for entry in json_parsed["data"]["items"]:
903 count += 1
904 yield self.url_result('https://www.nicovideo.jp/watch/%s' % entry['id'])
905 page_num += 1
906
907 def _real_extract(self, url):
908 list_id = self._match_id(url)
909 return self.playlist_result(self._entries(list_id), list_id, ie=NiconicoIE.ie_key())
910
911
912 class NiconicoLiveIE(InfoExtractor):
913 IE_NAME = 'niconico:live'
914 IE_DESC = 'ニコニコ生放送'
915 _VALID_URL = r'https?://(?:sp\.)?live2?\.nicovideo\.jp/(?:watch|gate)/(?P<id>lv\d+)'
916 _TESTS = [{
917 'note': 'this test case includes invisible characters for title, pasting them as-is',
918 'url': 'https://live.nicovideo.jp/watch/lv339533123',
919 'info_dict': {
920 'id': 'lv339533123',
921 'title': '激辛ペヤング食べます‪( ;ᯅ; )‬(歌枠オーディション参加中)',
922 'view_count': 1526,
923 'comment_count': 1772,
924 'description': '初めましてもかって言います❕\nのんびり自由に適当に暮らしてます',
925 'uploader': 'もか',
926 'channel': 'ゲストさんのコミュニティ',
927 'channel_id': 'co5776900',
928 'channel_url': 'https://com.nicovideo.jp/community/co5776900',
929 'timestamp': 1670677328,
930 'is_live': True,
931 },
932 'skip': 'livestream',
933 }, {
934 'url': 'https://live2.nicovideo.jp/watch/lv339533123',
935 'only_matching': True,
936 }, {
937 'url': 'https://sp.live.nicovideo.jp/watch/lv339533123',
938 'only_matching': True,
939 }, {
940 'url': 'https://sp.live2.nicovideo.jp/watch/lv339533123',
941 'only_matching': True,
942 }]
943
944 _KNOWN_LATENCY = ('high', 'low')
945
946 def _real_extract(self, url):
947 video_id = self._match_id(url)
948 webpage, urlh = self._download_webpage_handle(f'https://live.nicovideo.jp/watch/{video_id}', video_id)
949
950 embedded_data = self._parse_json(unescapeHTML(self._search_regex(
951 r'<script\s+id="embedded-data"\s*data-props="(.+?)"', webpage, 'embedded data')), video_id)
952
953 ws_url = traverse_obj(embedded_data, ('site', 'relive', 'webSocketUrl'))
954 if not ws_url:
955 raise ExtractorError('The live hasn\'t started yet or already ended.', expected=True)
956 ws_url = update_url_query(ws_url, {
957 'frontend_id': traverse_obj(embedded_data, ('site', 'frontendId')) or '9',
958 })
959
960 hostname = remove_start(urlparse(urlh.url).hostname, 'sp.')
961 latency = try_get(self._configuration_arg('latency'), lambda x: x[0])
962 if latency not in self._KNOWN_LATENCY:
963 latency = 'high'
964
965 ws = self._request_webpage(
966 Request(ws_url, headers={'Origin': f'https://{hostname}'}),
967 video_id=video_id, note='Connecting to WebSocket server')
968
969 self.write_debug('[debug] Sending HLS server request')
970 ws.send(json.dumps({
971 'type': 'startWatching',
972 'data': {
973 'stream': {
974 'quality': 'abr',
975 'protocol': 'hls+fmp4',
976 'latency': latency,
977 'chasePlay': False
978 },
979 'room': {
980 'protocol': 'webSocket',
981 'commentable': True
982 },
983 'reconnect': False,
984 }
985 }))
986
987 while True:
988 recv = ws.recv()
989 if not recv:
990 continue
991 data = json.loads(recv)
992 if not isinstance(data, dict):
993 continue
994 if data.get('type') == 'stream':
995 m3u8_url = data['data']['uri']
996 qualities = data['data']['availableQualities']
997 break
998 elif data.get('type') == 'disconnect':
999 self.write_debug(recv)
1000 raise ExtractorError('Disconnected at middle of extraction')
1001 elif data.get('type') == 'error':
1002 self.write_debug(recv)
1003 message = traverse_obj(data, ('body', 'code')) or recv
1004 raise ExtractorError(message)
1005 elif self.get_param('verbose', False):
1006 if len(recv) > 100:
1007 recv = recv[:100] + '...'
1008 self.write_debug('Server said: %s' % recv)
1009
1010 title = traverse_obj(embedded_data, ('program', 'title')) or self._html_search_meta(
1011 ('og:title', 'twitter:title'), webpage, 'live title', fatal=False)
1012
1013 raw_thumbs = traverse_obj(embedded_data, ('program', 'thumbnail')) or {}
1014 thumbnails = []
1015 for name, value in raw_thumbs.items():
1016 if not isinstance(value, dict):
1017 thumbnails.append({
1018 'id': name,
1019 'url': value,
1020 **parse_resolution(value, lenient=True),
1021 })
1022 continue
1023
1024 for k, img_url in value.items():
1025 res = parse_resolution(k, lenient=True) or parse_resolution(img_url, lenient=True)
1026 width, height = res.get('width'), res.get('height')
1027
1028 thumbnails.append({
1029 'id': f'{name}_{width}x{height}',
1030 'url': img_url,
1031 **res,
1032 })
1033
1034 formats = self._extract_m3u8_formats(m3u8_url, video_id, ext='mp4', live=True)
1035 for fmt, q in zip(formats, reversed(qualities[1:])):
1036 fmt.update({
1037 'format_id': q,
1038 'protocol': 'niconico_live',
1039 'ws': ws,
1040 'video_id': video_id,
1041 'live_latency': latency,
1042 'origin': hostname,
1043 })
1044
1045 return {
1046 'id': video_id,
1047 'title': title,
1048 **traverse_obj(embedded_data, {
1049 'view_count': ('program', 'statistics', 'watchCount'),
1050 'comment_count': ('program', 'statistics', 'commentCount'),
1051 'uploader': ('program', 'supplier', 'name'),
1052 'channel': ('socialGroup', 'name'),
1053 'channel_id': ('socialGroup', 'id'),
1054 'channel_url': ('socialGroup', 'socialGroupPageUrl'),
1055 }),
1056 'description': clean_html(traverse_obj(embedded_data, ('program', 'description'))),
1057 'timestamp': int_or_none(traverse_obj(embedded_data, ('program', 'openTime'))),
1058 'is_live': True,
1059 'thumbnails': thumbnails,
1060 'formats': formats,
1061 }