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'
176 'X-Frontend-ID': '6',
177 'X-Frontend-Version': '0',
178 'X-Niconico-Language': 'en-us',
179 'Referer': 'https://www.nicovideo.jp/',
180 'Origin': 'https://www.nicovideo.jp',
183 def _perform_login(self
, username
, password
):
186 'mail_tel': username
,
187 'password': password
,
189 self
._request
_webpage
(
190 'https://account.nicovideo.jp/login', None,
191 note
='Acquiring Login session')
192 page
= self
._download
_webpage
(
193 'https://account.nicovideo.jp/login/redirector?show_button_twitter=1&site=niconico&show_button_facebook=1', None,
194 note
='Logging in', errnote
='Unable to log in',
195 data
=urlencode_postdata(login_form_strs
),
197 'Referer': 'https://account.nicovideo.jp/login',
198 'Content-Type': 'application/x-www-form-urlencoded',
200 if 'oneTimePw' in page
:
201 post_url
= self
._search
_regex
(
202 r
'<form[^>]+action=(["\'])(?P
<url
>.+?
)\
1', page, 'post url
', group='url
')
203 page = self._download_webpage(
204 urljoin('https
://account
.nicovideo
.jp
', post_url), None,
205 note='Performing MFA
', errnote='Unable to complete MFA
',
206 data=urlencode_postdata({
207 'otp
': self._get_tfa_info('6 digits code
')
209 'Content
-Type
': 'application
/x
-www
-form
-urlencoded
',
211 if 'oneTimePw
' in page or 'formError
' in page:
212 err_msg = self._html_search_regex(
213 r'formError
["\']+>(.*?)</div>', page, 'form_error',
214 default='There\'s an error but the message can\'t be parsed.',
216 self.report_warning(f'Unable to log in: MFA challenge failed, "{err_msg}
"')
218 login_ok = 'class="notice error
"' not in page
220 self.report_warning('Unable to log in: bad username or password')
223 def _get_heartbeat_info(self, info_dict):
224 video_id, video_src_id, audio_src_id = info_dict['url'].split(':')[1].split('/')
225 dmc_protocol = info_dict['expected_protocol']
228 info_dict.get('_api_data')
230 self._html_search_regex(
231 'data-api-data="([^
"]+)"',
232 self._download_webpage('https
://www
.nicovideo
.jp
/watch
/' + video_id, video_id),
233 'API data
', default='{}'),
236 session_api_data = try_get(api_data, lambda x: x['media
']['delivery
']['movie
']['session
'])
237 session_api_endpoint = try_get(session_api_data, lambda x: x['urls
'][0])
240 tracking_id = traverse_obj(api_data, ('media
', 'delivery
', 'trackingId
'))
242 tracking_url = update_url_query('https
://nvapi
.nicovideo
.jp
/v1
/2ab0cbaa
/watch
', {'t': tracking_id})
243 watch_request_response = self._download_json(
244 tracking_url, video_id,
245 note='Acquiring permission
for downloading video
', fatal=False,
246 headers=self._API_HEADERS)
247 if traverse_obj(watch_request_response, ('meta
', 'status
')) != 200:
248 self.report_warning('Failed to acquire permission
for playing video
. Video download may fail
.')
250 yesno = lambda x: 'yes
' if x else 'no
'
252 if dmc_protocol == 'http
':
254 protocol_parameters = {
255 'http_output_download_parameters
': {
256 'use_ssl
': yesno(session_api_data['urls
'][0]['isSsl
']),
257 'use_well_known_port
': yesno(session_api_data['urls
'][0]['isWellKnownPort
']),
260 elif dmc_protocol == 'hls
':
262 segment_duration = try_get(self._configuration_arg('segment_duration
'), lambda x: int(x[0])) or 6000
263 parsed_token = self._parse_json(session_api_data['token
'], video_id)
264 encryption = traverse_obj(api_data, ('media
', 'delivery
', 'encryption
'))
265 protocol_parameters = {
267 'segment_duration
': segment_duration,
268 'transfer_preset
': '',
269 'use_ssl
': yesno(session_api_data['urls
'][0]['isSsl
']),
270 'use_well_known_port
': yesno(session_api_data['urls
'][0]['isWellKnownPort
']),
273 if 'hls_encryption
' in parsed_token and encryption:
274 protocol_parameters['hls_parameters
']['encryption
'] = {
275 parsed_token['hls_encryption
']: {
276 'encrypted_key
': encryption['encryptedKey
'],
277 'key_uri
': encryption['keyUri
'],
281 protocol = 'm3u8_native
'
283 raise ExtractorError(f'Unsupported DMC protocol
: {dmc_protocol}
')
285 session_response = self._download_json(
286 session_api_endpoint['url
'], video_id,
287 query={'_format': 'json'},
288 headers={'Content-Type': 'application/json'},
289 note='Downloading JSON metadata
for %s' % info_dict['format_id
'],
293 'player_id
': session_api_data.get('playerId
'),
296 'auth_type
': try_get(session_api_data, lambda x: x['authTypes
'][session_api_data['protocols
'][0]]),
297 'content_key_timeout
': session_api_data.get('contentKeyTimeout
'),
298 'service_id
': 'nicovideo
',
299 'service_user_id
': session_api_data.get('serviceUserId
')
301 'content_id
': session_api_data.get('contentId
'),
302 'content_src_id_sets
': [{
303 'content_src_ids
': [{
305 'audio_src_ids
': [audio_src_id],
306 'video_src_ids
': [video_src_id],
310 'content_type
': 'movie
',
314 'lifetime
': session_api_data.get('heartbeatLifetime
')
317 'priority
': session_api_data['priority
'],
322 'parameters
': protocol_parameters
326 'recipe_id
': session_api_data.get('recipeId
'),
327 'session_operation_auth
': {
328 'session_operation_auth_by_signature
': {
329 'signature
': session_api_data.get('signature
'),
330 'token
': session_api_data.get('token
'),
333 'timing_constraint
': 'unlimited
'
337 info_dict['url
'] = session_response['data
']['session
']['content_uri
']
338 info_dict['protocol
'] = protocol
341 heartbeat_info_dict = {
342 'url
': session_api_endpoint['url
'] + '/' + session_response['data
']['session
']['id'] + '?_format
=json
&_method
=PUT
',
343 'data
': json.dumps(session_response['data
']),
344 # interval, convert milliseconds to seconds, then halve to make a buffer.
345 'interval
': float_or_none(session_api_data.get('heartbeatLifetime
'), scale=3000),
349 return info_dict, heartbeat_info_dict
351 def _extract_format_for_quality(self, video_id, audio_quality, video_quality, dmc_protocol):
353 if not audio_quality.get('isAvailable
') or not video_quality.get('isAvailable
'):
356 def extract_video_quality(video_quality):
357 return parse_filesize('%sB
' % self._search_regex(
358 r'\|
([0-9]*\
.?
[0-9]*[MK
])', video_quality, 'vbr
', default=''))
360 format_id = '-'.join(
361 [remove_start(s['id'], 'archive_
') for s in (video_quality, audio_quality)] + [dmc_protocol])
363 vid_qual_label = traverse_obj(video_quality, ('metadata
', 'label
'))
364 vid_quality = traverse_obj(video_quality, ('metadata
', 'bitrate
'))
367 'url
': 'niconico_dmc
:%s/%s/%s' % (video_id, video_quality['id'], audio_quality['id']),
368 'format_id
': format_id,
369 'format_note
': join_nonempty('DMC
', vid_qual_label, dmc_protocol.upper(), delim=' '),
370 'ext
': 'mp4
', # Session API are used in HTML5, which always serves mp4
373 'abr
': float_or_none(traverse_obj(audio_quality, ('metadata
', 'bitrate
')), 1000),
374 'vbr
': float_or_none(vid_quality if vid_quality > 0 else extract_video_quality(vid_qual_label), 1000),
375 'height
': traverse_obj(video_quality, ('metadata
', 'resolution
', 'height
')),
376 'width
': traverse_obj(video_quality, ('metadata
', 'resolution
', 'width
')),
377 'quality
': -2 if 'low
' in video_quality['id'] else None,
378 'protocol
': 'niconico_dmc
',
379 'expected_protocol
': dmc_protocol, # XXX: This is not a documented field
381 'Origin
': 'https
://www
.nicovideo
.jp
',
382 'Referer
': 'https
://www
.nicovideo
.jp
/watch
/' + video_id,
386 def _real_extract(self, url):
387 video_id = self._match_id(url)
390 webpage, handle = self._download_webpage_handle(
391 'https
://www
.nicovideo
.jp
/watch
/' + video_id, video_id)
392 if video_id.startswith('so
'):
393 video_id = self._match_id(handle.url)
395 api_data = self._parse_json(self._html_search_regex(
396 'data
-api
-data
="([^"]+)"', webpage,
397 'API data', default='{}'), video_id)
398 except ExtractorError as e:
400 api_data = self._download_json(
401 'https://www.nicovideo.jp/api/watch/v3/%s?_frontendId=6&_frontendVersion=0&actionTrackId=AAAAAAAAAA_%d' % (video_id, round(time.time() * 1000)), video_id,
402 note='Downloading API JSON', errnote='Unable to fetch data')['data']
403 except ExtractorError:
404 if not isinstance(e.cause, HTTPError):
406 webpage = e.cause.response.read().decode('utf-8', 'replace')
407 error_msg = self._html_search_regex(
408 r'(?s)<section\s+class="(?
:(?
:ErrorMessage|WatchExceptionPage
-message
)\s
*)+">(.+?)</section>',
409 webpage, 'error reason', default=None)
412 raise ExtractorError(re.sub(r'\s+', ' ', error_msg), expected=True)
416 def get_video_info(*items, get_first=True, **kwargs):
417 return traverse_obj(api_data, ('video', *items), get_all=not get_first, **kwargs)
419 quality_info = api_data['media']['delivery']['movie']
420 session_api_data = quality_info['session']
421 for (audio_quality, video_quality, protocol) in itertools.product(quality_info['audios'], quality_info['videos'], session_api_data['protocols']):
422 fmt = self._extract_format_for_quality(video_id, audio_quality, video_quality, protocol)
426 # Start extracting information
429 # use og:video:tag (not logged in)
430 og_video_tags = re.finditer(r'<meta\s+property="og
:video
:tag
"\s*content="(.*?
)">', webpage)
431 tags = list(filter(None, (clean_html(x.group(1)) for x in og_video_tags)))
433 # use keywords and split with comma (not logged in)
434 kwds = self._html_search_meta('keywords', webpage, default=None)
436 tags = [x for x in kwds.split(',') if x]
438 # find in json (logged in)
439 tags = traverse_obj(api_data, ('tag', 'items', ..., 'name'))
441 thumb_prefs = qualities(['url', 'middleUrl', 'largeUrl', 'player', 'ogp'])
445 '_api_data': api_data,
446 'title': get_video_info(('originalTitle', 'title')) or self._og_search_title(webpage, default=None),
452 'preference': thumb_prefs(key),
453 **parse_resolution(url, lenient=True),
454 } for key, url in (get_video_info('thumbnail') or {}).items() if url],
455 'description': clean_html(get_video_info('description')),
456 'uploader': traverse_obj(api_data, ('owner', 'nickname'), ('channel', 'name'), ('community', 'name')),
457 'uploader_id': str_or_none(traverse_obj(api_data, ('owner', 'id'), ('channel', 'id'), ('community', 'id'))),
458 'timestamp': parse_iso8601(get_video_info('registeredAt')) or parse_iso8601(
459 self._html_search_meta('video:release_date', webpage, 'date published', default=None)),
460 'channel': traverse_obj(api_data, ('channel', 'name'), ('community', 'name')),
461 'channel_id': traverse_obj(api_data, ('channel', 'id'), ('community', 'id')),
462 'view_count': int_or_none(get_video_info('count', 'view')),
464 'genre': traverse_obj(api_data, ('genre', 'label'), ('genre', 'key')),
465 'comment_count': get_video_info('count', 'comment', expected_type=int),
467 parse_duration(self._html_search_meta('video:duration', webpage, 'video duration', default=None))
468 or get_video_info('duration')),
469 'webpage_url': url_or_none(url) or f'https://www.nicovideo.jp/watch/{video_id}',
470 'subtitles': self.extract_subtitles(video_id, api_data),
473 def _get_subtitles(self, video_id, api_data):
474 comments_info = traverse_obj(api_data, ('comment', 'nvComment', {dict})) or {}
475 danmaku = traverse_obj(self._download_json(
476 f'{comments_info.get("server")}/v1/threads', video_id, data=json.dumps({
478 'params': comments_info.get('params'),
479 'threadKey': comments_info.get('threadKey'),
480 }).encode(), fatal=False,
482 'Referer': 'https://www.nicovideo.jp/',
483 'Origin': 'https://www.nicovideo.jp',
484 'Content-Type': 'text/plain;charset=UTF-8',
485 'x-client-os-type': 'others',
486 'x-frontend-id': '6',
487 'x-frontend-version': '0',
489 note='Downloading comments', errnote='Failed to download comments'),
490 ('data', 'threads', ..., 'comments', ...))
493 self.report_warning(f'Failed to get comments. {bug_reports_message()}')
499 'data': json.dumps(danmaku),
504 class NiconicoPlaylistBaseIE(InfoExtractor):
508 'X-Frontend-ID': '6',
509 'X-Frontend-Version': '0',
510 'X-Niconico-Language': 'en-us'
513 def _call_api(self, list_id, resource, query):
514 raise NotImplementedError('Must be implemented in subclasses')
517 def _parse_owner(item):
519 'uploader': traverse_obj(item, ('owner', 'name')),
520 'uploader_id': traverse_obj(item, ('owner', 'id')),
523 def _fetch_page(self, list_id, page):
525 resp = self._call_api(list_id, 'page %d' % page, {
527 'pageSize': self._PAGE_SIZE,
529 # this is needed to support both mylist and user
530 for video in traverse_obj(resp, ('items', ..., ('video', None))) or []:
531 video_id = video.get('id')
533 # skip {"video": {"id": "blablabla", ...}}
535 count = video.get('count') or {}
536 get_count = lambda x: int_or_none(count.get(x))
540 'title': video.get('title'),
541 'url': f'https://www.nicovideo.jp/watch/{video_id}',
542 'description': video.get('shortDescription'),
543 'duration': int_or_none(video.get('duration')),
544 'view_count': get_count('view'),
545 'comment_count': get_count('comment'),
546 'thumbnail': traverse_obj(video, ('thumbnail', ('nHdUrl', 'largeUrl', 'listingUrl', 'url'))),
547 'ie_key': NiconicoIE.ie_key(),
548 **self._parse_owner(video),
551 def _entries(self, list_id):
552 return OnDemandPagedList(functools.partial(self._fetch_page, list_id), self._PAGE_SIZE)
555 class NiconicoPlaylistIE(NiconicoPlaylistBaseIE):
556 IE_NAME = 'niconico:playlist'
557 _VALID_URL = r'https?://(?:(?:www\.|sp\.)?nicovideo\.jp|nico\.ms)/(?:user/\d+/)?(?:my/)?mylist/(?:#/)?(?P<id>\d+)'
560 'url': 'http://www.nicovideo.jp/mylist/27411728',
563 'title': 'AKB48のオールナイトニッポン',
564 'description': 'md5:d89694c5ded4b6c693dea2db6e41aa08',
566 'uploader_id': '805442',
568 'playlist_mincount': 291,
570 'url': 'https://www.nicovideo.jp/user/805442/mylist/27411728',
571 'only_matching': True,
573 'url': 'https://www.nicovideo.jp/my/mylist/#/68048635',
574 'only_matching': True,
577 def _call_api(self, list_id, resource, query):
578 return self._download_json(
579 f'https://nvapi.nicovideo.jp/v2/mylists/{list_id}', list_id,
580 f'Downloading {resource}', query=query,
581 headers=self._API_HEADERS)['data']['mylist']
583 def _real_extract(self, url):
584 list_id = self._match_id(url)
585 mylist = self._call_api(list_id, 'list', {
588 return self.playlist_result(
589 self._entries(list_id), list_id,
590 mylist.get('name'), mylist.get('description'), **self._parse_owner(mylist))
593 class NiconicoSeriesIE(InfoExtractor):
594 IE_NAME = 'niconico:series'
595 _VALID_URL = r'https?://(?:(?:www\.|sp\.)?nicovideo\.jp(?:/user/\d+)?|nico\.ms)/series/(?P<id>\d+)'
598 'url': 'https://www.nicovideo.jp/user/44113208/series/110226',
601 'title': 'ご立派ァ!のシリーズ',
603 'playlist_mincount': 10,
605 'url': 'https://www.nicovideo.jp/series/12312/',
608 'title': 'バトルスピリッツ お勧めカード紹介(調整中)',
610 'playlist_mincount': 103,
612 'url': 'https://nico.ms/series/203559',
613 'only_matching': True,
616 def _real_extract(self, url):
617 list_id = self._match_id(url)
618 webpage = self._download_webpage(url, list_id)
620 title = self._search_regex(
622 r'<div class="TwitterShareButton
"\s+data-text="(.+)\s
+https
:'),
623 webpage, 'title
', fatal=False)
625 title = unescapeHTML(title)
626 json_data = next(self._yield_json_ld(webpage, None, fatal=False))
627 return self.playlist_from_matches(
628 traverse_obj(json_data, ('itemListElement
', ..., 'url
')), list_id, title, ie=NiconicoIE)
631 class NiconicoHistoryIE(NiconicoPlaylistBaseIE):
632 IE_NAME = 'niconico
:history
'
633 IE_DESC = 'NicoNico user history
or likes
. Requires cookies
.'
634 _VALID_URL = r'https?
://(?
:www\
.|sp\
.)?nicovideo\
.jp
/my
/(?P
<id>history(?
:/like
)?
)'
637 'note
': 'PC page
, with /video
',
638 'url
': 'https
://www
.nicovideo
.jp
/my
/history
/video
',
639 'only_matching
': True,
641 'note
': 'PC page
, without
/video
',
642 'url
': 'https
://www
.nicovideo
.jp
/my
/history
',
643 'only_matching
': True,
645 'note
': 'mobile page
, with /video
',
646 'url
': 'https
://sp
.nicovideo
.jp
/my
/history
/video
',
647 'only_matching
': True,
649 'note
': 'mobile page
, without
/video
',
650 'url
': 'https
://sp
.nicovideo
.jp
/my
/history
',
651 'only_matching
': True,
654 'url
': 'https
://www
.nicovideo
.jp
/my
/history
/like
',
655 'only_matching
': True,
657 'note
': 'Mobile page
',
658 'url
': 'https
://sp
.nicovideo
.jp
/my
/history
/like
',
659 'only_matching
': True,
662 def _call_api(self, list_id, resource, query):
663 path = 'likes
' if list_id == 'history
/like
' else 'watch
/history
'
664 return self._download_json(
665 f'https
://nvapi
.nicovideo
.jp
/v1
/users
/me
/{path}
', list_id,
666 f'Downloading {resource}
', query=query, headers=self._API_HEADERS)['data
']
668 def _real_extract(self, url):
669 list_id = self._match_id(url)
671 mylist = self._call_api(list_id, 'list', {'pageSize': 1})
672 except ExtractorError as e:
673 if isinstance(e.cause, HTTPError) and e.cause.status == 401:
674 self.raise_login_required('You have to be logged
in to get your history
')
676 return self.playlist_result(self._entries(list_id), list_id, **self._parse_owner(mylist))
679 class NicovideoSearchBaseIE(InfoExtractor):
680 _SEARCH_TYPE = 'search
'
682 def _entries(self, url, item_id, query=None, note='Downloading page
%(page)s'):
684 pages = [query['page
']] if 'page
' in query else itertools.count(1)
685 for page_num in pages:
686 query['page
'] = str(page_num)
687 webpage = self._download_webpage(url, item_id, query=query, note=note % {'page': page_num})
688 results = re.findall(r'(?
<=data
-video
-id=)["\']?(?P<videoid>.*?)(?=["\'])', webpage)
690 yield self.url_result(f'https
://www
.nicovideo
.jp
/watch
/{item}
', 'Niconico
', item)
694 def _search_results(self, query):
695 return self._entries(
696 self._proto_relative_url(f'//www
.nicovideo
.jp
/{self._SEARCH_TYPE}
/{query}
'), query)
699 class NicovideoSearchIE(NicovideoSearchBaseIE, SearchInfoExtractor):
700 IE_DESC = 'Nico video search
'
701 IE_NAME = 'nicovideo
:search
'
702 _SEARCH_KEY = 'nicosearch
'
705 class NicovideoSearchURLIE(NicovideoSearchBaseIE):
706 IE_NAME = f'{NicovideoSearchIE.IE_NAME}_url
'
707 IE_DESC = 'Nico video search URLs
'
708 _VALID_URL = r'https?
://(?
:www\
.)?nicovideo\
.jp
/search
/(?P
<id>[^?
#&]+)?'
710 'url': 'http://www.nicovideo.jp/search/sm9',
715 'playlist_mincount': 40,
717 'url': 'https://www.nicovideo.jp/search/sm9?sort=h&order=d&end=2020-12-31&start=2020-01-01',
722 'playlist_count': 31,
725 def _real_extract(self
, url
):
726 query
= self
._match
_id
(url
)
727 return self
.playlist_result(self
._entries
(url
, query
), query
, query
)
730 class NicovideoSearchDateIE(NicovideoSearchBaseIE
, SearchInfoExtractor
):
731 IE_DESC
= 'Nico video search, newest first'
732 IE_NAME
= f
'{NicovideoSearchIE.IE_NAME}:date'
733 _SEARCH_KEY
= 'nicosearchdate'
735 'url': 'nicosearchdateall:a',
740 'playlist_mincount': 1610,
743 _START_DATE
= datetime
.date(2007, 1, 1)
744 _RESULTS_PER_PAGE
= 32
747 def _entries(self
, url
, item_id
, start_date
=None, end_date
=None):
748 start_date
, end_date
= start_date
or self
._START
_DATE
, end_date
or datetime
.datetime
.now().date()
750 # If the last page has a full page of videos, we need to break down the query interval further
751 last_page_len
= len(list(self
._get
_entries
_for
_date
(
752 url
, item_id
, start_date
, end_date
, self
._MAX
_PAGES
,
753 note
=f
'Checking number of videos from {start_date} to {end_date}')))
754 if (last_page_len
== self
._RESULTS
_PER
_PAGE
and start_date
!= end_date
):
755 midpoint
= start_date
+ ((end_date
- start_date
) // 2)
756 yield from self
._entries
(url
, item_id
, midpoint
, end_date
)
757 yield from self
._entries
(url
, item_id
, start_date
, midpoint
)
759 self
.to_screen(f
'{item_id}: Downloading results from {start_date} to {end_date}')
760 yield from self
._get
_entries
_for
_date
(
761 url
, item_id
, start_date
, end_date
, note
=' Downloading page %(page)s')
763 def _get_entries_for_date(self
, url
, item_id
, start_date
, end_date
=None, page_num
=None, note
=None):
765 'start': str(start_date
),
766 'end': str(end_date
or start_date
),
771 query
['page'] = str(page_num
)
773 yield from super()._entries
(url
, item_id
, query
=query
, note
=note
)
776 class NicovideoTagURLIE(NicovideoSearchBaseIE
):
777 IE_NAME
= 'niconico:tag'
778 IE_DESC
= 'NicoNico video tag URLs'
780 _VALID_URL
= r
'https?://(?:www\.)?nicovideo\.jp/tag/(?P<id>[^?#&]+)?'
782 'url': 'https://www.nicovideo.jp/tag/ドキュメンタリー淫夢',
785 'title': 'ドキュメンタリー淫夢'
787 'playlist_mincount': 400,
790 def _real_extract(self
, url
):
791 query
= self
._match
_id
(url
)
792 return self
.playlist_result(self
._entries
(url
, query
), query
, query
)
795 class NiconicoUserIE(InfoExtractor
):
796 _VALID_URL
= r
'https?://(?:www\.)?nicovideo\.jp/user/(?P<id>\d+)/?(?:$|[#?])'
798 'url': 'https://www.nicovideo.jp/user/419948',
802 'playlist_mincount': 101,
804 _API_URL
= "https://nvapi.nicovideo.jp/v1/users/%s/videos?sortKey=registeredAt&sortOrder=desc&pageSize=%s&page=%s"
808 'X-Frontend-ID': '6',
809 'X-Frontend-Version': '0'
812 def _entries(self
, list_id
):
815 while count
< total_count
:
816 json_parsed
= self
._download
_json
(
817 self
._API
_URL
% (list_id
, self
._PAGE
_SIZE
, page_num
+ 1), list_id
,
818 headers
=self
._API
_HEADERS
,
819 note
='Downloading JSON metadata%s' % (' page %d' % page_num
if page_num
else ''))
821 total_count
= int_or_none(json_parsed
['data'].get('totalCount'))
822 for entry
in json_parsed
["data"]["items"]:
824 yield self
.url_result('https://www.nicovideo.jp/watch/%s' % entry
['id'])
827 def _real_extract(self
, url
):
828 list_id
= self
._match
_id
(url
)
829 return self
.playlist_result(self
._entries
(list_id
), list_id
, ie
=NiconicoIE
.ie_key())
832 class NiconicoLiveIE(InfoExtractor
):
833 IE_NAME
= 'niconico:live'
835 _VALID_URL
= r
'https?://(?:sp\.)?live2?\.nicovideo\.jp/(?:watch|gate)/(?P<id>lv\d+)'
837 'note': 'this test case includes invisible characters for title, pasting them as-is',
838 'url': 'https://live.nicovideo.jp/watch/lv339533123',
841 'title': '激辛ペヤング食べます( ;ᯅ; )(歌枠オーディション参加中)',
843 'comment_count': 1772,
844 'description': '初めましてもかって言います❕\nのんびり自由に適当に暮らしてます',
846 'channel': 'ゲストさんのコミュニティ',
847 'channel_id': 'co5776900',
848 'channel_url': 'https://com.nicovideo.jp/community/co5776900',
849 'timestamp': 1670677328,
852 'skip': 'livestream',
854 'url': 'https://live2.nicovideo.jp/watch/lv339533123',
855 'only_matching': True,
857 'url': 'https://sp.live.nicovideo.jp/watch/lv339533123',
858 'only_matching': True,
860 'url': 'https://sp.live2.nicovideo.jp/watch/lv339533123',
861 'only_matching': True,
864 _KNOWN_LATENCY
= ('high', 'low')
866 def _real_extract(self
, url
):
867 video_id
= self
._match
_id
(url
)
868 webpage
, urlh
= self
._download
_webpage
_handle
(f
'https://live.nicovideo.jp/watch/{video_id}', video_id
)
870 embedded_data
= self
._parse
_json
(unescapeHTML(self
._search
_regex
(
871 r
'<script\s+id="embedded-data"\s*data-props="(.+?)"', webpage
, 'embedded data')), video_id
)
873 ws_url
= traverse_obj(embedded_data
, ('site', 'relive', 'webSocketUrl'))
875 raise ExtractorError('The live hasn\'t started yet or already ended.', expected
=True)
876 ws_url
= update_url_query(ws_url
, {
877 'frontend_id': traverse_obj(embedded_data
, ('site', 'frontendId')) or '9',
880 hostname
= remove_start(urlparse(urlh
.url
).hostname
, 'sp.')
881 latency
= try_get(self
._configuration
_arg
('latency'), lambda x
: x
[0])
882 if latency
not in self
._KNOWN
_LATENCY
:
885 ws
= self
._request
_webpage
(
886 Request(ws_url
, headers
={'Origin': f'https://{hostname}
'}),
887 video_id=video_id, note='Connecting to WebSocket server
')
889 self.write_debug('[debug
] Sending HLS server request
')
891 'type': 'startWatching
',
895 'protocol
': 'hls
+fmp4
',
900 'protocol
': 'webSocket
',
911 data = json.loads(recv)
912 if not isinstance(data, dict):
914 if data.get('type') == 'stream
':
915 m3u8_url = data['data
']['uri
']
916 qualities = data['data
']['availableQualities
']
918 elif data.get('type') == 'disconnect
':
919 self.write_debug(recv)
920 raise ExtractorError('Disconnected at middle of extraction
')
921 elif data.get('type') == 'error
':
922 self.write_debug(recv)
923 message = traverse_obj(data, ('body
', 'code
')) or recv
924 raise ExtractorError(message)
925 elif self.get_param('verbose
', False):
927 recv = recv[:100] + '...'
928 self.write_debug('Server said
: %s' % recv)
930 title = traverse_obj(embedded_data, ('program
', 'title
')) or self._html_search_meta(
931 ('og
:title
', 'twitter
:title
'), webpage, 'live title
', fatal=False)
933 raw_thumbs = traverse_obj(embedded_data, ('program
', 'thumbnail
')) or {}
935 for name, value in raw_thumbs.items():
936 if not isinstance(value, dict):
940 **parse_resolution(value, lenient=True),
944 for k, img_url in value.items():
945 res = parse_resolution(k, lenient=True) or parse_resolution(img_url, lenient=True)
946 width, height = res.get('width
'), res.get('height
')
949 'id': f'{name}_{width}x{height}
',
954 formats = self._extract_m3u8_formats(m3u8_url, video_id, ext='mp4
', live=True)
955 for fmt, q in zip(formats, reversed(qualities[1:])):
958 'protocol
': 'niconico_live
',
960 'video_id
': video_id,
961 'live_latency
': latency,
968 **traverse_obj(embedded_data, {
969 'view_count
': ('program
', 'statistics
', 'watchCount
'),
970 'comment_count
': ('program
', 'statistics
', 'commentCount
'),
971 'uploader
': ('program
', 'supplier
', 'name
'),
972 'channel
': ('socialGroup
', 'name
'),
973 'channel_id
': ('socialGroup
', 'id'),
974 'channel_url
': ('socialGroup
', 'socialGroupPageUrl
'),
976 'description
': clean_html(traverse_obj(embedded_data, ('program
', 'description
'))),
977 'timestamp
': int_or_none(traverse_obj(embedded_data, ('program
', 'openTime
'))),
979 'thumbnails
': thumbnails,