]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/niconico.py
[extractor] Add `_perform_login` function (#2943)
[yt-dlp.git] / yt_dlp / extractor / niconico.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import datetime
5 import functools
6 import itertools
7 import json
8 import re
9 import time
10
11 from .common import InfoExtractor, SearchInfoExtractor
12 from ..compat import (
13 compat_parse_qs,
14 compat_urllib_parse_urlparse,
15 compat_HTTPError,
16 )
17 from ..utils import (
18 ExtractorError,
19 OnDemandPagedList,
20 bug_reports_message,
21 clean_html,
22 float_or_none,
23 int_or_none,
24 join_nonempty,
25 parse_duration,
26 parse_filesize,
27 parse_iso8601,
28 remove_start,
29 traverse_obj,
30 try_get,
31 unescapeHTML,
32 update_url_query,
33 url_or_none,
34 urlencode_postdata,
35 )
36
37
38 class NiconicoIE(InfoExtractor):
39 IE_NAME = 'niconico'
40 IE_DESC = 'ニコニコ動画'
41
42 _TESTS = [{
43 'url': 'http://www.nicovideo.jp/watch/sm22312215',
44 'md5': 'd1a75c0823e2f629128c43e1212760f9',
45 'info_dict': {
46 'id': 'sm22312215',
47 'ext': 'mp4',
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',
55 'duration': 33,
56 'view_count': int,
57 'comment_count': int,
58 },
59 'skip': 'Requires an account',
60 }, {
61 # File downloaded with and without credentials are different, so omit
62 # the md5 field
63 'url': 'http://www.nicovideo.jp/watch/nm14296458',
64 'info_dict': {
65 'id': 'nm14296458',
66 'ext': 'swf',
67 'title': '【鏡音リン】Dance on media【オリジナル】take2!',
68 'description': 'md5:689f066d74610b3b22e0f1739add0f58',
69 'thumbnail': r're:https?://.*',
70 'uploader': 'りょうた',
71 'uploader_id': '18822557',
72 'upload_date': '20110429',
73 'timestamp': 1304065916,
74 'duration': 209,
75 },
76 'skip': 'Requires an account',
77 }, {
78 # 'video exists but is marked as "deleted"
79 # md5 is unstable
80 'url': 'http://www.nicovideo.jp/watch/sm10000',
81 'info_dict': {
82 'id': '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
89 'duration': 304,
90 'view_count': int,
91 },
92 'skip': 'Requires an account',
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',
100 'thumbnail': r're:https?://.*',
101 'timestamp': 1388851200,
102 'upload_date': '20140104',
103 'uploader': 'アニメロチャンネル',
104 'uploader_id': '312',
105 },
106 'skip': 'The viewing period of the video you were searching for has expired.',
107 }, {
108 # video not available via `getflv`; "old" HTML5 video
109 'url': 'http://www.nicovideo.jp/watch/sm1151009',
110 'md5': '8fa81c364eb619d4085354eab075598a',
111 'info_dict': {
112 'id': 'sm1151009',
113 'ext': 'mp4',
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',
126 }, {
127 # "New" HTML5 video
128 # md5 is unstable
129 'url': 'http://www.nicovideo.jp/watch/sm31464864',
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',
137 'uploader': 'ゲスト',
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',
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',
164 }, {
165 'url': 'http://sp.nicovideo.jp/watch/sm28964488?ss_pos=1&cp_in=wt_tg',
166 'only_matching': True,
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,
171 }]
172
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',)
178 _API_HEADERS = {
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',
184 }
185
186 def _perform_login(self, username, password):
187 login_ok = True
188 login_form_strs = {
189 'mail_tel': username,
190 'password': password,
191 }
192 self._request_webpage(
193 'https://account.nicovideo.jp/login', None,
194 note='Acquiring Login session')
195 urlh = self._request_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),
199 headers={
200 'Referer': 'https://account.nicovideo.jp/login',
201 'Content-Type': 'application/x-www-form-urlencoded',
202 })
203 if urlh is False:
204 login_ok = False
205 else:
206 parts = compat_urllib_parse_urlparse(urlh.geturl())
207 if compat_parse_qs(parts.query).get('message', [None])[0] == 'cant_login':
208 login_ok = False
209 if not login_ok:
210 self.report_warning('unable to log in: bad username or password')
211 return login_ok
212
213 def _get_heartbeat_info(self, info_dict):
214 video_id, video_src_id, audio_src_id = info_dict['url'].split(':')[1].split('/')
215 dmc_protocol = info_dict['_expected_protocol']
216
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))
225
226 session_api_data = try_get(api_data, lambda x: x['media']['delivery']['movie']['session'])
227 session_api_endpoint = try_get(session_api_data, lambda x: x['urls'][0])
228
229 def ping():
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.')
239
240 yesno = lambda x: 'yes' if x else 'no'
241
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':
251 protocol = 'm3u8'
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']),
261 }
262 }
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'],
268 }
269 }
270 else:
271 protocol = 'm3u8_native'
272 else:
273 raise ExtractorError(f'Unsupported DMC protocol: {dmc_protocol}')
274
275 session_response = self._download_json(
276 session_api_endpoint['url'], video_id,
277 query={'_format': 'json'},
278 headers={'Content-Type': 'application/json'},
279 note='Downloading JSON metadata for %s' % info_dict['format_id'],
280 data=json.dumps({
281 'session': {
282 'client_info': {
283 'player_id': session_api_data.get('playerId'),
284 },
285 'content_auth': {
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'),
288 'service_id': 'nicovideo',
289 'service_user_id': session_api_data.get('serviceUserId')
290 },
291 'content_id': session_api_data.get('contentId'),
292 'content_src_id_sets': [{
293 'content_src_ids': [{
294 'src_id_to_mux': {
295 'audio_src_ids': [audio_src_id],
296 'video_src_ids': [video_src_id],
297 }
298 }]
299 }],
300 'content_type': 'movie',
301 'content_uri': '',
302 'keep_method': {
303 'heartbeat': {
304 'lifetime': session_api_data.get('heartbeatLifetime')
305 }
306 },
307 'priority': session_api_data['priority'],
308 'protocol': {
309 'name': 'http',
310 'parameters': {
311 'http_parameters': {
312 'parameters': protocol_parameters
313 }
314 }
315 },
316 'recipe_id': session_api_data.get('recipeId'),
317 'session_operation_auth': {
318 'session_operation_auth_by_signature': {
319 'signature': session_api_data.get('signature'),
320 'token': session_api_data.get('token'),
321 }
322 },
323 'timing_constraint': 'unlimited'
324 }
325 }).encode())
326
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.
335 'interval': float_or_none(session_api_data.get('heartbeatLifetime'), scale=3000),
336 'ping': ping
337 }
338
339 return info_dict, heartbeat_info_dict
340
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'))
355
356 return {
357 'url': 'niconico_dmc:%s/%s/%s' % (video_id, video_quality['id'], audio_quality['id']),
358 'format_id': format_id,
359 'format_note': join_nonempty('DMC', vid_qual_label, dmc_protocol.upper(), delim=' '),
360 'ext': 'mp4', # Session API are used in HTML5, which always serves mp4
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',
369 '_expected_protocol': dmc_protocol,
370 'http_headers': {
371 'Origin': 'https://www.nicovideo.jp',
372 'Referer': 'https://www.nicovideo.jp/watch/' + video_id,
373 }
374 }
375
376 def _real_extract(self, url):
377 video_id = self._match_id(url)
378
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())
384
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)
403
404 formats = []
405
406 def get_video_info(*items, get_first=True, **kwargs):
407 return traverse_obj(api_data, ('video', *items), get_all=not get_first, **kwargs)
408
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)
415
416 self._sort_formats(formats)
417
418 # Start extracting information
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'))
432
433 return {
434 'id': video_id,
435 '_api_data': api_data,
436 'title': get_video_info(('originalTitle', 'title')) or self._og_search_title(webpage, default=None),
437 'formats': formats,
438 'thumbnail': get_video_info('thumbnail', 'url') or self._html_search_meta(
439 ('image', 'og:image'), webpage, 'thumbnail', default=None),
440 'description': clean_html(get_video_info('description')),
441 'uploader': traverse_obj(api_data, ('owner', 'nickname')),
442 'timestamp': parse_iso8601(get_video_info('registeredAt')) or parse_iso8601(
443 self._html_search_meta('video:release_date', webpage, 'date published', default=None)),
444 'uploader_id': traverse_obj(api_data, ('owner', 'id')),
445 'channel': traverse_obj(api_data, ('channel', 'name'), ('community', 'name')),
446 'channel_id': traverse_obj(api_data, ('channel', 'id'), ('community', 'id')),
447 'view_count': int_or_none(get_video_info('count', 'view')),
448 'tags': tags,
449 'genre': traverse_obj(api_data, ('genre', 'label'), ('genre', 'key')),
450 'comment_count': get_video_info('count', 'comment', expected_type=int),
451 'duration': (
452 parse_duration(self._html_search_meta('video:duration', webpage, 'video duration', default=None))
453 or get_video_info('duration')),
454 'webpage_url': url_or_none(url) or f'https://www.nicovideo.jp/watch/{video_id}',
455 'subtitles': self.extract_subtitles(video_id, api_data, session_api_data),
456 }
457
458 def _get_subtitles(self, video_id, api_data, session_api_data):
459 comment_user_key = traverse_obj(api_data, ('comment', 'keys', 'userKey'))
460 user_id_str = session_api_data.get('serviceUserId')
461
462 thread_ids = [x for x in traverse_obj(api_data, ('comment', 'threads')) or [] if x['isActive']]
463 raw_danmaku = self._extract_all_comments(video_id, thread_ids, user_id_str, comment_user_key)
464 if not raw_danmaku:
465 self.report_warning(f'Failed to get comments. {bug_reports_message()}')
466 return
467 return {
468 'comments': [{
469 'ext': 'json',
470 'data': json.dumps(raw_danmaku),
471 }],
472 }
473
474 def _extract_all_comments(self, video_id, threads, user_id, user_key):
475 auth_data = {
476 'user_id': user_id,
477 'userkey': user_key,
478 } if user_id and user_key else {'user_id': ''}
479
480 # Request Start
481 post_data = [{'ping': {'content': 'rs:0'}}]
482 for i, thread in enumerate(threads):
483 thread_id = thread['id']
484 thread_fork = thread['fork']
485 # Post Start (2N)
486 post_data.append({'ping': {'content': f'ps:{i * 2}'}})
487 post_data.append({'thread': {
488 'fork': thread_fork,
489 'language': 0,
490 'nicoru': 3,
491 'scores': 1,
492 'thread': thread_id,
493 'version': '20090904',
494 'with_global': 1,
495 **auth_data,
496 }})
497 # Post Final (2N)
498 post_data.append({'ping': {'content': f'pf:{i * 2}'}})
499
500 # Post Start (2N+1)
501 post_data.append({'ping': {'content': f'ps:{i * 2 + 1}'}})
502 post_data.append({'thread_leaves': {
503 # format is '<bottom of minute range>-<top of minute range>:<comments per minute>,<total last comments'
504 # unfortunately NND limits (deletes?) comment returns this way, so you're only able to grab the last 1000 per language
505 'content': '0-999999:999999,999999,nicoru:999999',
506 'fork': thread_fork,
507 'language': 0,
508 'nicoru': 3,
509 'scores': 1,
510 'thread': thread_id,
511 **auth_data,
512 }})
513 # Post Final (2N+1)
514 post_data.append({'ping': {'content': f'pf:{i * 2 + 1}'}})
515 # Request Final
516 post_data.append({'ping': {'content': 'rf:0'}})
517
518 for api_url in self._COMMENT_API_ENDPOINTS:
519 comments = self._download_json(
520 api_url, video_id, data=json.dumps(post_data).encode(), fatal=False,
521 headers={
522 'Referer': 'https://www.nicovideo.jp/watch/%s' % video_id,
523 'Origin': 'https://www.nicovideo.jp',
524 'Content-Type': 'text/plain;charset=UTF-8',
525 },
526 note='Downloading comments', errnote=f'Failed to access endpoint {api_url}')
527 if comments:
528 return comments
529
530
531 class NiconicoPlaylistBaseIE(InfoExtractor):
532 _PAGE_SIZE = 100
533
534 _API_HEADERS = {
535 'X-Frontend-ID': '6',
536 'X-Frontend-Version': '0',
537 'X-Niconico-Language': 'en-us'
538 }
539
540 def _call_api(self, list_id, resource, query):
541 "Implement this in child class"
542 pass
543
544 @staticmethod
545 def _parse_owner(item):
546 return {
547 'uploader': traverse_obj(item, ('owner', 'name')),
548 'uploader_id': traverse_obj(item, ('owner', 'id')),
549 }
550
551 def _fetch_page(self, list_id, page):
552 page += 1
553 resp = self._call_api(list_id, 'page %d' % page, {
554 'page': page,
555 'pageSize': self._PAGE_SIZE,
556 })
557 # this is needed to support both mylist and user
558 for video in traverse_obj(resp, ('items', ..., ('video', None))) or []:
559 video_id = video.get('id')
560 if not video_id:
561 # skip {"video": {"id": "blablabla", ...}}
562 continue
563 count = video.get('count') or {}
564 get_count = lambda x: int_or_none(count.get(x))
565 yield {
566 '_type': 'url',
567 'id': video_id,
568 'title': video.get('title'),
569 'url': f'https://www.nicovideo.jp/watch/{video_id}',
570 'description': video.get('shortDescription'),
571 'duration': int_or_none(video.get('duration')),
572 'view_count': get_count('view'),
573 'comment_count': get_count('comment'),
574 'thumbnail': traverse_obj(video, ('thumbnail', ('nHdUrl', 'largeUrl', 'listingUrl', 'url'))),
575 'ie_key': NiconicoIE.ie_key(),
576 **self._parse_owner(video),
577 }
578
579 def _entries(self, list_id):
580 return OnDemandPagedList(functools.partial(self._fetch_page, list_id), self._PAGE_SIZE)
581
582
583 class NiconicoPlaylistIE(NiconicoPlaylistBaseIE):
584 IE_NAME = 'niconico:playlist'
585 _VALID_URL = r'https?://(?:(?:www\.|sp\.)?nicovideo\.jp|nico\.ms)/(?:user/\d+/)?(?:my/)?mylist/(?:#/)?(?P<id>\d+)'
586
587 _TESTS = [{
588 'url': 'http://www.nicovideo.jp/mylist/27411728',
589 'info_dict': {
590 'id': '27411728',
591 'title': 'AKB48のオールナイトニッポン',
592 'description': 'md5:d89694c5ded4b6c693dea2db6e41aa08',
593 'uploader': 'のっく',
594 'uploader_id': '805442',
595 },
596 'playlist_mincount': 291,
597 }, {
598 'url': 'https://www.nicovideo.jp/user/805442/mylist/27411728',
599 'only_matching': True,
600 }, {
601 'url': 'https://www.nicovideo.jp/my/mylist/#/68048635',
602 'only_matching': True,
603 }]
604
605 def _call_api(self, list_id, resource, query):
606 return self._download_json(
607 f'https://nvapi.nicovideo.jp/v2/mylists/{list_id}', list_id,
608 f'Downloading {resource}', query=query,
609 headers=self._API_HEADERS)['data']['mylist']
610
611 def _real_extract(self, url):
612 list_id = self._match_id(url)
613 mylist = self._call_api(list_id, 'list', {
614 'pageSize': 1,
615 })
616 return self.playlist_result(
617 self._entries(list_id), list_id,
618 mylist.get('name'), mylist.get('description'), **self._parse_owner(mylist))
619
620
621 class NiconicoSeriesIE(InfoExtractor):
622 IE_NAME = 'niconico:series'
623 _VALID_URL = r'https?://(?:(?:www\.|sp\.)?nicovideo\.jp|nico\.ms)/series/(?P<id>\d+)'
624
625 _TESTS = [{
626 'url': 'https://www.nicovideo.jp/series/110226',
627 'info_dict': {
628 'id': '110226',
629 'title': 'ご立派ァ!のシリーズ',
630 },
631 'playlist_mincount': 10, # as of 2021/03/17
632 }, {
633 'url': 'https://www.nicovideo.jp/series/12312/',
634 'info_dict': {
635 'id': '12312',
636 'title': 'バトルスピリッツ お勧めカード紹介(調整中)',
637 },
638 'playlist_mincount': 97, # as of 2021/03/17
639 }, {
640 'url': 'https://nico.ms/series/203559',
641 'only_matching': True,
642 }]
643
644 def _real_extract(self, url):
645 list_id = self._match_id(url)
646 webpage = self._download_webpage(f'https://www.nicovideo.jp/series/{list_id}', list_id)
647
648 title = self._search_regex(
649 (r'<title>「(.+)(全',
650 r'<div class="TwitterShareButton"\s+data-text="(.+)\s+https:'),
651 webpage, 'title', fatal=False)
652 if title:
653 title = unescapeHTML(title)
654 playlist = [
655 self.url_result(f'https://www.nicovideo.jp/watch/{v_id}', video_id=v_id)
656 for v_id in re.findall(r'href="/watch/([a-z0-9]+)" data-href="/watch/\1', webpage)]
657 return self.playlist_result(playlist, list_id, title)
658
659
660 class NiconicoHistoryIE(NiconicoPlaylistBaseIE):
661 IE_NAME = 'niconico:history'
662 IE_DESC = 'NicoNico user history. Requires cookies.'
663 _VALID_URL = r'https?://(?:www\.|sp\.)?nicovideo\.jp/my/history'
664
665 _TESTS = [{
666 'note': 'PC page, with /video',
667 'url': 'https://www.nicovideo.jp/my/history/video',
668 'only_matching': True,
669 }, {
670 'note': 'PC page, without /video',
671 'url': 'https://www.nicovideo.jp/my/history',
672 'only_matching': True,
673 }, {
674 'note': 'mobile page, with /video',
675 'url': 'https://sp.nicovideo.jp/my/history/video',
676 'only_matching': True,
677 }, {
678 'note': 'mobile page, without /video',
679 'url': 'https://sp.nicovideo.jp/my/history',
680 'only_matching': True,
681 }]
682
683 def _call_api(self, list_id, resource, query):
684 return self._download_json(
685 'https://nvapi.nicovideo.jp/v1/users/me/watch/history', 'history',
686 f'Downloading {resource}', query=query,
687 headers=self._API_HEADERS)['data']
688
689 def _real_extract(self, url):
690 list_id = 'history'
691 try:
692 mylist = self._call_api(list_id, 'list', {
693 'pageSize': 1,
694 })
695 except ExtractorError as e:
696 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
697 self.raise_login_required('You have to be logged in to get your watch history')
698 raise
699 return self.playlist_result(self._entries(list_id), list_id, **self._parse_owner(mylist))
700
701
702 class NicovideoSearchBaseIE(InfoExtractor):
703 _SEARCH_TYPE = 'search'
704
705 def _entries(self, url, item_id, query=None, note='Downloading page %(page)s'):
706 query = query or {}
707 pages = [query['page']] if 'page' in query else itertools.count(1)
708 for page_num in pages:
709 query['page'] = str(page_num)
710 webpage = self._download_webpage(url, item_id, query=query, note=note % {'page': page_num})
711 results = re.findall(r'(?<=data-video-id=)["\']?(?P<videoid>.*?)(?=["\'])', webpage)
712 for item in results:
713 yield self.url_result(f'http://www.nicovideo.jp/watch/{item}', 'Niconico', item)
714 if not results:
715 break
716
717 def _search_results(self, query):
718 return self._entries(
719 self._proto_relative_url(f'//www.nicovideo.jp/{self._SEARCH_TYPE}/{query}'), query)
720
721
722 class NicovideoSearchIE(NicovideoSearchBaseIE, SearchInfoExtractor):
723 IE_DESC = 'Nico video search'
724 IE_NAME = 'nicovideo:search'
725 _SEARCH_KEY = 'nicosearch'
726
727
728 class NicovideoSearchURLIE(NicovideoSearchBaseIE):
729 IE_NAME = f'{NicovideoSearchIE.IE_NAME}_url'
730 IE_DESC = 'Nico video search URLs'
731 _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/search/(?P<id>[^?#&]+)?'
732 _TESTS = [{
733 'url': 'http://www.nicovideo.jp/search/sm9',
734 'info_dict': {
735 'id': 'sm9',
736 'title': 'sm9'
737 },
738 'playlist_mincount': 40,
739 }, {
740 'url': 'https://www.nicovideo.jp/search/sm9?sort=h&order=d&end=2020-12-31&start=2020-01-01',
741 'info_dict': {
742 'id': 'sm9',
743 'title': 'sm9'
744 },
745 'playlist_count': 31,
746 }]
747
748 def _real_extract(self, url):
749 query = self._match_id(url)
750 return self.playlist_result(self._entries(url, query), query, query)
751
752
753 class NicovideoSearchDateIE(NicovideoSearchBaseIE, SearchInfoExtractor):
754 IE_DESC = 'Nico video search, newest first'
755 IE_NAME = f'{NicovideoSearchIE.IE_NAME}:date'
756 _SEARCH_KEY = 'nicosearchdate'
757 _TESTS = [{
758 'url': 'nicosearchdateall:a',
759 'info_dict': {
760 'id': 'a',
761 'title': 'a'
762 },
763 'playlist_mincount': 1610,
764 }]
765
766 _START_DATE = datetime.date(2007, 1, 1)
767 _RESULTS_PER_PAGE = 32
768 _MAX_PAGES = 50
769
770 def _entries(self, url, item_id, start_date=None, end_date=None):
771 start_date, end_date = start_date or self._START_DATE, end_date or datetime.datetime.now().date()
772
773 # If the last page has a full page of videos, we need to break down the query interval further
774 last_page_len = len(list(self._get_entries_for_date(
775 url, item_id, start_date, end_date, self._MAX_PAGES,
776 note=f'Checking number of videos from {start_date} to {end_date}')))
777 if (last_page_len == self._RESULTS_PER_PAGE and start_date != end_date):
778 midpoint = start_date + ((end_date - start_date) // 2)
779 yield from self._entries(url, item_id, midpoint, end_date)
780 yield from self._entries(url, item_id, start_date, midpoint)
781 else:
782 self.to_screen(f'{item_id}: Downloading results from {start_date} to {end_date}')
783 yield from self._get_entries_for_date(
784 url, item_id, start_date, end_date, note=' Downloading page %(page)s')
785
786 def _get_entries_for_date(self, url, item_id, start_date, end_date=None, page_num=None, note=None):
787 query = {
788 'start': str(start_date),
789 'end': str(end_date or start_date),
790 'sort': 'f',
791 'order': 'd',
792 }
793 if page_num:
794 query['page'] = str(page_num)
795
796 yield from super()._entries(url, item_id, query=query, note=note)
797
798
799 class NicovideoTagURLIE(NicovideoSearchBaseIE):
800 IE_NAME = 'niconico:tag'
801 IE_DESC = 'NicoNico video tag URLs'
802 _SEARCH_TYPE = 'tag'
803 _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/tag/(?P<id>[^?#&]+)?'
804 _TESTS = [{
805 'url': 'https://www.nicovideo.jp/tag/ドキュメンタリー淫夢',
806 'info_dict': {
807 'id': 'ドキュメンタリー淫夢',
808 'title': 'ドキュメンタリー淫夢'
809 },
810 'playlist_mincount': 400,
811 }]
812
813 def _real_extract(self, url):
814 query = self._match_id(url)
815 return self.playlist_result(self._entries(url, query), query, query)
816
817
818 class NiconicoUserIE(InfoExtractor):
819 _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/user/(?P<id>\d+)/?(?:$|[#?])'
820 _TEST = {
821 'url': 'https://www.nicovideo.jp/user/419948',
822 'info_dict': {
823 'id': '419948',
824 },
825 'playlist_mincount': 101,
826 }
827 _API_URL = "https://nvapi.nicovideo.jp/v1/users/%s/videos?sortKey=registeredAt&sortOrder=desc&pageSize=%s&page=%s"
828 _PAGE_SIZE = 100
829
830 _API_HEADERS = {
831 'X-Frontend-ID': '6',
832 'X-Frontend-Version': '0'
833 }
834
835 def _entries(self, list_id):
836 total_count = 1
837 count = page_num = 0
838 while count < total_count:
839 json_parsed = self._download_json(
840 self._API_URL % (list_id, self._PAGE_SIZE, page_num + 1), list_id,
841 headers=self._API_HEADERS,
842 note='Downloading JSON metadata%s' % (' page %d' % page_num if page_num else ''))
843 if not page_num:
844 total_count = int_or_none(json_parsed['data'].get('totalCount'))
845 for entry in json_parsed["data"]["items"]:
846 count += 1
847 yield self.url_result('https://www.nicovideo.jp/watch/%s' % entry['id'])
848 page_num += 1
849
850 def _real_extract(self, url):
851 list_id = self._match_id(url)
852 return self.playlist_result(self._entries(list_id), list_id, ie=NiconicoIE.ie_key())