]>
Commit | Line | Data |
---|---|---|
dcdb292f | 1 | # coding: utf-8 |
214c22c7 | 2 | from __future__ import unicode_literals |
52ad14ae | 3 | |
fb198a8a | 4 | import datetime |
abafce59 | 5 | import itertools |
6 | import json | |
7 | import re | |
52ad14ae | 8 | |
abafce59 | 9 | from .common import InfoExtractor, SearchInfoExtractor |
fb198a8a | 10 | from ..postprocessor.ffmpeg import FFmpegPostProcessor |
1cc79574 | 11 | from ..compat import ( |
7978e172 | 12 | compat_str, |
bb139491 | 13 | compat_parse_qs, |
29f7c58a | 14 | compat_urllib_parse_urlparse, |
1cc79574 PH |
15 | ) |
16 | from ..utils import ( | |
6110bbbf | 17 | ExtractorError, |
b868936c | 18 | dict_get, |
fb198a8a | 19 | float_or_none, |
b868936c | 20 | int_or_none, |
fb198a8a | 21 | OnDemandPagedList, |
1cc79574 | 22 | parse_duration, |
bb865f3a | 23 | parse_iso8601, |
fb198a8a | 24 | PostProcessingError, |
ee6a6116 | 25 | remove_start, |
b868936c | 26 | str_or_none, |
463e7216 YCH |
27 | try_get, |
28 | unified_timestamp, | |
6e6bc8da | 29 | urlencode_postdata, |
bb139491 | 30 | xpath_text, |
52ad14ae TT |
31 | ) |
32 | ||
13ebea79 | 33 | |
52ad14ae | 34 | class NiconicoIE(InfoExtractor): |
214c22c7 JMF |
35 | IE_NAME = 'niconico' |
36 | IE_DESC = 'ニコニコ動画' | |
52ad14ae | 37 | |
1c9a1457 | 38 | _TESTS = [{ |
214c22c7 | 39 | 'url': 'http://www.nicovideo.jp/watch/sm22312215', |
7978e172 | 40 | 'md5': 'a5bad06f1347452102953f323c69da34s', |
214c22c7 JMF |
41 | 'info_dict': { |
42 | 'id': 'sm22312215', | |
43 | 'ext': 'mp4', | |
44 | 'title': 'Big Buck Bunny', | |
463e7216 | 45 | 'thumbnail': r're:https?://.*', |
214c22c7 JMF |
46 | 'uploader': 'takuya0301', |
47 | 'uploader_id': '2698420', | |
48 | 'upload_date': '20131123', | |
aaab8c5e | 49 | 'timestamp': int, # timestamp is unstable |
214c22c7 | 50 | 'description': '(c) copyright 2008, Blender Foundation / www.bigbuckbunny.org', |
15ce1338 | 51 | 'duration': 33, |
463e7216 YCH |
52 | 'view_count': int, |
53 | 'comment_count': int, | |
52ad14ae | 54 | }, |
8e4988f1 | 55 | 'skip': 'Requires an account', |
1c9a1457 | 56 | }, { |
59d814f7 YCH |
57 | # File downloaded with and without credentials are different, so omit |
58 | # the md5 field | |
1c9a1457 | 59 | 'url': 'http://www.nicovideo.jp/watch/nm14296458', |
1c9a1457 S |
60 | 'info_dict': { |
61 | 'id': 'nm14296458', | |
62 | 'ext': 'swf', | |
63 | 'title': '【鏡音リン】Dance on media【オリジナル】take2!', | |
bb865f3a | 64 | 'description': 'md5:689f066d74610b3b22e0f1739add0f58', |
463e7216 | 65 | 'thumbnail': r're:https?://.*', |
1c9a1457 S |
66 | 'uploader': 'りょうた', |
67 | 'uploader_id': '18822557', | |
68 | 'upload_date': '20110429', | |
bb865f3a | 69 | 'timestamp': 1304065916, |
1c9a1457 S |
70 | 'duration': 209, |
71 | }, | |
8e4988f1 | 72 | 'skip': 'Requires an account', |
bb865f3a YCH |
73 | }, { |
74 | # 'video exists but is marked as "deleted" | |
b2e8e7da | 75 | # md5 is unstable |
bb865f3a | 76 | 'url': 'http://www.nicovideo.jp/watch/sm10000', |
bb865f3a YCH |
77 | 'info_dict': { |
78 | 'id': 'sm10000', | |
79 | 'ext': 'unknown_video', | |
80 | 'description': 'deleted', | |
81 | 'title': 'ドラえもんエターナル第3話「決戦第3新東京市」<前編>', | |
463e7216 | 82 | 'thumbnail': r're:https?://.*', |
b2e8e7da | 83 | 'upload_date': '20071224', |
8e4988f1 | 84 | 'timestamp': int, # timestamp field has different value if logged in |
b2e8e7da | 85 | 'duration': 304, |
463e7216 | 86 | 'view_count': int, |
bb865f3a | 87 | }, |
8e4988f1 | 88 | 'skip': 'Requires an account', |
621ffe7b YCH |
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', | |
463e7216 | 96 | 'thumbnail': r're:https?://.*', |
621ffe7b YCH |
97 | 'timestamp': 1388851200, |
98 | 'upload_date': '20140104', | |
99 | 'uploader': 'アニメロチャンネル', | |
100 | 'uploader_id': '312', | |
8e4988f1 YCH |
101 | }, |
102 | 'skip': 'The viewing period of the video you were searching for has expired.', | |
463e7216 | 103 | }, { |
ee6a6116 | 104 | # video not available via `getflv`; "old" HTML5 video |
463e7216 | 105 | 'url': 'http://www.nicovideo.jp/watch/sm1151009', |
ee6a6116 | 106 | 'md5': '8fa81c364eb619d4085354eab075598a', |
463e7216 YCH |
107 | 'info_dict': { |
108 | 'id': 'sm1151009', | |
ee6a6116 | 109 | 'ext': 'mp4', |
463e7216 YCH |
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', | |
ee6a6116 YCH |
122 | }, { |
123 | # "New" HTML5 video | |
aaab8c5e | 124 | # md5 is unstable |
ee6a6116 | 125 | 'url': 'http://www.nicovideo.jp/watch/sm31464864', |
ee6a6116 YCH |
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', | |
aaab8c5e | 133 | 'uploader': 'ゲスト', |
ee6a6116 YCH |
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', | |
aaab8c5e PP |
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', | |
4a87de72 LS |
160 | }, { |
161 | 'url': 'http://sp.nicovideo.jp/watch/sm28964488?ss_pos=1&cp_in=wt_tg', | |
162 | 'only_matching': True, | |
1c9a1457 | 163 | }] |
52ad14ae | 164 | |
4a87de72 | 165 | _VALID_URL = r'https?://(?:www\.|secure\.|sp\.)?nicovideo\.jp/watch/(?P<id>(?:[a-z]{2})?[0-9]+)' |
52ad14ae | 166 | _NETRC_MACHINE = 'niconico' |
52ad14ae | 167 | |
2291dbce | 168 | _API_HEADERS = { |
169 | 'X-Frontend-ID': '6', | |
170 | 'X-Frontend-Version': '0' | |
171 | } | |
172 | ||
52ad14ae | 173 | def _real_initialize(self): |
23d83ad4 | 174 | self._login() |
52ad14ae TT |
175 | |
176 | def _login(self): | |
68217024 | 177 | username, password = self._get_login_info() |
23d83ad4 NJ |
178 | # No authentication to be performed |
179 | if not username: | |
180 | return True | |
52ad14ae TT |
181 | |
182 | # Log in | |
bb139491 | 183 | login_ok = True |
52ad14ae | 184 | login_form_strs = { |
bb139491 | 185 | 'mail_tel': username, |
214c22c7 | 186 | 'password': password, |
52ad14ae | 187 | } |
bb139491 YCH |
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: | |
29f7c58a | 195 | parts = compat_urllib_parse_urlparse(urlh.geturl()) |
bb139491 YCH |
196 | if compat_parse_qs(parts.query).get('message', [None])[0] == 'cant_login': |
197 | login_ok = False | |
198 | if not login_ok: | |
6a39ee13 | 199 | self.report_warning('unable to log in: bad username or password') |
bb139491 | 200 | return login_ok |
52ad14ae | 201 | |
fb198a8a | 202 | def _get_heartbeat_info(self, info_dict): |
ee6a6116 | 203 | |
fb198a8a | 204 | video_id, video_src_id, audio_src_id = info_dict['url'].split(':')[1].split('/') |
ee6a6116 | 205 | |
2291dbce | 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)) | |
fb198a8a | 214 | |
7978e172 | 215 | session_api_data = try_get(api_data, lambda x: x['media']['delivery']['movie']['session']) |
fb198a8a | 216 | session_api_endpoint = try_get(session_api_data, lambda x: x['urls'][0]) |
217 | ||
2291dbce | 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.') | |
fb198a8a | 228 | |
229 | yesno = lambda x: 'yes' if x else 'no' | |
230 | ||
231 | # m3u8 (encryption) | |
2291dbce | 232 | if try_get(api_data, lambda x: x['media']['delivery']['encryption']) is not None: |
fb198a8a | 233 | protocol = 'm3u8' |
2291dbce | 234 | encryption = self._parse_json(session_api_data['token'], video_id)['hls_encryption'] |
fb198a8a | 235 | session_api_http_parameters = { |
236 | 'parameters': { | |
237 | 'hls_parameters': { | |
238 | 'encryption': { | |
2291dbce | 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']) | |
fb198a8a | 242 | } |
243 | }, | |
244 | 'transfer_preset': '', | |
2291dbce | 245 | 'use_ssl': yesno(session_api_endpoint['isSsl']), |
246 | 'use_well_known_port': yesno(session_api_endpoint['isWellKnownPort']), | |
247 | 'segment_duration': 6000, | |
fb198a8a | 248 | } |
249 | } | |
250 | } | |
251 | # http | |
252 | else: | |
253 | protocol = 'http' | |
254 | session_api_http_parameters = { | |
255 | 'parameters': { | |
256 | 'http_output_download_parameters': { | |
7978e172 | 257 | 'use_ssl': yesno(session_api_endpoint['isSsl']), |
258 | 'use_well_known_port': yesno(session_api_endpoint['isWellKnownPort']), | |
fb198a8a | 259 | } |
260 | } | |
261 | } | |
ee6a6116 YCH |
262 | |
263 | session_response = self._download_json( | |
264 | session_api_endpoint['url'], video_id, | |
265 | query={'_format': 'json'}, | |
266 | headers={'Content-Type': 'application/json'}, | |
fb198a8a | 267 | note='Downloading JSON metadata for %s' % info_dict['format_id'], |
ee6a6116 YCH |
268 | data=json.dumps({ |
269 | 'session': { | |
270 | 'client_info': { | |
7978e172 | 271 | 'player_id': session_api_data.get('playerId'), |
ee6a6116 YCH |
272 | }, |
273 | 'content_auth': { | |
7978e172 | 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'), | |
ee6a6116 | 276 | 'service_id': 'nicovideo', |
7978e172 | 277 | 'service_user_id': session_api_data.get('serviceUserId') |
ee6a6116 | 278 | }, |
7978e172 | 279 | 'content_id': session_api_data.get('contentId'), |
ee6a6116 YCH |
280 | 'content_src_id_sets': [{ |
281 | 'content_src_ids': [{ | |
282 | 'src_id_to_mux': { | |
fb198a8a | 283 | 'audio_src_ids': [audio_src_id], |
284 | 'video_src_ids': [video_src_id], | |
ee6a6116 YCH |
285 | } |
286 | }] | |
287 | }], | |
288 | 'content_type': 'movie', | |
289 | 'content_uri': '', | |
290 | 'keep_method': { | |
291 | 'heartbeat': { | |
7978e172 | 292 | 'lifetime': session_api_data.get('heartbeatLifetime') |
ee6a6116 YCH |
293 | } |
294 | }, | |
fb198a8a | 295 | 'priority': session_api_data.get('priority'), |
ee6a6116 YCH |
296 | 'protocol': { |
297 | 'name': 'http', | |
298 | 'parameters': { | |
fb198a8a | 299 | 'http_parameters': session_api_http_parameters |
ee6a6116 YCH |
300 | } |
301 | }, | |
7978e172 | 302 | 'recipe_id': session_api_data.get('recipeId'), |
ee6a6116 YCH |
303 | 'session_operation_auth': { |
304 | 'session_operation_auth_by_signature': { | |
fb198a8a | 305 | 'signature': session_api_data.get('signature'), |
306 | 'token': session_api_data.get('token'), | |
ee6a6116 YCH |
307 | } |
308 | }, | |
309 | 'timing_constraint': 'unlimited' | |
310 | } | |
4d59db5b | 311 | }).encode()) |
ee6a6116 | 312 | |
fb198a8a | 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. | |
2291dbce | 321 | 'interval': float_or_none(session_api_data.get('heartbeatLifetime'), scale=3000), |
322 | 'ping': ping | |
fb198a8a | 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']) | |
7978e172 | 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) | |
ee6a6116 YCH |
343 | |
344 | return { | |
fb198a8a | 345 | 'url': '%s:%s/%s/%s' % (protocol, video_id, video_quality['id'], audio_quality['id']), |
ee6a6116 | 346 | 'format_id': format_id, |
7978e172 | 347 | 'format_note': 'DMC %s' % try_get(video_quality, lambda x: x['metadata']['label'], compat_str), |
ee6a6116 | 348 | 'ext': 'mp4', # Session API are used in HTML5, which always serves mp4 |
fb198a8a | 349 | 'vcodec': vdict.get('codec'), |
350 | 'acodec': adict.get('codec'), | |
7978e172 | 351 | 'vbr': float_or_none(vbr, 1000) or float_or_none(vdict.get('br')), |
fb198a8a | 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 | } | |
ee6a6116 YCH |
361 | } |
362 | ||
52ad14ae | 363 | def _real_extract(self, url): |
937daef4 | 364 | video_id = self._match_id(url) |
52ad14ae | 365 | |
fb198a8a | 366 | # Get video webpage for API data. |
621ffe7b YCH |
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()) | |
52ad14ae | 371 | |
463e7216 YCH |
372 | api_data = self._parse_json(self._html_search_regex( |
373 | 'data-api-data="([^"]+)"', webpage, | |
374 | 'API data', default='{}'), video_id) | |
463e7216 | 375 | |
fb198a8a | 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 | |
7978e172 | 410 | quality_info = try_get(api_data, lambda x: x['media']['delivery']['movie']) |
411 | if not quality_info: | |
2291dbce | 412 | raise ExtractorError('The video can\'t be downloaded', expected=True) |
fb198a8a | 413 | |
fb198a8a | 414 | for audio_quality in quality_info.get('audios') or {}: |
415 | for video_quality in quality_info.get('videos') or {}: | |
7978e172 | 416 | if not audio_quality.get('isAvailable') or not video_quality.get('isAvailable'): |
fb198a8a | 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 | |
7978e172 | 422 | timestamp = None |
fb198a8a | 423 | video_real_url = try_get(api_data, lambda x: x['video']['smileInfo']['url']) |
2291dbce | 424 | if video_real_url: |
7978e172 | 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 | }) | |
fb198a8a | 495 | |
fb198a8a | 496 | self._sort_formats(formats) |
ee6a6116 | 497 | |
52ad14ae | 498 | # Start extracting information |
e1feb88f | 499 | title = ( |
6b1d8c1e C |
500 | get_video_info_xml('title') # prefer to get the untranslated original title |
501 | or get_video_info_web(['originalTitle', 'title']) | |
e1feb88f | 502 | or self._og_search_title(webpage, default=None) |
503 | or self._html_search_regex( | |
bb865f3a | 504 | r'<span[^>]+class="videoHeaderTitle"[^>]*>([^<]+)</span>', |
e1feb88f | 505 | webpage, 'video title')) |
bb865f3a | 506 | |
b2e8e7da YCH |
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 | ||
b2e8e7da | 513 | thumbnail = ( |
fb198a8a | 514 | self._html_search_regex(r'<meta property="og:image" content="([^"]+)">', webpage, 'thumbnail data', default=None) |
40078a55 | 515 | or dict_get( # choose highest from 720p to 240p |
6b1d8c1e C |
516 | get_video_info_web('thumbnail'), |
517 | ['ogp', 'player', 'largeUrl', 'middleUrl', 'url']) | |
3089bc74 S |
518 | or self._html_search_meta('image', webpage, 'thumbnail', default=None) |
519 | or video_detail.get('thumbnail')) | |
b2e8e7da | 520 | |
fb198a8a | 521 | description = get_video_info_web('description') |
b2e8e7da | 522 | |
b2e8e7da YCH |
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)) | |
7978e172 | 531 | timestamp = timestamp or try_get(api_data, lambda x: parse_iso8601(x['video']['registeredAt'])) |
b2e8e7da | 532 | |
fb198a8a | 533 | view_count = int_or_none(get_video_info_web(['view_counter', 'viewCount'])) |
b2e8e7da YCH |
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(',', '')) | |
7978e172 | 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'])) | |
b2e8e7da | 549 | |
b2e8e7da YCH |
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(',', '')) | |
b2e8e7da YCH |
556 | |
557 | duration = (parse_duration( | |
fb198a8a | 558 | get_video_info_web('length') |
3089bc74 S |
559 | or self._html_search_meta( |
560 | 'video:duration', webpage, 'video duration', default=None)) | |
561 | or video_detail.get('length') | |
fb198a8a | 562 | or get_video_info_web('duration')) |
b2e8e7da | 563 | |
fb198a8a | 564 | webpage_url = get_video_info_web('watch_url') or url |
15ce1338 | 565 | |
78b9a616 | 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 | ||
aaab8c5e PP |
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 {} | |
7978e172 | 579 | uploader_id = str_or_none( |
78b9a616 | 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 | ) | |
52ad14ae | 589 | |
b2e8e7da | 590 | return { |
214c22c7 | 591 | 'id': video_id, |
2291dbce | 592 | '_api_data': api_data, |
15ce1338 | 593 | 'title': title, |
ee6a6116 | 594 | 'formats': formats, |
15ce1338 S |
595 | 'thumbnail': thumbnail, |
596 | 'description': description, | |
597 | 'uploader': uploader, | |
bb865f3a | 598 | 'timestamp': timestamp, |
15ce1338 | 599 | 'uploader_id': uploader_id, |
78b9a616 | 600 | 'channel': channel, |
601 | 'channel_id': channel_id, | |
15ce1338 S |
602 | 'view_count': view_count, |
603 | 'comment_count': comment_count, | |
604 | 'duration': duration, | |
605 | 'webpage_url': webpage_url, | |
52ad14ae | 606 | } |
a9bad429 JMF |
607 | |
608 | ||
609 | class NiconicoPlaylistIE(InfoExtractor): | |
c1d3a4a8 | 610 | _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/(?:user/\d+/|my/)?mylist/(?P<id>\d+)' |
a9bad429 | 611 | |
29f7c58a | 612 | _TESTS = [{ |
a9bad429 JMF |
613 | 'url': 'http://www.nicovideo.jp/mylist/27411728', |
614 | 'info_dict': { | |
615 | 'id': '27411728', | |
616 | 'title': 'AKB48のオールナイトニッポン', | |
29f7c58a | 617 | 'description': 'md5:d89694c5ded4b6c693dea2db6e41aa08', |
618 | 'uploader': 'のっく', | |
619 | 'uploader_id': '805442', | |
a9bad429 JMF |
620 | }, |
621 | 'playlist_mincount': 225, | |
29f7c58a | 622 | }, { |
623 | 'url': 'https://www.nicovideo.jp/user/805442/mylist/27411728', | |
624 | 'only_matching': True, | |
625 | }] | |
a9bad429 | 626 | |
2291dbce | 627 | _API_HEADERS = { |
628 | 'X-Frontend-ID': '6', | |
629 | 'X-Frontend-Version': '0' | |
630 | } | |
631 | ||
a9bad429 JMF |
632 | def _real_extract(self, url): |
633 | list_id = self._match_id(url) | |
fb198a8a | 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}, | |
2291dbce | 639 | headers=self._API_HEADERS).get('data').get('mylist') |
fb198a8a | 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 | } | |
c1d3a4a8 | 663 | |
664 | ||
abafce59 | 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 | _MAX_RESULTS = float('inf') | |
708 | IE_NAME = NicovideoSearchIE_NAME | |
709 | _SEARCH_KEY = 'nicosearch' | |
710 | _TESTS = [] | |
711 | ||
712 | def _get_n_results(self, query, n): | |
713 | entries = self._entries(self._proto_relative_url(f'//www.nicovideo.jp/search/{query}'), query) | |
714 | if n < float('inf'): | |
715 | entries = itertools.islice(entries, 0, n) | |
716 | return self.playlist_result(entries, query, query) | |
717 | ||
718 | ||
719 | class NicovideoSearchDateIE(NicovideoSearchIE): | |
720 | IE_DESC = 'Nico video searches, newest first' | |
721 | IE_NAME = f'{NicovideoSearchIE_NAME}:date' | |
722 | _SEARCH_KEY = 'nicosearchdate' | |
723 | _TESTS = [{ | |
724 | 'url': 'nicosearchdateall:a', | |
725 | 'info_dict': { | |
726 | 'id': 'a', | |
727 | 'title': 'a' | |
728 | }, | |
729 | 'playlist_mincount': 1610, | |
730 | }] | |
731 | ||
732 | _START_DATE = datetime.date(2007, 1, 1) | |
733 | _RESULTS_PER_PAGE = 32 | |
734 | _MAX_PAGES = 50 | |
735 | ||
736 | def _entries(self, url, item_id, start_date=None, end_date=None): | |
737 | start_date, end_date = start_date or self._START_DATE, end_date or datetime.datetime.now().date() | |
738 | ||
739 | # If the last page has a full page of videos, we need to break down the query interval further | |
740 | last_page_len = len(list(self._get_entries_for_date( | |
741 | url, item_id, start_date, end_date, self._MAX_PAGES, | |
742 | note=f'Checking number of videos from {start_date} to {end_date}'))) | |
743 | if (last_page_len == self._RESULTS_PER_PAGE and start_date != end_date): | |
744 | midpoint = start_date + ((end_date - start_date) // 2) | |
745 | yield from self._entries(url, item_id, midpoint, end_date) | |
746 | yield from self._entries(url, item_id, start_date, midpoint) | |
747 | else: | |
748 | self.to_screen(f'{item_id}: Downloading results from {start_date} to {end_date}') | |
749 | yield from self._get_entries_for_date( | |
750 | url, item_id, start_date, end_date, note=' Downloading page %(page)s') | |
751 | ||
752 | def _get_entries_for_date(self, url, item_id, start_date, end_date=None, page_num=None, note=None): | |
753 | query = { | |
754 | 'start': str(start_date), | |
755 | 'end': str(end_date or start_date), | |
756 | 'sort': 'f', | |
757 | 'order': 'd', | |
758 | } | |
759 | if page_num: | |
760 | query['page'] = str(page_num) | |
761 | ||
762 | yield from NicovideoSearchURLIE._entries(self, url, item_id, query=query, note=note) | |
763 | ||
764 | ||
c1d3a4a8 | 765 | class NiconicoUserIE(InfoExtractor): |
766 | _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/user/(?P<id>\d+)/?(?:$|[#?])' | |
767 | _TEST = { | |
768 | 'url': 'https://www.nicovideo.jp/user/419948', | |
769 | 'info_dict': { | |
770 | 'id': '419948', | |
771 | }, | |
772 | 'playlist_mincount': 101, | |
773 | } | |
774 | _API_URL = "https://nvapi.nicovideo.jp/v1/users/%s/videos?sortKey=registeredAt&sortOrder=desc&pageSize=%s&page=%s" | |
2291dbce | 775 | _PAGE_SIZE = 100 |
776 | ||
777 | _API_HEADERS = { | |
c1d3a4a8 | 778 | 'X-Frontend-ID': '6', |
2291dbce | 779 | 'X-Frontend-Version': '0' |
c1d3a4a8 | 780 | } |
c1d3a4a8 | 781 | |
abafce59 | 782 | def _entries(self, list_id): |
c1d3a4a8 | 783 | total_count = 1 |
784 | count = page_num = 0 | |
785 | while count < total_count: | |
786 | json_parsed = self._download_json( | |
787 | self._API_URL % (list_id, self._PAGE_SIZE, page_num + 1), list_id, | |
2291dbce | 788 | headers=self._API_HEADERS, |
c1d3a4a8 | 789 | note='Downloading JSON metadata%s' % (' page %d' % page_num if page_num else '')) |
790 | if not page_num: | |
791 | total_count = int_or_none(json_parsed['data'].get('totalCount')) | |
792 | for entry in json_parsed["data"]["items"]: | |
793 | count += 1 | |
794 | yield self.url_result('https://www.nicovideo.jp/watch/%s' % entry['id']) | |
795 | page_num += 1 | |
796 | ||
797 | def _real_extract(self, url): | |
798 | list_id = self._match_id(url) | |
799 | return self.playlist_result(self._entries(list_id), list_id, ie=NiconicoIE.ie_key()) |