8 from urllib
.parse
import urlparse
10 from .common
import InfoExtractor
, SearchInfoExtractor
11 from ..networking
import Request
12 from ..networking
.exceptions
import HTTPError
38 class NiconicoIE(InfoExtractor
):
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',
59 'skip': 'Requires an account',
61 # File downloaded with and without credentials are different, so omit
63 'url': 'http://www.nicovideo.jp/watch/nm14296458',
67 'title': '【鏡音リン】Dance on media【オリジナル】take2!',
68 'description': 'md5:689f066d74610b3b22e0f1739add0f58',
69 'thumbnail': r
're:https?://.*',
71 'uploader_id': '18822557',
72 'upload_date': '20110429',
73 'timestamp': 1304065916,
76 'skip': 'Requires an account',
78 # 'video exists but is marked as "deleted"
80 'url': 'http://www.nicovideo.jp/watch/sm10000',
83 'ext': 'unknown_video',
84 'description': 'deleted',
85 'title': 'ドラえもんエターナル第3話「決戦第3新東京市」<前編>',
86 'thumbnail': r
're:https?://.*',
87 'upload_date': '20071224',
88 'timestamp': int, # timestamp field has different value if logged in
92 'skip': 'Requires an account',
94 'url': 'http://www.nicovideo.jp/watch/so22543406',
98 'title': '【第1回】RADIOアニメロミックス ラブライブ!~のぞえりRadio Garden~',
99 'description': 'md5:b27d224bb0ff53d3c8269e9f8b561cf1',
100 'thumbnail': r
're:https?://.*',
101 'timestamp': 1388851200,
102 'upload_date': '20140104',
103 'uploader': 'アニメロチャンネル',
104 'uploader_id': '312',
106 'skip': 'The viewing period of the video you were searching for has expired.',
108 # video not available via `getflv`; "old" HTML5 video
109 'url': 'http://www.nicovideo.jp/watch/sm1151009',
110 'md5': '8fa81c364eb619d4085354eab075598a',
114 'title': 'マスターシステム本体内蔵のスペハリのメインテーマ(PSG版)',
115 'description': 'md5:6ee077e0581ff5019773e2e714cdd0b7',
116 'thumbnail': r
're:https?://.*',
118 'timestamp': 1190868283,
119 'upload_date': '20070927',
120 'uploader': 'denden2',
121 'uploader_id': '1392194',
123 'comment_count': int,
125 'skip': 'Requires an account',
129 'url': 'http://www.nicovideo.jp/watch/sm31464864',
133 'title': '新作TVアニメ「戦姫絶唱シンフォギアAXZ」PV 最高画質',
134 'description': 'md5:e52974af9a96e739196b2c1ca72b5feb',
135 'timestamp': 1498514060,
136 'upload_date': '20170626',
138 'uploader_id': '40826363',
139 'thumbnail': r
're:https?://.*',
142 'comment_count': int,
144 'skip': 'Requires an account',
146 # Video without owner
147 'url': 'http://www.nicovideo.jp/watch/sm18238488',
148 'md5': 'd265680a1f92bdcbbd2a507fc9e78a9e',
152 'title': '【実写版】ミュータントタートルズ',
153 'description': 'md5:15df8988e47a86f9e978af2064bf6d8e',
154 'timestamp': 1341160408,
155 'upload_date': '20120701',
158 'thumbnail': r
're:https?://.*',
161 'comment_count': int,
163 'skip': 'Requires an account',
165 'url': 'http://sp.nicovideo.jp/watch/sm28964488?ss_pos=1&cp_in=wt_tg',
166 'only_matching': True,
168 'note': 'a video that is only served as an ENCRYPTED HLS.',
169 'url': 'https://www.nicovideo.jp/watch/so38016254',
170 'only_matching': True,
173 _VALID_URL
= r
'https?://(?:(?:www\.|secure\.|sp\.)?nicovideo\.jp/watch|nico\.ms)/(?P<id>(?:[a-z]{2})?[0-9]+)'
174 _NETRC_MACHINE
= 'niconico'
175 _COMMENT_API_ENDPOINTS
= (
176 'https://nvcomment.nicovideo.jp/legacy/api.json',
177 'https://nmsg.nicovideo.jp/api.json',)
179 'X-Frontend-ID': '6',
180 'X-Frontend-Version': '0',
181 'X-Niconico-Language': 'en-us',
182 'Referer': 'https://www.nicovideo.jp/',
183 'Origin': 'https://www.nicovideo.jp',
186 def _perform_login(self
, username
, password
):
189 'mail_tel': username
,
190 'password': password
,
192 self
._request
_webpage
(
193 'https://account.nicovideo.jp/login', None,
194 note
='Acquiring Login session')
195 page
= self
._download
_webpage
(
196 'https://account.nicovideo.jp/login/redirector?show_button_twitter=1&site=niconico&show_button_facebook=1', None,
197 note
='Logging in', errnote
='Unable to log in',
198 data
=urlencode_postdata(login_form_strs
),
200 'Referer': 'https://account.nicovideo.jp/login',
201 'Content-Type': 'application/x-www-form-urlencoded',
203 if 'oneTimePw' in page
:
204 post_url
= self
._search
_regex
(
205 r
'<form[^>]+action=(["\'])(?P
<url
>.+?
)\
1', page, 'post url
', group='url
')
206 page = self._download_webpage(
207 urljoin('https
://account
.nicovideo
.jp
', post_url), None,
208 note='Performing MFA
', errnote='Unable to complete MFA
',
209 data=urlencode_postdata({
210 'otp
': self._get_tfa_info('6 digits code
')
212 'Content
-Type
': 'application
/x
-www
-form
-urlencoded
',
214 if 'oneTimePw
' in page or 'formError
' in page:
215 err_msg = self._html_search_regex(
216 r'formError
["\']+>(.*?)</div>', page, 'form_error',
217 default='There\'s an error but the message can\'t be parsed.',
219 self.report_warning(f'Unable to log in: MFA challenge failed, "{err_msg}
"')
221 login_ok = 'class="notice error
"' not in page
223 self.report_warning('Unable to log in: bad username or password')
226 def _get_heartbeat_info(self, info_dict):
227 video_id, video_src_id, audio_src_id = info_dict['url'].split(':')[1].split('/')
228 dmc_protocol = info_dict['expected_protocol']
231 info_dict.get('_api_data')
233 self._html_search_regex(
234 'data-api-data="([^
"]+)"',
235 self._download_webpage('https
://www
.nicovideo
.jp
/watch
/' + video_id, video_id),
236 'API data
', default='{}'),
239 session_api_data = try_get(api_data, lambda x: x['media
']['delivery
']['movie
']['session
'])
240 session_api_endpoint = try_get(session_api_data, lambda x: x['urls
'][0])
243 tracking_id = traverse_obj(api_data, ('media
', 'delivery
', 'trackingId
'))
245 tracking_url = update_url_query('https
://nvapi
.nicovideo
.jp
/v1
/2ab0cbaa
/watch
', {'t': tracking_id})
246 watch_request_response = self._download_json(
247 tracking_url, video_id,
248 note='Acquiring permission
for downloading video
', fatal=False,
249 headers=self._API_HEADERS)
250 if traverse_obj(watch_request_response, ('meta
', 'status
')) != 200:
251 self.report_warning('Failed to acquire permission
for playing video
. Video download may fail
.')
253 yesno = lambda x: 'yes
' if x else 'no
'
255 if dmc_protocol == 'http
':
257 protocol_parameters = {
258 'http_output_download_parameters
': {
259 'use_ssl
': yesno(session_api_data['urls
'][0]['isSsl
']),
260 'use_well_known_port
': yesno(session_api_data['urls
'][0]['isWellKnownPort
']),
263 elif dmc_protocol == 'hls
':
265 segment_duration = try_get(self._configuration_arg('segment_duration
'), lambda x: int(x[0])) or 6000
266 parsed_token = self._parse_json(session_api_data['token
'], video_id)
267 encryption = traverse_obj(api_data, ('media
', 'delivery
', 'encryption
'))
268 protocol_parameters = {
270 'segment_duration
': segment_duration,
271 'transfer_preset
': '',
272 'use_ssl
': yesno(session_api_data['urls
'][0]['isSsl
']),
273 'use_well_known_port
': yesno(session_api_data['urls
'][0]['isWellKnownPort
']),
276 if 'hls_encryption
' in parsed_token and encryption:
277 protocol_parameters['hls_parameters
']['encryption
'] = {
278 parsed_token['hls_encryption
']: {
279 'encrypted_key
': encryption['encryptedKey
'],
280 'key_uri
': encryption['keyUri
'],
284 protocol = 'm3u8_native
'
286 raise ExtractorError(f'Unsupported DMC protocol
: {dmc_protocol}
')
288 session_response = self._download_json(
289 session_api_endpoint['url
'], video_id,
290 query={'_format': 'json'},
291 headers={'Content-Type': 'application/json'},
292 note='Downloading JSON metadata
for %s' % info_dict['format_id
'],
296 'player_id
': session_api_data.get('playerId
'),
299 'auth_type
': try_get(session_api_data, lambda x: x['authTypes
'][session_api_data['protocols
'][0]]),
300 'content_key_timeout
': session_api_data.get('contentKeyTimeout
'),
301 'service_id
': 'nicovideo
',
302 'service_user_id
': session_api_data.get('serviceUserId
')
304 'content_id
': session_api_data.get('contentId
'),
305 'content_src_id_sets
': [{
306 'content_src_ids
': [{
308 'audio_src_ids
': [audio_src_id],
309 'video_src_ids
': [video_src_id],
313 'content_type
': 'movie
',
317 'lifetime
': session_api_data.get('heartbeatLifetime
')
320 'priority
': session_api_data['priority
'],
325 'parameters
': protocol_parameters
329 'recipe_id
': session_api_data.get('recipeId
'),
330 'session_operation_auth
': {
331 'session_operation_auth_by_signature
': {
332 'signature
': session_api_data.get('signature
'),
333 'token
': session_api_data.get('token
'),
336 'timing_constraint
': 'unlimited
'
340 info_dict['url
'] = session_response['data
']['session
']['content_uri
']
341 info_dict['protocol
'] = protocol
344 heartbeat_info_dict = {
345 'url
': session_api_endpoint['url
'] + '/' + session_response['data
']['session
']['id'] + '?_format
=json
&_method
=PUT
',
346 'data
': json.dumps(session_response['data
']),
347 # interval, convert milliseconds to seconds, then halve to make a buffer.
348 'interval
': float_or_none(session_api_data.get('heartbeatLifetime
'), scale=3000),
352 return info_dict, heartbeat_info_dict
354 def _extract_format_for_quality(self, video_id, audio_quality, video_quality, dmc_protocol):
356 if not audio_quality.get('isAvailable
') or not video_quality.get('isAvailable
'):
359 def extract_video_quality(video_quality):
360 return parse_filesize('%sB
' % self._search_regex(
361 r'\|
([0-9]*\
.?
[0-9]*[MK
])', video_quality, 'vbr
', default=''))
363 format_id = '-'.join(
364 [remove_start(s['id'], 'archive_
') for s in (video_quality, audio_quality)] + [dmc_protocol])
366 vid_qual_label = traverse_obj(video_quality, ('metadata
', 'label
'))
367 vid_quality = traverse_obj(video_quality, ('metadata
', 'bitrate
'))
370 'url
': 'niconico_dmc
:%s/%s/%s' % (video_id, video_quality['id'], audio_quality['id']),
371 'format_id
': format_id,
372 'format_note
': join_nonempty('DMC
', vid_qual_label, dmc_protocol.upper(), delim=' '),
373 'ext
': 'mp4
', # Session API are used in HTML5, which always serves mp4
376 'abr
': float_or_none(traverse_obj(audio_quality, ('metadata
', 'bitrate
')), 1000),
377 'vbr
': float_or_none(vid_quality if vid_quality > 0 else extract_video_quality(vid_qual_label), 1000),
378 'height
': traverse_obj(video_quality, ('metadata
', 'resolution
', 'height
')),
379 'width
': traverse_obj(video_quality, ('metadata
', 'resolution
', 'width
')),
380 'quality
': -2 if 'low
' in video_quality['id'] else None,
381 'protocol
': 'niconico_dmc
',
382 'expected_protocol
': dmc_protocol, # XXX: This is not a documented field
384 'Origin
': 'https
://www
.nicovideo
.jp
',
385 'Referer
': 'https
://www
.nicovideo
.jp
/watch
/' + video_id,
389 def _real_extract(self, url):
390 video_id = self._match_id(url)
393 webpage, handle = self._download_webpage_handle(
394 'https
://www
.nicovideo
.jp
/watch
/' + video_id, video_id)
395 if video_id.startswith('so
'):
396 video_id = self._match_id(handle.url)
398 api_data = self._parse_json(self._html_search_regex(
399 'data
-api
-data
="([^"]+)"', webpage,
400 'API data', default='{}'), video_id)
401 except ExtractorError as e:
403 api_data = self._download_json(
404 'https://www.nicovideo.jp/api/watch/v3/%s?_frontendId=6&_frontendVersion=0&actionTrackId=AAAAAAAAAA_%d' % (video_id, round(time.time() * 1000)), video_id,
405 note='Downloading API JSON', errnote='Unable to fetch data')['data']
406 except ExtractorError:
407 if not isinstance(e.cause, HTTPError):
409 webpage = e.cause.response.read().decode('utf-8', 'replace')
410 error_msg = self._html_search_regex(
411 r'(?s)<section\s+class="(?
:(?
:ErrorMessage|WatchExceptionPage
-message
)\s
*)+">(.+?)</section>',
412 webpage, 'error reason', default=None)
415 raise ExtractorError(re.sub(r'\s+', ' ', error_msg), expected=True)
419 def get_video_info(*items, get_first=True, **kwargs):
420 return traverse_obj(api_data, ('video', *items), get_all=not get_first, **kwargs)
422 quality_info = api_data['media']['delivery']['movie']
423 session_api_data = quality_info['session']
424 for (audio_quality, video_quality, protocol) in itertools.product(quality_info['audios'], quality_info['videos'], session_api_data['protocols']):
425 fmt = self._extract_format_for_quality(video_id, audio_quality, video_quality, protocol)
429 # Start extracting information
432 # use og:video:tag (not logged in)
433 og_video_tags = re.finditer(r'<meta\s+property="og
:video
:tag
"\s*content="(.*?
)">', webpage)
434 tags = list(filter(None, (clean_html(x.group(1)) for x in og_video_tags)))
436 # use keywords and split with comma (not logged in)
437 kwds = self._html_search_meta('keywords', webpage, default=None)
439 tags = [x for x in kwds.split(',') if x]
441 # find in json (logged in)
442 tags = traverse_obj(api_data, ('tag', 'items', ..., 'name'))
444 thumb_prefs = qualities(['url', 'middleUrl', 'largeUrl', 'player', 'ogp'])
448 '_api_data': api_data,
449 'title': get_video_info(('originalTitle', 'title')) or self._og_search_title(webpage, default=None),
455 'preference': thumb_prefs(key),
456 **parse_resolution(url, lenient=True),
457 } for key, url in (get_video_info('thumbnail') or {}).items() if url],
458 'description': clean_html(get_video_info('description')),
459 'uploader': traverse_obj(api_data, ('owner', 'nickname'), ('channel', 'name'), ('community', 'name')),
460 'uploader_id': str_or_none(traverse_obj(api_data, ('owner', 'id'), ('channel', 'id'), ('community', 'id'))),
461 'timestamp': parse_iso8601(get_video_info('registeredAt')) or parse_iso8601(
462 self._html_search_meta('video:release_date', webpage, 'date published', default=None)),
463 'channel': traverse_obj(api_data, ('channel', 'name'), ('community', 'name')),
464 'channel_id': traverse_obj(api_data, ('channel', 'id'), ('community', 'id')),
465 'view_count': int_or_none(get_video_info('count', 'view')),
467 'genre': traverse_obj(api_data, ('genre', 'label'), ('genre', 'key')),
468 'comment_count': get_video_info('count', 'comment', expected_type=int),
470 parse_duration(self._html_search_meta('video:duration', webpage, 'video duration', default=None))
471 or get_video_info('duration')),
472 'webpage_url': url_or_none(url) or f'https://www.nicovideo.jp/watch/{video_id}',
473 'subtitles': self.extract_subtitles(video_id, api_data, session_api_data),
476 def _get_subtitles(self, video_id, api_data, session_api_data):
477 comment_user_key = traverse_obj(api_data, ('comment', 'keys', 'userKey'))
478 user_id_str = session_api_data.get('serviceUserId')
480 thread_ids = traverse_obj(api_data, ('comment', 'threads', lambda _, v: v['isActive']))
481 legacy_danmaku = self._extract_legacy_comments(video_id, thread_ids, user_id_str, comment_user_key) or []
483 new_comments = traverse_obj(api_data, ('comment', 'nvComment'))
484 new_danmaku = self._extract_new_comments(
485 new_comments.get('server'), video_id,
486 new_comments.get('params'), new_comments.get('threadKey'))
488 if not legacy_danmaku and not new_danmaku:
489 self.report_warning(f'Failed to get comments. {bug_reports_message()}')
495 'data': json.dumps(legacy_danmaku + new_danmaku),
499 def _extract_legacy_comments(self, video_id, threads, user_id, user_key):
503 } if user_id and user_key else {'user_id': ''}
505 api_url = traverse_obj(threads, (..., 'server'), get_all=False)
508 post_data = [{'ping': {'content': 'rs:0'}}]
509 for i, thread in enumerate(threads):
510 thread_id = thread['id']
511 thread_fork = thread['fork']
513 post_data.append({'ping': {'content': f'ps:{i * 2}'}})
514 post_data.append({'thread': {
520 'version': '20090904',
525 post_data.append({'ping': {'content': f'pf:{i * 2}'}})
528 post_data.append({'ping': {'content': f'ps:{i * 2 + 1}'}})
529 post_data.append({'thread_leaves': {
530 # format is '<bottom of minute range>-<top of minute range>:<comments per minute>,<total last comments'
531 # unfortunately NND limits (deletes?) comment returns this way, so you're only able to grab the last 1000 per language
532 'content': '0-999999:999999,999999,nicoru:999999',
541 post_data.append({'ping': {'content': f'pf:{i * 2 + 1}'}})
543 post_data.append({'ping': {'content': 'rf:0'}})
545 return self._download_json(
546 f'{api_url}/api.json', video_id, data=json.dumps(post_data).encode(), fatal=False,
548 'Referer': f'https://www.nicovideo.jp/watch/{video_id}',
549 'Origin': 'https://www.nicovideo.jp',
550 'Content-Type': 'text/plain;charset=UTF-8',
552 note='Downloading comments', errnote=f'Failed to access endpoint {api_url}')
554 def _extract_new_comments(self, endpoint, video_id, params, thread_key):
555 comments = self._download_json(
556 f'{endpoint}/v1/threads', video_id, data=json.dumps({
559 'threadKey': thread_key,
560 }).encode(), fatal=False,
562 'Referer': 'https://www.nicovideo.jp/',
563 'Origin': 'https://www.nicovideo.jp',
564 'Content-Type': 'text/plain;charset=UTF-8',
565 'x-client-os-type': 'others',
566 'x-frontend-id': '6',
567 'x-frontend-version': '0',
569 note='Downloading comments (new)', errnote='Failed to download comments (new)')
570 return traverse_obj(comments, ('data', 'threads', ..., 'comments', ...))
573 class NiconicoPlaylistBaseIE(InfoExtractor):
577 'X-Frontend-ID': '6',
578 'X-Frontend-Version': '0',
579 'X-Niconico-Language': 'en-us'
582 def _call_api(self, list_id, resource, query):
583 raise NotImplementedError('Must be implemented in subclasses')
586 def _parse_owner(item):
588 'uploader': traverse_obj(item, ('owner', 'name')),
589 'uploader_id': traverse_obj(item, ('owner', 'id')),
592 def _fetch_page(self, list_id, page):
594 resp = self._call_api(list_id, 'page %d' % page, {
596 'pageSize': self._PAGE_SIZE,
598 # this is needed to support both mylist and user
599 for video in traverse_obj(resp, ('items', ..., ('video', None))) or []:
600 video_id = video.get('id')
602 # skip {"video": {"id": "blablabla", ...}}
604 count = video.get('count') or {}
605 get_count = lambda x: int_or_none(count.get(x))
609 'title': video.get('title'),
610 'url': f'https://www.nicovideo.jp/watch/{video_id}',
611 'description': video.get('shortDescription'),
612 'duration': int_or_none(video.get('duration')),
613 'view_count': get_count('view'),
614 'comment_count': get_count('comment'),
615 'thumbnail': traverse_obj(video, ('thumbnail', ('nHdUrl', 'largeUrl', 'listingUrl', 'url'))),
616 'ie_key': NiconicoIE.ie_key(),
617 **self._parse_owner(video),
620 def _entries(self, list_id):
621 return OnDemandPagedList(functools.partial(self._fetch_page, list_id), self._PAGE_SIZE)
624 class NiconicoPlaylistIE(NiconicoPlaylistBaseIE):
625 IE_NAME = 'niconico:playlist'
626 _VALID_URL = r'https?://(?:(?:www\.|sp\.)?nicovideo\.jp|nico\.ms)/(?:user/\d+/)?(?:my/)?mylist/(?:#/)?(?P<id>\d+)'
629 'url': 'http://www.nicovideo.jp/mylist/27411728',
632 'title': 'AKB48のオールナイトニッポン',
633 'description': 'md5:d89694c5ded4b6c693dea2db6e41aa08',
635 'uploader_id': '805442',
637 'playlist_mincount': 291,
639 'url': 'https://www.nicovideo.jp/user/805442/mylist/27411728',
640 'only_matching': True,
642 'url': 'https://www.nicovideo.jp/my/mylist/#/68048635',
643 'only_matching': True,
646 def _call_api(self, list_id, resource, query):
647 return self._download_json(
648 f'https://nvapi.nicovideo.jp/v2/mylists/{list_id}', list_id,
649 f'Downloading {resource}', query=query,
650 headers=self._API_HEADERS)['data']['mylist']
652 def _real_extract(self, url):
653 list_id = self._match_id(url)
654 mylist = self._call_api(list_id, 'list', {
657 return self.playlist_result(
658 self._entries(list_id), list_id,
659 mylist.get('name'), mylist.get('description'), **self._parse_owner(mylist))
662 class NiconicoSeriesIE(InfoExtractor):
663 IE_NAME = 'niconico:series'
664 _VALID_URL = r'https?://(?:(?:www\.|sp\.)?nicovideo\.jp(?:/user/\d+)?|nico\.ms)/series/(?P<id>\d+)'
667 'url': 'https://www.nicovideo.jp/user/44113208/series/110226',
670 'title': 'ご立派ァ!のシリーズ',
672 'playlist_mincount': 10,
674 'url': 'https://www.nicovideo.jp/series/12312/',
677 'title': 'バトルスピリッツ お勧めカード紹介(調整中)',
679 'playlist_mincount': 103,
681 'url': 'https://nico.ms/series/203559',
682 'only_matching': True,
685 def _real_extract(self, url):
686 list_id = self._match_id(url)
687 webpage = self._download_webpage(url, list_id)
689 title = self._search_regex(
691 r'<div class="TwitterShareButton
"\s+data-text="(.+)\s
+https
:'),
692 webpage, 'title
', fatal=False)
694 title = unescapeHTML(title)
695 json_data = next(self._yield_json_ld(webpage, None, fatal=False))
696 return self.playlist_from_matches(
697 traverse_obj(json_data, ('itemListElement
', ..., 'url
')), list_id, title, ie=NiconicoIE)
700 class NiconicoHistoryIE(NiconicoPlaylistBaseIE):
701 IE_NAME = 'niconico
:history
'
702 IE_DESC = 'NicoNico user history
or likes
. Requires cookies
.'
703 _VALID_URL = r'https?
://(?
:www\
.|sp\
.)?nicovideo\
.jp
/my
/(?P
<id>history(?
:/like
)?
)'
706 'note
': 'PC page
, with /video
',
707 'url
': 'https
://www
.nicovideo
.jp
/my
/history
/video
',
708 'only_matching
': True,
710 'note
': 'PC page
, without
/video
',
711 'url
': 'https
://www
.nicovideo
.jp
/my
/history
',
712 'only_matching
': True,
714 'note
': 'mobile page
, with /video
',
715 'url
': 'https
://sp
.nicovideo
.jp
/my
/history
/video
',
716 'only_matching
': True,
718 'note
': 'mobile page
, without
/video
',
719 'url
': 'https
://sp
.nicovideo
.jp
/my
/history
',
720 'only_matching
': True,
723 'url
': 'https
://www
.nicovideo
.jp
/my
/history
/like
',
724 'only_matching
': True,
726 'note
': 'Mobile page
',
727 'url
': 'https
://sp
.nicovideo
.jp
/my
/history
/like
',
728 'only_matching
': True,
731 def _call_api(self, list_id, resource, query):
732 path = 'likes
' if list_id == 'history
/like
' else 'watch
/history
'
733 return self._download_json(
734 f'https
://nvapi
.nicovideo
.jp
/v1
/users
/me
/{path}
', list_id,
735 f'Downloading {resource}
', query=query, headers=self._API_HEADERS)['data
']
737 def _real_extract(self, url):
738 list_id = self._match_id(url)
740 mylist = self._call_api(list_id, 'list', {'pageSize': 1})
741 except ExtractorError as e:
742 if isinstance(e.cause, HTTPError) and e.cause.status == 401:
743 self.raise_login_required('You have to be logged
in to get your history
')
745 return self.playlist_result(self._entries(list_id), list_id, **self._parse_owner(mylist))
748 class NicovideoSearchBaseIE(InfoExtractor):
749 _SEARCH_TYPE = 'search
'
751 def _entries(self, url, item_id, query=None, note='Downloading page
%(page)s'):
753 pages = [query['page
']] if 'page
' in query else itertools.count(1)
754 for page_num in pages:
755 query['page
'] = str(page_num)
756 webpage = self._download_webpage(url, item_id, query=query, note=note % {'page': page_num})
757 results = re.findall(r'(?
<=data
-video
-id=)["\']?(?P<videoid>.*?)(?=["\'])', webpage)
759 yield self.url_result(f'https
://www
.nicovideo
.jp
/watch
/{item}
', 'Niconico
', item)
763 def _search_results(self, query):
764 return self._entries(
765 self._proto_relative_url(f'//www
.nicovideo
.jp
/{self._SEARCH_TYPE}
/{query}
'), query)
768 class NicovideoSearchIE(NicovideoSearchBaseIE, SearchInfoExtractor):
769 IE_DESC = 'Nico video search
'
770 IE_NAME = 'nicovideo
:search
'
771 _SEARCH_KEY = 'nicosearch
'
774 class NicovideoSearchURLIE(NicovideoSearchBaseIE):
775 IE_NAME = f'{NicovideoSearchIE.IE_NAME}_url
'
776 IE_DESC = 'Nico video search URLs
'
777 _VALID_URL = r'https?
://(?
:www\
.)?nicovideo\
.jp
/search
/(?P
<id>[^?
#&]+)?'
779 'url': 'http://www.nicovideo.jp/search/sm9',
784 'playlist_mincount': 40,
786 'url': 'https://www.nicovideo.jp/search/sm9?sort=h&order=d&end=2020-12-31&start=2020-01-01',
791 'playlist_count': 31,
794 def _real_extract(self
, url
):
795 query
= self
._match
_id
(url
)
796 return self
.playlist_result(self
._entries
(url
, query
), query
, query
)
799 class NicovideoSearchDateIE(NicovideoSearchBaseIE
, SearchInfoExtractor
):
800 IE_DESC
= 'Nico video search, newest first'
801 IE_NAME
= f
'{NicovideoSearchIE.IE_NAME}:date'
802 _SEARCH_KEY
= 'nicosearchdate'
804 'url': 'nicosearchdateall:a',
809 'playlist_mincount': 1610,
812 _START_DATE
= datetime
.date(2007, 1, 1)
813 _RESULTS_PER_PAGE
= 32
816 def _entries(self
, url
, item_id
, start_date
=None, end_date
=None):
817 start_date
, end_date
= start_date
or self
._START
_DATE
, end_date
or datetime
.datetime
.now().date()
819 # If the last page has a full page of videos, we need to break down the query interval further
820 last_page_len
= len(list(self
._get
_entries
_for
_date
(
821 url
, item_id
, start_date
, end_date
, self
._MAX
_PAGES
,
822 note
=f
'Checking number of videos from {start_date} to {end_date}')))
823 if (last_page_len
== self
._RESULTS
_PER
_PAGE
and start_date
!= end_date
):
824 midpoint
= start_date
+ ((end_date
- start_date
) // 2)
825 yield from self
._entries
(url
, item_id
, midpoint
, end_date
)
826 yield from self
._entries
(url
, item_id
, start_date
, midpoint
)
828 self
.to_screen(f
'{item_id}: Downloading results from {start_date} to {end_date}')
829 yield from self
._get
_entries
_for
_date
(
830 url
, item_id
, start_date
, end_date
, note
=' Downloading page %(page)s')
832 def _get_entries_for_date(self
, url
, item_id
, start_date
, end_date
=None, page_num
=None, note
=None):
834 'start': str(start_date
),
835 'end': str(end_date
or start_date
),
840 query
['page'] = str(page_num
)
842 yield from super()._entries
(url
, item_id
, query
=query
, note
=note
)
845 class NicovideoTagURLIE(NicovideoSearchBaseIE
):
846 IE_NAME
= 'niconico:tag'
847 IE_DESC
= 'NicoNico video tag URLs'
849 _VALID_URL
= r
'https?://(?:www\.)?nicovideo\.jp/tag/(?P<id>[^?#&]+)?'
851 'url': 'https://www.nicovideo.jp/tag/ドキュメンタリー淫夢',
854 'title': 'ドキュメンタリー淫夢'
856 'playlist_mincount': 400,
859 def _real_extract(self
, url
):
860 query
= self
._match
_id
(url
)
861 return self
.playlist_result(self
._entries
(url
, query
), query
, query
)
864 class NiconicoUserIE(InfoExtractor
):
865 _VALID_URL
= r
'https?://(?:www\.)?nicovideo\.jp/user/(?P<id>\d+)/?(?:$|[#?])'
867 'url': 'https://www.nicovideo.jp/user/419948',
871 'playlist_mincount': 101,
873 _API_URL
= "https://nvapi.nicovideo.jp/v1/users/%s/videos?sortKey=registeredAt&sortOrder=desc&pageSize=%s&page=%s"
877 'X-Frontend-ID': '6',
878 'X-Frontend-Version': '0'
881 def _entries(self
, list_id
):
884 while count
< total_count
:
885 json_parsed
= self
._download
_json
(
886 self
._API
_URL
% (list_id
, self
._PAGE
_SIZE
, page_num
+ 1), list_id
,
887 headers
=self
._API
_HEADERS
,
888 note
='Downloading JSON metadata%s' % (' page %d' % page_num
if page_num
else ''))
890 total_count
= int_or_none(json_parsed
['data'].get('totalCount'))
891 for entry
in json_parsed
["data"]["items"]:
893 yield self
.url_result('https://www.nicovideo.jp/watch/%s' % entry
['id'])
896 def _real_extract(self
, url
):
897 list_id
= self
._match
_id
(url
)
898 return self
.playlist_result(self
._entries
(list_id
), list_id
, ie
=NiconicoIE
.ie_key())
901 class NiconicoLiveIE(InfoExtractor
):
902 IE_NAME
= 'niconico:live'
904 _VALID_URL
= r
'https?://(?:sp\.)?live2?\.nicovideo\.jp/(?:watch|gate)/(?P<id>lv\d+)'
906 'note': 'this test case includes invisible characters for title, pasting them as-is',
907 'url': 'https://live.nicovideo.jp/watch/lv339533123',
910 'title': '激辛ペヤング食べます( ;ᯅ; )(歌枠オーディション参加中)',
912 'comment_count': 1772,
913 'description': '初めましてもかって言います❕\nのんびり自由に適当に暮らしてます',
915 'channel': 'ゲストさんのコミュニティ',
916 'channel_id': 'co5776900',
917 'channel_url': 'https://com.nicovideo.jp/community/co5776900',
918 'timestamp': 1670677328,
921 'skip': 'livestream',
923 'url': 'https://live2.nicovideo.jp/watch/lv339533123',
924 'only_matching': True,
926 'url': 'https://sp.live.nicovideo.jp/watch/lv339533123',
927 'only_matching': True,
929 'url': 'https://sp.live2.nicovideo.jp/watch/lv339533123',
930 'only_matching': True,
933 _KNOWN_LATENCY
= ('high', 'low')
935 def _real_extract(self
, url
):
936 video_id
= self
._match
_id
(url
)
937 webpage
, urlh
= self
._download
_webpage
_handle
(f
'https://live.nicovideo.jp/watch/{video_id}', video_id
)
939 embedded_data
= self
._parse
_json
(unescapeHTML(self
._search
_regex
(
940 r
'<script\s+id="embedded-data"\s*data-props="(.+?)"', webpage
, 'embedded data')), video_id
)
942 ws_url
= traverse_obj(embedded_data
, ('site', 'relive', 'webSocketUrl'))
944 raise ExtractorError('The live hasn\'t started yet or already ended.', expected
=True)
945 ws_url
= update_url_query(ws_url
, {
946 'frontend_id': traverse_obj(embedded_data
, ('site', 'frontendId')) or '9',
949 hostname
= remove_start(urlparse(urlh
.url
).hostname
, 'sp.')
950 latency
= try_get(self
._configuration
_arg
('latency'), lambda x
: x
[0])
951 if latency
not in self
._KNOWN
_LATENCY
:
954 ws
= self
._request
_webpage
(
955 Request(ws_url
, headers
={'Origin': f'https://{hostname}
'}),
956 video_id=video_id, note='Connecting to WebSocket server
')
958 self.write_debug('[debug
] Sending HLS server request
')
960 'type': 'startWatching
',
964 'protocol
': 'hls
+fmp4
',
969 'protocol
': 'webSocket
',
980 data = json.loads(recv)
981 if not isinstance(data, dict):
983 if data.get('type') == 'stream
':
984 m3u8_url = data['data
']['uri
']
985 qualities = data['data
']['availableQualities
']
987 elif data.get('type') == 'disconnect
':
988 self.write_debug(recv)
989 raise ExtractorError('Disconnected at middle of extraction
')
990 elif data.get('type') == 'error
':
991 self.write_debug(recv)
992 message = traverse_obj(data, ('body
', 'code
')) or recv
993 raise ExtractorError(message)
994 elif self.get_param('verbose
', False):
996 recv = recv[:100] + '...'
997 self.write_debug('Server said
: %s' % recv)
999 title = traverse_obj(embedded_data, ('program
', 'title
')) or self._html_search_meta(
1000 ('og
:title
', 'twitter
:title
'), webpage, 'live title
', fatal=False)
1002 raw_thumbs = traverse_obj(embedded_data, ('program
', 'thumbnail
')) or {}
1004 for name, value in raw_thumbs.items():
1005 if not isinstance(value, dict):
1009 **parse_resolution(value, lenient=True),
1013 for k, img_url in value.items():
1014 res = parse_resolution(k, lenient=True) or parse_resolution(img_url, lenient=True)
1015 width, height = res.get('width
'), res.get('height
')
1018 'id': f'{name}_{width}x{height}
',
1023 formats = self._extract_m3u8_formats(m3u8_url, video_id, ext='mp4
', live=True)
1024 for fmt, q in zip(formats, reversed(qualities[1:])):
1027 'protocol
': 'niconico_live
',
1029 'video_id
': video_id,
1030 'live_latency
': latency,
1037 **traverse_obj(embedded_data, {
1038 'view_count
': ('program
', 'statistics
', 'watchCount
'),
1039 'comment_count
': ('program
', 'statistics
', 'commentCount
'),
1040 'uploader
': ('program
', 'supplier
', 'name
'),
1041 'channel
': ('socialGroup
', 'name
'),
1042 'channel_id
': ('socialGroup
', 'id'),
1043 'channel_url
': ('socialGroup
', 'socialGroupPageUrl
'),
1045 'description
': clean_html(traverse_obj(embedded_data, ('program
', 'description
'))),
1046 'timestamp
': int_or_none(traverse_obj(embedded_data, ('program
', 'openTime
'))),
1048 'thumbnails
': thumbnails,