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