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