8 from urllib
.parse
import urlparse
10 from .common
import InfoExtractor
, SearchInfoExtractor
11 from ..dependencies
import websockets
12 from ..networking
.exceptions
import HTTPError
39 class NiconicoIE(InfoExtractor
):
44 'url': 'http://www.nicovideo.jp/watch/sm22312215',
45 'md5': 'd1a75c0823e2f629128c43e1212760f9',
49 'title': 'Big Buck Bunny',
50 'thumbnail': r
're:https?://.*',
51 'uploader': 'takuya0301',
52 'uploader_id': '2698420',
53 'upload_date': '20131123',
54 'timestamp': int, # timestamp is unstable
55 'description': '(c) copyright 2008, Blender Foundation / www.bigbuckbunny.org',
60 'skip': 'Requires an account',
62 # File downloaded with and without credentials are different, so omit
64 'url': 'http://www.nicovideo.jp/watch/nm14296458',
68 'title': '【鏡音リン】Dance on media【オリジナル】take2!',
69 'description': 'md5:689f066d74610b3b22e0f1739add0f58',
70 'thumbnail': r
're:https?://.*',
72 'uploader_id': '18822557',
73 'upload_date': '20110429',
74 'timestamp': 1304065916,
77 'skip': 'Requires an account',
79 # 'video exists but is marked as "deleted"
81 'url': 'http://www.nicovideo.jp/watch/sm10000',
84 'ext': 'unknown_video',
85 'description': 'deleted',
86 'title': 'ドラえもんエターナル第3話「決戦第3新東京市」<前編>',
87 'thumbnail': r
're:https?://.*',
88 'upload_date': '20071224',
89 'timestamp': int, # timestamp field has different value if logged in
93 'skip': 'Requires an account',
95 'url': 'http://www.nicovideo.jp/watch/so22543406',
99 'title': '【第1回】RADIOアニメロミックス ラブライブ!~のぞえりRadio Garden~',
100 'description': 'md5:b27d224bb0ff53d3c8269e9f8b561cf1',
101 'thumbnail': r
're:https?://.*',
102 'timestamp': 1388851200,
103 'upload_date': '20140104',
104 'uploader': 'アニメロチャンネル',
105 'uploader_id': '312',
107 'skip': 'The viewing period of the video you were searching for has expired.',
109 # video not available via `getflv`; "old" HTML5 video
110 'url': 'http://www.nicovideo.jp/watch/sm1151009',
111 'md5': '8fa81c364eb619d4085354eab075598a',
115 'title': 'マスターシステム本体内蔵のスペハリのメインテーマ(PSG版)',
116 'description': 'md5:6ee077e0581ff5019773e2e714cdd0b7',
117 'thumbnail': r
're:https?://.*',
119 'timestamp': 1190868283,
120 'upload_date': '20070927',
121 'uploader': 'denden2',
122 'uploader_id': '1392194',
124 'comment_count': int,
126 'skip': 'Requires an account',
130 'url': 'http://www.nicovideo.jp/watch/sm31464864',
134 'title': '新作TVアニメ「戦姫絶唱シンフォギアAXZ」PV 最高画質',
135 'description': 'md5:e52974af9a96e739196b2c1ca72b5feb',
136 'timestamp': 1498514060,
137 'upload_date': '20170626',
139 'uploader_id': '40826363',
140 'thumbnail': r
're:https?://.*',
143 'comment_count': int,
145 'skip': 'Requires an account',
147 # Video without owner
148 'url': 'http://www.nicovideo.jp/watch/sm18238488',
149 'md5': 'd265680a1f92bdcbbd2a507fc9e78a9e',
153 'title': '【実写版】ミュータントタートルズ',
154 'description': 'md5:15df8988e47a86f9e978af2064bf6d8e',
155 'timestamp': 1341160408,
156 'upload_date': '20120701',
159 'thumbnail': r
're:https?://.*',
162 'comment_count': int,
164 'skip': 'Requires an account',
166 'url': 'http://sp.nicovideo.jp/watch/sm28964488?ss_pos=1&cp_in=wt_tg',
167 'only_matching': True,
169 'note': 'a video that is only served as an ENCRYPTED HLS.',
170 'url': 'https://www.nicovideo.jp/watch/so38016254',
171 'only_matching': True,
174 _VALID_URL
= r
'https?://(?:(?:www\.|secure\.|sp\.)?nicovideo\.jp/watch|nico\.ms)/(?P<id>(?:[a-z]{2})?[0-9]+)'
175 _NETRC_MACHINE
= 'niconico'
176 _COMMENT_API_ENDPOINTS
= (
177 'https://nvcomment.nicovideo.jp/legacy/api.json',
178 'https://nmsg.nicovideo.jp/api.json',)
180 'X-Frontend-ID': '6',
181 'X-Frontend-Version': '0',
182 'X-Niconico-Language': 'en-us',
183 'Referer': 'https://www.nicovideo.jp/',
184 'Origin': 'https://www.nicovideo.jp',
187 def _perform_login(self
, username
, password
):
190 'mail_tel': username
,
191 'password': password
,
193 self
._request
_webpage
(
194 'https://account.nicovideo.jp/login', None,
195 note
='Acquiring Login session')
196 page
= self
._download
_webpage
(
197 'https://account.nicovideo.jp/login/redirector?show_button_twitter=1&site=niconico&show_button_facebook=1', None,
198 note
='Logging in', errnote
='Unable to log in',
199 data
=urlencode_postdata(login_form_strs
),
201 'Referer': 'https://account.nicovideo.jp/login',
202 'Content-Type': 'application/x-www-form-urlencoded',
204 if 'oneTimePw' in page
:
205 post_url
= self
._search
_regex
(
206 r
'<form[^>]+action=(["\'])(?P
<url
>.+?
)\
1', page, 'post url
', group='url
')
207 page = self._download_webpage(
208 urljoin('https
://account
.nicovideo
.jp
', post_url), None,
209 note='Performing MFA
', errnote='Unable to complete MFA
',
210 data=urlencode_postdata({
211 'otp
': self._get_tfa_info('6 digits code
')
213 'Content
-Type
': 'application
/x
-www
-form
-urlencoded
',
215 if 'oneTimePw
' in page or 'formError
' in page:
216 err_msg = self._html_search_regex(
217 r'formError
["\']+>(.*?)</div>', page, 'form_error',
218 default='There\'s an error but the message can\'t be parsed.',
220 self.report_warning(f'Unable to log in: MFA challenge failed, "{err_msg}
"')
222 login_ok = 'class="notice error
"' not in page
224 self.report_warning('Unable to log in: bad username or password')
227 def _get_heartbeat_info(self, info_dict):
228 video_id, video_src_id, audio_src_id = info_dict['url'].split(':')[1].split('/')
229 dmc_protocol = info_dict['expected_protocol']
232 info_dict.get('_api_data')
234 self._html_search_regex(
235 'data-api-data="([^
"]+)"',
236 self._download_webpage('https
://www
.nicovideo
.jp
/watch
/' + video_id, video_id),
237 'API data
', default='{}'),
240 session_api_data = try_get(api_data, lambda x: x['media
']['delivery
']['movie
']['session
'])
241 session_api_endpoint = try_get(session_api_data, lambda x: x['urls
'][0])
244 tracking_id = traverse_obj(api_data, ('media
', 'delivery
', 'trackingId
'))
246 tracking_url = update_url_query('https
://nvapi
.nicovideo
.jp
/v1
/2ab0cbaa
/watch
', {'t': tracking_id})
247 watch_request_response = self._download_json(
248 tracking_url, video_id,
249 note='Acquiring permission
for downloading video
', fatal=False,
250 headers=self._API_HEADERS)
251 if traverse_obj(watch_request_response, ('meta
', 'status
')) != 200:
252 self.report_warning('Failed to acquire permission
for playing video
. Video download may fail
.')
254 yesno = lambda x: 'yes
' if x else 'no
'
256 if dmc_protocol == 'http
':
258 protocol_parameters = {
259 'http_output_download_parameters
': {
260 'use_ssl
': yesno(session_api_data['urls
'][0]['isSsl
']),
261 'use_well_known_port
': yesno(session_api_data['urls
'][0]['isWellKnownPort
']),
264 elif dmc_protocol == 'hls
':
266 segment_duration = try_get(self._configuration_arg('segment_duration
'), lambda x: int(x[0])) or 6000
267 parsed_token = self._parse_json(session_api_data['token
'], video_id)
268 encryption = traverse_obj(api_data, ('media
', 'delivery
', 'encryption
'))
269 protocol_parameters = {
271 'segment_duration
': segment_duration,
272 'transfer_preset
': '',
273 'use_ssl
': yesno(session_api_data['urls
'][0]['isSsl
']),
274 'use_well_known_port
': yesno(session_api_data['urls
'][0]['isWellKnownPort
']),
277 if 'hls_encryption
' in parsed_token and encryption:
278 protocol_parameters['hls_parameters
']['encryption
'] = {
279 parsed_token['hls_encryption
']: {
280 'encrypted_key
': encryption['encryptedKey
'],
281 'key_uri
': encryption['keyUri
'],
285 protocol = 'm3u8_native
'
287 raise ExtractorError(f'Unsupported DMC protocol
: {dmc_protocol}
')
289 session_response = self._download_json(
290 session_api_endpoint['url
'], video_id,
291 query={'_format': 'json'},
292 headers={'Content-Type': 'application/json'},
293 note='Downloading JSON metadata
for %s' % info_dict['format_id
'],
297 'player_id
': session_api_data.get('playerId
'),
300 'auth_type
': try_get(session_api_data, lambda x: x['authTypes
'][session_api_data['protocols
'][0]]),
301 'content_key_timeout
': session_api_data.get('contentKeyTimeout
'),
302 'service_id
': 'nicovideo
',
303 'service_user_id
': session_api_data.get('serviceUserId
')
305 'content_id
': session_api_data.get('contentId
'),
306 'content_src_id_sets
': [{
307 'content_src_ids
': [{
309 'audio_src_ids
': [audio_src_id],
310 'video_src_ids
': [video_src_id],
314 'content_type
': 'movie
',
318 'lifetime
': session_api_data.get('heartbeatLifetime
')
321 'priority
': session_api_data['priority
'],
326 'parameters
': protocol_parameters
330 'recipe_id
': session_api_data.get('recipeId
'),
331 'session_operation_auth
': {
332 'session_operation_auth_by_signature
': {
333 'signature
': session_api_data.get('signature
'),
334 'token
': session_api_data.get('token
'),
337 'timing_constraint
': 'unlimited
'
341 info_dict['url
'] = session_response['data
']['session
']['content_uri
']
342 info_dict['protocol
'] = protocol
345 heartbeat_info_dict = {
346 'url
': session_api_endpoint['url
'] + '/' + session_response['data
']['session
']['id'] + '?_format
=json
&_method
=PUT
',
347 'data
': json.dumps(session_response['data
']),
348 # interval, convert milliseconds to seconds, then halve to make a buffer.
349 'interval
': float_or_none(session_api_data.get('heartbeatLifetime
'), scale=3000),
353 return info_dict, heartbeat_info_dict
355 def _extract_format_for_quality(self, video_id, audio_quality, video_quality, dmc_protocol):
357 if not audio_quality.get('isAvailable
') or not video_quality.get('isAvailable
'):
360 def extract_video_quality(video_quality):
361 return parse_filesize('%sB
' % self._search_regex(
362 r'\|
([0-9]*\
.?
[0-9]*[MK
])', video_quality, 'vbr
', default=''))
364 format_id = '-'.join(
365 [remove_start(s['id'], 'archive_
') for s in (video_quality, audio_quality)] + [dmc_protocol])
367 vid_qual_label = traverse_obj(video_quality, ('metadata
', 'label
'))
368 vid_quality = traverse_obj(video_quality, ('metadata
', 'bitrate
'))
371 'url
': 'niconico_dmc
:%s/%s/%s' % (video_id, video_quality['id'], audio_quality['id']),
372 'format_id
': format_id,
373 'format_note
': join_nonempty('DMC
', vid_qual_label, dmc_protocol.upper(), delim=' '),
374 'ext
': 'mp4
', # Session API are used in HTML5, which always serves mp4
377 'abr
': float_or_none(traverse_obj(audio_quality, ('metadata
', 'bitrate
')), 1000),
378 'vbr
': float_or_none(vid_quality if vid_quality > 0 else extract_video_quality(vid_qual_label), 1000),
379 'height
': traverse_obj(video_quality, ('metadata
', 'resolution
', 'height
')),
380 'width
': traverse_obj(video_quality, ('metadata
', 'resolution
', 'width
')),
381 'quality
': -2 if 'low
' in video_quality['id'] else None,
382 'protocol
': 'niconico_dmc
',
383 'expected_protocol
': dmc_protocol, # XXX: This is not a documented field
385 'Origin
': 'https
://www
.nicovideo
.jp
',
386 'Referer
': 'https
://www
.nicovideo
.jp
/watch
/' + video_id,
390 def _real_extract(self, url):
391 video_id = self._match_id(url)
394 webpage, handle = self._download_webpage_handle(
395 'https
://www
.nicovideo
.jp
/watch
/' + video_id, video_id)
396 if video_id.startswith('so
'):
397 video_id = self._match_id(handle.url)
399 api_data = self._parse_json(self._html_search_regex(
400 'data
-api
-data
="([^"]+)"', webpage,
401 'API data', default='{}'), video_id)
402 except ExtractorError as e:
404 api_data = self._download_json(
405 'https://www.nicovideo.jp/api/watch/v3/%s?_frontendId=6&_frontendVersion=0&actionTrackId=AAAAAAAAAA_%d' % (video_id, round(time.time() * 1000)), video_id,
406 note='Downloading API JSON', errnote='Unable to fetch data')['data']
407 except ExtractorError:
408 if not isinstance(e.cause, HTTPError):
410 webpage = e.cause.response.read().decode('utf-8', 'replace')
411 error_msg = self._html_search_regex(
412 r'(?s)<section\s+class="(?
:(?
:ErrorMessage|WatchExceptionPage
-message
)\s
*)+">(.+?)</section>',
413 webpage, 'error reason', default=None)
416 raise ExtractorError(re.sub(r'\s+', ' ', error_msg), expected=True)
420 def get_video_info(*items, get_first=True, **kwargs):
421 return traverse_obj(api_data, ('video', *items), get_all=not get_first, **kwargs)
423 quality_info = api_data['media']['delivery']['movie']
424 session_api_data = quality_info['session']
425 for (audio_quality, video_quality, protocol) in itertools.product(quality_info['audios'], quality_info['videos'], session_api_data['protocols']):
426 fmt = self._extract_format_for_quality(video_id, audio_quality, video_quality, protocol)
430 # Start extracting information
433 # use og:video:tag (not logged in)
434 og_video_tags = re.finditer(r'<meta\s+property="og
:video
:tag
"\s*content="(.*?
)">', webpage)
435 tags = list(filter(None, (clean_html(x.group(1)) for x in og_video_tags)))
437 # use keywords and split with comma (not logged in)
438 kwds = self._html_search_meta('keywords', webpage, default=None)
440 tags = [x for x in kwds.split(',') if x]
442 # find in json (logged in)
443 tags = traverse_obj(api_data, ('tag', 'items', ..., 'name'))
445 thumb_prefs = qualities(['url', 'middleUrl', 'largeUrl', 'player', 'ogp'])
449 '_api_data': api_data,
450 'title': get_video_info(('originalTitle', 'title')) or self._og_search_title(webpage, default=None),
456 'preference': thumb_prefs(key),
457 **parse_resolution(url, lenient=True),
458 } for key, url in (get_video_info('thumbnail') or {}).items() if url],
459 'description': clean_html(get_video_info('description')),
460 'uploader': traverse_obj(api_data, ('owner', 'nickname'), ('channel', 'name'), ('community', 'name')),
461 'uploader_id': str_or_none(traverse_obj(api_data, ('owner', 'id'), ('channel', 'id'), ('community', 'id'))),
462 'timestamp': parse_iso8601(get_video_info('registeredAt')) or parse_iso8601(
463 self._html_search_meta('video:release_date', webpage, 'date published', default=None)),
464 'channel': traverse_obj(api_data, ('channel', 'name'), ('community', 'name')),
465 'channel_id': traverse_obj(api_data, ('channel', 'id'), ('community', 'id')),
466 'view_count': int_or_none(get_video_info('count', 'view')),
468 'genre': traverse_obj(api_data, ('genre', 'label'), ('genre', 'key')),
469 'comment_count': get_video_info('count', 'comment', expected_type=int),
471 parse_duration(self._html_search_meta('video:duration', webpage, 'video duration', default=None))
472 or get_video_info('duration')),
473 'webpage_url': url_or_none(url) or f'https://www.nicovideo.jp/watch/{video_id}',
474 'subtitles': self.extract_subtitles(video_id, api_data, session_api_data),
477 def _get_subtitles(self, video_id, api_data, session_api_data):
478 comment_user_key = traverse_obj(api_data, ('comment', 'keys', 'userKey'))
479 user_id_str = session_api_data.get('serviceUserId')
481 thread_ids = traverse_obj(api_data, ('comment', 'threads', lambda _, v: v['isActive']))
482 legacy_danmaku = self._extract_legacy_comments(video_id, thread_ids, user_id_str, comment_user_key) or []
484 new_comments = traverse_obj(api_data, ('comment', 'nvComment'))
485 new_danmaku = self._extract_new_comments(
486 new_comments.get('server'), video_id,
487 new_comments.get('params'), new_comments.get('threadKey'))
489 if not legacy_danmaku and not new_danmaku:
490 self.report_warning(f'Failed to get comments. {bug_reports_message()}')
496 'data': json.dumps(legacy_danmaku + new_danmaku),
500 def _extract_legacy_comments(self, video_id, threads, user_id, user_key):
504 } if user_id and user_key else {'user_id': ''}
506 api_url = traverse_obj(threads, (..., 'server'), get_all=False)
509 post_data = [{'ping': {'content': 'rs:0'}}]
510 for i, thread in enumerate(threads):
511 thread_id = thread['id']
512 thread_fork = thread['fork']
514 post_data.append({'ping': {'content': f'ps:{i * 2}'}})
515 post_data.append({'thread': {
521 'version': '20090904',
526 post_data.append({'ping': {'content': f'pf:{i * 2}'}})
529 post_data.append({'ping': {'content': f'ps:{i * 2 + 1}'}})
530 post_data.append({'thread_leaves': {
531 # format is '<bottom of minute range>-<top of minute range>:<comments per minute>,<total last comments'
532 # unfortunately NND limits (deletes?) comment returns this way, so you're only able to grab the last 1000 per language
533 'content': '0-999999:999999,999999,nicoru:999999',
542 post_data.append({'ping': {'content': f'pf:{i * 2 + 1}'}})
544 post_data.append({'ping': {'content': 'rf:0'}})
546 return self._download_json(
547 f'{api_url}/api.json', video_id, data=json.dumps(post_data).encode(), fatal=False,
549 'Referer': f'https://www.nicovideo.jp/watch/{video_id}',
550 'Origin': 'https://www.nicovideo.jp',
551 'Content-Type': 'text/plain;charset=UTF-8',
553 note='Downloading comments', errnote=f'Failed to access endpoint {api_url}')
555 def _extract_new_comments(self, endpoint, video_id, params, thread_key):
556 comments = self._download_json(
557 f'{endpoint}/v1/threads', video_id, data=json.dumps({
560 'threadKey': thread_key,
561 }).encode(), fatal=False,
563 'Referer': 'https://www.nicovideo.jp/',
564 'Origin': 'https://www.nicovideo.jp',
565 'Content-Type': 'text/plain;charset=UTF-8',
566 'x-client-os-type': 'others',
567 'x-frontend-id': '6',
568 'x-frontend-version': '0',
570 note='Downloading comments (new)', errnote='Failed to download comments (new)')
571 return traverse_obj(comments, ('data', 'threads', ..., 'comments', ...))
574 class NiconicoPlaylistBaseIE(InfoExtractor):
578 'X-Frontend-ID': '6',
579 'X-Frontend-Version': '0',
580 'X-Niconico-Language': 'en-us'
583 def _call_api(self, list_id, resource, query):
584 raise NotImplementedError('Must be implemented in subclasses')
587 def _parse_owner(item):
589 'uploader': traverse_obj(item, ('owner', 'name')),
590 'uploader_id': traverse_obj(item, ('owner', 'id')),
593 def _fetch_page(self, list_id, page):
595 resp = self._call_api(list_id, 'page %d' % page, {
597 'pageSize': self._PAGE_SIZE,
599 # this is needed to support both mylist and user
600 for video in traverse_obj(resp, ('items', ..., ('video', None))) or []:
601 video_id = video.get('id')
603 # skip {"video": {"id": "blablabla", ...}}
605 count = video.get('count') or {}
606 get_count = lambda x: int_or_none(count.get(x))
610 'title': video.get('title'),
611 'url': f'https://www.nicovideo.jp/watch/{video_id}',
612 'description': video.get('shortDescription'),
613 'duration': int_or_none(video.get('duration')),
614 'view_count': get_count('view'),
615 'comment_count': get_count('comment'),
616 'thumbnail': traverse_obj(video, ('thumbnail', ('nHdUrl', 'largeUrl', 'listingUrl', 'url'))),
617 'ie_key': NiconicoIE.ie_key(),
618 **self._parse_owner(video),
621 def _entries(self, list_id):
622 return OnDemandPagedList(functools.partial(self._fetch_page, list_id), self._PAGE_SIZE)
625 class NiconicoPlaylistIE(NiconicoPlaylistBaseIE):
626 IE_NAME = 'niconico:playlist'
627 _VALID_URL = r'https?://(?:(?:www\.|sp\.)?nicovideo\.jp|nico\.ms)/(?:user/\d+/)?(?:my/)?mylist/(?:#/)?(?P<id>\d+)'
630 'url': 'http://www.nicovideo.jp/mylist/27411728',
633 'title': 'AKB48のオールナイトニッポン',
634 'description': 'md5:d89694c5ded4b6c693dea2db6e41aa08',
636 'uploader_id': '805442',
638 'playlist_mincount': 291,
640 'url': 'https://www.nicovideo.jp/user/805442/mylist/27411728',
641 'only_matching': True,
643 'url': 'https://www.nicovideo.jp/my/mylist/#/68048635',
644 'only_matching': True,
647 def _call_api(self, list_id, resource, query):
648 return self._download_json(
649 f'https://nvapi.nicovideo.jp/v2/mylists/{list_id}', list_id,
650 f'Downloading {resource}', query=query,
651 headers=self._API_HEADERS)['data']['mylist']
653 def _real_extract(self, url):
654 list_id = self._match_id(url)
655 mylist = self._call_api(list_id, 'list', {
658 return self.playlist_result(
659 self._entries(list_id), list_id,
660 mylist.get('name'), mylist.get('description'), **self._parse_owner(mylist))
663 class NiconicoSeriesIE(InfoExtractor):
664 IE_NAME = 'niconico:series'
665 _VALID_URL = r'https?://(?:(?:www\.|sp\.)?nicovideo\.jp(?:/user/\d+)?|nico\.ms)/series/(?P<id>\d+)'
668 'url': 'https://www.nicovideo.jp/user/44113208/series/110226',
671 'title': 'ご立派ァ!のシリーズ',
673 'playlist_mincount': 10,
675 'url': 'https://www.nicovideo.jp/series/12312/',
678 'title': 'バトルスピリッツ お勧めカード紹介(調整中)',
680 'playlist_mincount': 103,
682 'url': 'https://nico.ms/series/203559',
683 'only_matching': True,
686 def _real_extract(self, url):
687 list_id = self._match_id(url)
688 webpage = self._download_webpage(url, list_id)
690 title = self._search_regex(
692 r'<div class="TwitterShareButton
"\s+data-text="(.+)\s
+https
:'),
693 webpage, 'title
', fatal=False)
695 title = unescapeHTML(title)
696 json_data = next(self._yield_json_ld(webpage, None, fatal=False))
697 return self.playlist_from_matches(
698 traverse_obj(json_data, ('itemListElement
', ..., 'url
')), list_id, title, ie=NiconicoIE)
701 class NiconicoHistoryIE(NiconicoPlaylistBaseIE):
702 IE_NAME = 'niconico
:history
'
703 IE_DESC = 'NicoNico user history
or likes
. Requires cookies
.'
704 _VALID_URL = r'https?
://(?
:www\
.|sp\
.)?nicovideo\
.jp
/my
/(?P
<id>history(?
:/like
)?
)'
707 'note
': 'PC page
, with /video
',
708 'url
': 'https
://www
.nicovideo
.jp
/my
/history
/video
',
709 'only_matching
': True,
711 'note
': 'PC page
, without
/video
',
712 'url
': 'https
://www
.nicovideo
.jp
/my
/history
',
713 'only_matching
': True,
715 'note
': 'mobile page
, with /video
',
716 'url
': 'https
://sp
.nicovideo
.jp
/my
/history
/video
',
717 'only_matching
': True,
719 'note
': 'mobile page
, without
/video
',
720 'url
': 'https
://sp
.nicovideo
.jp
/my
/history
',
721 'only_matching
': True,
724 'url
': 'https
://www
.nicovideo
.jp
/my
/history
/like
',
725 'only_matching
': True,
727 'note
': 'Mobile page
',
728 'url
': 'https
://sp
.nicovideo
.jp
/my
/history
/like
',
729 'only_matching
': True,
732 def _call_api(self, list_id, resource, query):
733 path = 'likes
' if list_id == 'history
/like
' else 'watch
/history
'
734 return self._download_json(
735 f'https
://nvapi
.nicovideo
.jp
/v1
/users
/me
/{path}
', list_id,
736 f'Downloading {resource}
', query=query, headers=self._API_HEADERS)['data
']
738 def _real_extract(self, url):
739 list_id = self._match_id(url)
741 mylist = self._call_api(list_id, 'list', {'pageSize': 1})
742 except ExtractorError as e:
743 if isinstance(e.cause, HTTPError) and e.cause.status == 401:
744 self.raise_login_required('You have to be logged
in to get your history
')
746 return self.playlist_result(self._entries(list_id), list_id, **self._parse_owner(mylist))
749 class NicovideoSearchBaseIE(InfoExtractor):
750 _SEARCH_TYPE = 'search
'
752 def _entries(self, url, item_id, query=None, note='Downloading page
%(page)s'):
754 pages = [query['page
']] if 'page
' in query else itertools.count(1)
755 for page_num in pages:
756 query['page
'] = str(page_num)
757 webpage = self._download_webpage(url, item_id, query=query, note=note % {'page': page_num})
758 results = re.findall(r'(?
<=data
-video
-id=)["\']?(?P<videoid>.*?)(?=["\'])', webpage)
760 yield self.url_result(f'https
://www
.nicovideo
.jp
/watch
/{item}
', 'Niconico
', item)
764 def _search_results(self, query):
765 return self._entries(
766 self._proto_relative_url(f'//www
.nicovideo
.jp
/{self._SEARCH_TYPE}
/{query}
'), query)
769 class NicovideoSearchIE(NicovideoSearchBaseIE, SearchInfoExtractor):
770 IE_DESC = 'Nico video search
'
771 IE_NAME = 'nicovideo
:search
'
772 _SEARCH_KEY = 'nicosearch
'
775 class NicovideoSearchURLIE(NicovideoSearchBaseIE):
776 IE_NAME = f'{NicovideoSearchIE.IE_NAME}_url
'
777 IE_DESC = 'Nico video search URLs
'
778 _VALID_URL = r'https?
://(?
:www\
.)?nicovideo\
.jp
/search
/(?P
<id>[^?
#&]+)?'
780 'url': 'http://www.nicovideo.jp/search/sm9',
785 'playlist_mincount': 40,
787 'url': 'https://www.nicovideo.jp/search/sm9?sort=h&order=d&end=2020-12-31&start=2020-01-01',
792 'playlist_count': 31,
795 def _real_extract(self
, url
):
796 query
= self
._match
_id
(url
)
797 return self
.playlist_result(self
._entries
(url
, query
), query
, query
)
800 class NicovideoSearchDateIE(NicovideoSearchBaseIE
, SearchInfoExtractor
):
801 IE_DESC
= 'Nico video search, newest first'
802 IE_NAME
= f
'{NicovideoSearchIE.IE_NAME}:date'
803 _SEARCH_KEY
= 'nicosearchdate'
805 'url': 'nicosearchdateall:a',
810 'playlist_mincount': 1610,
813 _START_DATE
= datetime
.date(2007, 1, 1)
814 _RESULTS_PER_PAGE
= 32
817 def _entries(self
, url
, item_id
, start_date
=None, end_date
=None):
818 start_date
, end_date
= start_date
or self
._START
_DATE
, end_date
or datetime
.datetime
.now().date()
820 # If the last page has a full page of videos, we need to break down the query interval further
821 last_page_len
= len(list(self
._get
_entries
_for
_date
(
822 url
, item_id
, start_date
, end_date
, self
._MAX
_PAGES
,
823 note
=f
'Checking number of videos from {start_date} to {end_date}')))
824 if (last_page_len
== self
._RESULTS
_PER
_PAGE
and start_date
!= end_date
):
825 midpoint
= start_date
+ ((end_date
- start_date
) // 2)
826 yield from self
._entries
(url
, item_id
, midpoint
, end_date
)
827 yield from self
._entries
(url
, item_id
, start_date
, midpoint
)
829 self
.to_screen(f
'{item_id}: Downloading results from {start_date} to {end_date}')
830 yield from self
._get
_entries
_for
_date
(
831 url
, item_id
, start_date
, end_date
, note
=' Downloading page %(page)s')
833 def _get_entries_for_date(self
, url
, item_id
, start_date
, end_date
=None, page_num
=None, note
=None):
835 'start': str(start_date
),
836 'end': str(end_date
or start_date
),
841 query
['page'] = str(page_num
)
843 yield from super()._entries
(url
, item_id
, query
=query
, note
=note
)
846 class NicovideoTagURLIE(NicovideoSearchBaseIE
):
847 IE_NAME
= 'niconico:tag'
848 IE_DESC
= 'NicoNico video tag URLs'
850 _VALID_URL
= r
'https?://(?:www\.)?nicovideo\.jp/tag/(?P<id>[^?#&]+)?'
852 'url': 'https://www.nicovideo.jp/tag/ドキュメンタリー淫夢',
855 'title': 'ドキュメンタリー淫夢'
857 'playlist_mincount': 400,
860 def _real_extract(self
, url
):
861 query
= self
._match
_id
(url
)
862 return self
.playlist_result(self
._entries
(url
, query
), query
, query
)
865 class NiconicoUserIE(InfoExtractor
):
866 _VALID_URL
= r
'https?://(?:www\.)?nicovideo\.jp/user/(?P<id>\d+)/?(?:$|[#?])'
868 'url': 'https://www.nicovideo.jp/user/419948',
872 'playlist_mincount': 101,
874 _API_URL
= "https://nvapi.nicovideo.jp/v1/users/%s/videos?sortKey=registeredAt&sortOrder=desc&pageSize=%s&page=%s"
878 'X-Frontend-ID': '6',
879 'X-Frontend-Version': '0'
882 def _entries(self
, list_id
):
885 while count
< total_count
:
886 json_parsed
= self
._download
_json
(
887 self
._API
_URL
% (list_id
, self
._PAGE
_SIZE
, page_num
+ 1), list_id
,
888 headers
=self
._API
_HEADERS
,
889 note
='Downloading JSON metadata%s' % (' page %d' % page_num
if page_num
else ''))
891 total_count
= int_or_none(json_parsed
['data'].get('totalCount'))
892 for entry
in json_parsed
["data"]["items"]:
894 yield self
.url_result('https://www.nicovideo.jp/watch/%s' % entry
['id'])
897 def _real_extract(self
, url
):
898 list_id
= self
._match
_id
(url
)
899 return self
.playlist_result(self
._entries
(list_id
), list_id
, ie
=NiconicoIE
.ie_key())
902 class NiconicoLiveIE(InfoExtractor
):
903 IE_NAME
= 'niconico:live'
905 _VALID_URL
= r
'https?://(?:sp\.)?live2?\.nicovideo\.jp/(?:watch|gate)/(?P<id>lv\d+)'
907 'note': 'this test case includes invisible characters for title, pasting them as-is',
908 'url': 'https://live.nicovideo.jp/watch/lv339533123',
911 'title': '激辛ペヤング食べます( ;ᯅ; )(歌枠オーディション参加中)',
913 'comment_count': 1772,
914 'description': '初めましてもかって言います❕\nのんびり自由に適当に暮らしてます',
916 'channel': 'ゲストさんのコミュニティ',
917 'channel_id': 'co5776900',
918 'channel_url': 'https://com.nicovideo.jp/community/co5776900',
919 'timestamp': 1670677328,
922 'skip': 'livestream',
924 'url': 'https://live2.nicovideo.jp/watch/lv339533123',
925 'only_matching': True,
927 'url': 'https://sp.live.nicovideo.jp/watch/lv339533123',
928 'only_matching': True,
930 'url': 'https://sp.live2.nicovideo.jp/watch/lv339533123',
931 'only_matching': True,
934 _KNOWN_LATENCY
= ('high', 'low')
936 def _real_extract(self
, url
):
938 raise ExtractorError('websockets library is not available. Please install it.', expected
=True)
939 video_id
= self
._match
_id
(url
)
940 webpage
, urlh
= self
._download
_webpage
_handle
(f
'https://live.nicovideo.jp/watch/{video_id}', video_id
)
942 embedded_data
= self
._parse
_json
(unescapeHTML(self
._search
_regex
(
943 r
'<script\s+id="embedded-data"\s*data-props="(.+?)"', webpage
, 'embedded data')), video_id
)
945 ws_url
= traverse_obj(embedded_data
, ('site', 'relive', 'webSocketUrl'))
947 raise ExtractorError('The live hasn\'t started yet or already ended.', expected
=True)
948 ws_url
= update_url_query(ws_url
, {
949 'frontend_id': traverse_obj(embedded_data
, ('site', 'frontendId')) or '9',
952 hostname
= remove_start(urlparse(urlh
.url
).hostname
, 'sp.')
953 cookies
= try_get(urlh
.url
, self
._downloader
._calc
_cookies
)
954 latency
= try_get(self
._configuration
_arg
('latency'), lambda x
: x
[0])
955 if latency
not in self
._KNOWN
_LATENCY
:
958 ws
= WebSocketsWrapper(ws_url
, {
959 'Cookies': str_or_none(cookies
) or '',
960 'Origin': f
'https://{hostname}',
962 'User-Agent': self
.get_param('http_headers')['User-Agent'],
965 self
.write_debug('[debug] Sending HLS server request')
967 'type': 'startWatching',
971 'protocol': 'hls+fmp4',
976 'protocol': 'webSocket',
987 data
= json
.loads(recv
)
988 if not isinstance(data
, dict):
990 if data
.get('type') == 'stream':
991 m3u8_url
= data
['data']['uri']
992 qualities
= data
['data']['availableQualities']
994 elif data
.get('type') == 'disconnect':
995 self
.write_debug(recv
)
996 raise ExtractorError('Disconnected at middle of extraction')
997 elif data
.get('type') == 'error':
998 self
.write_debug(recv
)
999 message
= traverse_obj(data
, ('body', 'code')) or recv
1000 raise ExtractorError(message
)
1001 elif self
.get_param('verbose', False):
1003 recv
= recv
[:100] + '...'
1004 self
.write_debug('Server said: %s' % recv
)
1006 title
= traverse_obj(embedded_data
, ('program', 'title')) or self
._html
_search
_meta
(
1007 ('og:title', 'twitter:title'), webpage
, 'live title', fatal
=False)
1009 raw_thumbs
= traverse_obj(embedded_data
, ('program', 'thumbnail')) or {}
1011 for name
, value
in raw_thumbs
.items():
1012 if not isinstance(value
, dict):
1016 **parse_resolution(value
, lenient
=True),
1020 for k
, img_url
in value
.items():
1021 res
= parse_resolution(k
, lenient
=True) or parse_resolution(img_url
, lenient
=True)
1022 width
, height
= res
.get('width'), res
.get('height')
1025 'id': f
'{name}_{width}x{height}',
1030 formats
= self
._extract
_m
3u8_formats
(m3u8_url
, video_id
, ext
='mp4', live
=True)
1031 for fmt
, q
in zip(formats
, reversed(qualities
[1:])):
1034 'protocol': 'niconico_live',
1036 'video_id': video_id
,
1038 'live_latency': latency
,
1045 **traverse_obj(embedded_data
, {
1046 'view_count': ('program', 'statistics', 'watchCount'),
1047 'comment_count': ('program', 'statistics', 'commentCount'),
1048 'uploader': ('program', 'supplier', 'name'),
1049 'channel': ('socialGroup', 'name'),
1050 'channel_id': ('socialGroup', 'id'),
1051 'channel_url': ('socialGroup', 'socialGroupPageUrl'),
1053 'description': clean_html(traverse_obj(embedded_data
, ('program', 'description'))),
1054 'timestamp': int_or_none(traverse_obj(embedded_data
, ('program', 'openTime'))),
1056 'thumbnails': thumbnails
,