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