8 from urllib
.parse
import urlparse
10 from .common
import InfoExtractor
, SearchInfoExtractor
11 from ..compat
import (
14 from ..dependencies
import websockets
41 class NiconicoIE(InfoExtractor
):
46 'url': 'http://www.nicovideo.jp/watch/sm22312215',
47 'md5': 'd1a75c0823e2f629128c43e1212760f9',
51 'title': 'Big Buck Bunny',
52 'thumbnail': r
're:https?://.*',
53 'uploader': 'takuya0301',
54 'uploader_id': '2698420',
55 'upload_date': '20131123',
56 'timestamp': int, # timestamp is unstable
57 'description': '(c) copyright 2008, Blender Foundation / www.bigbuckbunny.org',
62 'skip': 'Requires an account',
64 # File downloaded with and without credentials are different, so omit
66 'url': 'http://www.nicovideo.jp/watch/nm14296458',
70 'title': '【鏡音リン】Dance on media【オリジナル】take2!',
71 'description': 'md5:689f066d74610b3b22e0f1739add0f58',
72 'thumbnail': r
're:https?://.*',
74 'uploader_id': '18822557',
75 'upload_date': '20110429',
76 'timestamp': 1304065916,
79 'skip': 'Requires an account',
81 # 'video exists but is marked as "deleted"
83 'url': 'http://www.nicovideo.jp/watch/sm10000',
86 'ext': 'unknown_video',
87 'description': 'deleted',
88 'title': 'ドラえもんエターナル第3話「決戦第3新東京市」<前編>',
89 'thumbnail': r
're:https?://.*',
90 'upload_date': '20071224',
91 'timestamp': int, # timestamp field has different value if logged in
95 'skip': 'Requires an account',
97 'url': 'http://www.nicovideo.jp/watch/so22543406',
101 'title': '【第1回】RADIOアニメロミックス ラブライブ!~のぞえりRadio Garden~',
102 'description': 'md5:b27d224bb0ff53d3c8269e9f8b561cf1',
103 'thumbnail': r
're:https?://.*',
104 'timestamp': 1388851200,
105 'upload_date': '20140104',
106 'uploader': 'アニメロチャンネル',
107 'uploader_id': '312',
109 'skip': 'The viewing period of the video you were searching for has expired.',
111 # video not available via `getflv`; "old" HTML5 video
112 'url': 'http://www.nicovideo.jp/watch/sm1151009',
113 'md5': '8fa81c364eb619d4085354eab075598a',
117 'title': 'マスターシステム本体内蔵のスペハリのメインテーマ(PSG版)',
118 'description': 'md5:6ee077e0581ff5019773e2e714cdd0b7',
119 'thumbnail': r
're:https?://.*',
121 'timestamp': 1190868283,
122 'upload_date': '20070927',
123 'uploader': 'denden2',
124 'uploader_id': '1392194',
126 'comment_count': int,
128 'skip': 'Requires an account',
132 'url': 'http://www.nicovideo.jp/watch/sm31464864',
136 'title': '新作TVアニメ「戦姫絶唱シンフォギアAXZ」PV 最高画質',
137 'description': 'md5:e52974af9a96e739196b2c1ca72b5feb',
138 'timestamp': 1498514060,
139 'upload_date': '20170626',
141 'uploader_id': '40826363',
142 'thumbnail': r
're:https?://.*',
145 'comment_count': int,
147 'skip': 'Requires an account',
149 # Video without owner
150 'url': 'http://www.nicovideo.jp/watch/sm18238488',
151 'md5': 'd265680a1f92bdcbbd2a507fc9e78a9e',
155 'title': '【実写版】ミュータントタートルズ',
156 'description': 'md5:15df8988e47a86f9e978af2064bf6d8e',
157 'timestamp': 1341160408,
158 'upload_date': '20120701',
161 'thumbnail': r
're:https?://.*',
164 'comment_count': int,
166 'skip': 'Requires an account',
168 'url': 'http://sp.nicovideo.jp/watch/sm28964488?ss_pos=1&cp_in=wt_tg',
169 'only_matching': True,
171 'note': 'a video that is only served as an ENCRYPTED HLS.',
172 'url': 'https://www.nicovideo.jp/watch/so38016254',
173 'only_matching': True,
176 _VALID_URL
= r
'https?://(?:(?:www\.|secure\.|sp\.)?nicovideo\.jp/watch|nico\.ms)/(?P<id>(?:[a-z]{2})?[0-9]+)'
177 _NETRC_MACHINE
= 'niconico'
178 _COMMENT_API_ENDPOINTS
= (
179 'https://nvcomment.nicovideo.jp/legacy/api.json',
180 'https://nmsg.nicovideo.jp/api.json',)
182 'X-Frontend-ID': '6',
183 'X-Frontend-Version': '0',
184 'X-Niconico-Language': 'en-us',
185 'Referer': 'https://www.nicovideo.jp/',
186 'Origin': 'https://www.nicovideo.jp',
189 def _perform_login(self
, username
, password
):
192 'mail_tel': username
,
193 'password': password
,
195 self
._request
_webpage
(
196 'https://account.nicovideo.jp/login', None,
197 note
='Acquiring Login session')
198 page
= self
._download
_webpage
(
199 'https://account.nicovideo.jp/login/redirector?show_button_twitter=1&site=niconico&show_button_facebook=1', None,
200 note
='Logging in', errnote
='Unable to log in',
201 data
=urlencode_postdata(login_form_strs
),
203 'Referer': 'https://account.nicovideo.jp/login',
204 'Content-Type': 'application/x-www-form-urlencoded',
206 if 'oneTimePw' in page
:
207 post_url
= self
._search
_regex
(
208 r
'<form[^>]+action=(["\'])(?P
<url
>.+?
)\
1', page, 'post url
', group='url
')
209 page = self._download_webpage(
210 urljoin('https
://account
.nicovideo
.jp
', post_url), None,
211 note='Performing MFA
', errnote='Unable to complete MFA
',
212 data=urlencode_postdata({
213 'otp
': self._get_tfa_info('6 digits code
')
215 'Content
-Type
': 'application
/x
-www
-form
-urlencoded
',
217 if 'oneTimePw
' in page or 'formError
' in page:
218 err_msg = self._html_search_regex(
219 r'formError
["\']+>(.*?)</div>', page, 'form_error',
220 default='There\'s an error but the message can\'t be parsed.',
222 self.report_warning(f'Unable to log in: MFA challenge failed, "{err_msg}
"')
224 login_ok = 'class="notice error
"' not in page
226 self.report_warning('Unable to log in: bad username or password')
229 def _get_heartbeat_info(self, info_dict):
230 video_id, video_src_id, audio_src_id = info_dict['url'].split(':')[1].split('/')
231 dmc_protocol = info_dict['expected_protocol']
234 info_dict.get('_api_data')
236 self._html_search_regex(
237 'data-api-data="([^
"]+)"',
238 self._download_webpage('https
://www
.nicovideo
.jp
/watch
/' + video_id, video_id),
239 'API data
', default='{}'),
242 session_api_data = try_get(api_data, lambda x: x['media
']['delivery
']['movie
']['session
'])
243 session_api_endpoint = try_get(session_api_data, lambda x: x['urls
'][0])
246 tracking_id = traverse_obj(api_data, ('media
', 'delivery
', 'trackingId
'))
248 tracking_url = update_url_query('https
://nvapi
.nicovideo
.jp
/v1
/2ab0cbaa
/watch
', {'t': tracking_id})
249 watch_request_response = self._download_json(
250 tracking_url, video_id,
251 note='Acquiring permission
for downloading video
', fatal=False,
252 headers=self._API_HEADERS)
253 if traverse_obj(watch_request_response, ('meta
', 'status
')) != 200:
254 self.report_warning('Failed to acquire permission
for playing video
. Video download may fail
.')
256 yesno = lambda x: 'yes
' if x else 'no
'
258 if dmc_protocol == 'http
':
260 protocol_parameters = {
261 'http_output_download_parameters
': {
262 'use_ssl
': yesno(session_api_data['urls
'][0]['isSsl
']),
263 'use_well_known_port
': yesno(session_api_data['urls
'][0]['isWellKnownPort
']),
266 elif dmc_protocol == 'hls
':
268 segment_duration = try_get(self._configuration_arg('segment_duration
'), lambda x: int(x[0])) or 6000
269 parsed_token = self._parse_json(session_api_data['token
'], video_id)
270 encryption = traverse_obj(api_data, ('media
', 'delivery
', 'encryption
'))
271 protocol_parameters = {
273 'segment_duration
': segment_duration,
274 'transfer_preset
': '',
275 'use_ssl
': yesno(session_api_data['urls
'][0]['isSsl
']),
276 'use_well_known_port
': yesno(session_api_data['urls
'][0]['isWellKnownPort
']),
279 if 'hls_encryption
' in parsed_token and encryption:
280 protocol_parameters['hls_parameters
']['encryption
'] = {
281 parsed_token['hls_encryption
']: {
282 'encrypted_key
': encryption['encryptedKey
'],
283 'key_uri
': encryption['keyUri
'],
287 protocol = 'm3u8_native
'
289 raise ExtractorError(f'Unsupported DMC protocol
: {dmc_protocol}
')
291 session_response = self._download_json(
292 session_api_endpoint['url
'], video_id,
293 query={'_format': 'json'},
294 headers={'Content-Type': 'application/json'},
295 note='Downloading JSON metadata
for %s' % info_dict['format_id
'],
299 'player_id
': session_api_data.get('playerId
'),
302 'auth_type
': try_get(session_api_data, lambda x: x['authTypes
'][session_api_data['protocols
'][0]]),
303 'content_key_timeout
': session_api_data.get('contentKeyTimeout
'),
304 'service_id
': 'nicovideo
',
305 'service_user_id
': session_api_data.get('serviceUserId
')
307 'content_id
': session_api_data.get('contentId
'),
308 'content_src_id_sets
': [{
309 'content_src_ids
': [{
311 'audio_src_ids
': [audio_src_id],
312 'video_src_ids
': [video_src_id],
316 'content_type
': 'movie
',
320 'lifetime
': session_api_data.get('heartbeatLifetime
')
323 'priority
': session_api_data['priority
'],
328 'parameters
': protocol_parameters
332 'recipe_id
': session_api_data.get('recipeId
'),
333 'session_operation_auth
': {
334 'session_operation_auth_by_signature
': {
335 'signature
': session_api_data.get('signature
'),
336 'token
': session_api_data.get('token
'),
339 'timing_constraint
': 'unlimited
'
343 info_dict['url
'] = session_response['data
']['session
']['content_uri
']
344 info_dict['protocol
'] = protocol
347 heartbeat_info_dict = {
348 'url
': session_api_endpoint['url
'] + '/' + session_response['data
']['session
']['id'] + '?_format
=json
&_method
=PUT
',
349 'data
': json.dumps(session_response['data
']),
350 # interval, convert milliseconds to seconds, then halve to make a buffer.
351 'interval
': float_or_none(session_api_data.get('heartbeatLifetime
'), scale=3000),
355 return info_dict, heartbeat_info_dict
357 def _extract_format_for_quality(self, video_id, audio_quality, video_quality, dmc_protocol):
359 if not audio_quality.get('isAvailable
') or not video_quality.get('isAvailable
'):
362 def extract_video_quality(video_quality):
363 return parse_filesize('%sB
' % self._search_regex(
364 r'\|
([0-9]*\
.?
[0-9]*[MK
])', video_quality, 'vbr
', default=''))
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
'))
370 vid_quality = traverse_obj(video_quality, ('metadata
', 'bitrate
'))
373 'url
': 'niconico_dmc
:%s/%s/%s' % (video_id, video_quality['id'], audio_quality['id']),
374 'format_id
': format_id,
375 'format_note
': join_nonempty('DMC
', vid_qual_label, dmc_protocol.upper(), delim=' '),
376 'ext
': 'mp4
', # Session API are used in HTML5, which always serves mp4
379 'abr
': float_or_none(traverse_obj(audio_quality, ('metadata
', 'bitrate
')), 1000),
380 'vbr
': float_or_none(vid_quality if vid_quality > 0 else extract_video_quality(vid_qual_label), 1000),
381 'height
': traverse_obj(video_quality, ('metadata
', 'resolution
', 'height
')),
382 'width
': traverse_obj(video_quality, ('metadata
', 'resolution
', 'width
')),
383 'quality
': -2 if 'low
' in video_quality['id'] else None,
384 'protocol
': 'niconico_dmc
',
385 'expected_protocol
': dmc_protocol, # XXX: This is not a documented field
387 'Origin
': 'https
://www
.nicovideo
.jp
',
388 'Referer
': 'https
://www
.nicovideo
.jp
/watch
/' + video_id,
392 def _real_extract(self, url):
393 video_id = self._match_id(url)
396 webpage, handle = self._download_webpage_handle(
397 'https
://www
.nicovideo
.jp
/watch
/' + video_id, video_id)
398 if video_id.startswith('so
'):
399 video_id = self._match_id(handle.geturl())
401 api_data = self._parse_json(self._html_search_regex(
402 'data
-api
-data
="([^"]+)"', webpage,
403 'API data', default='{}'), video_id)
404 except ExtractorError as e:
406 api_data = self._download_json(
407 'https://www.nicovideo.jp/api/watch/v3/%s?_frontendId=6&_frontendVersion=0&actionTrackId=AAAAAAAAAA_%d' % (video_id, round(time.time() * 1000)), video_id,
408 note='Downloading API JSON', errnote='Unable to fetch data')['data']
409 except ExtractorError:
410 if not isinstance(e.cause, compat_HTTPError):
412 webpage = e.cause.read().decode('utf-8', 'replace')
413 error_msg = self._html_search_regex(
414 r'(?s)<section\s+class="(?
:(?
:ErrorMessage|WatchExceptionPage
-message
)\s
*)+">(.+?)</section>',
415 webpage, 'error reason', default=None)
418 raise ExtractorError(re.sub(r'\s+', ' ', error_msg), expected=True)
422 def get_video_info(*items, get_first=True, **kwargs):
423 return traverse_obj(api_data, ('video', *items), get_all=not get_first, **kwargs)
425 quality_info = api_data['media']['delivery']['movie']
426 session_api_data = quality_info['session']
427 for (audio_quality, video_quality, protocol) in itertools.product(quality_info['audios'], quality_info['videos'], session_api_data['protocols']):
428 fmt = self._extract_format_for_quality(video_id, audio_quality, video_quality, protocol)
432 # Start extracting information
435 # use og:video:tag (not logged in)
436 og_video_tags = re.finditer(r'<meta\s+property="og
:video
:tag
"\s*content="(.*?
)">', webpage)
437 tags = list(filter(None, (clean_html(x.group(1)) for x in og_video_tags)))
439 # use keywords and split with comma (not logged in)
440 kwds = self._html_search_meta('keywords', webpage, default=None)
442 tags = [x for x in kwds.split(',') if x]
444 # find in json (logged in)
445 tags = traverse_obj(api_data, ('tag', 'items', ..., 'name'))
447 thumb_prefs = qualities(['url', 'middleUrl', 'largeUrl', 'player', 'ogp'])
451 '_api_data': api_data,
452 'title': get_video_info(('originalTitle', 'title')) or self._og_search_title(webpage, default=None),
458 'preference': thumb_prefs(key),
459 **parse_resolution(url, lenient=True),
460 } for key, url in (get_video_info('thumbnail') or {}).items() if url],
461 'description': clean_html(get_video_info('description')),
462 'uploader': traverse_obj(api_data, ('owner', 'nickname'), ('channel', 'name'), ('community', 'name')),
463 'uploader_id': str_or_none(traverse_obj(api_data, ('owner', 'id'), ('channel', 'id'), ('community', 'id'))),
464 'timestamp': parse_iso8601(get_video_info('registeredAt')) or parse_iso8601(
465 self._html_search_meta('video:release_date', webpage, 'date published', default=None)),
466 'channel': traverse_obj(api_data, ('channel', 'name'), ('community', 'name')),
467 'channel_id': traverse_obj(api_data, ('channel', 'id'), ('community', 'id')),
468 'view_count': int_or_none(get_video_info('count', 'view')),
470 'genre': traverse_obj(api_data, ('genre', 'label'), ('genre', 'key')),
471 'comment_count': get_video_info('count', 'comment', expected_type=int),
473 parse_duration(self._html_search_meta('video:duration', webpage, 'video duration', default=None))
474 or get_video_info('duration')),
475 'webpage_url': url_or_none(url) or f'https://www.nicovideo.jp/watch/{video_id}',
476 'subtitles': self.extract_subtitles(video_id, api_data, session_api_data),
479 def _get_subtitles(self, video_id, api_data, session_api_data):
480 comment_user_key = traverse_obj(api_data, ('comment', 'keys', 'userKey'))
481 user_id_str = session_api_data.get('serviceUserId')
483 thread_ids = traverse_obj(api_data, ('comment', 'threads', lambda _, v: v['isActive']))
484 legacy_danmaku = self._extract_legacy_comments(video_id, thread_ids, user_id_str, comment_user_key) or []
486 new_comments = traverse_obj(api_data, ('comment', 'nvComment'))
487 new_danmaku = self._extract_new_comments(
488 new_comments.get('server'), video_id,
489 new_comments.get('params'), new_comments.get('threadKey'))
491 if not legacy_danmaku and not new_danmaku:
492 self.report_warning(f'Failed to get comments. {bug_reports_message()}')
498 'data': json.dumps(legacy_danmaku + new_danmaku),
502 def _extract_legacy_comments(self, video_id, threads, user_id, user_key):
506 } if user_id and user_key else {'user_id': ''}
508 api_url = traverse_obj(threads, (..., 'server'), get_all=False)
511 post_data = [{'ping': {'content': 'rs:0'}}]
512 for i, thread in enumerate(threads):
513 thread_id = thread['id']
514 thread_fork = thread['fork']
516 post_data.append({'ping': {'content': f'ps:{i * 2}'}})
517 post_data.append({'thread': {
523 'version': '20090904',
528 post_data.append({'ping': {'content': f'pf:{i * 2}'}})
531 post_data.append({'ping': {'content': f'ps:{i * 2 + 1}'}})
532 post_data.append({'thread_leaves': {
533 # format is '<bottom of minute range>-<top of minute range>:<comments per minute>,<total last comments'
534 # unfortunately NND limits (deletes?) comment returns this way, so you're only able to grab the last 1000 per language
535 'content': '0-999999:999999,999999,nicoru:999999',
544 post_data.append({'ping': {'content': f'pf:{i * 2 + 1}'}})
546 post_data.append({'ping': {'content': 'rf:0'}})
548 return self._download_json(
549 f'{api_url}/api.json', video_id, data=json.dumps(post_data).encode(), fatal=False,
551 'Referer': f'https://www.nicovideo.jp/watch/{video_id}',
552 'Origin': 'https://www.nicovideo.jp',
553 'Content-Type': 'text/plain;charset=UTF-8',
555 note='Downloading comments', errnote=f'Failed to access endpoint {api_url}')
557 def _extract_new_comments(self, endpoint, video_id, params, thread_key):
558 comments = self._download_json(
559 f'{endpoint}/v1/threads', video_id, data=json.dumps({
562 'threadKey': thread_key,
563 }).encode(), fatal=False,
565 'Referer': 'https://www.nicovideo.jp/',
566 'Origin': 'https://www.nicovideo.jp',
567 'Content-Type': 'text/plain;charset=UTF-8',
568 'x-client-os-type': 'others',
569 'x-frontend-id': '6',
570 'x-frontend-version': '0',
572 note='Downloading comments (new)', errnote='Failed to download comments (new)')
573 return traverse_obj(comments, ('data', 'threads', ..., 'comments', ...))
576 class NiconicoPlaylistBaseIE(InfoExtractor):
580 'X-Frontend-ID': '6',
581 'X-Frontend-Version': '0',
582 'X-Niconico-Language': 'en-us'
585 def _call_api(self, list_id, resource, query):
586 raise NotImplementedError('Must be implemented in subclasses')
589 def _parse_owner(item):
591 'uploader': traverse_obj(item, ('owner', 'name')),
592 'uploader_id': traverse_obj(item, ('owner', 'id')),
595 def _fetch_page(self, list_id, page):
597 resp = self._call_api(list_id, 'page %d' % page, {
599 'pageSize': self._PAGE_SIZE,
601 # this is needed to support both mylist and user
602 for video in traverse_obj(resp, ('items', ..., ('video', None))) or []:
603 video_id = video.get('id')
605 # skip {"video": {"id": "blablabla", ...}}
607 count = video.get('count') or {}
608 get_count = lambda x: int_or_none(count.get(x))
612 'title': video.get('title'),
613 'url': f'https://www.nicovideo.jp/watch/{video_id}',
614 'description': video.get('shortDescription'),
615 'duration': int_or_none(video.get('duration')),
616 'view_count': get_count('view'),
617 'comment_count': get_count('comment'),
618 'thumbnail': traverse_obj(video, ('thumbnail', ('nHdUrl', 'largeUrl', 'listingUrl', 'url'))),
619 'ie_key': NiconicoIE.ie_key(),
620 **self._parse_owner(video),
623 def _entries(self, list_id):
624 return OnDemandPagedList(functools.partial(self._fetch_page, list_id), self._PAGE_SIZE)
627 class NiconicoPlaylistIE(NiconicoPlaylistBaseIE):
628 IE_NAME = 'niconico:playlist'
629 _VALID_URL = r'https?://(?:(?:www\.|sp\.)?nicovideo\.jp|nico\.ms)/(?:user/\d+/)?(?:my/)?mylist/(?:#/)?(?P<id>\d+)'
632 'url': 'http://www.nicovideo.jp/mylist/27411728',
635 'title': 'AKB48のオールナイトニッポン',
636 'description': 'md5:d89694c5ded4b6c693dea2db6e41aa08',
638 'uploader_id': '805442',
640 'playlist_mincount': 291,
642 'url': 'https://www.nicovideo.jp/user/805442/mylist/27411728',
643 'only_matching': True,
645 'url': 'https://www.nicovideo.jp/my/mylist/#/68048635',
646 'only_matching': True,
649 def _call_api(self, list_id, resource, query):
650 return self._download_json(
651 f'https://nvapi.nicovideo.jp/v2/mylists/{list_id}', list_id,
652 f'Downloading {resource}', query=query,
653 headers=self._API_HEADERS)['data']['mylist']
655 def _real_extract(self, url):
656 list_id = self._match_id(url)
657 mylist = self._call_api(list_id, 'list', {
660 return self.playlist_result(
661 self._entries(list_id), list_id,
662 mylist.get('name'), mylist.get('description'), **self._parse_owner(mylist))
665 class NiconicoSeriesIE(InfoExtractor):
666 IE_NAME = 'niconico:series'
667 _VALID_URL = r'https?://(?:(?:www\.|sp\.)?nicovideo\.jp(?:/user/\d+)?|nico\.ms)/series/(?P<id>\d+)'
670 'url': 'https://www.nicovideo.jp/user/44113208/series/110226',
673 'title': 'ご立派ァ!のシリーズ',
675 'playlist_mincount': 10,
677 'url': 'https://www.nicovideo.jp/series/12312/',
680 'title': 'バトルスピリッツ お勧めカード紹介(調整中)',
682 'playlist_mincount': 103,
684 'url': 'https://nico.ms/series/203559',
685 'only_matching': True,
688 def _real_extract(self, url):
689 list_id = self._match_id(url)
690 webpage = self._download_webpage(url, list_id)
692 title = self._search_regex(
694 r'<div class="TwitterShareButton
"\s+data-text="(.+)\s
+https
:'),
695 webpage, 'title
', fatal=False)
697 title = unescapeHTML(title)
698 json_data = next(self._yield_json_ld(webpage, None, fatal=False))
699 return self.playlist_from_matches(
700 traverse_obj(json_data, ('itemListElement
', ..., 'url
')), list_id, title, ie=NiconicoIE)
703 class NiconicoHistoryIE(NiconicoPlaylistBaseIE):
704 IE_NAME = 'niconico
:history
'
705 IE_DESC = 'NicoNico user history
or likes
. Requires cookies
.'
706 _VALID_URL = r'https?
://(?
:www\
.|sp\
.)?nicovideo\
.jp
/my
/(?P
<id>history(?
:/like
)?
)'
709 'note
': 'PC page
, with /video
',
710 'url
': 'https
://www
.nicovideo
.jp
/my
/history
/video
',
711 'only_matching
': True,
713 'note
': 'PC page
, without
/video
',
714 'url
': 'https
://www
.nicovideo
.jp
/my
/history
',
715 'only_matching
': True,
717 'note
': 'mobile page
, with /video
',
718 'url
': 'https
://sp
.nicovideo
.jp
/my
/history
/video
',
719 'only_matching
': True,
721 'note
': 'mobile page
, without
/video
',
722 'url
': 'https
://sp
.nicovideo
.jp
/my
/history
',
723 'only_matching
': True,
726 'url
': 'https
://www
.nicovideo
.jp
/my
/history
/like
',
727 'only_matching
': True,
729 'note
': 'Mobile page
',
730 'url
': 'https
://sp
.nicovideo
.jp
/my
/history
/like
',
731 'only_matching
': True,
734 def _call_api(self, list_id, resource, query):
735 path = 'likes
' if list_id == 'history
/like
' else 'watch
/history
'
736 return self._download_json(
737 f'https
://nvapi
.nicovideo
.jp
/v1
/users
/me
/{path}
', list_id,
738 f'Downloading {resource}
', query=query, headers=self._API_HEADERS)['data
']
740 def _real_extract(self, url):
741 list_id = self._match_id(url)
743 mylist = self._call_api(list_id, 'list', {'pageSize': 1})
744 except ExtractorError as e:
745 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
746 self.raise_login_required('You have to be logged
in to get your history
')
748 return self.playlist_result(self._entries(list_id), list_id, **self._parse_owner(mylist))
751 class NicovideoSearchBaseIE(InfoExtractor):
752 _SEARCH_TYPE = 'search
'
754 def _entries(self, url, item_id, query=None, note='Downloading page
%(page)s'):
756 pages = [query['page
']] if 'page
' in query else itertools.count(1)
757 for page_num in pages:
758 query['page
'] = str(page_num)
759 webpage = self._download_webpage(url, item_id, query=query, note=note % {'page': page_num})
760 results = re.findall(r'(?
<=data
-video
-id=)["\']?(?P<videoid>.*?)(?=["\'])', webpage)
762 yield self.url_result(f'https
://www
.nicovideo
.jp
/watch
/{item}
', 'Niconico
', item)
766 def _search_results(self, query):
767 return self._entries(
768 self._proto_relative_url(f'//www
.nicovideo
.jp
/{self._SEARCH_TYPE}
/{query}
'), query)
771 class NicovideoSearchIE(NicovideoSearchBaseIE, SearchInfoExtractor):
772 IE_DESC = 'Nico video search
'
773 IE_NAME = 'nicovideo
:search
'
774 _SEARCH_KEY = 'nicosearch
'
777 class NicovideoSearchURLIE(NicovideoSearchBaseIE):
778 IE_NAME = f'{NicovideoSearchIE.IE_NAME}_url
'
779 IE_DESC = 'Nico video search URLs
'
780 _VALID_URL = r'https?
://(?
:www\
.)?nicovideo\
.jp
/search
/(?P
<id>[^?
#&]+)?'
782 'url': 'http://www.nicovideo.jp/search/sm9',
787 'playlist_mincount': 40,
789 'url': 'https://www.nicovideo.jp/search/sm9?sort=h&order=d&end=2020-12-31&start=2020-01-01',
794 'playlist_count': 31,
797 def _real_extract(self
, url
):
798 query
= self
._match
_id
(url
)
799 return self
.playlist_result(self
._entries
(url
, query
), query
, query
)
802 class NicovideoSearchDateIE(NicovideoSearchBaseIE
, SearchInfoExtractor
):
803 IE_DESC
= 'Nico video search, newest first'
804 IE_NAME
= f
'{NicovideoSearchIE.IE_NAME}:date'
805 _SEARCH_KEY
= 'nicosearchdate'
807 'url': 'nicosearchdateall:a',
812 'playlist_mincount': 1610,
815 _START_DATE
= datetime
.date(2007, 1, 1)
816 _RESULTS_PER_PAGE
= 32
819 def _entries(self
, url
, item_id
, start_date
=None, end_date
=None):
820 start_date
, end_date
= start_date
or self
._START
_DATE
, end_date
or datetime
.datetime
.now().date()
822 # If the last page has a full page of videos, we need to break down the query interval further
823 last_page_len
= len(list(self
._get
_entries
_for
_date
(
824 url
, item_id
, start_date
, end_date
, self
._MAX
_PAGES
,
825 note
=f
'Checking number of videos from {start_date} to {end_date}')))
826 if (last_page_len
== self
._RESULTS
_PER
_PAGE
and start_date
!= end_date
):
827 midpoint
= start_date
+ ((end_date
- start_date
) // 2)
828 yield from self
._entries
(url
, item_id
, midpoint
, end_date
)
829 yield from self
._entries
(url
, item_id
, start_date
, midpoint
)
831 self
.to_screen(f
'{item_id}: Downloading results from {start_date} to {end_date}')
832 yield from self
._get
_entries
_for
_date
(
833 url
, item_id
, start_date
, end_date
, note
=' Downloading page %(page)s')
835 def _get_entries_for_date(self
, url
, item_id
, start_date
, end_date
=None, page_num
=None, note
=None):
837 'start': str(start_date
),
838 'end': str(end_date
or start_date
),
843 query
['page'] = str(page_num
)
845 yield from super()._entries
(url
, item_id
, query
=query
, note
=note
)
848 class NicovideoTagURLIE(NicovideoSearchBaseIE
):
849 IE_NAME
= 'niconico:tag'
850 IE_DESC
= 'NicoNico video tag URLs'
852 _VALID_URL
= r
'https?://(?:www\.)?nicovideo\.jp/tag/(?P<id>[^?#&]+)?'
854 'url': 'https://www.nicovideo.jp/tag/ドキュメンタリー淫夢',
857 'title': 'ドキュメンタリー淫夢'
859 'playlist_mincount': 400,
862 def _real_extract(self
, url
):
863 query
= self
._match
_id
(url
)
864 return self
.playlist_result(self
._entries
(url
, query
), query
, query
)
867 class NiconicoUserIE(InfoExtractor
):
868 _VALID_URL
= r
'https?://(?:www\.)?nicovideo\.jp/user/(?P<id>\d+)/?(?:$|[#?])'
870 'url': 'https://www.nicovideo.jp/user/419948',
874 'playlist_mincount': 101,
876 _API_URL
= "https://nvapi.nicovideo.jp/v1/users/%s/videos?sortKey=registeredAt&sortOrder=desc&pageSize=%s&page=%s"
880 'X-Frontend-ID': '6',
881 'X-Frontend-Version': '0'
884 def _entries(self
, list_id
):
887 while count
< total_count
:
888 json_parsed
= self
._download
_json
(
889 self
._API
_URL
% (list_id
, self
._PAGE
_SIZE
, page_num
+ 1), list_id
,
890 headers
=self
._API
_HEADERS
,
891 note
='Downloading JSON metadata%s' % (' page %d' % page_num
if page_num
else ''))
893 total_count
= int_or_none(json_parsed
['data'].get('totalCount'))
894 for entry
in json_parsed
["data"]["items"]:
896 yield self
.url_result('https://www.nicovideo.jp/watch/%s' % entry
['id'])
899 def _real_extract(self
, url
):
900 list_id
= self
._match
_id
(url
)
901 return self
.playlist_result(self
._entries
(list_id
), list_id
, ie
=NiconicoIE
.ie_key())
904 class NiconicoLiveIE(InfoExtractor
):
905 IE_NAME
= 'niconico:live'
907 _VALID_URL
= r
'https?://(?:sp\.)?live2?\.nicovideo\.jp/(?:watch|gate)/(?P<id>lv\d+)'
909 'note': 'this test case includes invisible characters for title, pasting them as-is',
910 'url': 'https://live.nicovideo.jp/watch/lv339533123',
913 'title': '激辛ペヤング食べます( ;ᯅ; )(歌枠オーディション参加中)',
915 'comment_count': 1772,
916 'description': '初めましてもかって言います❕\nのんびり自由に適当に暮らしてます',
918 'channel': 'ゲストさんのコミュニティ',
919 'channel_id': 'co5776900',
920 'channel_url': 'https://com.nicovideo.jp/community/co5776900',
921 'timestamp': 1670677328,
924 'skip': 'livestream',
926 'url': 'https://live2.nicovideo.jp/watch/lv339533123',
927 'only_matching': True,
929 'url': 'https://sp.live.nicovideo.jp/watch/lv339533123',
930 'only_matching': True,
932 'url': 'https://sp.live2.nicovideo.jp/watch/lv339533123',
933 'only_matching': True,
936 _KNOWN_LATENCY
= ('high', 'low')
938 def _real_extract(self
, url
):
940 raise ExtractorError('websockets library is not available. Please install it.', expected
=True)
941 video_id
= self
._match
_id
(url
)
942 webpage
, urlh
= self
._download
_webpage
_handle
(f
'https://live.nicovideo.jp/watch/{video_id}', video_id
)
944 embedded_data
= self
._parse
_json
(unescapeHTML(self
._search
_regex
(
945 r
'<script\s+id="embedded-data"\s*data-props="(.+?)"', webpage
, 'embedded data')), video_id
)
947 ws_url
= traverse_obj(embedded_data
, ('site', 'relive', 'webSocketUrl'))
949 raise ExtractorError('The live hasn\'t started yet or already ended.', expected
=True)
950 ws_url
= update_url_query(ws_url
, {
951 'frontend_id': traverse_obj(embedded_data
, ('site', 'frontendId')) or '9',
954 hostname
= remove_start(urlparse(urlh
.geturl()).hostname
, 'sp.')
955 cookies
= try_get(urlh
.geturl(), self
._downloader
._calc
_cookies
)
956 latency
= try_get(self
._configuration
_arg
('latency'), lambda x
: x
[0])
957 if latency
not in self
._KNOWN
_LATENCY
:
960 ws
= WebSocketsWrapper(ws_url
, {
961 'Cookies': str_or_none(cookies
) or '',
962 'Origin': f
'https://{hostname}',
964 'User-Agent': self
.get_param('http_headers')['User-Agent'],
967 self
.write_debug('[debug] Sending HLS server request')
969 'type': 'startWatching',
973 'protocol': 'hls+fmp4',
978 'protocol': 'webSocket',
989 data
= json
.loads(recv
)
990 if not isinstance(data
, dict):
992 if data
.get('type') == 'stream':
993 m3u8_url
= data
['data']['uri']
994 qualities
= data
['data']['availableQualities']
996 elif data
.get('type') == 'disconnect':
997 self
.write_debug(recv
)
998 raise ExtractorError('Disconnected at middle of extraction')
999 elif data
.get('type') == 'error':
1000 self
.write_debug(recv
)
1001 message
= traverse_obj(data
, ('body', 'code')) or recv
1002 raise ExtractorError(message
)
1003 elif self
.get_param('verbose', False):
1005 recv
= recv
[:100] + '...'
1006 self
.write_debug('Server said: %s' % recv
)
1008 title
= traverse_obj(embedded_data
, ('program', 'title')) or self
._html
_search
_meta
(
1009 ('og:title', 'twitter:title'), webpage
, 'live title', fatal
=False)
1011 raw_thumbs
= traverse_obj(embedded_data
, ('program', 'thumbnail')) or {}
1013 for name
, value
in raw_thumbs
.items():
1014 if not isinstance(value
, dict):
1018 **parse_resolution(value
, lenient
=True),
1022 for k
, img_url
in value
.items():
1023 res
= parse_resolution(k
, lenient
=True) or parse_resolution(img_url
, lenient
=True)
1024 width
, height
= res
.get('width'), res
.get('height')
1027 'id': f
'{name}_{width}x{height}',
1032 formats
= self
._extract
_m
3u8_formats
(m3u8_url
, video_id
, ext
='mp4', live
=True)
1033 for fmt
, q
in zip(formats
, reversed(qualities
[1:])):
1036 'protocol': 'niconico_live',
1038 'video_id': video_id
,
1040 'live_latency': latency
,
1047 **traverse_obj(embedded_data
, {
1048 'view_count': ('program', 'statistics', 'watchCount'),
1049 'comment_count': ('program', 'statistics', 'commentCount'),
1050 'uploader': ('program', 'supplier', 'name'),
1051 'channel': ('socialGroup', 'name'),
1052 'channel_id': ('socialGroup', 'id'),
1053 'channel_url': ('socialGroup', 'socialGroupPageUrl'),
1055 'description': clean_html(traverse_obj(embedded_data
, ('program', 'description'))),
1056 'timestamp': int_or_none(traverse_obj(embedded_data
, ('program', 'openTime'))),
1058 'thumbnails': thumbnails
,