]>
Commit | Line | Data |
---|---|---|
1 | # coding: utf-8 | |
2 | from __future__ import unicode_literals | |
3 | ||
4 | import datetime | |
5 | import itertools | |
6 | import json | |
7 | import re | |
8 | ||
9 | from .common import InfoExtractor, SearchInfoExtractor | |
10 | from ..postprocessor.ffmpeg import FFmpegPostProcessor | |
11 | from ..compat import ( | |
12 | compat_str, | |
13 | compat_parse_qs, | |
14 | compat_urllib_parse_urlparse, | |
15 | ) | |
16 | from ..utils import ( | |
17 | ExtractorError, | |
18 | dict_get, | |
19 | float_or_none, | |
20 | int_or_none, | |
21 | OnDemandPagedList, | |
22 | parse_duration, | |
23 | parse_iso8601, | |
24 | PostProcessingError, | |
25 | remove_start, | |
26 | str_or_none, | |
27 | try_get, | |
28 | unified_timestamp, | |
29 | urlencode_postdata, | |
30 | xpath_text, | |
31 | ) | |
32 | ||
33 | ||
34 | class NiconicoIE(InfoExtractor): | |
35 | IE_NAME = 'niconico' | |
36 | IE_DESC = 'ニコニコ動画' | |
37 | ||
38 | _TESTS = [{ | |
39 | 'url': 'http://www.nicovideo.jp/watch/sm22312215', | |
40 | 'md5': 'a5bad06f1347452102953f323c69da34s', | |
41 | 'info_dict': { | |
42 | 'id': 'sm22312215', | |
43 | 'ext': 'mp4', | |
44 | 'title': 'Big Buck Bunny', | |
45 | 'thumbnail': r're:https?://.*', | |
46 | 'uploader': 'takuya0301', | |
47 | 'uploader_id': '2698420', | |
48 | 'upload_date': '20131123', | |
49 | 'timestamp': int, # timestamp is unstable | |
50 | 'description': '(c) copyright 2008, Blender Foundation / www.bigbuckbunny.org', | |
51 | 'duration': 33, | |
52 | 'view_count': int, | |
53 | 'comment_count': int, | |
54 | }, | |
55 | 'skip': 'Requires an account', | |
56 | }, { | |
57 | # File downloaded with and without credentials are different, so omit | |
58 | # the md5 field | |
59 | 'url': 'http://www.nicovideo.jp/watch/nm14296458', | |
60 | 'info_dict': { | |
61 | 'id': 'nm14296458', | |
62 | 'ext': 'swf', | |
63 | 'title': '【鏡音リン】Dance on media【オリジナル】take2!', | |
64 | 'description': 'md5:689f066d74610b3b22e0f1739add0f58', | |
65 | 'thumbnail': r're:https?://.*', | |
66 | 'uploader': 'りょうた', | |
67 | 'uploader_id': '18822557', | |
68 | 'upload_date': '20110429', | |
69 | 'timestamp': 1304065916, | |
70 | 'duration': 209, | |
71 | }, | |
72 | 'skip': 'Requires an account', | |
73 | }, { | |
74 | # 'video exists but is marked as "deleted" | |
75 | # md5 is unstable | |
76 | 'url': 'http://www.nicovideo.jp/watch/sm10000', | |
77 | 'info_dict': { | |
78 | 'id': 'sm10000', | |
79 | 'ext': 'unknown_video', | |
80 | 'description': 'deleted', | |
81 | 'title': 'ドラえもんエターナル第3話「決戦第3新東京市」<前編>', | |
82 | 'thumbnail': r're:https?://.*', | |
83 | 'upload_date': '20071224', | |
84 | 'timestamp': int, # timestamp field has different value if logged in | |
85 | 'duration': 304, | |
86 | 'view_count': int, | |
87 | }, | |
88 | 'skip': 'Requires an account', | |
89 | }, { | |
90 | 'url': 'http://www.nicovideo.jp/watch/so22543406', | |
91 | 'info_dict': { | |
92 | 'id': '1388129933', | |
93 | 'ext': 'mp4', | |
94 | 'title': '【第1回】RADIOアニメロミックス ラブライブ!~のぞえりRadio Garden~', | |
95 | 'description': 'md5:b27d224bb0ff53d3c8269e9f8b561cf1', | |
96 | 'thumbnail': r're:https?://.*', | |
97 | 'timestamp': 1388851200, | |
98 | 'upload_date': '20140104', | |
99 | 'uploader': 'アニメロチャンネル', | |
100 | 'uploader_id': '312', | |
101 | }, | |
102 | 'skip': 'The viewing period of the video you were searching for has expired.', | |
103 | }, { | |
104 | # video not available via `getflv`; "old" HTML5 video | |
105 | 'url': 'http://www.nicovideo.jp/watch/sm1151009', | |
106 | 'md5': '8fa81c364eb619d4085354eab075598a', | |
107 | 'info_dict': { | |
108 | 'id': 'sm1151009', | |
109 | 'ext': 'mp4', | |
110 | 'title': 'マスターシステム本体内蔵のスペハリのメインテーマ(PSG版)', | |
111 | 'description': 'md5:6ee077e0581ff5019773e2e714cdd0b7', | |
112 | 'thumbnail': r're:https?://.*', | |
113 | 'duration': 184, | |
114 | 'timestamp': 1190868283, | |
115 | 'upload_date': '20070927', | |
116 | 'uploader': 'denden2', | |
117 | 'uploader_id': '1392194', | |
118 | 'view_count': int, | |
119 | 'comment_count': int, | |
120 | }, | |
121 | 'skip': 'Requires an account', | |
122 | }, { | |
123 | # "New" HTML5 video | |
124 | # md5 is unstable | |
125 | 'url': 'http://www.nicovideo.jp/watch/sm31464864', | |
126 | 'info_dict': { | |
127 | 'id': 'sm31464864', | |
128 | 'ext': 'mp4', | |
129 | 'title': '新作TVアニメ「戦姫絶唱シンフォギアAXZ」PV 最高画質', | |
130 | 'description': 'md5:e52974af9a96e739196b2c1ca72b5feb', | |
131 | 'timestamp': 1498514060, | |
132 | 'upload_date': '20170626', | |
133 | 'uploader': 'ゲスト', | |
134 | 'uploader_id': '40826363', | |
135 | 'thumbnail': r're:https?://.*', | |
136 | 'duration': 198, | |
137 | 'view_count': int, | |
138 | 'comment_count': int, | |
139 | }, | |
140 | 'skip': 'Requires an account', | |
141 | }, { | |
142 | # Video without owner | |
143 | 'url': 'http://www.nicovideo.jp/watch/sm18238488', | |
144 | 'md5': 'd265680a1f92bdcbbd2a507fc9e78a9e', | |
145 | 'info_dict': { | |
146 | 'id': 'sm18238488', | |
147 | 'ext': 'mp4', | |
148 | 'title': '【実写版】ミュータントタートルズ', | |
149 | 'description': 'md5:15df8988e47a86f9e978af2064bf6d8e', | |
150 | 'timestamp': 1341160408, | |
151 | 'upload_date': '20120701', | |
152 | 'uploader': None, | |
153 | 'uploader_id': None, | |
154 | 'thumbnail': r're:https?://.*', | |
155 | 'duration': 5271, | |
156 | 'view_count': int, | |
157 | 'comment_count': int, | |
158 | }, | |
159 | 'skip': 'Requires an account', | |
160 | }, { | |
161 | 'url': 'http://sp.nicovideo.jp/watch/sm28964488?ss_pos=1&cp_in=wt_tg', | |
162 | 'only_matching': True, | |
163 | }] | |
164 | ||
165 | _VALID_URL = r'https?://(?:www\.|secure\.|sp\.)?nicovideo\.jp/watch/(?P<id>(?:[a-z]{2})?[0-9]+)' | |
166 | _NETRC_MACHINE = 'niconico' | |
167 | ||
168 | _API_HEADERS = { | |
169 | 'X-Frontend-ID': '6', | |
170 | 'X-Frontend-Version': '0' | |
171 | } | |
172 | ||
173 | def _real_initialize(self): | |
174 | self._login() | |
175 | ||
176 | def _login(self): | |
177 | username, password = self._get_login_info() | |
178 | # No authentication to be performed | |
179 | if not username: | |
180 | return True | |
181 | ||
182 | # Log in | |
183 | login_ok = True | |
184 | login_form_strs = { | |
185 | 'mail_tel': username, | |
186 | 'password': password, | |
187 | } | |
188 | urlh = self._request_webpage( | |
189 | 'https://account.nicovideo.jp/api/v1/login', None, | |
190 | note='Logging in', errnote='Unable to log in', | |
191 | data=urlencode_postdata(login_form_strs)) | |
192 | if urlh is False: | |
193 | login_ok = False | |
194 | else: | |
195 | parts = compat_urllib_parse_urlparse(urlh.geturl()) | |
196 | if compat_parse_qs(parts.query).get('message', [None])[0] == 'cant_login': | |
197 | login_ok = False | |
198 | if not login_ok: | |
199 | self.report_warning('unable to log in: bad username or password') | |
200 | return login_ok | |
201 | ||
202 | def _get_heartbeat_info(self, info_dict): | |
203 | ||
204 | video_id, video_src_id, audio_src_id = info_dict['url'].split(':')[1].split('/') | |
205 | ||
206 | api_data = ( | |
207 | info_dict.get('_api_data') | |
208 | or self._parse_json( | |
209 | self._html_search_regex( | |
210 | 'data-api-data="([^"]+)"', | |
211 | self._download_webpage('http://www.nicovideo.jp/watch/' + video_id, video_id), | |
212 | 'API data', default='{}'), | |
213 | video_id)) | |
214 | ||
215 | session_api_data = try_get(api_data, lambda x: x['media']['delivery']['movie']['session']) | |
216 | session_api_endpoint = try_get(session_api_data, lambda x: x['urls'][0]) | |
217 | ||
218 | def ping(): | |
219 | status = try_get( | |
220 | self._download_json( | |
221 | 'https://nvapi.nicovideo.jp/v1/2ab0cbaa/watch', video_id, | |
222 | query={'t': try_get(api_data, lambda x: x['media']['delivery']['trackingId'])}, | |
223 | note='Acquiring permission for downloading video', | |
224 | headers=self._API_HEADERS), | |
225 | lambda x: x['meta']['status']) | |
226 | if status != 200: | |
227 | self.report_warning('Failed to acquire permission for playing video. The video may not download.') | |
228 | ||
229 | yesno = lambda x: 'yes' if x else 'no' | |
230 | ||
231 | # m3u8 (encryption) | |
232 | if try_get(api_data, lambda x: x['media']['delivery']['encryption']) is not None: | |
233 | protocol = 'm3u8' | |
234 | encryption = self._parse_json(session_api_data['token'], video_id)['hls_encryption'] | |
235 | session_api_http_parameters = { | |
236 | 'parameters': { | |
237 | 'hls_parameters': { | |
238 | 'encryption': { | |
239 | encryption: { | |
240 | 'encrypted_key': try_get(api_data, lambda x: x['media']['delivery']['encryption']['encryptedKey']), | |
241 | 'key_uri': try_get(api_data, lambda x: x['media']['delivery']['encryption']['keyUri']) | |
242 | } | |
243 | }, | |
244 | 'transfer_preset': '', | |
245 | 'use_ssl': yesno(session_api_endpoint['isSsl']), | |
246 | 'use_well_known_port': yesno(session_api_endpoint['isWellKnownPort']), | |
247 | 'segment_duration': 6000, | |
248 | } | |
249 | } | |
250 | } | |
251 | # http | |
252 | else: | |
253 | protocol = 'http' | |
254 | session_api_http_parameters = { | |
255 | 'parameters': { | |
256 | 'http_output_download_parameters': { | |
257 | 'use_ssl': yesno(session_api_endpoint['isSsl']), | |
258 | 'use_well_known_port': yesno(session_api_endpoint['isWellKnownPort']), | |
259 | } | |
260 | } | |
261 | } | |
262 | ||
263 | session_response = self._download_json( | |
264 | session_api_endpoint['url'], video_id, | |
265 | query={'_format': 'json'}, | |
266 | headers={'Content-Type': 'application/json'}, | |
267 | note='Downloading JSON metadata for %s' % info_dict['format_id'], | |
268 | data=json.dumps({ | |
269 | 'session': { | |
270 | 'client_info': { | |
271 | 'player_id': session_api_data.get('playerId'), | |
272 | }, | |
273 | 'content_auth': { | |
274 | 'auth_type': try_get(session_api_data, lambda x: x['authTypes'][session_api_data['protocols'][0]]), | |
275 | 'content_key_timeout': session_api_data.get('contentKeyTimeout'), | |
276 | 'service_id': 'nicovideo', | |
277 | 'service_user_id': session_api_data.get('serviceUserId') | |
278 | }, | |
279 | 'content_id': session_api_data.get('contentId'), | |
280 | 'content_src_id_sets': [{ | |
281 | 'content_src_ids': [{ | |
282 | 'src_id_to_mux': { | |
283 | 'audio_src_ids': [audio_src_id], | |
284 | 'video_src_ids': [video_src_id], | |
285 | } | |
286 | }] | |
287 | }], | |
288 | 'content_type': 'movie', | |
289 | 'content_uri': '', | |
290 | 'keep_method': { | |
291 | 'heartbeat': { | |
292 | 'lifetime': session_api_data.get('heartbeatLifetime') | |
293 | } | |
294 | }, | |
295 | 'priority': session_api_data.get('priority'), | |
296 | 'protocol': { | |
297 | 'name': 'http', | |
298 | 'parameters': { | |
299 | 'http_parameters': session_api_http_parameters | |
300 | } | |
301 | }, | |
302 | 'recipe_id': session_api_data.get('recipeId'), | |
303 | 'session_operation_auth': { | |
304 | 'session_operation_auth_by_signature': { | |
305 | 'signature': session_api_data.get('signature'), | |
306 | 'token': session_api_data.get('token'), | |
307 | } | |
308 | }, | |
309 | 'timing_constraint': 'unlimited' | |
310 | } | |
311 | }).encode()) | |
312 | ||
313 | info_dict['url'] = session_response['data']['session']['content_uri'] | |
314 | info_dict['protocol'] = protocol | |
315 | ||
316 | # get heartbeat info | |
317 | heartbeat_info_dict = { | |
318 | 'url': session_api_endpoint['url'] + '/' + session_response['data']['session']['id'] + '?_format=json&_method=PUT', | |
319 | 'data': json.dumps(session_response['data']), | |
320 | # interval, convert milliseconds to seconds, then halve to make a buffer. | |
321 | 'interval': float_or_none(session_api_data.get('heartbeatLifetime'), scale=3000), | |
322 | 'ping': ping | |
323 | } | |
324 | ||
325 | return info_dict, heartbeat_info_dict | |
326 | ||
327 | def _extract_format_for_quality(self, api_data, video_id, audio_quality, video_quality): | |
328 | def parse_format_id(id_code): | |
329 | mobj = re.match(r'''(?x) | |
330 | (?:archive_)? | |
331 | (?:(?P<codec>[^_]+)_)? | |
332 | (?:(?P<br>[\d]+)kbps_)? | |
333 | (?:(?P<res>[\d+]+)p_)? | |
334 | ''', '%s_' % id_code) | |
335 | return mobj.groupdict() if mobj else {} | |
336 | ||
337 | protocol = 'niconico_dmc' | |
338 | format_id = '-'.join(map(lambda s: remove_start(s['id'], 'archive_'), [video_quality, audio_quality])) | |
339 | vdict = parse_format_id(video_quality['id']) | |
340 | adict = parse_format_id(audio_quality['id']) | |
341 | resolution = try_get(video_quality, lambda x: x['metadata']['resolution'], dict) or {'height': vdict.get('res')} | |
342 | vbr = try_get(video_quality, lambda x: x['metadata']['bitrate'], float) | |
343 | ||
344 | return { | |
345 | 'url': '%s:%s/%s/%s' % (protocol, video_id, video_quality['id'], audio_quality['id']), | |
346 | 'format_id': format_id, | |
347 | 'format_note': 'DMC %s' % try_get(video_quality, lambda x: x['metadata']['label'], compat_str), | |
348 | 'ext': 'mp4', # Session API are used in HTML5, which always serves mp4 | |
349 | 'vcodec': vdict.get('codec'), | |
350 | 'acodec': adict.get('codec'), | |
351 | 'vbr': float_or_none(vbr, 1000) or float_or_none(vdict.get('br')), | |
352 | 'abr': float_or_none(audio_quality.get('bitrate'), 1000) or float_or_none(adict.get('br')), | |
353 | 'height': int_or_none(resolution.get('height', vdict.get('res'))), | |
354 | 'width': int_or_none(resolution.get('width')), | |
355 | 'quality': -2 if 'low' in format_id else -1, # Default quality value is -1 | |
356 | 'protocol': protocol, | |
357 | 'http_headers': { | |
358 | 'Origin': 'https://www.nicovideo.jp', | |
359 | 'Referer': 'https://www.nicovideo.jp/watch/' + video_id, | |
360 | } | |
361 | } | |
362 | ||
363 | def _real_extract(self, url): | |
364 | video_id = self._match_id(url) | |
365 | ||
366 | # Get video webpage for API data. | |
367 | webpage, handle = self._download_webpage_handle( | |
368 | 'http://www.nicovideo.jp/watch/' + video_id, video_id) | |
369 | if video_id.startswith('so'): | |
370 | video_id = self._match_id(handle.geturl()) | |
371 | ||
372 | api_data = self._parse_json(self._html_search_regex( | |
373 | 'data-api-data="([^"]+)"', webpage, | |
374 | 'API data', default='{}'), video_id) | |
375 | ||
376 | def get_video_info_web(items): | |
377 | return dict_get(api_data['video'], items) | |
378 | ||
379 | # Get video info | |
380 | video_info_xml = self._download_xml( | |
381 | 'http://ext.nicovideo.jp/api/getthumbinfo/' + video_id, | |
382 | video_id, note='Downloading video info page') | |
383 | ||
384 | def get_video_info_xml(items): | |
385 | if not isinstance(items, list): | |
386 | items = [items] | |
387 | for item in items: | |
388 | ret = xpath_text(video_info_xml, './/' + item) | |
389 | if ret: | |
390 | return ret | |
391 | ||
392 | if get_video_info_xml('error'): | |
393 | error_code = get_video_info_xml('code') | |
394 | ||
395 | if error_code == 'DELETED': | |
396 | raise ExtractorError('The video has been deleted.', | |
397 | expected=True) | |
398 | elif error_code == 'NOT_FOUND': | |
399 | raise ExtractorError('The video is not found.', | |
400 | expected=True) | |
401 | elif error_code == 'COMMUNITY': | |
402 | self.to_screen('%s: The video is community members only.' % video_id) | |
403 | else: | |
404 | raise ExtractorError('%s reports error: %s' % (self.IE_NAME, error_code)) | |
405 | ||
406 | # Start extracting video formats | |
407 | formats = [] | |
408 | ||
409 | # Get HTML5 videos info | |
410 | quality_info = try_get(api_data, lambda x: x['media']['delivery']['movie']) | |
411 | if not quality_info: | |
412 | raise ExtractorError('The video can\'t be downloaded', expected=True) | |
413 | ||
414 | for audio_quality in quality_info.get('audios') or {}: | |
415 | for video_quality in quality_info.get('videos') or {}: | |
416 | if not audio_quality.get('isAvailable') or not video_quality.get('isAvailable'): | |
417 | continue | |
418 | formats.append(self._extract_format_for_quality( | |
419 | api_data, video_id, audio_quality, video_quality)) | |
420 | ||
421 | # Get flv/swf info | |
422 | timestamp = None | |
423 | video_real_url = try_get(api_data, lambda x: x['video']['smileInfo']['url']) | |
424 | if video_real_url: | |
425 | is_economy = video_real_url.endswith('low') | |
426 | ||
427 | if is_economy: | |
428 | self.report_warning('Site is currently in economy mode! You will only have access to lower quality streams') | |
429 | ||
430 | # Invoking ffprobe to determine resolution | |
431 | pp = FFmpegPostProcessor(self._downloader) | |
432 | cookies = self._get_cookies('https://nicovideo.jp').output(header='', sep='; path=/; domain=nicovideo.jp;\n') | |
433 | ||
434 | self.to_screen('%s: %s' % (video_id, 'Checking smile format with ffprobe')) | |
435 | ||
436 | try: | |
437 | metadata = pp.get_metadata_object(video_real_url, ['-cookies', cookies]) | |
438 | except PostProcessingError as err: | |
439 | raise ExtractorError(err.msg, expected=True) | |
440 | ||
441 | v_stream = a_stream = {} | |
442 | ||
443 | # Some complex swf files doesn't have video stream (e.g. nm4809023) | |
444 | for stream in metadata['streams']: | |
445 | if stream['codec_type'] == 'video': | |
446 | v_stream = stream | |
447 | elif stream['codec_type'] == 'audio': | |
448 | a_stream = stream | |
449 | ||
450 | # Community restricted videos seem to have issues with the thumb API not returning anything at all | |
451 | filesize = int( | |
452 | (get_video_info_xml('size_high') if not is_economy else get_video_info_xml('size_low')) | |
453 | or metadata['format']['size'] | |
454 | ) | |
455 | extension = ( | |
456 | get_video_info_xml('movie_type') | |
457 | or 'mp4' if 'mp4' in metadata['format']['format_name'] else metadata['format']['format_name'] | |
458 | ) | |
459 | ||
460 | # 'creation_time' tag on video stream of re-encoded SMILEVIDEO mp4 files are '1970-01-01T00:00:00.000000Z'. | |
461 | timestamp = ( | |
462 | parse_iso8601(get_video_info_web('first_retrieve')) | |
463 | or unified_timestamp(get_video_info_web('postedDateTime')) | |
464 | ) | |
465 | metadata_timestamp = ( | |
466 | parse_iso8601(try_get(v_stream, lambda x: x['tags']['creation_time'])) | |
467 | or timestamp if extension != 'mp4' else 0 | |
468 | ) | |
469 | ||
470 | # According to compconf, smile videos from pre-2017 are always better quality than their DMC counterparts | |
471 | smile_threshold_timestamp = parse_iso8601('2016-12-08T00:00:00+09:00') | |
472 | ||
473 | is_source = timestamp < smile_threshold_timestamp or metadata_timestamp > 0 | |
474 | ||
475 | # If movie file size is unstable, old server movie is not source movie. | |
476 | if filesize > 1: | |
477 | formats.append({ | |
478 | 'url': video_real_url, | |
479 | 'format_id': 'smile' if not is_economy else 'smile_low', | |
480 | 'format_note': 'SMILEVIDEO source' if not is_economy else 'SMILEVIDEO low quality', | |
481 | 'ext': extension, | |
482 | 'container': extension, | |
483 | 'vcodec': v_stream.get('codec_name'), | |
484 | 'acodec': a_stream.get('codec_name'), | |
485 | # Some complex swf files doesn't have total bit rate metadata (e.g. nm6049209) | |
486 | 'tbr': int_or_none(metadata['format'].get('bit_rate'), scale=1000), | |
487 | 'vbr': int_or_none(v_stream.get('bit_rate'), scale=1000), | |
488 | 'abr': int_or_none(a_stream.get('bit_rate'), scale=1000), | |
489 | 'height': int_or_none(v_stream.get('height')), | |
490 | 'width': int_or_none(v_stream.get('width')), | |
491 | 'source_preference': 5 if not is_economy else -2, | |
492 | 'quality': 5 if is_source and not is_economy else None, | |
493 | 'filesize': filesize | |
494 | }) | |
495 | ||
496 | self._sort_formats(formats) | |
497 | ||
498 | # Start extracting information | |
499 | title = ( | |
500 | get_video_info_xml('title') # prefer to get the untranslated original title | |
501 | or get_video_info_web(['originalTitle', 'title']) | |
502 | or self._og_search_title(webpage, default=None) | |
503 | or self._html_search_regex( | |
504 | r'<span[^>]+class="videoHeaderTitle"[^>]*>([^<]+)</span>', | |
505 | webpage, 'video title')) | |
506 | ||
507 | watch_api_data_string = self._html_search_regex( | |
508 | r'<div[^>]+id="watchAPIDataContainer"[^>]+>([^<]+)</div>', | |
509 | webpage, 'watch api data', default=None) | |
510 | watch_api_data = self._parse_json(watch_api_data_string, video_id) if watch_api_data_string else {} | |
511 | video_detail = watch_api_data.get('videoDetail', {}) | |
512 | ||
513 | thumbnail = ( | |
514 | self._html_search_regex(r'<meta property="og:image" content="([^"]+)">', webpage, 'thumbnail data', default=None) | |
515 | or dict_get( # choose highest from 720p to 240p | |
516 | get_video_info_web('thumbnail'), | |
517 | ['ogp', 'player', 'largeUrl', 'middleUrl', 'url']) | |
518 | or self._html_search_meta('image', webpage, 'thumbnail', default=None) | |
519 | or video_detail.get('thumbnail')) | |
520 | ||
521 | description = get_video_info_web('description') | |
522 | ||
523 | if not timestamp: | |
524 | match = self._html_search_meta('datePublished', webpage, 'date published', default=None) | |
525 | if match: | |
526 | timestamp = parse_iso8601(match.replace('+', ':00+')) | |
527 | if not timestamp and video_detail.get('postedAt'): | |
528 | timestamp = parse_iso8601( | |
529 | video_detail['postedAt'].replace('/', '-'), | |
530 | delimiter=' ', timezone=datetime.timedelta(hours=9)) | |
531 | timestamp = timestamp or try_get(api_data, lambda x: parse_iso8601(x['video']['registeredAt'])) | |
532 | ||
533 | view_count = int_or_none(get_video_info_web(['view_counter', 'viewCount'])) | |
534 | if not view_count: | |
535 | match = self._html_search_regex( | |
536 | r'>Views: <strong[^>]*>([^<]+)</strong>', | |
537 | webpage, 'view count', default=None) | |
538 | if match: | |
539 | view_count = int_or_none(match.replace(',', '')) | |
540 | view_count = ( | |
541 | view_count | |
542 | or video_detail.get('viewCount') | |
543 | or try_get(api_data, lambda x: x['video']['count']['view'])) | |
544 | ||
545 | comment_count = ( | |
546 | int_or_none(get_video_info_web('comment_num')) | |
547 | or video_detail.get('commentCount') | |
548 | or try_get(api_data, lambda x: x['video']['count']['comment'])) | |
549 | ||
550 | if not comment_count: | |
551 | match = self._html_search_regex( | |
552 | r'>Comments: <strong[^>]*>([^<]+)</strong>', | |
553 | webpage, 'comment count', default=None) | |
554 | if match: | |
555 | comment_count = int_or_none(match.replace(',', '')) | |
556 | ||
557 | duration = (parse_duration( | |
558 | get_video_info_web('length') | |
559 | or self._html_search_meta( | |
560 | 'video:duration', webpage, 'video duration', default=None)) | |
561 | or video_detail.get('length') | |
562 | or get_video_info_web('duration')) | |
563 | ||
564 | webpage_url = get_video_info_web('watch_url') or url | |
565 | ||
566 | # for channel movie and community movie | |
567 | channel_id = try_get( | |
568 | api_data, | |
569 | (lambda x: x['channel']['globalId'], | |
570 | lambda x: x['community']['globalId'])) | |
571 | channel = try_get( | |
572 | api_data, | |
573 | (lambda x: x['channel']['name'], | |
574 | lambda x: x['community']['name'])) | |
575 | ||
576 | # Note: cannot use api_data.get('owner', {}) because owner may be set to "null" | |
577 | # in the JSON, which will cause None to be returned instead of {}. | |
578 | owner = try_get(api_data, lambda x: x.get('owner'), dict) or {} | |
579 | uploader_id = str_or_none( | |
580 | get_video_info_web(['ch_id', 'user_id']) | |
581 | or owner.get('id') | |
582 | or channel_id | |
583 | ) | |
584 | uploader = ( | |
585 | get_video_info_web(['ch_name', 'user_nickname']) | |
586 | or owner.get('nickname') | |
587 | or channel | |
588 | ) | |
589 | ||
590 | return { | |
591 | 'id': video_id, | |
592 | '_api_data': api_data, | |
593 | 'title': title, | |
594 | 'formats': formats, | |
595 | 'thumbnail': thumbnail, | |
596 | 'description': description, | |
597 | 'uploader': uploader, | |
598 | 'timestamp': timestamp, | |
599 | 'uploader_id': uploader_id, | |
600 | 'channel': channel, | |
601 | 'channel_id': channel_id, | |
602 | 'view_count': view_count, | |
603 | 'comment_count': comment_count, | |
604 | 'duration': duration, | |
605 | 'webpage_url': webpage_url, | |
606 | } | |
607 | ||
608 | ||
609 | class NiconicoPlaylistIE(InfoExtractor): | |
610 | _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/(?:user/\d+/|my/)?mylist/(?P<id>\d+)' | |
611 | ||
612 | _TESTS = [{ | |
613 | 'url': 'http://www.nicovideo.jp/mylist/27411728', | |
614 | 'info_dict': { | |
615 | 'id': '27411728', | |
616 | 'title': 'AKB48のオールナイトニッポン', | |
617 | 'description': 'md5:d89694c5ded4b6c693dea2db6e41aa08', | |
618 | 'uploader': 'のっく', | |
619 | 'uploader_id': '805442', | |
620 | }, | |
621 | 'playlist_mincount': 225, | |
622 | }, { | |
623 | 'url': 'https://www.nicovideo.jp/user/805442/mylist/27411728', | |
624 | 'only_matching': True, | |
625 | }] | |
626 | ||
627 | _API_HEADERS = { | |
628 | 'X-Frontend-ID': '6', | |
629 | 'X-Frontend-Version': '0' | |
630 | } | |
631 | ||
632 | def _real_extract(self, url): | |
633 | list_id = self._match_id(url) | |
634 | ||
635 | def get_page_data(pagenum, pagesize): | |
636 | return self._download_json( | |
637 | 'http://nvapi.nicovideo.jp/v2/mylists/' + list_id, list_id, | |
638 | query={'page': 1 + pagenum, 'pageSize': pagesize}, | |
639 | headers=self._API_HEADERS).get('data').get('mylist') | |
640 | ||
641 | data = get_page_data(0, 1) | |
642 | title = data.get('name') | |
643 | description = data.get('description') | |
644 | uploader = data.get('owner').get('name') | |
645 | uploader_id = data.get('owner').get('id') | |
646 | ||
647 | def pagefunc(pagenum): | |
648 | data = get_page_data(pagenum, 25) | |
649 | return ({ | |
650 | '_type': 'url', | |
651 | 'url': 'http://www.nicovideo.jp/watch/' + item.get('watchId'), | |
652 | } for item in data.get('items')) | |
653 | ||
654 | return { | |
655 | '_type': 'playlist', | |
656 | 'id': list_id, | |
657 | 'title': title, | |
658 | 'description': description, | |
659 | 'uploader': uploader, | |
660 | 'uploader_id': uploader_id, | |
661 | 'entries': OnDemandPagedList(pagefunc, 25), | |
662 | } | |
663 | ||
664 | ||
665 | NicovideoSearchIE_NAME = 'nicovideo:search' | |
666 | ||
667 | ||
668 | class NicovideoSearchURLIE(InfoExtractor): | |
669 | IE_NAME = f'{NicovideoSearchIE_NAME}_url' | |
670 | IE_DESC = 'Nico video search URLs' | |
671 | _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/search/(?P<id>[^?#&]+)?' | |
672 | _TESTS = [{ | |
673 | 'url': 'http://www.nicovideo.jp/search/sm9', | |
674 | 'info_dict': { | |
675 | 'id': 'sm9', | |
676 | 'title': 'sm9' | |
677 | }, | |
678 | 'playlist_mincount': 40, | |
679 | }, { | |
680 | 'url': 'https://www.nicovideo.jp/search/sm9?sort=h&order=d&end=2020-12-31&start=2020-01-01', | |
681 | 'info_dict': { | |
682 | 'id': 'sm9', | |
683 | 'title': 'sm9' | |
684 | }, | |
685 | 'playlist_count': 31, | |
686 | }] | |
687 | ||
688 | def _entries(self, url, item_id, query=None, note='Downloading page %(page)s'): | |
689 | query = query or {} | |
690 | pages = [query['page']] if 'page' in query else itertools.count(1) | |
691 | for page_num in pages: | |
692 | query['page'] = str(page_num) | |
693 | webpage = self._download_webpage(url, item_id, query=query, note=note % {'page': page_num}) | |
694 | results = re.findall(r'(?<=data-video-id=)["\']?(?P<videoid>.*?)(?=["\'])', webpage) | |
695 | for item in results: | |
696 | yield self.url_result(f'http://www.nicovideo.jp/watch/{item}', 'Niconico', item) | |
697 | if not results: | |
698 | break | |
699 | ||
700 | def _real_extract(self, url): | |
701 | query = self._match_id(url) | |
702 | return self.playlist_result(self._entries(url, query), query, query) | |
703 | ||
704 | ||
705 | class NicovideoSearchIE(SearchInfoExtractor, NicovideoSearchURLIE): | |
706 | IE_DESC = 'Nico video searches' | |
707 | IE_NAME = NicovideoSearchIE_NAME | |
708 | _SEARCH_KEY = 'nicosearch' | |
709 | _TESTS = [] | |
710 | ||
711 | def _search_results(self, query): | |
712 | return self._entries( | |
713 | self._proto_relative_url(f'//www.nicovideo.jp/search/{query}'), query) | |
714 | ||
715 | ||
716 | class NicovideoSearchDateIE(NicovideoSearchIE): | |
717 | IE_DESC = 'Nico video searches, newest first' | |
718 | IE_NAME = f'{NicovideoSearchIE_NAME}:date' | |
719 | _SEARCH_KEY = 'nicosearchdate' | |
720 | _TESTS = [{ | |
721 | 'url': 'nicosearchdateall:a', | |
722 | 'info_dict': { | |
723 | 'id': 'a', | |
724 | 'title': 'a' | |
725 | }, | |
726 | 'playlist_mincount': 1610, | |
727 | }] | |
728 | ||
729 | _START_DATE = datetime.date(2007, 1, 1) | |
730 | _RESULTS_PER_PAGE = 32 | |
731 | _MAX_PAGES = 50 | |
732 | ||
733 | def _entries(self, url, item_id, start_date=None, end_date=None): | |
734 | start_date, end_date = start_date or self._START_DATE, end_date or datetime.datetime.now().date() | |
735 | ||
736 | # If the last page has a full page of videos, we need to break down the query interval further | |
737 | last_page_len = len(list(self._get_entries_for_date( | |
738 | url, item_id, start_date, end_date, self._MAX_PAGES, | |
739 | note=f'Checking number of videos from {start_date} to {end_date}'))) | |
740 | if (last_page_len == self._RESULTS_PER_PAGE and start_date != end_date): | |
741 | midpoint = start_date + ((end_date - start_date) // 2) | |
742 | yield from self._entries(url, item_id, midpoint, end_date) | |
743 | yield from self._entries(url, item_id, start_date, midpoint) | |
744 | else: | |
745 | self.to_screen(f'{item_id}: Downloading results from {start_date} to {end_date}') | |
746 | yield from self._get_entries_for_date( | |
747 | url, item_id, start_date, end_date, note=' Downloading page %(page)s') | |
748 | ||
749 | def _get_entries_for_date(self, url, item_id, start_date, end_date=None, page_num=None, note=None): | |
750 | query = { | |
751 | 'start': str(start_date), | |
752 | 'end': str(end_date or start_date), | |
753 | 'sort': 'f', | |
754 | 'order': 'd', | |
755 | } | |
756 | if page_num: | |
757 | query['page'] = str(page_num) | |
758 | ||
759 | yield from NicovideoSearchURLIE._entries(self, url, item_id, query=query, note=note) | |
760 | ||
761 | ||
762 | class NiconicoUserIE(InfoExtractor): | |
763 | _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/user/(?P<id>\d+)/?(?:$|[#?])' | |
764 | _TEST = { | |
765 | 'url': 'https://www.nicovideo.jp/user/419948', | |
766 | 'info_dict': { | |
767 | 'id': '419948', | |
768 | }, | |
769 | 'playlist_mincount': 101, | |
770 | } | |
771 | _API_URL = "https://nvapi.nicovideo.jp/v1/users/%s/videos?sortKey=registeredAt&sortOrder=desc&pageSize=%s&page=%s" | |
772 | _PAGE_SIZE = 100 | |
773 | ||
774 | _API_HEADERS = { | |
775 | 'X-Frontend-ID': '6', | |
776 | 'X-Frontend-Version': '0' | |
777 | } | |
778 | ||
779 | def _entries(self, list_id): | |
780 | total_count = 1 | |
781 | count = page_num = 0 | |
782 | while count < total_count: | |
783 | json_parsed = self._download_json( | |
784 | self._API_URL % (list_id, self._PAGE_SIZE, page_num + 1), list_id, | |
785 | headers=self._API_HEADERS, | |
786 | note='Downloading JSON metadata%s' % (' page %d' % page_num if page_num else '')) | |
787 | if not page_num: | |
788 | total_count = int_or_none(json_parsed['data'].get('totalCount')) | |
789 | for entry in json_parsed["data"]["items"]: | |
790 | count += 1 | |
791 | yield self.url_result('https://www.nicovideo.jp/watch/%s' % entry['id']) | |
792 | page_num += 1 | |
793 | ||
794 | def _real_extract(self, url): | |
795 | list_id = self._match_id(url) | |
796 | return self.playlist_result(self._entries(list_id), list_id, ie=NiconicoIE.ie_key()) |