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