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