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