]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/niconico.py
[niconico] Set `expected_protocol` to a public field
[yt-dlp.git] / yt_dlp / extractor / niconico.py
CommitLineData
fb198a8a 1import datetime
f494ddad 2import functools
7bdcb4a4 3import itertools
abafce59 4import json
5import re
7bdcb4a4 6import time
52ad14ae 7
abafce59 8from .common import InfoExtractor, SearchInfoExtractor
1cc79574 9from ..compat import (
bb139491 10 compat_parse_qs,
29f7c58a 11 compat_urllib_parse_urlparse,
f494ddad 12 compat_HTTPError,
1cc79574
PH
13)
14from ..utils import (
6110bbbf 15 ExtractorError,
7bdcb4a4
LNO
16 OnDemandPagedList,
17 bug_reports_message,
18 clean_html,
fb198a8a 19 float_or_none,
b868936c 20 int_or_none,
7bdcb4a4 21 join_nonempty,
1cc79574 22 parse_duration,
7bdcb4a4 23 parse_filesize,
bb865f3a 24 parse_iso8601,
5d45484c
LNO
25 parse_resolution,
26 qualities,
ee6a6116 27 remove_start,
5d45484c 28 str_or_none,
f494ddad 29 traverse_obj,
463e7216 30 try_get,
f494ddad 31 unescapeHTML,
7bdcb4a4
LNO
32 update_url_query,
33 url_or_none,
6e6bc8da 34 urlencode_postdata,
52ad14ae
TT
35)
36
13ebea79 37
52ad14ae 38class NiconicoIE(InfoExtractor):
214c22c7
JMF
39 IE_NAME = 'niconico'
40 IE_DESC = 'ニコニコ動画'
52ad14ae 41
1c9a1457 42 _TESTS = [{
214c22c7 43 'url': 'http://www.nicovideo.jp/watch/sm22312215',
7bdcb4a4 44 'md5': 'd1a75c0823e2f629128c43e1212760f9',
214c22c7
JMF
45 'info_dict': {
46 'id': 'sm22312215',
47 'ext': 'mp4',
48 'title': 'Big Buck Bunny',
463e7216 49 'thumbnail': r're:https?://.*',
214c22c7
JMF
50 'uploader': 'takuya0301',
51 'uploader_id': '2698420',
52 'upload_date': '20131123',
aaab8c5e 53 'timestamp': int, # timestamp is unstable
214c22c7 54 'description': '(c) copyright 2008, Blender Foundation / www.bigbuckbunny.org',
15ce1338 55 'duration': 33,
463e7216
YCH
56 'view_count': int,
57 'comment_count': int,
52ad14ae 58 },
8e4988f1 59 'skip': 'Requires an account',
1c9a1457 60 }, {
59d814f7
YCH
61 # File downloaded with and without credentials are different, so omit
62 # the md5 field
1c9a1457 63 'url': 'http://www.nicovideo.jp/watch/nm14296458',
1c9a1457
S
64 'info_dict': {
65 'id': 'nm14296458',
66 'ext': 'swf',
67 'title': '【鏡音リン】Dance on media【オリジナル】take2!',
bb865f3a 68 'description': 'md5:689f066d74610b3b22e0f1739add0f58',
463e7216 69 'thumbnail': r're:https?://.*',
1c9a1457
S
70 'uploader': 'りょうた',
71 'uploader_id': '18822557',
72 'upload_date': '20110429',
bb865f3a 73 'timestamp': 1304065916,
1c9a1457
S
74 'duration': 209,
75 },
8e4988f1 76 'skip': 'Requires an account',
bb865f3a
YCH
77 }, {
78 # 'video exists but is marked as "deleted"
b2e8e7da 79 # md5 is unstable
bb865f3a 80 'url': 'http://www.nicovideo.jp/watch/sm10000',
bb865f3a
YCH
81 'info_dict': {
82 'id': 'sm10000',
83 'ext': 'unknown_video',
84 'description': 'deleted',
85 'title': 'ドラえもんエターナル第3話「決戦第3新東京市」<前編>',
463e7216 86 'thumbnail': r're:https?://.*',
b2e8e7da 87 'upload_date': '20071224',
8e4988f1 88 'timestamp': int, # timestamp field has different value if logged in
b2e8e7da 89 'duration': 304,
463e7216 90 'view_count': int,
bb865f3a 91 },
8e4988f1 92 'skip': 'Requires an account',
621ffe7b
YCH
93 }, {
94 'url': 'http://www.nicovideo.jp/watch/so22543406',
95 'info_dict': {
96 'id': '1388129933',
97 'ext': 'mp4',
98 'title': '【第1回】RADIOアニメロミックス ラブライブ!~のぞえりRadio Garden~',
99 'description': 'md5:b27d224bb0ff53d3c8269e9f8b561cf1',
463e7216 100 'thumbnail': r're:https?://.*',
621ffe7b
YCH
101 'timestamp': 1388851200,
102 'upload_date': '20140104',
103 'uploader': 'アニメロチャンネル',
104 'uploader_id': '312',
8e4988f1
YCH
105 },
106 'skip': 'The viewing period of the video you were searching for has expired.',
463e7216 107 }, {
ee6a6116 108 # video not available via `getflv`; "old" HTML5 video
463e7216 109 'url': 'http://www.nicovideo.jp/watch/sm1151009',
ee6a6116 110 'md5': '8fa81c364eb619d4085354eab075598a',
463e7216
YCH
111 'info_dict': {
112 'id': 'sm1151009',
ee6a6116 113 'ext': 'mp4',
463e7216
YCH
114 'title': 'マスターシステム本体内蔵のスペハリのメインテーマ(PSG版)',
115 'description': 'md5:6ee077e0581ff5019773e2e714cdd0b7',
116 'thumbnail': r're:https?://.*',
117 'duration': 184,
118 'timestamp': 1190868283,
119 'upload_date': '20070927',
120 'uploader': 'denden2',
121 'uploader_id': '1392194',
122 'view_count': int,
123 'comment_count': int,
124 },
125 'skip': 'Requires an account',
ee6a6116
YCH
126 }, {
127 # "New" HTML5 video
aaab8c5e 128 # md5 is unstable
ee6a6116 129 'url': 'http://www.nicovideo.jp/watch/sm31464864',
ee6a6116
YCH
130 'info_dict': {
131 'id': 'sm31464864',
132 'ext': 'mp4',
133 'title': '新作TVアニメ「戦姫絶唱シンフォギアAXZ」PV 最高画質',
134 'description': 'md5:e52974af9a96e739196b2c1ca72b5feb',
135 'timestamp': 1498514060,
136 'upload_date': '20170626',
aaab8c5e 137 'uploader': 'ゲスト',
ee6a6116
YCH
138 'uploader_id': '40826363',
139 'thumbnail': r're:https?://.*',
140 'duration': 198,
141 'view_count': int,
142 'comment_count': int,
143 },
144 'skip': 'Requires an account',
aaab8c5e
PP
145 }, {
146 # Video without owner
147 'url': 'http://www.nicovideo.jp/watch/sm18238488',
148 'md5': 'd265680a1f92bdcbbd2a507fc9e78a9e',
149 'info_dict': {
150 'id': 'sm18238488',
151 'ext': 'mp4',
152 'title': '【実写版】ミュータントタートルズ',
153 'description': 'md5:15df8988e47a86f9e978af2064bf6d8e',
154 'timestamp': 1341160408,
155 'upload_date': '20120701',
156 'uploader': None,
157 'uploader_id': None,
158 'thumbnail': r're:https?://.*',
159 'duration': 5271,
160 'view_count': int,
161 'comment_count': int,
162 },
163 'skip': 'Requires an account',
4a87de72
LS
164 }, {
165 'url': 'http://sp.nicovideo.jp/watch/sm28964488?ss_pos=1&cp_in=wt_tg',
166 'only_matching': True,
7bdcb4a4
LNO
167 }, {
168 'note': 'a video that is only served as an ENCRYPTED HLS.',
169 'url': 'https://www.nicovideo.jp/watch/so38016254',
170 'only_matching': True,
1c9a1457 171 }]
52ad14ae 172
7bdcb4a4 173 _VALID_URL = r'https?://(?:(?:www\.|secure\.|sp\.)?nicovideo\.jp/watch|nico\.ms)/(?P<id>(?:[a-z]{2})?[0-9]+)'
52ad14ae 174 _NETRC_MACHINE = 'niconico'
7bdcb4a4
LNO
175 _COMMENT_API_ENDPOINTS = (
176 'https://nvcomment.nicovideo.jp/legacy/api.json',
177 'https://nmsg.nicovideo.jp/api.json',)
2291dbce 178 _API_HEADERS = {
179 'X-Frontend-ID': '6',
7bdcb4a4
LNO
180 'X-Frontend-Version': '0',
181 'X-Niconico-Language': 'en-us',
182 'Referer': 'https://www.nicovideo.jp/',
183 'Origin': 'https://www.nicovideo.jp',
2291dbce 184 }
185
52efa4b3 186 def _perform_login(self, username, password):
bb139491 187 login_ok = True
52ad14ae 188 login_form_strs = {
bb139491 189 'mail_tel': username,
214c22c7 190 'password': password,
52ad14ae 191 }
7bdcb4a4
LNO
192 self._request_webpage(
193 'https://account.nicovideo.jp/login', None,
194 note='Acquiring Login session')
bb139491 195 urlh = self._request_webpage(
7bdcb4a4 196 'https://account.nicovideo.jp/login/redirector?show_button_twitter=1&site=niconico&show_button_facebook=1', None,
bb139491 197 note='Logging in', errnote='Unable to log in',
7bdcb4a4
LNO
198 data=urlencode_postdata(login_form_strs),
199 headers={
200 'Referer': 'https://account.nicovideo.jp/login',
201 'Content-Type': 'application/x-www-form-urlencoded',
202 })
bb139491
YCH
203 if urlh is False:
204 login_ok = False
205 else:
29f7c58a 206 parts = compat_urllib_parse_urlparse(urlh.geturl())
bb139491
YCH
207 if compat_parse_qs(parts.query).get('message', [None])[0] == 'cant_login':
208 login_ok = False
209 if not login_ok:
6a39ee13 210 self.report_warning('unable to log in: bad username or password')
bb139491 211 return login_ok
52ad14ae 212
fb198a8a 213 def _get_heartbeat_info(self, info_dict):
fb198a8a 214 video_id, video_src_id, audio_src_id = info_dict['url'].split(':')[1].split('/')
2e25ce3a 215 dmc_protocol = info_dict['expected_protocol']
ee6a6116 216
2291dbce 217 api_data = (
218 info_dict.get('_api_data')
219 or self._parse_json(
220 self._html_search_regex(
221 'data-api-data="([^"]+)"',
222 self._download_webpage('http://www.nicovideo.jp/watch/' + video_id, video_id),
223 'API data', default='{}'),
224 video_id))
fb198a8a 225
7978e172 226 session_api_data = try_get(api_data, lambda x: x['media']['delivery']['movie']['session'])
fb198a8a 227 session_api_endpoint = try_get(session_api_data, lambda x: x['urls'][0])
228
2291dbce 229 def ping():
7bdcb4a4
LNO
230 tracking_id = traverse_obj(api_data, ('media', 'delivery', 'trackingId'))
231 if tracking_id:
232 tracking_url = update_url_query('https://nvapi.nicovideo.jp/v1/2ab0cbaa/watch', {'t': tracking_id})
233 watch_request_response = self._download_json(
234 tracking_url, video_id,
235 note='Acquiring permission for downloading video', fatal=False,
236 headers=self._API_HEADERS)
237 if traverse_obj(watch_request_response, ('meta', 'status')) != 200:
238 self.report_warning('Failed to acquire permission for playing video. Video download may fail.')
fb198a8a 239
240 yesno = lambda x: 'yes' if x else 'no'
241
7bdcb4a4
LNO
242 if dmc_protocol == 'http':
243 protocol = 'http'
244 protocol_parameters = {
245 'http_output_download_parameters': {
246 'use_ssl': yesno(session_api_data['urls'][0]['isSsl']),
247 'use_well_known_port': yesno(session_api_data['urls'][0]['isWellKnownPort']),
248 }
249 }
250 elif dmc_protocol == 'hls':
fb198a8a 251 protocol = 'm3u8'
7bdcb4a4
LNO
252 segment_duration = try_get(self._configuration_arg('segment_duration'), lambda x: int(x[0])) or 6000
253 parsed_token = self._parse_json(session_api_data['token'], video_id)
254 encryption = traverse_obj(api_data, ('media', 'delivery', 'encryption'))
255 protocol_parameters = {
256 'hls_parameters': {
257 'segment_duration': segment_duration,
258 'transfer_preset': '',
259 'use_ssl': yesno(session_api_data['urls'][0]['isSsl']),
260 'use_well_known_port': yesno(session_api_data['urls'][0]['isWellKnownPort']),
fb198a8a 261 }
262 }
7bdcb4a4
LNO
263 if 'hls_encryption' in parsed_token and encryption:
264 protocol_parameters['hls_parameters']['encryption'] = {
265 parsed_token['hls_encryption']: {
266 'encrypted_key': encryption['encryptedKey'],
267 'key_uri': encryption['keyUri'],
fb198a8a 268 }
269 }
7bdcb4a4
LNO
270 else:
271 protocol = 'm3u8_native'
272 else:
273 raise ExtractorError(f'Unsupported DMC protocol: {dmc_protocol}')
ee6a6116
YCH
274
275 session_response = self._download_json(
276 session_api_endpoint['url'], video_id,
277 query={'_format': 'json'},
278 headers={'Content-Type': 'application/json'},
fb198a8a 279 note='Downloading JSON metadata for %s' % info_dict['format_id'],
ee6a6116
YCH
280 data=json.dumps({
281 'session': {
282 'client_info': {
7978e172 283 'player_id': session_api_data.get('playerId'),
ee6a6116
YCH
284 },
285 'content_auth': {
7978e172 286 'auth_type': try_get(session_api_data, lambda x: x['authTypes'][session_api_data['protocols'][0]]),
287 'content_key_timeout': session_api_data.get('contentKeyTimeout'),
ee6a6116 288 'service_id': 'nicovideo',
7978e172 289 'service_user_id': session_api_data.get('serviceUserId')
ee6a6116 290 },
7978e172 291 'content_id': session_api_data.get('contentId'),
ee6a6116
YCH
292 'content_src_id_sets': [{
293 'content_src_ids': [{
294 'src_id_to_mux': {
fb198a8a 295 'audio_src_ids': [audio_src_id],
296 'video_src_ids': [video_src_id],
ee6a6116
YCH
297 }
298 }]
299 }],
300 'content_type': 'movie',
301 'content_uri': '',
302 'keep_method': {
303 'heartbeat': {
7978e172 304 'lifetime': session_api_data.get('heartbeatLifetime')
ee6a6116
YCH
305 }
306 },
7bdcb4a4 307 'priority': session_api_data['priority'],
ee6a6116
YCH
308 'protocol': {
309 'name': 'http',
310 'parameters': {
7bdcb4a4
LNO
311 'http_parameters': {
312 'parameters': protocol_parameters
313 }
ee6a6116
YCH
314 }
315 },
7978e172 316 'recipe_id': session_api_data.get('recipeId'),
ee6a6116
YCH
317 'session_operation_auth': {
318 'session_operation_auth_by_signature': {
fb198a8a 319 'signature': session_api_data.get('signature'),
320 'token': session_api_data.get('token'),
ee6a6116
YCH
321 }
322 },
323 'timing_constraint': 'unlimited'
324 }
4d59db5b 325 }).encode())
ee6a6116 326
fb198a8a 327 info_dict['url'] = session_response['data']['session']['content_uri']
328 info_dict['protocol'] = protocol
329
330 # get heartbeat info
331 heartbeat_info_dict = {
332 'url': session_api_endpoint['url'] + '/' + session_response['data']['session']['id'] + '?_format=json&_method=PUT',
333 'data': json.dumps(session_response['data']),
334 # interval, convert milliseconds to seconds, then halve to make a buffer.
2291dbce 335 'interval': float_or_none(session_api_data.get('heartbeatLifetime'), scale=3000),
336 'ping': ping
fb198a8a 337 }
338
339 return info_dict, heartbeat_info_dict
340
7bdcb4a4
LNO
341 def _extract_format_for_quality(self, video_id, audio_quality, video_quality, dmc_protocol):
342
343 if not audio_quality.get('isAvailable') or not video_quality.get('isAvailable'):
344 return None
345
346 def extract_video_quality(video_quality):
347 return parse_filesize('%sB' % self._search_regex(
348 r'\| ([0-9]*\.?[0-9]*[MK])', video_quality, 'vbr', default=''))
349
350 format_id = '-'.join(
351 [remove_start(s['id'], 'archive_') for s in (video_quality, audio_quality)] + [dmc_protocol])
352
353 vid_qual_label = traverse_obj(video_quality, ('metadata', 'label'))
354 vid_quality = traverse_obj(video_quality, ('metadata', 'bitrate'))
ee6a6116
YCH
355
356 return {
7bdcb4a4 357 'url': 'niconico_dmc:%s/%s/%s' % (video_id, video_quality['id'], audio_quality['id']),
ee6a6116 358 'format_id': format_id,
7bdcb4a4 359 'format_note': join_nonempty('DMC', vid_qual_label, dmc_protocol.upper(), delim=' '),
ee6a6116 360 'ext': 'mp4', # Session API are used in HTML5, which always serves mp4
7bdcb4a4
LNO
361 'acodec': 'aac',
362 'vcodec': 'h264',
363 'abr': float_or_none(traverse_obj(audio_quality, ('metadata', 'bitrate')), 1000),
364 'vbr': float_or_none(vid_quality if vid_quality > 0 else extract_video_quality(vid_qual_label), 1000),
365 'height': traverse_obj(video_quality, ('metadata', 'resolution', 'height')),
366 'width': traverse_obj(video_quality, ('metadata', 'resolution', 'width')),
367 'quality': -2 if 'low' in video_quality['id'] else None,
368 'protocol': 'niconico_dmc',
2e25ce3a 369 'expected_protocol': dmc_protocol, # XXX: This is not a documented field
fb198a8a 370 'http_headers': {
371 'Origin': 'https://www.nicovideo.jp',
372 'Referer': 'https://www.nicovideo.jp/watch/' + video_id,
373 }
ee6a6116
YCH
374 }
375
52ad14ae 376 def _real_extract(self, url):
937daef4 377 video_id = self._match_id(url)
52ad14ae 378
7bdcb4a4
LNO
379 try:
380 webpage, handle = self._download_webpage_handle(
381 'http://www.nicovideo.jp/watch/' + video_id, video_id)
382 if video_id.startswith('so'):
383 video_id = self._match_id(handle.geturl())
fb198a8a 384
7bdcb4a4
LNO
385 api_data = self._parse_json(self._html_search_regex(
386 'data-api-data="([^"]+)"', webpage,
387 'API data', default='{}'), video_id)
388 except ExtractorError as e:
389 try:
390 api_data = self._download_json(
391 'https://www.nicovideo.jp/api/watch/v3/%s?_frontendId=6&_frontendVersion=0&actionTrackId=AAAAAAAAAA_%d' % (video_id, round(time.time() * 1000)), video_id,
392 note='Downloading API JSON', errnote='Unable to fetch data')['data']
393 except ExtractorError:
394 if not isinstance(e.cause, compat_HTTPError):
395 raise
396 webpage = e.cause.read().decode('utf-8', 'replace')
397 error_msg = self._html_search_regex(
398 r'(?s)<section\s+class="(?:(?:ErrorMessage|WatchExceptionPage-message)\s*)+">(.+?)</section>',
399 webpage, 'error reason', default=None)
400 if not error_msg:
401 raise
402 raise ExtractorError(re.sub(r'\s+', ' ', error_msg), expected=True)
7978e172 403
7bdcb4a4 404 formats = []
7978e172 405
7bdcb4a4
LNO
406 def get_video_info(*items, get_first=True, **kwargs):
407 return traverse_obj(api_data, ('video', *items), get_all=not get_first, **kwargs)
7978e172 408
7bdcb4a4
LNO
409 quality_info = api_data['media']['delivery']['movie']
410 session_api_data = quality_info['session']
411 for (audio_quality, video_quality, protocol) in itertools.product(quality_info['audios'], quality_info['videos'], session_api_data['protocols']):
412 fmt = self._extract_format_for_quality(video_id, audio_quality, video_quality, protocol)
413 if fmt:
414 formats.append(fmt)
fb198a8a 415
fb198a8a 416 self._sort_formats(formats)
ee6a6116 417
52ad14ae 418 # Start extracting information
7bdcb4a4
LNO
419 tags = None
420 if webpage:
421 # use og:video:tag (not logged in)
422 og_video_tags = re.finditer(r'<meta\s+property="og:video:tag"\s*content="(.*?)">', webpage)
423 tags = list(filter(None, (clean_html(x.group(1)) for x in og_video_tags)))
424 if not tags:
425 # use keywords and split with comma (not logged in)
426 kwds = self._html_search_meta('keywords', webpage, default=None)
427 if kwds:
428 tags = [x for x in kwds.split(',') if x]
429 if not tags:
430 # find in json (logged in)
431 tags = traverse_obj(api_data, ('tag', 'items', ..., 'name'))
52ad14ae 432
5d45484c
LNO
433 thumb_prefs = qualities(['url', 'middleUrl', 'largeUrl', 'player', 'ogp'])
434
b2e8e7da 435 return {
214c22c7 436 'id': video_id,
2291dbce 437 '_api_data': api_data,
7bdcb4a4 438 'title': get_video_info(('originalTitle', 'title')) or self._og_search_title(webpage, default=None),
ee6a6116 439 'formats': formats,
5d45484c
LNO
440 'thumbnails': [{
441 'id': key,
442 'url': url,
443 'ext': 'jpg',
444 'preference': thumb_prefs(key),
445 **parse_resolution(url, lenient=True),
446 } for key, url in (get_video_info('thumbnail') or {}).items() if url],
7bdcb4a4 447 'description': clean_html(get_video_info('description')),
5d45484c
LNO
448 'uploader': traverse_obj(api_data, ('owner', 'nickname'), ('channel', 'name'), ('community', 'name')),
449 'uploader_id': str_or_none(traverse_obj(api_data, ('owner', 'id'), ('channel', 'id'), ('community', 'id'))),
7bdcb4a4
LNO
450 'timestamp': parse_iso8601(get_video_info('registeredAt')) or parse_iso8601(
451 self._html_search_meta('video:release_date', webpage, 'date published', default=None)),
7bdcb4a4
LNO
452 'channel': traverse_obj(api_data, ('channel', 'name'), ('community', 'name')),
453 'channel_id': traverse_obj(api_data, ('channel', 'id'), ('community', 'id')),
454 'view_count': int_or_none(get_video_info('count', 'view')),
455 'tags': tags,
456 'genre': traverse_obj(api_data, ('genre', 'label'), ('genre', 'key')),
457 'comment_count': get_video_info('count', 'comment', expected_type=int),
458 'duration': (
459 parse_duration(self._html_search_meta('video:duration', webpage, 'video duration', default=None))
460 or get_video_info('duration')),
461 'webpage_url': url_or_none(url) or f'https://www.nicovideo.jp/watch/{video_id}',
462 'subtitles': self.extract_subtitles(video_id, api_data, session_api_data),
52ad14ae 463 }
a9bad429 464
7bdcb4a4
LNO
465 def _get_subtitles(self, video_id, api_data, session_api_data):
466 comment_user_key = traverse_obj(api_data, ('comment', 'keys', 'userKey'))
467 user_id_str = session_api_data.get('serviceUserId')
468
a44ca5a4 469 thread_ids = traverse_obj(api_data, ('comment', 'threads', lambda _, v: v['isActive']))
7bdcb4a4
LNO
470 raw_danmaku = self._extract_all_comments(video_id, thread_ids, user_id_str, comment_user_key)
471 if not raw_danmaku:
472 self.report_warning(f'Failed to get comments. {bug_reports_message()}')
473 return
474 return {
475 'comments': [{
476 'ext': 'json',
477 'data': json.dumps(raw_danmaku),
478 }],
479 }
480
481 def _extract_all_comments(self, video_id, threads, user_id, user_key):
482 auth_data = {
483 'user_id': user_id,
484 'userkey': user_key,
485 } if user_id and user_key else {'user_id': ''}
486
487 # Request Start
488 post_data = [{'ping': {'content': 'rs:0'}}]
489 for i, thread in enumerate(threads):
490 thread_id = thread['id']
491 thread_fork = thread['fork']
492 # Post Start (2N)
493 post_data.append({'ping': {'content': f'ps:{i * 2}'}})
494 post_data.append({'thread': {
495 'fork': thread_fork,
496 'language': 0,
497 'nicoru': 3,
498 'scores': 1,
499 'thread': thread_id,
500 'version': '20090904',
501 'with_global': 1,
502 **auth_data,
503 }})
504 # Post Final (2N)
505 post_data.append({'ping': {'content': f'pf:{i * 2}'}})
506
507 # Post Start (2N+1)
508 post_data.append({'ping': {'content': f'ps:{i * 2 + 1}'}})
509 post_data.append({'thread_leaves': {
510 # format is '<bottom of minute range>-<top of minute range>:<comments per minute>,<total last comments'
511 # unfortunately NND limits (deletes?) comment returns this way, so you're only able to grab the last 1000 per language
512 'content': '0-999999:999999,999999,nicoru:999999',
513 'fork': thread_fork,
514 'language': 0,
515 'nicoru': 3,
516 'scores': 1,
517 'thread': thread_id,
518 **auth_data,
519 }})
520 # Post Final (2N+1)
521 post_data.append({'ping': {'content': f'pf:{i * 2 + 1}'}})
522 # Request Final
523 post_data.append({'ping': {'content': 'rf:0'}})
524
525 for api_url in self._COMMENT_API_ENDPOINTS:
526 comments = self._download_json(
527 api_url, video_id, data=json.dumps(post_data).encode(), fatal=False,
528 headers={
529 'Referer': 'https://www.nicovideo.jp/watch/%s' % video_id,
530 'Origin': 'https://www.nicovideo.jp',
531 'Content-Type': 'text/plain;charset=UTF-8',
532 },
533 note='Downloading comments', errnote=f'Failed to access endpoint {api_url}')
534 if comments:
535 return comments
536
a9bad429 537
f494ddad
LNO
538class NiconicoPlaylistBaseIE(InfoExtractor):
539 _PAGE_SIZE = 100
540
541 _API_HEADERS = {
542 'X-Frontend-ID': '6',
543 'X-Frontend-Version': '0',
544 'X-Niconico-Language': 'en-us'
545 }
546
547 def _call_api(self, list_id, resource, query):
548 "Implement this in child class"
549 pass
550
551 @staticmethod
552 def _parse_owner(item):
553 return {
554 'uploader': traverse_obj(item, ('owner', 'name')),
555 'uploader_id': traverse_obj(item, ('owner', 'id')),
556 }
557
558 def _fetch_page(self, list_id, page):
559 page += 1
560 resp = self._call_api(list_id, 'page %d' % page, {
561 'page': page,
562 'pageSize': self._PAGE_SIZE,
563 })
564 # this is needed to support both mylist and user
565 for video in traverse_obj(resp, ('items', ..., ('video', None))) or []:
566 video_id = video.get('id')
567 if not video_id:
568 # skip {"video": {"id": "blablabla", ...}}
569 continue
570 count = video.get('count') or {}
571 get_count = lambda x: int_or_none(count.get(x))
572 yield {
573 '_type': 'url',
574 'id': video_id,
575 'title': video.get('title'),
576 'url': f'https://www.nicovideo.jp/watch/{video_id}',
577 'description': video.get('shortDescription'),
578 'duration': int_or_none(video.get('duration')),
579 'view_count': get_count('view'),
580 'comment_count': get_count('comment'),
581 'thumbnail': traverse_obj(video, ('thumbnail', ('nHdUrl', 'largeUrl', 'listingUrl', 'url'))),
582 'ie_key': NiconicoIE.ie_key(),
583 **self._parse_owner(video),
584 }
585
586 def _entries(self, list_id):
587 return OnDemandPagedList(functools.partial(self._fetch_page, list_id), self._PAGE_SIZE)
588
589
590class NiconicoPlaylistIE(NiconicoPlaylistBaseIE):
591 IE_NAME = 'niconico:playlist'
592 _VALID_URL = r'https?://(?:(?:www\.|sp\.)?nicovideo\.jp|nico\.ms)/(?:user/\d+/)?(?:my/)?mylist/(?:#/)?(?P<id>\d+)'
a9bad429 593
29f7c58a 594 _TESTS = [{
a9bad429
JMF
595 'url': 'http://www.nicovideo.jp/mylist/27411728',
596 'info_dict': {
597 'id': '27411728',
598 'title': 'AKB48のオールナイトニッポン',
29f7c58a 599 'description': 'md5:d89694c5ded4b6c693dea2db6e41aa08',
600 'uploader': 'のっく',
601 'uploader_id': '805442',
a9bad429 602 },
f494ddad 603 'playlist_mincount': 291,
29f7c58a 604 }, {
605 'url': 'https://www.nicovideo.jp/user/805442/mylist/27411728',
606 'only_matching': True,
f494ddad
LNO
607 }, {
608 'url': 'https://www.nicovideo.jp/my/mylist/#/68048635',
609 'only_matching': True,
29f7c58a 610 }]
a9bad429 611
f494ddad
LNO
612 def _call_api(self, list_id, resource, query):
613 return self._download_json(
614 f'https://nvapi.nicovideo.jp/v2/mylists/{list_id}', list_id,
615 f'Downloading {resource}', query=query,
616 headers=self._API_HEADERS)['data']['mylist']
2291dbce 617
a9bad429
JMF
618 def _real_extract(self, url):
619 list_id = self._match_id(url)
f494ddad
LNO
620 mylist = self._call_api(list_id, 'list', {
621 'pageSize': 1,
622 })
623 return self.playlist_result(
624 self._entries(list_id), list_id,
625 mylist.get('name'), mylist.get('description'), **self._parse_owner(mylist))
fb198a8a 626
fb198a8a 627
f494ddad
LNO
628class NiconicoSeriesIE(InfoExtractor):
629 IE_NAME = 'niconico:series'
630 _VALID_URL = r'https?://(?:(?:www\.|sp\.)?nicovideo\.jp|nico\.ms)/series/(?P<id>\d+)'
631
632 _TESTS = [{
633 'url': 'https://www.nicovideo.jp/series/110226',
634 'info_dict': {
635 'id': '110226',
636 'title': 'ご立派ァ!のシリーズ',
637 },
638 'playlist_mincount': 10, # as of 2021/03/17
639 }, {
640 'url': 'https://www.nicovideo.jp/series/12312/',
641 'info_dict': {
642 'id': '12312',
643 'title': 'バトルスピリッツ お勧めカード紹介(調整中)',
644 },
645 'playlist_mincount': 97, # as of 2021/03/17
646 }, {
647 'url': 'https://nico.ms/series/203559',
648 'only_matching': True,
649 }]
650
651 def _real_extract(self, url):
652 list_id = self._match_id(url)
653 webpage = self._download_webpage(f'https://www.nicovideo.jp/series/{list_id}', list_id)
654
655 title = self._search_regex(
656 (r'<title>「(.+)(全',
657 r'<div class="TwitterShareButton"\s+data-text="(.+)\s+https:'),
658 webpage, 'title', fatal=False)
659 if title:
660 title = unescapeHTML(title)
661 playlist = [
662 self.url_result(f'https://www.nicovideo.jp/watch/{v_id}', video_id=v_id)
663 for v_id in re.findall(r'href="/watch/([a-z0-9]+)" data-href="/watch/\1', webpage)]
664 return self.playlist_result(playlist, list_id, title)
665
666
667class NiconicoHistoryIE(NiconicoPlaylistBaseIE):
668 IE_NAME = 'niconico:history'
669 IE_DESC = 'NicoNico user history. Requires cookies.'
670 _VALID_URL = r'https?://(?:www\.|sp\.)?nicovideo\.jp/my/history'
671
672 _TESTS = [{
673 'note': 'PC page, with /video',
674 'url': 'https://www.nicovideo.jp/my/history/video',
675 'only_matching': True,
676 }, {
677 'note': 'PC page, without /video',
678 'url': 'https://www.nicovideo.jp/my/history',
679 'only_matching': True,
680 }, {
681 'note': 'mobile page, with /video',
682 'url': 'https://sp.nicovideo.jp/my/history/video',
683 'only_matching': True,
684 }, {
685 'note': 'mobile page, without /video',
686 'url': 'https://sp.nicovideo.jp/my/history',
687 'only_matching': True,
688 }]
689
690 def _call_api(self, list_id, resource, query):
691 return self._download_json(
692 'https://nvapi.nicovideo.jp/v1/users/me/watch/history', 'history',
693 f'Downloading {resource}', query=query,
694 headers=self._API_HEADERS)['data']
695
696 def _real_extract(self, url):
697 list_id = 'history'
698 try:
699 mylist = self._call_api(list_id, 'list', {
700 'pageSize': 1,
701 })
702 except ExtractorError as e:
703 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
704 self.raise_login_required('You have to be logged in to get your watch history')
705 raise
706 return self.playlist_result(self._entries(list_id), list_id, **self._parse_owner(mylist))
c1d3a4a8 707
708
63ccf4ff 709class NicovideoSearchBaseIE(InfoExtractor):
9a5b0125
LNO
710 _SEARCH_TYPE = 'search'
711
63ccf4ff 712 def _entries(self, url, item_id, query=None, note='Downloading page %(page)s'):
713 query = query or {}
714 pages = [query['page']] if 'page' in query else itertools.count(1)
715 for page_num in pages:
716 query['page'] = str(page_num)
717 webpage = self._download_webpage(url, item_id, query=query, note=note % {'page': page_num})
718 results = re.findall(r'(?<=data-video-id=)["\']?(?P<videoid>.*?)(?=["\'])', webpage)
719 for item in results:
720 yield self.url_result(f'http://www.nicovideo.jp/watch/{item}', 'Niconico', item)
721 if not results:
722 break
723
146cc411 724 def _search_results(self, query):
725 return self._entries(
9a5b0125 726 self._proto_relative_url(f'//www.nicovideo.jp/{self._SEARCH_TYPE}/{query}'), query)
146cc411 727
63ccf4ff 728
729class NicovideoSearchIE(NicovideoSearchBaseIE, SearchInfoExtractor):
730 IE_DESC = 'Nico video search'
731 IE_NAME = 'nicovideo:search'
732 _SEARCH_KEY = 'nicosearch'
abafce59 733
63ccf4ff 734
735class NicovideoSearchURLIE(NicovideoSearchBaseIE):
736 IE_NAME = f'{NicovideoSearchIE.IE_NAME}_url'
abafce59 737 IE_DESC = 'Nico video search URLs'
738 _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/search/(?P<id>[^?#&]+)?'
739 _TESTS = [{
740 'url': 'http://www.nicovideo.jp/search/sm9',
741 'info_dict': {
742 'id': 'sm9',
743 'title': 'sm9'
744 },
745 'playlist_mincount': 40,
746 }, {
747 'url': 'https://www.nicovideo.jp/search/sm9?sort=h&order=d&end=2020-12-31&start=2020-01-01',
748 'info_dict': {
749 'id': 'sm9',
750 'title': 'sm9'
751 },
752 'playlist_count': 31,
753 }]
754
abafce59 755 def _real_extract(self, url):
756 query = self._match_id(url)
757 return self.playlist_result(self._entries(url, query), query, query)
758
759
63ccf4ff 760class NicovideoSearchDateIE(NicovideoSearchBaseIE, SearchInfoExtractor):
f304da8a 761 IE_DESC = 'Nico video search, newest first'
63ccf4ff 762 IE_NAME = f'{NicovideoSearchIE.IE_NAME}:date'
abafce59 763 _SEARCH_KEY = 'nicosearchdate'
764 _TESTS = [{
765 'url': 'nicosearchdateall:a',
766 'info_dict': {
767 'id': 'a',
768 'title': 'a'
769 },
770 'playlist_mincount': 1610,
771 }]
772
773 _START_DATE = datetime.date(2007, 1, 1)
774 _RESULTS_PER_PAGE = 32
775 _MAX_PAGES = 50
776
777 def _entries(self, url, item_id, start_date=None, end_date=None):
778 start_date, end_date = start_date or self._START_DATE, end_date or datetime.datetime.now().date()
779
780 # If the last page has a full page of videos, we need to break down the query interval further
781 last_page_len = len(list(self._get_entries_for_date(
782 url, item_id, start_date, end_date, self._MAX_PAGES,
783 note=f'Checking number of videos from {start_date} to {end_date}')))
784 if (last_page_len == self._RESULTS_PER_PAGE and start_date != end_date):
785 midpoint = start_date + ((end_date - start_date) // 2)
786 yield from self._entries(url, item_id, midpoint, end_date)
787 yield from self._entries(url, item_id, start_date, midpoint)
788 else:
789 self.to_screen(f'{item_id}: Downloading results from {start_date} to {end_date}')
790 yield from self._get_entries_for_date(
791 url, item_id, start_date, end_date, note=' Downloading page %(page)s')
792
793 def _get_entries_for_date(self, url, item_id, start_date, end_date=None, page_num=None, note=None):
794 query = {
795 'start': str(start_date),
796 'end': str(end_date or start_date),
797 'sort': 'f',
798 'order': 'd',
799 }
800 if page_num:
801 query['page'] = str(page_num)
802
63ccf4ff 803 yield from super()._entries(url, item_id, query=query, note=note)
abafce59 804
805
9a5b0125
LNO
806class NicovideoTagURLIE(NicovideoSearchBaseIE):
807 IE_NAME = 'niconico:tag'
808 IE_DESC = 'NicoNico video tag URLs'
809 _SEARCH_TYPE = 'tag'
810 _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/tag/(?P<id>[^?#&]+)?'
811 _TESTS = [{
812 'url': 'https://www.nicovideo.jp/tag/ドキュメンタリー淫夢',
813 'info_dict': {
814 'id': 'ドキュメンタリー淫夢',
815 'title': 'ドキュメンタリー淫夢'
816 },
817 'playlist_mincount': 400,
818 }]
819
820 def _real_extract(self, url):
821 query = self._match_id(url)
822 return self.playlist_result(self._entries(url, query), query, query)
823
824
c1d3a4a8 825class NiconicoUserIE(InfoExtractor):
826 _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/user/(?P<id>\d+)/?(?:$|[#?])'
827 _TEST = {
828 'url': 'https://www.nicovideo.jp/user/419948',
829 'info_dict': {
830 'id': '419948',
831 },
832 'playlist_mincount': 101,
833 }
834 _API_URL = "https://nvapi.nicovideo.jp/v1/users/%s/videos?sortKey=registeredAt&sortOrder=desc&pageSize=%s&page=%s"
2291dbce 835 _PAGE_SIZE = 100
836
837 _API_HEADERS = {
c1d3a4a8 838 'X-Frontend-ID': '6',
2291dbce 839 'X-Frontend-Version': '0'
c1d3a4a8 840 }
c1d3a4a8 841
abafce59 842 def _entries(self, list_id):
c1d3a4a8 843 total_count = 1
844 count = page_num = 0
845 while count < total_count:
846 json_parsed = self._download_json(
847 self._API_URL % (list_id, self._PAGE_SIZE, page_num + 1), list_id,
2291dbce 848 headers=self._API_HEADERS,
c1d3a4a8 849 note='Downloading JSON metadata%s' % (' page %d' % page_num if page_num else ''))
850 if not page_num:
851 total_count = int_or_none(json_parsed['data'].get('totalCount'))
852 for entry in json_parsed["data"]["items"]:
853 count += 1
854 yield self.url_result('https://www.nicovideo.jp/watch/%s' % entry['id'])
855 page_num += 1
856
857 def _real_extract(self, url):
858 list_id = self._match_id(url)
859 return self.playlist_result(self._entries(list_id), list_id, ie=NiconicoIE.ie_key())