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