8 from .common
import InfoExtractor
, SearchInfoExtractor
37 class NiconicoIE(InfoExtractor
):
42 'url': 'http://www.nicovideo.jp/watch/sm22312215',
43 'md5': 'd1a75c0823e2f629128c43e1212760f9',
47 'title': 'Big Buck Bunny',
48 'thumbnail': r
're:https?://.*',
49 'uploader': 'takuya0301',
50 'uploader_id': '2698420',
51 'upload_date': '20131123',
52 'timestamp': int, # timestamp is unstable
53 'description': '(c) copyright 2008, Blender Foundation / www.bigbuckbunny.org',
58 'skip': 'Requires an account',
60 # File downloaded with and without credentials are different, so omit
62 'url': 'http://www.nicovideo.jp/watch/nm14296458',
66 'title': '【鏡音リン】Dance on media【オリジナル】take2!',
67 'description': 'md5:689f066d74610b3b22e0f1739add0f58',
68 'thumbnail': r
're:https?://.*',
70 'uploader_id': '18822557',
71 'upload_date': '20110429',
72 'timestamp': 1304065916,
75 'skip': 'Requires an account',
77 # 'video exists but is marked as "deleted"
79 'url': 'http://www.nicovideo.jp/watch/sm10000',
82 'ext': 'unknown_video',
83 'description': 'deleted',
84 'title': 'ドラえもんエターナル第3話「決戦第3新東京市」<前編>',
85 'thumbnail': r
're:https?://.*',
86 'upload_date': '20071224',
87 'timestamp': int, # timestamp field has different value if logged in
91 'skip': 'Requires an account',
93 'url': 'http://www.nicovideo.jp/watch/so22543406',
97 'title': '【第1回】RADIOアニメロミックス ラブライブ!~のぞえりRadio Garden~',
98 'description': 'md5:b27d224bb0ff53d3c8269e9f8b561cf1',
99 'thumbnail': r
're:https?://.*',
100 'timestamp': 1388851200,
101 'upload_date': '20140104',
102 'uploader': 'アニメロチャンネル',
103 'uploader_id': '312',
105 'skip': 'The viewing period of the video you were searching for has expired.',
107 # video not available via `getflv`; "old" HTML5 video
108 'url': 'http://www.nicovideo.jp/watch/sm1151009',
109 'md5': '8fa81c364eb619d4085354eab075598a',
113 'title': 'マスターシステム本体内蔵のスペハリのメインテーマ(PSG版)',
114 'description': 'md5:6ee077e0581ff5019773e2e714cdd0b7',
115 'thumbnail': r
're:https?://.*',
117 'timestamp': 1190868283,
118 'upload_date': '20070927',
119 'uploader': 'denden2',
120 'uploader_id': '1392194',
122 'comment_count': int,
124 'skip': 'Requires an account',
128 'url': 'http://www.nicovideo.jp/watch/sm31464864',
132 'title': '新作TVアニメ「戦姫絶唱シンフォギアAXZ」PV 最高画質',
133 'description': 'md5:e52974af9a96e739196b2c1ca72b5feb',
134 'timestamp': 1498514060,
135 'upload_date': '20170626',
137 'uploader_id': '40826363',
138 'thumbnail': r
're:https?://.*',
141 'comment_count': int,
143 'skip': 'Requires an account',
145 # Video without owner
146 'url': 'http://www.nicovideo.jp/watch/sm18238488',
147 'md5': 'd265680a1f92bdcbbd2a507fc9e78a9e',
151 'title': '【実写版】ミュータントタートルズ',
152 'description': 'md5:15df8988e47a86f9e978af2064bf6d8e',
153 'timestamp': 1341160408,
154 'upload_date': '20120701',
157 'thumbnail': r
're:https?://.*',
160 'comment_count': int,
162 'skip': 'Requires an account',
164 'url': 'http://sp.nicovideo.jp/watch/sm28964488?ss_pos=1&cp_in=wt_tg',
165 'only_matching': True,
167 'note': 'a video that is only served as an ENCRYPTED HLS.',
168 'url': 'https://www.nicovideo.jp/watch/so38016254',
169 'only_matching': True,
172 _VALID_URL
= r
'https?://(?:(?:www\.|secure\.|sp\.)?nicovideo\.jp/watch|nico\.ms)/(?P<id>(?:[a-z]{2})?[0-9]+)'
173 _NETRC_MACHINE
= 'niconico'
174 _COMMENT_API_ENDPOINTS
= (
175 'https://nvcomment.nicovideo.jp/legacy/api.json',
176 'https://nmsg.nicovideo.jp/api.json',)
178 'X-Frontend-ID': '6',
179 'X-Frontend-Version': '0',
180 'X-Niconico-Language': 'en-us',
181 'Referer': 'https://www.nicovideo.jp/',
182 'Origin': 'https://www.nicovideo.jp',
185 def _perform_login(self
, username
, password
):
188 'mail_tel': username
,
189 'password': password
,
191 self
._request
_webpage
(
192 'https://account.nicovideo.jp/login', None,
193 note
='Acquiring Login session')
194 page
= self
._download
_webpage
(
195 'https://account.nicovideo.jp/login/redirector?show_button_twitter=1&site=niconico&show_button_facebook=1', None,
196 note
='Logging in', errnote
='Unable to log in',
197 data
=urlencode_postdata(login_form_strs
),
199 'Referer': 'https://account.nicovideo.jp/login',
200 'Content-Type': 'application/x-www-form-urlencoded',
202 if 'oneTimePw' in page
:
203 post_url
= self
._search
_regex
(
204 r
'<form[^>]+action=(["\'])(?P
<url
>.+?
)\
1', page, 'post url
', group='url
')
205 page = self._download_webpage(
206 urljoin('https
://account
.nicovideo
.jp
', post_url), None,
207 note='Performing MFA
', errnote='Unable to complete MFA
',
208 data=urlencode_postdata({
209 'otp
': self._get_tfa_info('6 digits code
')
211 'Content
-Type
': 'application
/x
-www
-form
-urlencoded
',
213 if 'oneTimePw
' in page or 'formError
' in page:
214 err_msg = self._html_search_regex(
215 r'formError
["\']+>(.*?)</div>', page, 'form_error',
216 default='There\'s an error but the message can\'t be parsed.',
218 self.report_warning(f'Unable to log in: MFA challenge failed, "{err_msg}
"')
220 login_ok = 'class="notice error
"' not in page
222 self.report_warning('Unable to log in: bad username or password')
225 def _get_heartbeat_info(self, info_dict):
226 video_id, video_src_id, audio_src_id = info_dict['url'].split(':')[1].split('/')
227 dmc_protocol = info_dict['expected_protocol']
230 info_dict.get('_api_data')
232 self._html_search_regex(
233 'data-api-data="([^
"]+)"',
234 self._download_webpage('https
://www
.nicovideo
.jp
/watch
/' + video_id, video_id),
235 'API data
', default='{}'),
238 session_api_data = try_get(api_data, lambda x: x['media
']['delivery
']['movie
']['session
'])
239 session_api_endpoint = try_get(session_api_data, lambda x: x['urls
'][0])
242 tracking_id = traverse_obj(api_data, ('media
', 'delivery
', 'trackingId
'))
244 tracking_url = update_url_query('https
://nvapi
.nicovideo
.jp
/v1
/2ab0cbaa
/watch
', {'t': tracking_id})
245 watch_request_response = self._download_json(
246 tracking_url, video_id,
247 note='Acquiring permission
for downloading video
', fatal=False,
248 headers=self._API_HEADERS)
249 if traverse_obj(watch_request_response, ('meta
', 'status
')) != 200:
250 self.report_warning('Failed to acquire permission
for playing video
. Video download may fail
.')
252 yesno = lambda x: 'yes
' if x else 'no
'
254 if dmc_protocol == 'http
':
256 protocol_parameters = {
257 'http_output_download_parameters
': {
258 'use_ssl
': yesno(session_api_data['urls
'][0]['isSsl
']),
259 'use_well_known_port
': yesno(session_api_data['urls
'][0]['isWellKnownPort
']),
262 elif dmc_protocol == 'hls
':
264 segment_duration = try_get(self._configuration_arg('segment_duration
'), lambda x: int(x[0])) or 6000
265 parsed_token = self._parse_json(session_api_data['token
'], video_id)
266 encryption = traverse_obj(api_data, ('media
', 'delivery
', 'encryption
'))
267 protocol_parameters = {
269 'segment_duration
': segment_duration,
270 'transfer_preset
': '',
271 'use_ssl
': yesno(session_api_data['urls
'][0]['isSsl
']),
272 'use_well_known_port
': yesno(session_api_data['urls
'][0]['isWellKnownPort
']),
275 if 'hls_encryption
' in parsed_token and encryption:
276 protocol_parameters['hls_parameters
']['encryption
'] = {
277 parsed_token['hls_encryption
']: {
278 'encrypted_key
': encryption['encryptedKey
'],
279 'key_uri
': encryption['keyUri
'],
283 protocol = 'm3u8_native
'
285 raise ExtractorError(f'Unsupported DMC protocol
: {dmc_protocol}
')
287 session_response = self._download_json(
288 session_api_endpoint['url
'], video_id,
289 query={'_format': 'json'},
290 headers={'Content-Type': 'application/json'},
291 note='Downloading JSON metadata
for %s' % info_dict['format_id
'],
295 'player_id
': session_api_data.get('playerId
'),
298 'auth_type
': try_get(session_api_data, lambda x: x['authTypes
'][session_api_data['protocols
'][0]]),
299 'content_key_timeout
': session_api_data.get('contentKeyTimeout
'),
300 'service_id
': 'nicovideo
',
301 'service_user_id
': session_api_data.get('serviceUserId
')
303 'content_id
': session_api_data.get('contentId
'),
304 'content_src_id_sets
': [{
305 'content_src_ids
': [{
307 'audio_src_ids
': [audio_src_id],
308 'video_src_ids
': [video_src_id],
312 'content_type
': 'movie
',
316 'lifetime
': session_api_data.get('heartbeatLifetime
')
319 'priority
': session_api_data['priority
'],
324 'parameters
': protocol_parameters
328 'recipe_id
': session_api_data.get('recipeId
'),
329 'session_operation_auth
': {
330 'session_operation_auth_by_signature
': {
331 'signature
': session_api_data.get('signature
'),
332 'token
': session_api_data.get('token
'),
335 'timing_constraint
': 'unlimited
'
339 info_dict['url
'] = session_response['data
']['session
']['content_uri
']
340 info_dict['protocol
'] = protocol
343 heartbeat_info_dict = {
344 'url
': session_api_endpoint['url
'] + '/' + session_response['data
']['session
']['id'] + '?_format
=json
&_method
=PUT
',
345 'data
': json.dumps(session_response['data
']),
346 # interval, convert milliseconds to seconds, then halve to make a buffer.
347 'interval
': float_or_none(session_api_data.get('heartbeatLifetime
'), scale=3000),
351 return info_dict, heartbeat_info_dict
353 def _extract_format_for_quality(self, video_id, audio_quality, video_quality, dmc_protocol):
355 if not audio_quality.get('isAvailable
') or not video_quality.get('isAvailable
'):
358 def extract_video_quality(video_quality):
359 return parse_filesize('%sB
' % self._search_regex(
360 r'\|
([0-9]*\
.?
[0-9]*[MK
])', video_quality, 'vbr
', default=''))
362 format_id = '-'.join(
363 [remove_start(s['id'], 'archive_
') for s in (video_quality, audio_quality)] + [dmc_protocol])
365 vid_qual_label = traverse_obj(video_quality, ('metadata
', 'label
'))
366 vid_quality = traverse_obj(video_quality, ('metadata
', 'bitrate
'))
369 'url
': 'niconico_dmc
:%s/%s/%s' % (video_id, video_quality['id'], audio_quality['id']),
370 'format_id
': format_id,
371 'format_note
': join_nonempty('DMC
', vid_qual_label, dmc_protocol.upper(), delim=' '),
372 'ext
': 'mp4
', # Session API are used in HTML5, which always serves mp4
375 'abr
': float_or_none(traverse_obj(audio_quality, ('metadata
', 'bitrate
')), 1000),
376 'vbr
': float_or_none(vid_quality if vid_quality > 0 else extract_video_quality(vid_qual_label), 1000),
377 'height
': traverse_obj(video_quality, ('metadata
', 'resolution
', 'height
')),
378 'width
': traverse_obj(video_quality, ('metadata
', 'resolution
', 'width
')),
379 'quality
': -2 if 'low
' in video_quality['id'] else None,
380 'protocol
': 'niconico_dmc
',
381 'expected_protocol
': dmc_protocol, # XXX: This is not a documented field
383 'Origin
': 'https
://www
.nicovideo
.jp
',
384 'Referer
': 'https
://www
.nicovideo
.jp
/watch
/' + video_id,
388 def _real_extract(self, url):
389 video_id = self._match_id(url)
392 webpage, handle = self._download_webpage_handle(
393 'https
://www
.nicovideo
.jp
/watch
/' + video_id, video_id)
394 if video_id.startswith('so
'):
395 video_id = self._match_id(handle.geturl())
397 api_data = self._parse_json(self._html_search_regex(
398 'data
-api
-data
="([^"]+)"', webpage,
399 'API data', default='{}'), video_id)
400 except ExtractorError as e:
402 api_data = self._download_json(
403 'https://www.nicovideo.jp/api/watch/v3/%s?_frontendId=6&_frontendVersion=0&actionTrackId=AAAAAAAAAA_%d' % (video_id, round(time.time() * 1000)), video_id,
404 note='Downloading API JSON', errnote='Unable to fetch data')['data']
405 except ExtractorError:
406 if not isinstance(e.cause, compat_HTTPError):
408 webpage = e.cause.read().decode('utf-8', 'replace')
409 error_msg = self._html_search_regex(
410 r'(?s)<section\s+class="(?
:(?
:ErrorMessage|WatchExceptionPage
-message
)\s
*)+">(.+?)</section>',
411 webpage, 'error reason', default=None)
414 raise ExtractorError(re.sub(r'\s+', ' ', error_msg), expected=True)
418 def get_video_info(*items, get_first=True, **kwargs):
419 return traverse_obj(api_data, ('video', *items), get_all=not get_first, **kwargs)
421 quality_info = api_data['media']['delivery']['movie']
422 session_api_data = quality_info['session']
423 for (audio_quality, video_quality, protocol) in itertools.product(quality_info['audios'], quality_info['videos'], session_api_data['protocols']):
424 fmt = self._extract_format_for_quality(video_id, audio_quality, video_quality, protocol)
428 # Start extracting information
431 # use og:video:tag (not logged in)
432 og_video_tags = re.finditer(r'<meta\s+property="og
:video
:tag
"\s*content="(.*?
)">', webpage)
433 tags = list(filter(None, (clean_html(x.group(1)) for x in og_video_tags)))
435 # use keywords and split with comma (not logged in)
436 kwds = self._html_search_meta('keywords', webpage, default=None)
438 tags = [x for x in kwds.split(',') if x]
440 # find in json (logged in)
441 tags = traverse_obj(api_data, ('tag', 'items', ..., 'name'))
443 thumb_prefs = qualities(['url', 'middleUrl', 'largeUrl', 'player', 'ogp'])
447 '_api_data': api_data,
448 'title': get_video_info(('originalTitle', 'title')) or self._og_search_title(webpage, default=None),
454 'preference': thumb_prefs(key),
455 **parse_resolution(url, lenient=True),
456 } for key, url in (get_video_info('thumbnail') or {}).items() if url],
457 'description': clean_html(get_video_info('description')),
458 'uploader': traverse_obj(api_data, ('owner', 'nickname'), ('channel', 'name'), ('community', 'name')),
459 'uploader_id': str_or_none(traverse_obj(api_data, ('owner', 'id'), ('channel', 'id'), ('community', 'id'))),
460 'timestamp': parse_iso8601(get_video_info('registeredAt')) or parse_iso8601(
461 self._html_search_meta('video:release_date', webpage, 'date published', default=None)),
462 'channel': traverse_obj(api_data, ('channel', 'name'), ('community', 'name')),
463 'channel_id': traverse_obj(api_data, ('channel', 'id'), ('community', 'id')),
464 'view_count': int_or_none(get_video_info('count', 'view')),
466 'genre': traverse_obj(api_data, ('genre', 'label'), ('genre', 'key')),
467 'comment_count': get_video_info('count', 'comment', expected_type=int),
469 parse_duration(self._html_search_meta('video:duration', webpage, 'video duration', default=None))
470 or get_video_info('duration')),
471 'webpage_url': url_or_none(url) or f'https://www.nicovideo.jp/watch/{video_id}',
472 'subtitles': self.extract_subtitles(video_id, api_data, session_api_data),
475 def _get_subtitles(self, video_id, api_data, session_api_data):
476 comment_user_key = traverse_obj(api_data, ('comment', 'keys', 'userKey'))
477 user_id_str = session_api_data.get('serviceUserId')
479 thread_ids = traverse_obj(api_data, ('comment', 'threads', lambda _, v: v['isActive']))
480 legacy_danmaku = self._extract_legacy_comments(video_id, thread_ids, user_id_str, comment_user_key) or []
482 new_comments = traverse_obj(api_data, ('comment', 'nvComment'))
483 new_danmaku = self._extract_new_comments(
484 new_comments.get('server'), video_id,
485 new_comments.get('params'), new_comments.get('threadKey'))
487 if not legacy_danmaku and not new_danmaku:
488 self.report_warning(f'Failed to get comments. {bug_reports_message()}')
494 'data': json.dumps(legacy_danmaku + new_danmaku),
498 def _extract_legacy_comments(self, video_id, threads, user_id, user_key):
502 } if user_id and user_key else {'user_id': ''}
504 api_url = traverse_obj(threads, (..., 'server'), get_all=False)
507 post_data = [{'ping': {'content': 'rs:0'}}]
508 for i, thread in enumerate(threads):
509 thread_id = thread['id']
510 thread_fork = thread['fork']
512 post_data.append({'ping': {'content': f'ps:{i * 2}'}})
513 post_data.append({'thread': {
519 'version': '20090904',
524 post_data.append({'ping': {'content': f'pf:{i * 2}'}})
527 post_data.append({'ping': {'content': f'ps:{i * 2 + 1}'}})
528 post_data.append({'thread_leaves': {
529 # format is '<bottom of minute range>-<top of minute range>:<comments per minute>,<total last comments'
530 # unfortunately NND limits (deletes?) comment returns this way, so you're only able to grab the last 1000 per language
531 'content': '0-999999:999999,999999,nicoru:999999',
540 post_data.append({'ping': {'content': f'pf:{i * 2 + 1}'}})
542 post_data.append({'ping': {'content': 'rf:0'}})
544 return self._download_json(
545 f'{api_url}/api.json', video_id, data=json.dumps(post_data).encode(), fatal=False,
547 'Referer': f'https://www.nicovideo.jp/watch/{video_id}',
548 'Origin': 'https://www.nicovideo.jp',
549 'Content-Type': 'text/plain;charset=UTF-8',
551 note='Downloading comments', errnote=f'Failed to access endpoint {api_url}')
553 def _extract_new_comments(self, endpoint, video_id, params, thread_key):
554 comments = self._download_json(
555 f'{endpoint}/v1/threads', video_id, data=json.dumps({
558 'threadKey': thread_key,
559 }).encode(), fatal=False,
561 'Referer': 'https://www.nicovideo.jp/',
562 'Origin': 'https://www.nicovideo.jp',
563 'Content-Type': 'text/plain;charset=UTF-8',
564 'x-client-os-type': 'others',
565 'x-frontend-id': '6',
566 'x-frontend-version': '0',
568 note='Downloading comments (new)', errnote='Failed to download comments (new)')
569 return traverse_obj(comments, ('data', 'threads', ..., 'comments', ...))
572 class NiconicoPlaylistBaseIE(InfoExtractor):
576 'X-Frontend-ID': '6',
577 'X-Frontend-Version': '0',
578 'X-Niconico-Language': 'en-us'
581 def _call_api(self, list_id, resource, query):
582 raise NotImplementedError('Must be implemented in subclasses')
585 def _parse_owner(item):
587 'uploader': traverse_obj(item, ('owner', 'name')),
588 'uploader_id': traverse_obj(item, ('owner', 'id')),
591 def _fetch_page(self, list_id, page):
593 resp = self._call_api(list_id, 'page %d' % page, {
595 'pageSize': self._PAGE_SIZE,
597 # this is needed to support both mylist and user
598 for video in traverse_obj(resp, ('items', ..., ('video', None))) or []:
599 video_id = video.get('id')
601 # skip {"video": {"id": "blablabla", ...}}
603 count = video.get('count') or {}
604 get_count = lambda x: int_or_none(count.get(x))
608 'title': video.get('title'),
609 'url': f'https://www.nicovideo.jp/watch/{video_id}',
610 'description': video.get('shortDescription'),
611 'duration': int_or_none(video.get('duration')),
612 'view_count': get_count('view'),
613 'comment_count': get_count('comment'),
614 'thumbnail': traverse_obj(video, ('thumbnail', ('nHdUrl', 'largeUrl', 'listingUrl', 'url'))),
615 'ie_key': NiconicoIE.ie_key(),
616 **self._parse_owner(video),
619 def _entries(self, list_id):
620 return OnDemandPagedList(functools.partial(self._fetch_page, list_id), self._PAGE_SIZE)
623 class NiconicoPlaylistIE(NiconicoPlaylistBaseIE):
624 IE_NAME = 'niconico:playlist'
625 _VALID_URL = r'https?://(?:(?:www\.|sp\.)?nicovideo\.jp|nico\.ms)/(?:user/\d+/)?(?:my/)?mylist/(?:#/)?(?P<id>\d+)'
628 'url': 'http://www.nicovideo.jp/mylist/27411728',
631 'title': 'AKB48のオールナイトニッポン',
632 'description': 'md5:d89694c5ded4b6c693dea2db6e41aa08',
634 'uploader_id': '805442',
636 'playlist_mincount': 291,
638 'url': 'https://www.nicovideo.jp/user/805442/mylist/27411728',
639 'only_matching': True,
641 'url': 'https://www.nicovideo.jp/my/mylist/#/68048635',
642 'only_matching': True,
645 def _call_api(self, list_id, resource, query):
646 return self._download_json(
647 f'https://nvapi.nicovideo.jp/v2/mylists/{list_id}', list_id,
648 f'Downloading {resource}', query=query,
649 headers=self._API_HEADERS)['data']['mylist']
651 def _real_extract(self, url):
652 list_id = self._match_id(url)
653 mylist = self._call_api(list_id, 'list', {
656 return self.playlist_result(
657 self._entries(list_id), list_id,
658 mylist.get('name'), mylist.get('description'), **self._parse_owner(mylist))
661 class NiconicoSeriesIE(InfoExtractor):
662 IE_NAME = 'niconico:series'
663 _VALID_URL = r'https?://(?:(?:www\.|sp\.)?nicovideo\.jp(?:/user/\d+)?|nico\.ms)/series/(?P<id>\d+)'
666 'url': 'https://www.nicovideo.jp/user/44113208/series/110226',
669 'title': 'ご立派ァ!のシリーズ',
671 'playlist_mincount': 10,
673 'url': 'https://www.nicovideo.jp/series/12312/',
676 'title': 'バトルスピリッツ お勧めカード紹介(調整中)',
678 'playlist_mincount': 103,
680 'url': 'https://nico.ms/series/203559',
681 'only_matching': True,
684 def _real_extract(self, url):
685 list_id = self._match_id(url)
686 webpage = self._download_webpage(url, list_id)
688 title = self._search_regex(
690 r'<div class="TwitterShareButton
"\s+data-text="(.+)\s
+https
:'),
691 webpage, 'title
', fatal=False)
693 title = unescapeHTML(title)
694 json_data = next(self._yield_json_ld(webpage, None, fatal=False))
695 return self.playlist_from_matches(
696 traverse_obj(json_data, ('itemListElement
', ..., 'url
')), list_id, title, ie=NiconicoIE)
699 class NiconicoHistoryIE(NiconicoPlaylistBaseIE):
700 IE_NAME = 'niconico
:history
'
701 IE_DESC = 'NicoNico user history
or likes
. Requires cookies
.'
702 _VALID_URL = r'https?
://(?
:www\
.|sp\
.)?nicovideo\
.jp
/my
/(?P
<id>history(?
:/like
)?
)'
705 'note
': 'PC page
, with /video
',
706 'url
': 'https
://www
.nicovideo
.jp
/my
/history
/video
',
707 'only_matching
': True,
709 'note
': 'PC page
, without
/video
',
710 'url
': 'https
://www
.nicovideo
.jp
/my
/history
',
711 'only_matching
': True,
713 'note
': 'mobile page
, with /video
',
714 'url
': 'https
://sp
.nicovideo
.jp
/my
/history
/video
',
715 'only_matching
': True,
717 'note
': 'mobile page
, without
/video
',
718 'url
': 'https
://sp
.nicovideo
.jp
/my
/history
',
719 'only_matching
': True,
722 'url
': 'https
://www
.nicovideo
.jp
/my
/history
/like
',
723 'only_matching
': True,
725 'note
': 'Mobile page
',
726 'url
': 'https
://sp
.nicovideo
.jp
/my
/history
/like
',
727 'only_matching
': True,
730 def _call_api(self, list_id, resource, query):
731 path = 'likes
' if list_id == 'history
/like
' else 'watch
/history
'
732 return self._download_json(
733 f'https
://nvapi
.nicovideo
.jp
/v1
/users
/me
/{path}
', list_id,
734 f'Downloading {resource}
', query=query, headers=self._API_HEADERS)['data
']
736 def _real_extract(self, url):
737 list_id = self._match_id(url)
739 mylist = self._call_api(list_id, 'list', {'pageSize': 1})
740 except ExtractorError as e:
741 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
742 self.raise_login_required('You have to be logged
in to get your history
')
744 return self.playlist_result(self._entries(list_id), list_id, **self._parse_owner(mylist))
747 class NicovideoSearchBaseIE(InfoExtractor):
748 _SEARCH_TYPE = 'search
'
750 def _entries(self, url, item_id, query=None, note='Downloading page
%(page)s'):
752 pages = [query['page
']] if 'page
' in query else itertools.count(1)
753 for page_num in pages:
754 query['page
'] = str(page_num)
755 webpage = self._download_webpage(url, item_id, query=query, note=note % {'page': page_num})
756 results = re.findall(r'(?
<=data
-video
-id=)["\']?(?P<videoid>.*?)(?=["\'])', webpage)
758 yield self.url_result(f'https
://www
.nicovideo
.jp
/watch
/{item}
', 'Niconico
', item)
762 def _search_results(self, query):
763 return self._entries(
764 self._proto_relative_url(f'//www
.nicovideo
.jp
/{self._SEARCH_TYPE}
/{query}
'), query)
767 class NicovideoSearchIE(NicovideoSearchBaseIE, SearchInfoExtractor):
768 IE_DESC = 'Nico video search
'
769 IE_NAME = 'nicovideo
:search
'
770 _SEARCH_KEY = 'nicosearch
'
773 class NicovideoSearchURLIE(NicovideoSearchBaseIE):
774 IE_NAME = f'{NicovideoSearchIE.IE_NAME}_url
'
775 IE_DESC = 'Nico video search URLs
'
776 _VALID_URL = r'https?
://(?
:www\
.)?nicovideo\
.jp
/search
/(?P
<id>[^?
#&]+)?'
778 'url': 'http://www.nicovideo.jp/search/sm9',
783 'playlist_mincount': 40,
785 'url': 'https://www.nicovideo.jp/search/sm9?sort=h&order=d&end=2020-12-31&start=2020-01-01',
790 'playlist_count': 31,
793 def _real_extract(self
, url
):
794 query
= self
._match
_id
(url
)
795 return self
.playlist_result(self
._entries
(url
, query
), query
, query
)
798 class NicovideoSearchDateIE(NicovideoSearchBaseIE
, SearchInfoExtractor
):
799 IE_DESC
= 'Nico video search, newest first'
800 IE_NAME
= f
'{NicovideoSearchIE.IE_NAME}:date'
801 _SEARCH_KEY
= 'nicosearchdate'
803 'url': 'nicosearchdateall:a',
808 'playlist_mincount': 1610,
811 _START_DATE
= datetime
.date(2007, 1, 1)
812 _RESULTS_PER_PAGE
= 32
815 def _entries(self
, url
, item_id
, start_date
=None, end_date
=None):
816 start_date
, end_date
= start_date
or self
._START
_DATE
, end_date
or datetime
.datetime
.now().date()
818 # If the last page has a full page of videos, we need to break down the query interval further
819 last_page_len
= len(list(self
._get
_entries
_for
_date
(
820 url
, item_id
, start_date
, end_date
, self
._MAX
_PAGES
,
821 note
=f
'Checking number of videos from {start_date} to {end_date}')))
822 if (last_page_len
== self
._RESULTS
_PER
_PAGE
and start_date
!= end_date
):
823 midpoint
= start_date
+ ((end_date
- start_date
) // 2)
824 yield from self
._entries
(url
, item_id
, midpoint
, end_date
)
825 yield from self
._entries
(url
, item_id
, start_date
, midpoint
)
827 self
.to_screen(f
'{item_id}: Downloading results from {start_date} to {end_date}')
828 yield from self
._get
_entries
_for
_date
(
829 url
, item_id
, start_date
, end_date
, note
=' Downloading page %(page)s')
831 def _get_entries_for_date(self
, url
, item_id
, start_date
, end_date
=None, page_num
=None, note
=None):
833 'start': str(start_date
),
834 'end': str(end_date
or start_date
),
839 query
['page'] = str(page_num
)
841 yield from super()._entries
(url
, item_id
, query
=query
, note
=note
)
844 class NicovideoTagURLIE(NicovideoSearchBaseIE
):
845 IE_NAME
= 'niconico:tag'
846 IE_DESC
= 'NicoNico video tag URLs'
848 _VALID_URL
= r
'https?://(?:www\.)?nicovideo\.jp/tag/(?P<id>[^?#&]+)?'
850 'url': 'https://www.nicovideo.jp/tag/ドキュメンタリー淫夢',
853 'title': 'ドキュメンタリー淫夢'
855 'playlist_mincount': 400,
858 def _real_extract(self
, url
):
859 query
= self
._match
_id
(url
)
860 return self
.playlist_result(self
._entries
(url
, query
), query
, query
)
863 class NiconicoUserIE(InfoExtractor
):
864 _VALID_URL
= r
'https?://(?:www\.)?nicovideo\.jp/user/(?P<id>\d+)/?(?:$|[#?])'
866 'url': 'https://www.nicovideo.jp/user/419948',
870 'playlist_mincount': 101,
872 _API_URL
= "https://nvapi.nicovideo.jp/v1/users/%s/videos?sortKey=registeredAt&sortOrder=desc&pageSize=%s&page=%s"
876 'X-Frontend-ID': '6',
877 'X-Frontend-Version': '0'
880 def _entries(self
, list_id
):
883 while count
< total_count
:
884 json_parsed
= self
._download
_json
(
885 self
._API
_URL
% (list_id
, self
._PAGE
_SIZE
, page_num
+ 1), list_id
,
886 headers
=self
._API
_HEADERS
,
887 note
='Downloading JSON metadata%s' % (' page %d' % page_num
if page_num
else ''))
889 total_count
= int_or_none(json_parsed
['data'].get('totalCount'))
890 for entry
in json_parsed
["data"]["items"]:
892 yield self
.url_result('https://www.nicovideo.jp/watch/%s' % entry
['id'])
895 def _real_extract(self
, url
):
896 list_id
= self
._match
_id
(url
)
897 return self
.playlist_result(self
._entries
(list_id
), list_id
, ie
=NiconicoIE
.ie_key())