]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/niconico.py
[ie/niconico] Support DMS formats (#9282)
[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
40 _TESTS = [{
41 'url': 'http://www.nicovideo.jp/watch/sm22312215',
42 'md5': 'd1a75c0823e2f629128c43e1212760f9',
43 'info_dict': {
44 'id': 'sm22312215',
45 'ext': 'mp4',
46 'title': 'Big Buck Bunny',
47 'thumbnail': r're:https?://.*',
48 'uploader': 'takuya0301',
49 'uploader_id': '2698420',
50 'upload_date': '20131123',
51 'timestamp': int, # timestamp is unstable
52 'description': '(c) copyright 2008, Blender Foundation / www.bigbuckbunny.org',
53 'duration': 33,
54 'view_count': int,
55 'comment_count': int,
56 'genres': ['未設定'],
57 'tags': [],
58 'expected_protocol': str,
59 },
60 }, {
61 # File downloaded with and without credentials are different, so omit
62 # the md5 field
63 'url': 'http://www.nicovideo.jp/watch/nm14296458',
64 'info_dict': {
65 'id': 'nm14296458',
66 'ext': 'mp4',
67 'title': '【Kagamine Rin】Dance on media【Original】take2!',
68 'description': 'md5:9368f2b1f4178de64f2602c2f3d6cbf5',
69 'thumbnail': r're:https?://.*',
70 'uploader': 'りょうた',
71 'uploader_id': '18822557',
72 'upload_date': '20110429',
73 'timestamp': 1304065916,
74 'duration': 208.0,
75 'comment_count': int,
76 'view_count': int,
77 'genres': ['音楽・サウンド'],
78 'tags': ['Translation_Request', 'Kagamine_Rin', 'Rin_Original'],
79 'expected_protocol': str,
80 },
81 }, {
82 # 'video exists but is marked as "deleted"
83 # md5 is unstable
84 'url': 'http://www.nicovideo.jp/watch/sm10000',
85 'info_dict': {
86 'id': 'sm10000',
87 'ext': 'unknown_video',
88 'description': 'deleted',
89 'title': 'ドラえもんエターナル第3話「決戦第3新東京市」<前編>',
90 'thumbnail': r're:https?://.*',
91 'upload_date': '20071224',
92 'timestamp': int, # timestamp field has different value if logged in
93 'duration': 304,
94 'view_count': int,
95 },
96 'skip': 'Requires an account',
97 }, {
98 'url': 'http://www.nicovideo.jp/watch/so22543406',
99 'info_dict': {
100 'id': '1388129933',
101 'ext': 'mp4',
102 'title': '【第1回】RADIOアニメロミックス ラブライブ!~のぞえりRadio Garden~',
103 'description': 'md5:b27d224bb0ff53d3c8269e9f8b561cf1',
104 'thumbnail': r're:https?://.*',
105 'timestamp': 1388851200,
106 'upload_date': '20140104',
107 'uploader': 'アニメロチャンネル',
108 'uploader_id': '312',
109 },
110 'skip': 'The viewing period of the video you were searching for has expired.',
111 }, {
112 # video not available via `getflv`; "old" HTML5 video
113 'url': 'http://www.nicovideo.jp/watch/sm1151009',
114 'md5': 'f95a3d259172667b293530cc2e41ebda',
115 'info_dict': {
116 'id': 'sm1151009',
117 'ext': 'mp4',
118 'title': 'マスターシステム本体内蔵のスペハリのメインテーマ(PSG版)',
119 'description': 'md5:f95a3d259172667b293530cc2e41ebda',
120 'thumbnail': r're:https?://.*',
121 'duration': 184,
122 'timestamp': 1190835883,
123 'upload_date': '20070926',
124 'uploader': 'denden2',
125 'uploader_id': '1392194',
126 'view_count': int,
127 'comment_count': int,
128 'genres': ['ゲーム'],
129 'tags': [],
130 'expected_protocol': str,
131 },
132 }, {
133 # "New" HTML5 video
134 # md5 is unstable
135 'url': 'http://www.nicovideo.jp/watch/sm31464864',
136 'info_dict': {
137 'id': 'sm31464864',
138 'ext': 'mp4',
139 'title': '新作TVアニメ「戦姫絶唱シンフォギアAXZ」PV 最高画質',
140 'description': 'md5:e52974af9a96e739196b2c1ca72b5feb',
141 'timestamp': 1498481660,
142 'upload_date': '20170626',
143 'uploader': 'no-namamae',
144 'uploader_id': '40826363',
145 'thumbnail': r're:https?://.*',
146 'duration': 198,
147 'view_count': int,
148 'comment_count': int,
149 'genres': ['アニメ'],
150 'tags': [],
151 'expected_protocol': str,
152 },
153 }, {
154 # Video without owner
155 'url': 'http://www.nicovideo.jp/watch/sm18238488',
156 'md5': 'd265680a1f92bdcbbd2a507fc9e78a9e',
157 'info_dict': {
158 'id': 'sm18238488',
159 'ext': 'mp4',
160 'title': '【実写版】ミュータントタートルズ',
161 'description': 'md5:15df8988e47a86f9e978af2064bf6d8e',
162 'timestamp': 1341128008,
163 'upload_date': '20120701',
164 'uploader': None,
165 'uploader_id': None,
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 club_joined = traverse_obj(api_data, ('channel', 'viewer', 'follow', 'isFollowed', {bool}))
482 if club_joined is None:
483 fail_msg = self._html_search_regex(
484 r'<p[^>]+\bclass="fail-message"[^>]*>(?P<msg>.+?)</p>',
485 webpage, 'fail message', default=None, group='msg')
486 if fail_msg:
487 self.raise_login_required(clean_html(fail_msg), metadata_available=True)
488 elif not club_joined:
489 self.raise_login_required('This video is for members only', metadata_available=True)
490
491 # Start extracting information
492 tags = None
493 if webpage:
494 # use og:video:tag (not logged in)
495 og_video_tags = re.finditer(r'<meta\s+property="og:video:tag"\s*content="(.*?)">', webpage)
496 tags = list(filter(None, (clean_html(x.group(1)) for x in og_video_tags)))
497 if not tags:
498 # use keywords and split with comma (not logged in)
499 kwds = self._html_search_meta('keywords', webpage, default=None)
500 if kwds:
501 tags = [x for x in kwds.split(',') if x]
502 if not tags:
503 # find in json (logged in)
504 tags = traverse_obj(api_data, ('tag', 'items', ..., 'name'))
505
506 thumb_prefs = qualities(['url', 'middleUrl', 'largeUrl', 'player', 'ogp'])
507
508 def get_video_info(*items, get_first=True, **kwargs):
509 return traverse_obj(api_data, ('video', *items), get_all=not get_first, **kwargs)
510
511 return {
512 'id': video_id,
513 '_api_data': api_data,
514 'title': get_video_info(('originalTitle', 'title')) or self._og_search_title(webpage, default=None),
515 'formats': [*self._yield_dmc_formats(api_data, video_id),
516 *self._yield_dms_formats(api_data, video_id)],
517 'thumbnails': [{
518 'id': key,
519 'url': url,
520 'ext': 'jpg',
521 'preference': thumb_prefs(key),
522 **parse_resolution(url, lenient=True),
523 } for key, url in (get_video_info('thumbnail') or {}).items() if url],
524 'description': clean_html(get_video_info('description')),
525 'uploader': traverse_obj(api_data, ('owner', 'nickname'), ('channel', 'name'), ('community', 'name')),
526 'uploader_id': str_or_none(traverse_obj(api_data, ('owner', 'id'), ('channel', 'id'), ('community', 'id'))),
527 'timestamp': parse_iso8601(get_video_info('registeredAt')) or parse_iso8601(
528 self._html_search_meta('video:release_date', webpage, 'date published', default=None)),
529 'channel': traverse_obj(api_data, ('channel', 'name'), ('community', 'name')),
530 'channel_id': traverse_obj(api_data, ('channel', 'id'), ('community', 'id')),
531 'view_count': int_or_none(get_video_info('count', 'view')),
532 'tags': tags,
533 'genre': traverse_obj(api_data, ('genre', 'label'), ('genre', 'key')),
534 'comment_count': get_video_info('count', 'comment', expected_type=int),
535 'duration': (
536 parse_duration(self._html_search_meta('video:duration', webpage, 'video duration', default=None))
537 or get_video_info('duration')),
538 'webpage_url': url_or_none(url) or f'https://www.nicovideo.jp/watch/{video_id}',
539 'subtitles': self.extract_subtitles(video_id, api_data),
540 }
541
542 def _get_subtitles(self, video_id, api_data):
543 comments_info = traverse_obj(api_data, ('comment', 'nvComment', {dict})) or {}
544 if not comments_info.get('server'):
545 return
546
547 danmaku = traverse_obj(self._download_json(
548 f'{comments_info["server"]}/v1/threads', video_id, data=json.dumps({
549 'additionals': {},
550 'params': comments_info.get('params'),
551 'threadKey': comments_info.get('threadKey'),
552 }).encode(), fatal=False,
553 headers={
554 'Referer': 'https://www.nicovideo.jp/',
555 'Origin': 'https://www.nicovideo.jp',
556 'Content-Type': 'text/plain;charset=UTF-8',
557 'x-client-os-type': 'others',
558 'x-frontend-id': '6',
559 'x-frontend-version': '0',
560 },
561 note='Downloading comments', errnote='Failed to download comments'),
562 ('data', 'threads', ..., 'comments', ...))
563
564 return {
565 'comments': [{
566 'ext': 'json',
567 'data': json.dumps(danmaku),
568 }],
569 }
570
571
572 class NiconicoPlaylistBaseIE(InfoExtractor):
573 _PAGE_SIZE = 100
574
575 _API_HEADERS = {
576 'X-Frontend-ID': '6',
577 'X-Frontend-Version': '0',
578 'X-Niconico-Language': 'en-us'
579 }
580
581 def _call_api(self, list_id, resource, query):
582 raise NotImplementedError('Must be implemented in subclasses')
583
584 @staticmethod
585 def _parse_owner(item):
586 return {
587 'uploader': traverse_obj(item, ('owner', 'name')),
588 'uploader_id': traverse_obj(item, ('owner', 'id')),
589 }
590
591 def _fetch_page(self, list_id, page):
592 page += 1
593 resp = self._call_api(list_id, 'page %d' % page, {
594 'page': page,
595 'pageSize': self._PAGE_SIZE,
596 })
597 # this is needed to support both mylist and user
598 for video in traverse_obj(resp, ('items', ..., ('video', None))) or []:
599 video_id = video.get('id')
600 if not video_id:
601 # skip {"video": {"id": "blablabla", ...}}
602 continue
603 count = video.get('count') or {}
604 get_count = lambda x: int_or_none(count.get(x))
605 yield {
606 '_type': 'url',
607 'id': video_id,
608 'title': video.get('title'),
609 'url': f'https://www.nicovideo.jp/watch/{video_id}',
610 'description': video.get('shortDescription'),
611 'duration': int_or_none(video.get('duration')),
612 'view_count': get_count('view'),
613 'comment_count': get_count('comment'),
614 'thumbnail': traverse_obj(video, ('thumbnail', ('nHdUrl', 'largeUrl', 'listingUrl', 'url'))),
615 'ie_key': NiconicoIE.ie_key(),
616 **self._parse_owner(video),
617 }
618
619 def _entries(self, list_id):
620 return OnDemandPagedList(functools.partial(self._fetch_page, list_id), self._PAGE_SIZE)
621
622
623 class NiconicoPlaylistIE(NiconicoPlaylistBaseIE):
624 IE_NAME = 'niconico:playlist'
625 _VALID_URL = r'https?://(?:(?:www\.|sp\.)?nicovideo\.jp|nico\.ms)/(?:user/\d+/)?(?:my/)?mylist/(?:#/)?(?P<id>\d+)'
626
627 _TESTS = [{
628 'url': 'http://www.nicovideo.jp/mylist/27411728',
629 'info_dict': {
630 'id': '27411728',
631 'title': 'AKB48のオールナイトニッポン',
632 'description': 'md5:d89694c5ded4b6c693dea2db6e41aa08',
633 'uploader': 'のっく',
634 'uploader_id': '805442',
635 },
636 'playlist_mincount': 291,
637 }, {
638 'url': 'https://www.nicovideo.jp/user/805442/mylist/27411728',
639 'only_matching': True,
640 }, {
641 'url': 'https://www.nicovideo.jp/my/mylist/#/68048635',
642 'only_matching': True,
643 }]
644
645 def _call_api(self, list_id, resource, query):
646 return self._download_json(
647 f'https://nvapi.nicovideo.jp/v2/mylists/{list_id}', list_id,
648 f'Downloading {resource}', query=query,
649 headers=self._API_HEADERS)['data']['mylist']
650
651 def _real_extract(self, url):
652 list_id = self._match_id(url)
653 mylist = self._call_api(list_id, 'list', {
654 'pageSize': 1,
655 })
656 return self.playlist_result(
657 self._entries(list_id), list_id,
658 mylist.get('name'), mylist.get('description'), **self._parse_owner(mylist))
659
660
661 class NiconicoSeriesIE(InfoExtractor):
662 IE_NAME = 'niconico:series'
663 _VALID_URL = r'https?://(?:(?:www\.|sp\.)?nicovideo\.jp(?:/user/\d+)?|nico\.ms)/series/(?P<id>\d+)'
664
665 _TESTS = [{
666 'url': 'https://www.nicovideo.jp/user/44113208/series/110226',
667 'info_dict': {
668 'id': '110226',
669 'title': 'ご立派ァ!のシリーズ',
670 },
671 'playlist_mincount': 10,
672 }, {
673 'url': 'https://www.nicovideo.jp/series/12312/',
674 'info_dict': {
675 'id': '12312',
676 'title': 'バトルスピリッツ お勧めカード紹介(調整中)',
677 },
678 'playlist_mincount': 103,
679 }, {
680 'url': 'https://nico.ms/series/203559',
681 'only_matching': True,
682 }]
683
684 def _real_extract(self, url):
685 list_id = self._match_id(url)
686 webpage = self._download_webpage(url, list_id)
687
688 title = self._search_regex(
689 (r'<title>「(.+)(全',
690 r'<div class="TwitterShareButton"\s+data-text="(.+)\s+https:'),
691 webpage, 'title', fatal=False)
692 if title:
693 title = unescapeHTML(title)
694 json_data = next(self._yield_json_ld(webpage, None, fatal=False))
695 return self.playlist_from_matches(
696 traverse_obj(json_data, ('itemListElement', ..., 'url')), list_id, title, ie=NiconicoIE)
697
698
699 class NiconicoHistoryIE(NiconicoPlaylistBaseIE):
700 IE_NAME = 'niconico:history'
701 IE_DESC = 'NicoNico user history or likes. Requires cookies.'
702 _VALID_URL = r'https?://(?:www\.|sp\.)?nicovideo\.jp/my/(?P<id>history(?:/like)?)'
703
704 _TESTS = [{
705 'note': 'PC page, with /video',
706 'url': 'https://www.nicovideo.jp/my/history/video',
707 'only_matching': True,
708 }, {
709 'note': 'PC page, without /video',
710 'url': 'https://www.nicovideo.jp/my/history',
711 'only_matching': True,
712 }, {
713 'note': 'mobile page, with /video',
714 'url': 'https://sp.nicovideo.jp/my/history/video',
715 'only_matching': True,
716 }, {
717 'note': 'mobile page, without /video',
718 'url': 'https://sp.nicovideo.jp/my/history',
719 'only_matching': True,
720 }, {
721 'note': 'PC page',
722 'url': 'https://www.nicovideo.jp/my/history/like',
723 'only_matching': True,
724 }, {
725 'note': 'Mobile page',
726 'url': 'https://sp.nicovideo.jp/my/history/like',
727 'only_matching': True,
728 }]
729
730 def _call_api(self, list_id, resource, query):
731 path = 'likes' if list_id == 'history/like' else 'watch/history'
732 return self._download_json(
733 f'https://nvapi.nicovideo.jp/v1/users/me/{path}', list_id,
734 f'Downloading {resource}', query=query, headers=self._API_HEADERS)['data']
735
736 def _real_extract(self, url):
737 list_id = self._match_id(url)
738 try:
739 mylist = self._call_api(list_id, 'list', {'pageSize': 1})
740 except ExtractorError as e:
741 if isinstance(e.cause, HTTPError) and e.cause.status == 401:
742 self.raise_login_required('You have to be logged in to get your history')
743 raise
744 return self.playlist_result(self._entries(list_id), list_id, **self._parse_owner(mylist))
745
746
747 class NicovideoSearchBaseIE(InfoExtractor):
748 _SEARCH_TYPE = 'search'
749
750 def _entries(self, url, item_id, query=None, note='Downloading page %(page)s'):
751 query = query or {}
752 pages = [query['page']] if 'page' in query else itertools.count(1)
753 for page_num in pages:
754 query['page'] = str(page_num)
755 webpage = self._download_webpage(url, item_id, query=query, note=note % {'page': page_num})
756 results = re.findall(r'(?<=data-video-id=)["\']?(?P<videoid>.*?)(?=["\'])', webpage)
757 for item in results:
758 yield self.url_result(f'https://www.nicovideo.jp/watch/{item}', 'Niconico', item)
759 if not results:
760 break
761
762 def _search_results(self, query):
763 return self._entries(
764 self._proto_relative_url(f'//www.nicovideo.jp/{self._SEARCH_TYPE}/{query}'), query)
765
766
767 class NicovideoSearchIE(NicovideoSearchBaseIE, SearchInfoExtractor):
768 IE_DESC = 'Nico video search'
769 IE_NAME = 'nicovideo:search'
770 _SEARCH_KEY = 'nicosearch'
771
772
773 class NicovideoSearchURLIE(NicovideoSearchBaseIE):
774 IE_NAME = f'{NicovideoSearchIE.IE_NAME}_url'
775 IE_DESC = 'Nico video search URLs'
776 _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/search/(?P<id>[^?#&]+)?'
777 _TESTS = [{
778 'url': 'http://www.nicovideo.jp/search/sm9',
779 'info_dict': {
780 'id': 'sm9',
781 'title': 'sm9'
782 },
783 'playlist_mincount': 40,
784 }, {
785 'url': 'https://www.nicovideo.jp/search/sm9?sort=h&order=d&end=2020-12-31&start=2020-01-01',
786 'info_dict': {
787 'id': 'sm9',
788 'title': 'sm9'
789 },
790 'playlist_count': 31,
791 }]
792
793 def _real_extract(self, url):
794 query = self._match_id(url)
795 return self.playlist_result(self._entries(url, query), query, query)
796
797
798 class NicovideoSearchDateIE(NicovideoSearchBaseIE, SearchInfoExtractor):
799 IE_DESC = 'Nico video search, newest first'
800 IE_NAME = f'{NicovideoSearchIE.IE_NAME}:date'
801 _SEARCH_KEY = 'nicosearchdate'
802 _TESTS = [{
803 'url': 'nicosearchdateall:a',
804 'info_dict': {
805 'id': 'a',
806 'title': 'a'
807 },
808 'playlist_mincount': 1610,
809 }]
810
811 _START_DATE = datetime.date(2007, 1, 1)
812 _RESULTS_PER_PAGE = 32
813 _MAX_PAGES = 50
814
815 def _entries(self, url, item_id, start_date=None, end_date=None):
816 start_date, end_date = start_date or self._START_DATE, end_date or datetime.datetime.now().date()
817
818 # If the last page has a full page of videos, we need to break down the query interval further
819 last_page_len = len(list(self._get_entries_for_date(
820 url, item_id, start_date, end_date, self._MAX_PAGES,
821 note=f'Checking number of videos from {start_date} to {end_date}')))
822 if (last_page_len == self._RESULTS_PER_PAGE and start_date != end_date):
823 midpoint = start_date + ((end_date - start_date) // 2)
824 yield from self._entries(url, item_id, midpoint, end_date)
825 yield from self._entries(url, item_id, start_date, midpoint)
826 else:
827 self.to_screen(f'{item_id}: Downloading results from {start_date} to {end_date}')
828 yield from self._get_entries_for_date(
829 url, item_id, start_date, end_date, note=' Downloading page %(page)s')
830
831 def _get_entries_for_date(self, url, item_id, start_date, end_date=None, page_num=None, note=None):
832 query = {
833 'start': str(start_date),
834 'end': str(end_date or start_date),
835 'sort': 'f',
836 'order': 'd',
837 }
838 if page_num:
839 query['page'] = str(page_num)
840
841 yield from super()._entries(url, item_id, query=query, note=note)
842
843
844 class NicovideoTagURLIE(NicovideoSearchBaseIE):
845 IE_NAME = 'niconico:tag'
846 IE_DESC = 'NicoNico video tag URLs'
847 _SEARCH_TYPE = 'tag'
848 _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/tag/(?P<id>[^?#&]+)?'
849 _TESTS = [{
850 'url': 'https://www.nicovideo.jp/tag/ドキュメンタリー淫夢',
851 'info_dict': {
852 'id': 'ドキュメンタリー淫夢',
853 'title': 'ドキュメンタリー淫夢'
854 },
855 'playlist_mincount': 400,
856 }]
857
858 def _real_extract(self, url):
859 query = self._match_id(url)
860 return self.playlist_result(self._entries(url, query), query, query)
861
862
863 class NiconicoUserIE(InfoExtractor):
864 _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/user/(?P<id>\d+)/?(?:$|[#?])'
865 _TEST = {
866 'url': 'https://www.nicovideo.jp/user/419948',
867 'info_dict': {
868 'id': '419948',
869 },
870 'playlist_mincount': 101,
871 }
872 _API_URL = "https://nvapi.nicovideo.jp/v1/users/%s/videos?sortKey=registeredAt&sortOrder=desc&pageSize=%s&page=%s"
873 _PAGE_SIZE = 100
874
875 _API_HEADERS = {
876 'X-Frontend-ID': '6',
877 'X-Frontend-Version': '0'
878 }
879
880 def _entries(self, list_id):
881 total_count = 1
882 count = page_num = 0
883 while count < total_count:
884 json_parsed = self._download_json(
885 self._API_URL % (list_id, self._PAGE_SIZE, page_num + 1), list_id,
886 headers=self._API_HEADERS,
887 note='Downloading JSON metadata%s' % (' page %d' % page_num if page_num else ''))
888 if not page_num:
889 total_count = int_or_none(json_parsed['data'].get('totalCount'))
890 for entry in json_parsed["data"]["items"]:
891 count += 1
892 yield self.url_result('https://www.nicovideo.jp/watch/%s' % entry['id'])
893 page_num += 1
894
895 def _real_extract(self, url):
896 list_id = self._match_id(url)
897 return self.playlist_result(self._entries(list_id), list_id, ie=NiconicoIE.ie_key())
898
899
900 class NiconicoLiveIE(InfoExtractor):
901 IE_NAME = 'niconico:live'
902 IE_DESC = 'ニコニコ生放送'
903 _VALID_URL = r'https?://(?:sp\.)?live2?\.nicovideo\.jp/(?:watch|gate)/(?P<id>lv\d+)'
904 _TESTS = [{
905 'note': 'this test case includes invisible characters for title, pasting them as-is',
906 'url': 'https://live.nicovideo.jp/watch/lv339533123',
907 'info_dict': {
908 'id': 'lv339533123',
909 'title': '激辛ペヤング食べます‪( ;ᯅ; )‬(歌枠オーディション参加中)',
910 'view_count': 1526,
911 'comment_count': 1772,
912 'description': '初めましてもかって言います❕\nのんびり自由に適当に暮らしてます',
913 'uploader': 'もか',
914 'channel': 'ゲストさんのコミュニティ',
915 'channel_id': 'co5776900',
916 'channel_url': 'https://com.nicovideo.jp/community/co5776900',
917 'timestamp': 1670677328,
918 'is_live': True,
919 },
920 'skip': 'livestream',
921 }, {
922 'url': 'https://live2.nicovideo.jp/watch/lv339533123',
923 'only_matching': True,
924 }, {
925 'url': 'https://sp.live.nicovideo.jp/watch/lv339533123',
926 'only_matching': True,
927 }, {
928 'url': 'https://sp.live2.nicovideo.jp/watch/lv339533123',
929 'only_matching': True,
930 }]
931
932 _KNOWN_LATENCY = ('high', 'low')
933
934 def _real_extract(self, url):
935 video_id = self._match_id(url)
936 webpage, urlh = self._download_webpage_handle(f'https://live.nicovideo.jp/watch/{video_id}', video_id)
937
938 embedded_data = self._parse_json(unescapeHTML(self._search_regex(
939 r'<script\s+id="embedded-data"\s*data-props="(.+?)"', webpage, 'embedded data')), video_id)
940
941 ws_url = traverse_obj(embedded_data, ('site', 'relive', 'webSocketUrl'))
942 if not ws_url:
943 raise ExtractorError('The live hasn\'t started yet or already ended.', expected=True)
944 ws_url = update_url_query(ws_url, {
945 'frontend_id': traverse_obj(embedded_data, ('site', 'frontendId')) or '9',
946 })
947
948 hostname = remove_start(urlparse(urlh.url).hostname, 'sp.')
949 latency = try_get(self._configuration_arg('latency'), lambda x: x[0])
950 if latency not in self._KNOWN_LATENCY:
951 latency = 'high'
952
953 ws = self._request_webpage(
954 Request(ws_url, headers={'Origin': f'https://{hostname}'}),
955 video_id=video_id, note='Connecting to WebSocket server')
956
957 self.write_debug('[debug] Sending HLS server request')
958 ws.send(json.dumps({
959 'type': 'startWatching',
960 'data': {
961 'stream': {
962 'quality': 'abr',
963 'protocol': 'hls+fmp4',
964 'latency': latency,
965 'chasePlay': False
966 },
967 'room': {
968 'protocol': 'webSocket',
969 'commentable': True
970 },
971 'reconnect': False,
972 }
973 }))
974
975 while True:
976 recv = ws.recv()
977 if not recv:
978 continue
979 data = json.loads(recv)
980 if not isinstance(data, dict):
981 continue
982 if data.get('type') == 'stream':
983 m3u8_url = data['data']['uri']
984 qualities = data['data']['availableQualities']
985 break
986 elif data.get('type') == 'disconnect':
987 self.write_debug(recv)
988 raise ExtractorError('Disconnected at middle of extraction')
989 elif data.get('type') == 'error':
990 self.write_debug(recv)
991 message = traverse_obj(data, ('body', 'code')) or recv
992 raise ExtractorError(message)
993 elif self.get_param('verbose', False):
994 if len(recv) > 100:
995 recv = recv[:100] + '...'
996 self.write_debug('Server said: %s' % recv)
997
998 title = traverse_obj(embedded_data, ('program', 'title')) or self._html_search_meta(
999 ('og:title', 'twitter:title'), webpage, 'live title', fatal=False)
1000
1001 raw_thumbs = traverse_obj(embedded_data, ('program', 'thumbnail')) or {}
1002 thumbnails = []
1003 for name, value in raw_thumbs.items():
1004 if not isinstance(value, dict):
1005 thumbnails.append({
1006 'id': name,
1007 'url': value,
1008 **parse_resolution(value, lenient=True),
1009 })
1010 continue
1011
1012 for k, img_url in value.items():
1013 res = parse_resolution(k, lenient=True) or parse_resolution(img_url, lenient=True)
1014 width, height = res.get('width'), res.get('height')
1015
1016 thumbnails.append({
1017 'id': f'{name}_{width}x{height}',
1018 'url': img_url,
1019 **res,
1020 })
1021
1022 formats = self._extract_m3u8_formats(m3u8_url, video_id, ext='mp4', live=True)
1023 for fmt, q in zip(formats, reversed(qualities[1:])):
1024 fmt.update({
1025 'format_id': q,
1026 'protocol': 'niconico_live',
1027 'ws': ws,
1028 'video_id': video_id,
1029 'live_latency': latency,
1030 'origin': hostname,
1031 })
1032
1033 return {
1034 'id': video_id,
1035 'title': title,
1036 **traverse_obj(embedded_data, {
1037 'view_count': ('program', 'statistics', 'watchCount'),
1038 'comment_count': ('program', 'statistics', 'commentCount'),
1039 'uploader': ('program', 'supplier', 'name'),
1040 'channel': ('socialGroup', 'name'),
1041 'channel_id': ('socialGroup', 'id'),
1042 'channel_url': ('socialGroup', 'socialGroupPageUrl'),
1043 }),
1044 'description': clean_html(traverse_obj(embedded_data, ('program', 'description'))),
1045 'timestamp': int_or_none(traverse_obj(embedded_data, ('program', 'openTime'))),
1046 'is_live': True,
1047 'thumbnails': thumbnails,
1048 'formats': formats,
1049 }