8 from urllib
.parse
import urlparse
10 from .common
import InfoExtractor
, SearchInfoExtractor
11 from ..networking
import Request
12 from ..networking
.exceptions
import HTTPError
36 class NiconicoIE(InfoExtractor
):
39 _GEO_COUNTRIES
= ['JP']
43 'url': 'http://www.nicovideo.jp/watch/sm22312215',
44 'md5': 'd1a75c0823e2f629128c43e1212760f9',
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',
60 'expected_protocol': str,
63 # File downloaded with and without credentials are different, so omit
65 'url': 'http://www.nicovideo.jp/watch/nm14296458',
69 'title': '【Kagamine Rin】Dance on media【Original】take2!',
70 'description': 'md5:9368f2b1f4178de64f2602c2f3d6cbf5',
71 'thumbnail': r
're:https?://.*',
73 'uploader_id': '18822557',
74 'upload_date': '20110429',
75 'timestamp': 1304065916,
79 'genres': ['音楽・サウンド'],
80 'tags': ['Translation_Request', 'Kagamine_Rin', 'Rin_Original'],
81 'expected_protocol': str,
84 # 'video exists but is marked as "deleted"
86 'url': 'http://www.nicovideo.jp/watch/sm10000',
89 'ext': 'unknown_video',
90 'description': 'deleted',
91 'title': 'ドラえもんエターナル第3話「決戦第3新東京市」<前編>',
92 'thumbnail': r
're:https?://.*',
93 'upload_date': '20071224',
94 'timestamp': int, # timestamp field has different value if logged in
98 'skip': 'Requires an account',
100 'url': 'http://www.nicovideo.jp/watch/so22543406',
104 'title': '【第1回】RADIOアニメロミックス ラブライブ!~のぞえりRadio Garden~',
105 'description': 'md5:b27d224bb0ff53d3c8269e9f8b561cf1',
106 'thumbnail': r
're:https?://.*',
107 'timestamp': 1388851200,
108 'upload_date': '20140104',
109 'uploader': 'アニメロチャンネル',
110 'uploader_id': '312',
112 'skip': 'The viewing period of the video you were searching for has expired.',
114 # video not available via `getflv`; "old" HTML5 video
115 'url': 'http://www.nicovideo.jp/watch/sm1151009',
116 'md5': 'f95a3d259172667b293530cc2e41ebda',
120 'title': 'マスターシステム本体内蔵のスペハリのメインテーマ(PSG版)',
121 'description': 'md5:f95a3d259172667b293530cc2e41ebda',
122 'thumbnail': r
're:https?://.*',
124 'timestamp': 1190835883,
125 'upload_date': '20070926',
126 'uploader': 'denden2',
127 'uploader_id': '1392194',
129 'comment_count': int,
132 'expected_protocol': str,
137 'url': 'http://www.nicovideo.jp/watch/sm31464864',
141 'title': '新作TVアニメ「戦姫絶唱シンフォギアAXZ」PV 最高画質',
142 'description': 'md5:e52974af9a96e739196b2c1ca72b5feb',
143 'timestamp': 1498481660,
144 'upload_date': '20170626',
145 'uploader': 'no-namamae',
146 'uploader_id': '40826363',
147 'thumbnail': r
're:https?://.*',
150 'comment_count': int,
153 'expected_protocol': str,
156 # Video without owner
157 'url': 'http://www.nicovideo.jp/watch/sm18238488',
158 'md5': 'd265680a1f92bdcbbd2a507fc9e78a9e',
162 'title': '【実写版】ミュータントタートルズ',
163 'description': 'md5:15df8988e47a86f9e978af2064bf6d8e',
164 'timestamp': 1341128008,
165 'upload_date': '20120701',
166 'thumbnail': r
're:https?://.*',
169 'comment_count': int,
170 'genres': ['エンターテイメント'],
172 'expected_protocol': str,
175 'url': 'http://sp.nicovideo.jp/watch/sm28964488?ss_pos=1&cp_in=wt_tg',
176 'only_matching': True,
178 'note': 'a video that is only served as an ENCRYPTED HLS.',
179 'url': 'https://www.nicovideo.jp/watch/so38016254',
180 'only_matching': True,
183 _VALID_URL
= r
'https?://(?:(?:www\.|secure\.|sp\.)?nicovideo\.jp/watch|nico\.ms)/(?P<id>(?:[a-z]{2})?[0-9]+)'
184 _NETRC_MACHINE
= 'niconico'
186 'X-Frontend-ID': '6',
187 'X-Frontend-Version': '0',
188 'X-Niconico-Language': 'en-us',
189 'Referer': 'https://www.nicovideo.jp/',
190 'Origin': 'https://www.nicovideo.jp',
193 def _perform_login(self
, username
, password
):
196 'mail_tel': username
,
197 'password': password
,
199 self
._request
_webpage
(
200 'https://account.nicovideo.jp/login', None,
201 note
='Acquiring Login session')
202 page
= self
._download
_webpage
(
203 'https://account.nicovideo.jp/login/redirector?show_button_twitter=1&site=niconico&show_button_facebook=1', None,
204 note
='Logging in', errnote
='Unable to log in',
205 data
=urlencode_postdata(login_form_strs
),
207 'Referer': 'https://account.nicovideo.jp/login',
208 'Content-Type': 'application/x-www-form-urlencoded',
210 if 'oneTimePw' in page
:
211 post_url
= self
._search
_regex
(
212 r
'<form[^>]+action=(["\'])(?P
<url
>.+?
)\
1', page, 'post url
', group='url
')
213 page = self._download_webpage(
214 urljoin('https
://account
.nicovideo
.jp
', post_url), None,
215 note='Performing MFA
', errnote='Unable to complete MFA
',
216 data=urlencode_postdata({
217 'otp
': self._get_tfa_info('6 digits code
')
219 'Content
-Type
': 'application
/x
-www
-form
-urlencoded
',
221 if 'oneTimePw
' in page or 'formError
' in page:
222 err_msg = self._html_search_regex(
223 r'formError
["\']+>(.*?)</div>', page, 'form_error',
224 default='There\'s an error but the message can\'t be parsed.',
226 self.report_warning(f'Unable to log in: MFA challenge failed, "{err_msg}
"')
228 login_ok = 'class="notice error
"' not in page
230 self.report_warning('Unable to log in: bad username or password')
233 def _get_heartbeat_info(self, info_dict):
234 video_id, video_src_id, audio_src_id = info_dict['url'].split(':')[1].split('/')
235 dmc_protocol = info_dict['expected_protocol']
238 info_dict.get('_api_data')
240 self._html_search_regex(
241 'data-api-data="([^
"]+)"',
242 self._download_webpage('https
://www
.nicovideo
.jp
/watch
/' + video_id, video_id),
243 'API data
', default='{}'),
246 session_api_data = try_get(api_data, lambda x: x['media
']['delivery
']['movie
']['session
'])
247 session_api_endpoint = try_get(session_api_data, lambda x: x['urls
'][0])
250 tracking_id = traverse_obj(api_data, ('media
', 'delivery
', 'trackingId
'))
252 tracking_url = update_url_query('https
://nvapi
.nicovideo
.jp
/v1
/2ab0cbaa
/watch
', {'t': tracking_id})
253 watch_request_response = self._download_json(
254 tracking_url, video_id,
255 note='Acquiring permission
for downloading video
', fatal=False,
256 headers=self._API_HEADERS)
257 if traverse_obj(watch_request_response, ('meta
', 'status
')) != 200:
258 self.report_warning('Failed to acquire permission
for playing video
. Video download may fail
.')
260 yesno = lambda x: 'yes
' if x else 'no
'
262 if dmc_protocol == 'http
':
264 protocol_parameters = {
265 'http_output_download_parameters
': {
266 'use_ssl
': yesno(session_api_data['urls
'][0]['isSsl
']),
267 'use_well_known_port
': yesno(session_api_data['urls
'][0]['isWellKnownPort
']),
270 elif dmc_protocol == 'hls
':
272 segment_duration = try_get(self._configuration_arg('segment_duration
'), lambda x: int(x[0])) or 6000
273 parsed_token = self._parse_json(session_api_data['token
'], video_id)
274 encryption = traverse_obj(api_data, ('media
', 'delivery
', 'encryption
'))
275 protocol_parameters = {
277 'segment_duration
': segment_duration,
278 'transfer_preset
': '',
279 'use_ssl
': yesno(session_api_data['urls
'][0]['isSsl
']),
280 'use_well_known_port
': yesno(session_api_data['urls
'][0]['isWellKnownPort
']),
283 if 'hls_encryption
' in parsed_token and encryption:
284 protocol_parameters['hls_parameters
']['encryption
'] = {
285 parsed_token['hls_encryption
']: {
286 'encrypted_key
': encryption['encryptedKey
'],
287 'key_uri
': encryption['keyUri
'],
291 protocol = 'm3u8_native
'
293 raise ExtractorError(f'Unsupported DMC protocol
: {dmc_protocol}
')
295 session_response = self._download_json(
296 session_api_endpoint['url
'], video_id,
297 query={'_format': 'json'},
298 headers={'Content-Type': 'application/json'},
299 note='Downloading JSON metadata
for %s' % info_dict['format_id
'],
303 'player_id
': session_api_data.get('playerId
'),
306 'auth_type
': try_get(session_api_data, lambda x: x['authTypes
'][session_api_data['protocols
'][0]]),
307 'content_key_timeout
': session_api_data.get('contentKeyTimeout
'),
308 'service_id
': 'nicovideo
',
309 'service_user_id
': session_api_data.get('serviceUserId
')
311 'content_id
': session_api_data.get('contentId
'),
312 'content_src_id_sets
': [{
313 'content_src_ids
': [{
315 'audio_src_ids
': [audio_src_id],
316 'video_src_ids
': [video_src_id],
320 'content_type
': 'movie
',
324 'lifetime
': session_api_data.get('heartbeatLifetime
')
327 'priority
': session_api_data['priority
'],
332 'parameters
': protocol_parameters
336 'recipe_id
': session_api_data.get('recipeId
'),
337 'session_operation_auth
': {
338 'session_operation_auth_by_signature
': {
339 'signature
': session_api_data.get('signature
'),
340 'token
': session_api_data.get('token
'),
343 'timing_constraint
': 'unlimited
'
347 info_dict['url
'] = session_response['data
']['session
']['content_uri
']
348 info_dict['protocol
'] = protocol
351 heartbeat_info_dict = {
352 'url
': session_api_endpoint['url
'] + '/' + session_response['data
']['session
']['id'] + '?_format
=json
&_method
=PUT
',
353 'data
': json.dumps(session_response['data
']),
354 # interval, convert milliseconds to seconds, then halve to make a buffer.
355 'interval
': float_or_none(session_api_data.get('heartbeatLifetime
'), scale=3000),
359 return info_dict, heartbeat_info_dict
361 def _extract_format_for_quality(self, video_id, audio_quality, video_quality, dmc_protocol):
363 if not audio_quality.get('isAvailable
') or not video_quality.get('isAvailable
'):
366 format_id = '-'.join(
367 [remove_start(s['id'], 'archive_
') for s in (video_quality, audio_quality)] + [dmc_protocol])
369 vid_qual_label = traverse_obj(video_quality, ('metadata
', 'label
'))
372 'url
': 'niconico_dmc
:%s/%s/%s' % (video_id, video_quality['id'], audio_quality['id']),
373 'format_id
': format_id,
374 'format_note
': join_nonempty('DMC
', vid_qual_label, dmc_protocol.upper(), delim=' '),
375 'ext
': 'mp4
', # Session API are used in HTML5, which always serves mp4
378 **traverse_obj(audio_quality, ('metadata
', {
379 'abr
': ('bitrate
', {functools.partial(float_or_none, scale=1000)}),
380 'asr
': ('samplingRate
', {int_or_none}),
382 **traverse_obj(video_quality, ('metadata
', {
383 'vbr
': ('bitrate
', {functools.partial(float_or_none, scale=1000)}),
384 'height
': ('resolution
', 'height
', {int_or_none}),
385 'width
': ('resolution
', 'width
', {int_or_none}),
387 'quality
': -2 if 'low
' in video_quality['id'] else None,
388 'protocol
': 'niconico_dmc
',
389 'expected_protocol
': dmc_protocol, # XXX: This is not a documented field
391 'Origin
': 'https
://www
.nicovideo
.jp
',
392 'Referer
': 'https
://www
.nicovideo
.jp
/watch
/' + video_id,
396 def _yield_dmc_formats(self, api_data, video_id):
397 dmc_data = traverse_obj(api_data, ('media
', 'delivery
', 'movie
'))
398 audios = traverse_obj(dmc_data, ('audios
', ..., {dict}))
399 videos = traverse_obj(dmc_data, ('videos
', ..., {dict}))
400 protocols = traverse_obj(dmc_data, ('session
', 'protocols
', ..., {str}))
401 if not all((audios, videos, protocols)):
404 for audio_quality, video_quality, protocol in itertools.product(audios, videos, protocols):
405 if fmt := self._extract_format_for_quality(video_id, audio_quality, video_quality, protocol):
408 def _yield_dms_formats(self, api_data, video_id):
409 fmt_filter = lambda _, v: v['isAvailable
'] and v['id']
410 videos = traverse_obj(api_data, ('media
', 'domand
', 'videos
', fmt_filter))
411 audios = traverse_obj(api_data, ('media
', 'domand
', 'audios
', fmt_filter))
412 access_key = traverse_obj(api_data, ('media
', 'domand
', 'accessRightKey
', {str}))
413 track_id = traverse_obj(api_data, ('client
', 'watchTrackId
', {str}))
414 if not all((videos, audios, access_key, track_id)):
417 dms_m3u8_url = self._download_json(
418 f'https
://nvapi
.nicovideo
.jp
/v1
/watch
/{video_id}
/access
-rights
/hls
', video_id,
420 'outputs
': list(itertools.product((v['id'] for v in videos), (a['id'] for a in audios)))
421 }).encode(), query={'actionTrackId': track_id}, headers={
422 'x
-access
-right
-key
': access_key,
424 'x
-frontend
-version
': 0,
425 'x
-request
-with': 'https
://www
.nicovideo
.jp
',
426 })['data
']['contentUrl
']
427 # Getting all audio formats results in duplicate video formats which we filter out later
428 dms_fmts = self._extract_m3u8_formats(dms_m3u8_url, video_id)
430 # m3u8 extraction does not provide audio bitrates, so extract from the API data and fix
431 for audio_fmt in traverse_obj(dms_fmts, lambda _, v: v['vcodec
'] == 'none
'):
434 **traverse_obj(audios, (lambda _, v: audio_fmt['format_id
'].startswith(v['id']), {
435 'format_id
': ('id', {str}),
436 'abr
': ('bitRate
', {functools.partial(float_or_none, scale=1000)}),
437 'asr
': ('samplingRate
', {int_or_none}),
443 # Sort before removing dupes to keep the format dicts with the lowest tbr
444 video_fmts = sorted((fmt for fmt in dms_fmts if fmt['vcodec
'] != 'none
'), key=lambda f: f['tbr
'])
445 self._remove_duplicate_formats(video_fmts)
446 # Calculate the true vbr/tbr by subtracting the lowest abr
447 min_abr = min(traverse_obj(audios, (..., 'bitRate
', {float_or_none})), default=0) / 1000
448 for video_fmt in video_fmts:
449 video_fmt['tbr
'] -= min_abr
450 video_fmt['format_id
'] = f'video
-{video_fmt["tbr"]:.0f}
'
453 def _real_extract(self, url):
454 video_id = self._match_id(url)
457 webpage, handle = self._download_webpage_handle(
458 'https
://www
.nicovideo
.jp
/watch
/' + video_id, video_id)
459 if video_id.startswith('so
'):
460 video_id = self._match_id(handle.url)
462 api_data = self._parse_json(self._html_search_regex(
463 'data
-api
-data
="([^"]+)"', webpage,
464 'API data', default='{}'), video_id)
465 except ExtractorError as e:
467 api_data = self._download_json(
468 'https://www.nicovideo.jp/api/watch/v3/%s?_frontendId=6&_frontendVersion=0&actionTrackId=AAAAAAAAAA_%d' % (video_id, round(time.time() * 1000)), video_id,
469 note='Downloading API JSON', errnote='Unable to fetch data')['data']
470 except ExtractorError:
471 if not isinstance(e.cause, HTTPError):
473 webpage = e.cause.response.read().decode('utf-8', 'replace')
474 error_msg = self._html_search_regex(
475 r'(?s)<section\s+class="(?
:(?
:ErrorMessage|WatchExceptionPage
-message
)\s
*)+">(.+?)</section>',
476 webpage, 'error reason', default=None)
479 raise ExtractorError(clean_html(error_msg), expected=True)
481 availability = self._availability(**(traverse_obj(api_data, ('payment', 'video', {
482 'needs_premium': ('isPremium', {bool}),
483 'needs_subscription': ('isAdmission', {bool}),
484 })) or {'needs_auth': True}))
485 formats = [*self._yield_dmc_formats(api_data, video_id),
486 *self._yield_dms_formats(api_data, video_id)]
488 fail_msg = clean_html(self._html_search_regex(
489 r'<p[^>]+\bclass="fail
-message
"[^>]*>(?P<msg>.+?)</p>',
490 webpage, 'fail message', default=None, group='msg'))
492 self.to_screen(f'Niconico said: {fail_msg}')
493 if fail_msg and 'された地域と同じ地域からのみ視聴できます。' in fail_msg:
495 self.raise_geo_restricted(countries=self._GEO_COUNTRIES, metadata_available=True)
496 elif availability == 'premium_only':
497 self.raise_login_required('This video requires premium', metadata_available=True)
498 elif availability == 'subscriber_only':
499 self.raise_login_required('This video is for members only', metadata_available=True)
500 elif availability == 'needs_auth':
501 self.raise_login_required(metadata_available=False)
503 # Start extracting information
506 # use og:video:tag (not logged in)
507 og_video_tags = re.finditer(r'<meta\s+property="og
:video
:tag
"\s*content="(.*?
)">', webpage)
508 tags = list(filter(None, (clean_html(x.group(1)) for x in og_video_tags)))
510 # use keywords and split with comma (not logged in)
511 kwds = self._html_search_meta('keywords', webpage, default=None)
513 tags = [x for x in kwds.split(',') if x]
515 # find in json (logged in)
516 tags = traverse_obj(api_data, ('tag', 'items', ..., 'name'))
518 thumb_prefs = qualities(['url', 'middleUrl', 'largeUrl', 'player', 'ogp'])
520 def get_video_info(*items, get_first=True, **kwargs):
521 return traverse_obj(api_data, ('video', *items), get_all=not get_first, **kwargs)
525 '_api_data': api_data,
526 'title': get_video_info(('originalTitle', 'title')) or self._og_search_title(webpage, default=None),
528 'availability': availability,
533 'preference': thumb_prefs(key),
534 **parse_resolution(url, lenient=True),
535 } for key, url in (get_video_info('thumbnail') or {}).items() if url],
536 'description': clean_html(get_video_info('description')),
537 'uploader': traverse_obj(api_data, ('owner', 'nickname'), ('channel', 'name'), ('community', 'name')),
538 'uploader_id': str_or_none(traverse_obj(api_data, ('owner', 'id'), ('channel', 'id'), ('community', 'id'))),
539 'timestamp': parse_iso8601(get_video_info('registeredAt')) or parse_iso8601(
540 self._html_search_meta('video:release_date', webpage, 'date published', default=None)),
541 'channel': traverse_obj(api_data, ('channel', 'name'), ('community', 'name')),
542 'channel_id': traverse_obj(api_data, ('channel', 'id'), ('community', 'id')),
543 'view_count': int_or_none(get_video_info('count', 'view')),
545 'genre': traverse_obj(api_data, ('genre', 'label'), ('genre', 'key')),
546 'comment_count': get_video_info('count', 'comment', expected_type=int),
548 parse_duration(self._html_search_meta('video:duration', webpage, 'video duration', default=None))
549 or get_video_info('duration')),
550 'webpage_url': url_or_none(url) or f'https://www.nicovideo.jp/watch/{video_id}',
551 'subtitles': self.extract_subtitles(video_id, api_data),
554 def _get_subtitles(self, video_id, api_data):
555 comments_info = traverse_obj(api_data, ('comment', 'nvComment', {dict})) or {}
556 if not comments_info.get('server'):
559 danmaku = traverse_obj(self._download_json(
560 f'{comments_info["server"]}/v1/threads', video_id, data=json.dumps({
562 'params': comments_info.get('params'),
563 'threadKey': comments_info.get('threadKey'),
564 }).encode(), fatal=False,
566 'Referer': 'https://www.nicovideo.jp/',
567 'Origin': 'https://www.nicovideo.jp',
568 'Content-Type': 'text/plain;charset=UTF-8',
569 'x-client-os-type': 'others',
570 'x-frontend-id': '6',
571 'x-frontend-version': '0',
573 note='Downloading comments', errnote='Failed to download comments'),
574 ('data', 'threads', ..., 'comments', ...))
579 'data': json.dumps(danmaku),
584 class NiconicoPlaylistBaseIE(InfoExtractor):
588 'X-Frontend-ID': '6',
589 'X-Frontend-Version': '0',
590 'X-Niconico-Language': 'en-us'
593 def _call_api(self, list_id, resource, query):
594 raise NotImplementedError('Must be implemented in subclasses')
597 def _parse_owner(item):
599 'uploader': traverse_obj(item, ('owner', 'name')),
600 'uploader_id': traverse_obj(item, ('owner', 'id')),
603 def _fetch_page(self, list_id, page):
605 resp = self._call_api(list_id, 'page %d' % page, {
607 'pageSize': self._PAGE_SIZE,
609 # this is needed to support both mylist and user
610 for video in traverse_obj(resp, ('items', ..., ('video', None))) or []:
611 video_id = video.get('id')
613 # skip {"video": {"id": "blablabla", ...}}
615 count = video.get('count') or {}
616 get_count = lambda x: int_or_none(count.get(x))
620 'title': video.get('title'),
621 'url': f'https://www.nicovideo.jp/watch/{video_id}',
622 'description': video.get('shortDescription'),
623 'duration': int_or_none(video.get('duration')),
624 'view_count': get_count('view'),
625 'comment_count': get_count('comment'),
626 'thumbnail': traverse_obj(video, ('thumbnail', ('nHdUrl', 'largeUrl', 'listingUrl', 'url'))),
627 'ie_key': NiconicoIE.ie_key(),
628 **self._parse_owner(video),
631 def _entries(self, list_id):
632 return OnDemandPagedList(functools.partial(self._fetch_page, list_id), self._PAGE_SIZE)
635 class NiconicoPlaylistIE(NiconicoPlaylistBaseIE):
636 IE_NAME = 'niconico:playlist'
637 _VALID_URL = r'https?://(?:(?:www\.|sp\.)?nicovideo\.jp|nico\.ms)/(?:user/\d+/)?(?:my/)?mylist/(?:#/)?(?P<id>\d+)'
640 'url': 'http://www.nicovideo.jp/mylist/27411728',
643 'title': 'AKB48のオールナイトニッポン',
644 'description': 'md5:d89694c5ded4b6c693dea2db6e41aa08',
646 'uploader_id': '805442',
648 'playlist_mincount': 291,
650 'url': 'https://www.nicovideo.jp/user/805442/mylist/27411728',
651 'only_matching': True,
653 'url': 'https://www.nicovideo.jp/my/mylist/#/68048635',
654 'only_matching': True,
657 def _call_api(self, list_id, resource, query):
658 return self._download_json(
659 f'https://nvapi.nicovideo.jp/v2/mylists/{list_id}', list_id,
660 f'Downloading {resource}', query=query,
661 headers=self._API_HEADERS)['data']['mylist']
663 def _real_extract(self, url):
664 list_id = self._match_id(url)
665 mylist = self._call_api(list_id, 'list', {
668 return self.playlist_result(
669 self._entries(list_id), list_id,
670 mylist.get('name'), mylist.get('description'), **self._parse_owner(mylist))
673 class NiconicoSeriesIE(InfoExtractor):
674 IE_NAME = 'niconico:series'
675 _VALID_URL = r'https?://(?:(?:www\.|sp\.)?nicovideo\.jp(?:/user/\d+)?|nico\.ms)/series/(?P<id>\d+)'
678 'url': 'https://www.nicovideo.jp/user/44113208/series/110226',
681 'title': 'ご立派ァ!のシリーズ',
683 'playlist_mincount': 10,
685 'url': 'https://www.nicovideo.jp/series/12312/',
688 'title': 'バトルスピリッツ お勧めカード紹介(調整中)',
690 'playlist_mincount': 103,
692 'url': 'https://nico.ms/series/203559',
693 'only_matching': True,
696 def _real_extract(self, url):
697 list_id = self._match_id(url)
698 webpage = self._download_webpage(url, list_id)
700 title = self._search_regex(
702 r'<div class="TwitterShareButton
"\s+data-text="(.+)\s
+https
:'),
703 webpage, 'title
', fatal=False)
705 title = unescapeHTML(title)
706 json_data = next(self._yield_json_ld(webpage, None, fatal=False))
707 return self.playlist_from_matches(
708 traverse_obj(json_data, ('itemListElement
', ..., 'url
')), list_id, title, ie=NiconicoIE)
711 class NiconicoHistoryIE(NiconicoPlaylistBaseIE):
712 IE_NAME = 'niconico
:history
'
713 IE_DESC = 'NicoNico user history
or likes
. Requires cookies
.'
714 _VALID_URL = r'https?
://(?
:www\
.|sp\
.)?nicovideo\
.jp
/my
/(?P
<id>history(?
:/like
)?
)'
717 'note
': 'PC page
, with /video
',
718 'url
': 'https
://www
.nicovideo
.jp
/my
/history
/video
',
719 'only_matching
': True,
721 'note
': 'PC page
, without
/video
',
722 'url
': 'https
://www
.nicovideo
.jp
/my
/history
',
723 'only_matching
': True,
725 'note
': 'mobile page
, with /video
',
726 'url
': 'https
://sp
.nicovideo
.jp
/my
/history
/video
',
727 'only_matching
': True,
729 'note
': 'mobile page
, without
/video
',
730 'url
': 'https
://sp
.nicovideo
.jp
/my
/history
',
731 'only_matching
': True,
734 'url
': 'https
://www
.nicovideo
.jp
/my
/history
/like
',
735 'only_matching
': True,
737 'note
': 'Mobile page
',
738 'url
': 'https
://sp
.nicovideo
.jp
/my
/history
/like
',
739 'only_matching
': True,
742 def _call_api(self, list_id, resource, query):
743 path = 'likes
' if list_id == 'history
/like
' else 'watch
/history
'
744 return self._download_json(
745 f'https
://nvapi
.nicovideo
.jp
/v1
/users
/me
/{path}
', list_id,
746 f'Downloading {resource}
', query=query, headers=self._API_HEADERS)['data
']
748 def _real_extract(self, url):
749 list_id = self._match_id(url)
751 mylist = self._call_api(list_id, 'list', {'pageSize': 1})
752 except ExtractorError as e:
753 if isinstance(e.cause, HTTPError) and e.cause.status == 401:
754 self.raise_login_required('You have to be logged
in to get your history
')
756 return self.playlist_result(self._entries(list_id), list_id, **self._parse_owner(mylist))
759 class NicovideoSearchBaseIE(InfoExtractor):
760 _SEARCH_TYPE = 'search
'
762 def _entries(self, url, item_id, query=None, note='Downloading page
%(page)s'):
764 pages = [query['page
']] if 'page
' in query else itertools.count(1)
765 for page_num in pages:
766 query['page
'] = str(page_num)
767 webpage = self._download_webpage(url, item_id, query=query, note=note % {'page': page_num})
768 results = re.findall(r'(?
<=data
-video
-id=)["\']?(?P<videoid>.*?)(?=["\'])', webpage)
770 yield self.url_result(f'https
://www
.nicovideo
.jp
/watch
/{item}
', 'Niconico
', item)
774 def _search_results(self, query):
775 return self._entries(
776 self._proto_relative_url(f'//www
.nicovideo
.jp
/{self._SEARCH_TYPE}
/{query}
'), query)
779 class NicovideoSearchIE(NicovideoSearchBaseIE, SearchInfoExtractor):
780 IE_DESC = 'Nico video search
'
781 IE_NAME = 'nicovideo
:search
'
782 _SEARCH_KEY = 'nicosearch
'
785 class NicovideoSearchURLIE(NicovideoSearchBaseIE):
786 IE_NAME = f'{NicovideoSearchIE.IE_NAME}_url
'
787 IE_DESC = 'Nico video search URLs
'
788 _VALID_URL = r'https?
://(?
:www\
.)?nicovideo\
.jp
/search
/(?P
<id>[^?
#&]+)?'
790 'url': 'http://www.nicovideo.jp/search/sm9',
795 'playlist_mincount': 40,
797 'url': 'https://www.nicovideo.jp/search/sm9?sort=h&order=d&end=2020-12-31&start=2020-01-01',
802 'playlist_count': 31,
805 def _real_extract(self
, url
):
806 query
= self
._match
_id
(url
)
807 return self
.playlist_result(self
._entries
(url
, query
), query
, query
)
810 class NicovideoSearchDateIE(NicovideoSearchBaseIE
, SearchInfoExtractor
):
811 IE_DESC
= 'Nico video search, newest first'
812 IE_NAME
= f
'{NicovideoSearchIE.IE_NAME}:date'
813 _SEARCH_KEY
= 'nicosearchdate'
815 'url': 'nicosearchdateall:a',
820 'playlist_mincount': 1610,
823 _START_DATE
= datetime
.date(2007, 1, 1)
824 _RESULTS_PER_PAGE
= 32
827 def _entries(self
, url
, item_id
, start_date
=None, end_date
=None):
828 start_date
, end_date
= start_date
or self
._START
_DATE
, end_date
or datetime
.datetime
.now().date()
830 # If the last page has a full page of videos, we need to break down the query interval further
831 last_page_len
= len(list(self
._get
_entries
_for
_date
(
832 url
, item_id
, start_date
, end_date
, self
._MAX
_PAGES
,
833 note
=f
'Checking number of videos from {start_date} to {end_date}')))
834 if (last_page_len
== self
._RESULTS
_PER
_PAGE
and start_date
!= end_date
):
835 midpoint
= start_date
+ ((end_date
- start_date
) // 2)
836 yield from self
._entries
(url
, item_id
, midpoint
, end_date
)
837 yield from self
._entries
(url
, item_id
, start_date
, midpoint
)
839 self
.to_screen(f
'{item_id}: Downloading results from {start_date} to {end_date}')
840 yield from self
._get
_entries
_for
_date
(
841 url
, item_id
, start_date
, end_date
, note
=' Downloading page %(page)s')
843 def _get_entries_for_date(self
, url
, item_id
, start_date
, end_date
=None, page_num
=None, note
=None):
845 'start': str(start_date
),
846 'end': str(end_date
or start_date
),
851 query
['page'] = str(page_num
)
853 yield from super()._entries
(url
, item_id
, query
=query
, note
=note
)
856 class NicovideoTagURLIE(NicovideoSearchBaseIE
):
857 IE_NAME
= 'niconico:tag'
858 IE_DESC
= 'NicoNico video tag URLs'
860 _VALID_URL
= r
'https?://(?:www\.)?nicovideo\.jp/tag/(?P<id>[^?#&]+)?'
862 'url': 'https://www.nicovideo.jp/tag/ドキュメンタリー淫夢',
865 'title': 'ドキュメンタリー淫夢'
867 'playlist_mincount': 400,
870 def _real_extract(self
, url
):
871 query
= self
._match
_id
(url
)
872 return self
.playlist_result(self
._entries
(url
, query
), query
, query
)
875 class NiconicoUserIE(InfoExtractor
):
876 _VALID_URL
= r
'https?://(?:www\.)?nicovideo\.jp/user/(?P<id>\d+)/?(?:$|[#?])'
878 'url': 'https://www.nicovideo.jp/user/419948',
882 'playlist_mincount': 101,
884 _API_URL
= "https://nvapi.nicovideo.jp/v1/users/%s/videos?sortKey=registeredAt&sortOrder=desc&pageSize=%s&page=%s"
888 'X-Frontend-ID': '6',
889 'X-Frontend-Version': '0'
892 def _entries(self
, list_id
):
895 while count
< total_count
:
896 json_parsed
= self
._download
_json
(
897 self
._API
_URL
% (list_id
, self
._PAGE
_SIZE
, page_num
+ 1), list_id
,
898 headers
=self
._API
_HEADERS
,
899 note
='Downloading JSON metadata%s' % (' page %d' % page_num
if page_num
else ''))
901 total_count
= int_or_none(json_parsed
['data'].get('totalCount'))
902 for entry
in json_parsed
["data"]["items"]:
904 yield self
.url_result('https://www.nicovideo.jp/watch/%s' % entry
['id'])
907 def _real_extract(self
, url
):
908 list_id
= self
._match
_id
(url
)
909 return self
.playlist_result(self
._entries
(list_id
), list_id
, ie
=NiconicoIE
.ie_key())
912 class NiconicoLiveIE(InfoExtractor
):
913 IE_NAME
= 'niconico:live'
915 _VALID_URL
= r
'https?://(?:sp\.)?live2?\.nicovideo\.jp/(?:watch|gate)/(?P<id>lv\d+)'
917 'note': 'this test case includes invisible characters for title, pasting them as-is',
918 'url': 'https://live.nicovideo.jp/watch/lv339533123',
921 'title': '激辛ペヤング食べます( ;ᯅ; )(歌枠オーディション参加中)',
923 'comment_count': 1772,
924 'description': '初めましてもかって言います❕\nのんびり自由に適当に暮らしてます',
926 'channel': 'ゲストさんのコミュニティ',
927 'channel_id': 'co5776900',
928 'channel_url': 'https://com.nicovideo.jp/community/co5776900',
929 'timestamp': 1670677328,
932 'skip': 'livestream',
934 'url': 'https://live2.nicovideo.jp/watch/lv339533123',
935 'only_matching': True,
937 'url': 'https://sp.live.nicovideo.jp/watch/lv339533123',
938 'only_matching': True,
940 'url': 'https://sp.live2.nicovideo.jp/watch/lv339533123',
941 'only_matching': True,
944 _KNOWN_LATENCY
= ('high', 'low')
946 def _real_extract(self
, url
):
947 video_id
= self
._match
_id
(url
)
948 webpage
, urlh
= self
._download
_webpage
_handle
(f
'https://live.nicovideo.jp/watch/{video_id}', video_id
)
950 embedded_data
= self
._parse
_json
(unescapeHTML(self
._search
_regex
(
951 r
'<script\s+id="embedded-data"\s*data-props="(.+?)"', webpage
, 'embedded data')), video_id
)
953 ws_url
= traverse_obj(embedded_data
, ('site', 'relive', 'webSocketUrl'))
955 raise ExtractorError('The live hasn\'t started yet or already ended.', expected
=True)
956 ws_url
= update_url_query(ws_url
, {
957 'frontend_id': traverse_obj(embedded_data
, ('site', 'frontendId')) or '9',
960 hostname
= remove_start(urlparse(urlh
.url
).hostname
, 'sp.')
961 latency
= try_get(self
._configuration
_arg
('latency'), lambda x
: x
[0])
962 if latency
not in self
._KNOWN
_LATENCY
:
965 ws
= self
._request
_webpage
(
966 Request(ws_url
, headers
={'Origin': f'https://{hostname}
'}),
967 video_id=video_id, note='Connecting to WebSocket server
')
969 self.write_debug('[debug
] Sending HLS server request
')
971 'type': 'startWatching
',
975 'protocol
': 'hls
+fmp4
',
980 'protocol
': 'webSocket
',
991 data = json.loads(recv)
992 if not isinstance(data, dict):
994 if data.get('type') == 'stream
':
995 m3u8_url = data['data
']['uri
']
996 qualities = data['data
']['availableQualities
']
998 elif data.get('type') == 'disconnect
':
999 self.write_debug(recv)
1000 raise ExtractorError('Disconnected at middle of extraction
')
1001 elif data.get('type') == 'error
':
1002 self.write_debug(recv)
1003 message = traverse_obj(data, ('body
', 'code
')) or recv
1004 raise ExtractorError(message)
1005 elif self.get_param('verbose
', False):
1007 recv = recv[:100] + '...'
1008 self.write_debug('Server said
: %s' % recv)
1010 title = traverse_obj(embedded_data, ('program
', 'title
')) or self._html_search_meta(
1011 ('og
:title
', 'twitter
:title
'), webpage, 'live title
', fatal=False)
1013 raw_thumbs = traverse_obj(embedded_data, ('program
', 'thumbnail
')) or {}
1015 for name, value in raw_thumbs.items():
1016 if not isinstance(value, dict):
1020 **parse_resolution(value, lenient=True),
1024 for k, img_url in value.items():
1025 res = parse_resolution(k, lenient=True) or parse_resolution(img_url, lenient=True)
1026 width, height = res.get('width
'), res.get('height
')
1029 'id': f'{name}_{width}x{height}
',
1034 formats = self._extract_m3u8_formats(m3u8_url, video_id, ext='mp4
', live=True)
1035 for fmt, q in zip(formats, reversed(qualities[1:])):
1038 'protocol
': 'niconico_live
',
1040 'video_id
': video_id,
1041 'live_latency
': latency,
1048 **traverse_obj(embedded_data, {
1049 'view_count
': ('program
', 'statistics
', 'watchCount
'),
1050 'comment_count
': ('program
', 'statistics
', 'commentCount
'),
1051 'uploader
': ('program
', 'supplier
', 'name
'),
1052 'channel
': ('socialGroup
', 'name
'),
1053 'channel_id
': ('socialGroup
', 'id'),
1054 'channel_url
': ('socialGroup
', 'socialGroupPageUrl
'),
1056 'description
': clean_html(traverse_obj(embedded_data, ('program
', 'description
'))),
1057 'timestamp
': int_or_none(traverse_obj(embedded_data, ('program
', 'openTime
'))),
1059 'thumbnails
': thumbnails,