]>
Commit | Line | Data |
---|---|---|
1 | # coding: utf-8 | |
2 | from __future__ import unicode_literals | |
3 | ||
4 | import re | |
5 | import json | |
6 | import datetime | |
7 | ||
8 | from .common import InfoExtractor | |
9 | from ..postprocessor.ffmpeg import FFmpegPostProcessor | |
10 | from ..compat import ( | |
11 | compat_parse_qs, | |
12 | compat_urllib_parse_urlparse, | |
13 | ) | |
14 | from ..utils import ( | |
15 | dict_get, | |
16 | ExtractorError, | |
17 | int_or_none, | |
18 | float_or_none, | |
19 | OnDemandPagedList, | |
20 | parse_duration, | |
21 | parse_iso8601, | |
22 | PostProcessingError, | |
23 | remove_start, | |
24 | try_get, | |
25 | unified_timestamp, | |
26 | urlencode_postdata, | |
27 | xpath_text, | |
28 | ) | |
29 | ||
30 | ||
31 | class NiconicoIE(InfoExtractor): | |
32 | IE_NAME = 'niconico' | |
33 | IE_DESC = 'ニコニコ動画' | |
34 | ||
35 | _TESTS = [{ | |
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', | |
42 | 'thumbnail': r're:https?://.*', | |
43 | 'uploader': 'takuya0301', | |
44 | 'uploader_id': '2698420', | |
45 | 'upload_date': '20131123', | |
46 | 'timestamp': int, # timestamp is unstable | |
47 | 'description': '(c) copyright 2008, Blender Foundation / www.bigbuckbunny.org', | |
48 | 'duration': 33, | |
49 | 'view_count': int, | |
50 | 'comment_count': int, | |
51 | }, | |
52 | 'skip': 'Requires an account', | |
53 | }, { | |
54 | # File downloaded with and without credentials are different, so omit | |
55 | # the md5 field | |
56 | 'url': 'http://www.nicovideo.jp/watch/nm14296458', | |
57 | 'info_dict': { | |
58 | 'id': 'nm14296458', | |
59 | 'ext': 'swf', | |
60 | 'title': '【鏡音リン】Dance on media【オリジナル】take2!', | |
61 | 'description': 'md5:689f066d74610b3b22e0f1739add0f58', | |
62 | 'thumbnail': r're:https?://.*', | |
63 | 'uploader': 'りょうた', | |
64 | 'uploader_id': '18822557', | |
65 | 'upload_date': '20110429', | |
66 | 'timestamp': 1304065916, | |
67 | 'duration': 209, | |
68 | }, | |
69 | 'skip': 'Requires an account', | |
70 | }, { | |
71 | # 'video exists but is marked as "deleted" | |
72 | # md5 is unstable | |
73 | 'url': 'http://www.nicovideo.jp/watch/sm10000', | |
74 | 'info_dict': { | |
75 | 'id': 'sm10000', | |
76 | 'ext': 'unknown_video', | |
77 | 'description': 'deleted', | |
78 | 'title': 'ドラえもんエターナル第3話「決戦第3新東京市」<前編>', | |
79 | 'thumbnail': r're:https?://.*', | |
80 | 'upload_date': '20071224', | |
81 | 'timestamp': int, # timestamp field has different value if logged in | |
82 | 'duration': 304, | |
83 | 'view_count': int, | |
84 | }, | |
85 | 'skip': 'Requires an account', | |
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', | |
93 | 'thumbnail': r're:https?://.*', | |
94 | 'timestamp': 1388851200, | |
95 | 'upload_date': '20140104', | |
96 | 'uploader': 'アニメロチャンネル', | |
97 | 'uploader_id': '312', | |
98 | }, | |
99 | 'skip': 'The viewing period of the video you were searching for has expired.', | |
100 | }, { | |
101 | # video not available via `getflv`; "old" HTML5 video | |
102 | 'url': 'http://www.nicovideo.jp/watch/sm1151009', | |
103 | 'md5': '8fa81c364eb619d4085354eab075598a', | |
104 | 'info_dict': { | |
105 | 'id': 'sm1151009', | |
106 | 'ext': 'mp4', | |
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', | |
119 | }, { | |
120 | # "New" HTML5 video | |
121 | # md5 is unstable | |
122 | 'url': 'http://www.nicovideo.jp/watch/sm31464864', | |
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', | |
130 | 'uploader': 'ゲスト', | |
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', | |
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', | |
157 | }, { | |
158 | 'url': 'http://sp.nicovideo.jp/watch/sm28964488?ss_pos=1&cp_in=wt_tg', | |
159 | 'only_matching': True, | |
160 | }] | |
161 | ||
162 | _VALID_URL = r'https?://(?:www\.|secure\.|sp\.)?nicovideo\.jp/watch/(?P<id>(?:[a-z]{2})?[0-9]+)' | |
163 | _NETRC_MACHINE = 'niconico' | |
164 | ||
165 | def _real_initialize(self): | |
166 | self._login() | |
167 | ||
168 | def _login(self): | |
169 | username, password = self._get_login_info() | |
170 | # No authentication to be performed | |
171 | if not username: | |
172 | return True | |
173 | ||
174 | # Log in | |
175 | login_ok = True | |
176 | login_form_strs = { | |
177 | 'mail_tel': username, | |
178 | 'password': password, | |
179 | } | |
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: | |
187 | parts = compat_urllib_parse_urlparse(urlh.geturl()) | |
188 | if compat_parse_qs(parts.query).get('message', [None])[0] == 'cant_login': | |
189 | login_ok = False | |
190 | if not login_ok: | |
191 | self._downloader.report_warning('unable to log in: bad username or password') | |
192 | return login_ok | |
193 | ||
194 | def _get_heartbeat_info(self, info_dict): | |
195 | ||
196 | video_id, video_src_id, audio_src_id = info_dict['url'].split(':')[1].split('/') | |
197 | ||
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 | } | |
252 | ||
253 | session_response = self._download_json( | |
254 | session_api_endpoint['url'], video_id, | |
255 | query={'_format': 'json'}, | |
256 | headers={'Content-Type': 'application/json'}, | |
257 | note='Downloading JSON metadata for %s' % info_dict['format_id'], | |
258 | data=json.dumps({ | |
259 | 'session': { | |
260 | 'client_info': { | |
261 | 'player_id': session_api_data.get('player_id'), | |
262 | }, | |
263 | 'content_auth': { | |
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'), | |
266 | 'service_id': 'nicovideo', | |
267 | 'service_user_id': session_api_data.get('service_user_id') | |
268 | }, | |
269 | 'content_id': session_api_data.get('content_id'), | |
270 | 'content_src_id_sets': [{ | |
271 | 'content_src_ids': [{ | |
272 | 'src_id_to_mux': { | |
273 | 'audio_src_ids': [audio_src_id], | |
274 | 'video_src_ids': [video_src_id], | |
275 | } | |
276 | }] | |
277 | }], | |
278 | 'content_type': 'movie', | |
279 | 'content_uri': '', | |
280 | 'keep_method': { | |
281 | 'heartbeat': { | |
282 | 'lifetime': session_api_data.get('heartbeat_lifetime') | |
283 | } | |
284 | }, | |
285 | 'priority': session_api_data.get('priority'), | |
286 | 'protocol': { | |
287 | 'name': 'http', | |
288 | 'parameters': { | |
289 | 'http_parameters': session_api_http_parameters | |
290 | } | |
291 | }, | |
292 | 'recipe_id': session_api_data.get('recipe_id'), | |
293 | 'session_operation_auth': { | |
294 | 'session_operation_auth_by_signature': { | |
295 | 'signature': session_api_data.get('signature'), | |
296 | 'token': session_api_data.get('token'), | |
297 | } | |
298 | }, | |
299 | 'timing_constraint': 'unlimited' | |
300 | } | |
301 | }).encode()) | |
302 | ||
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')}) | |
331 | ||
332 | return { | |
333 | 'url': '%s:%s/%s/%s' % (protocol, video_id, video_quality['id'], audio_quality['id']), | |
334 | 'format_id': format_id, | |
335 | 'ext': 'mp4', # Session API are used in HTML5, which always serves mp4 | |
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 | } | |
348 | } | |
349 | ||
350 | def _real_extract(self, url): | |
351 | video_id = self._match_id(url) | |
352 | ||
353 | # Get video webpage for API data. | |
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()) | |
358 | ||
359 | api_data = self._parse_json(self._html_search_regex( | |
360 | 'data-api-data="([^"]+)"', webpage, | |
361 | 'API data', default='{}'), video_id) | |
362 | ||
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')) | |
423 | ||
424 | try: | |
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({ | |
466 | 'url': video_real_url, | |
467 | 'format_id': 'smile' if not is_economy else 'smile_low', | |
468 | 'format_note': 'SMILEVIDEO source' if not is_economy else 'SMILEVIDEO low quality', | |
469 | 'ext': extension, | |
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) | |
488 | ||
489 | # Start extracting information | |
490 | title = get_video_info_web('originalTitle') | |
491 | if not title: | |
492 | title = self._og_search_title(webpage, default=None) | |
493 | if not title: | |
494 | title = self._html_search_regex( | |
495 | r'<span[^>]+class="videoHeaderTitle"[^>]*>([^<]+)</span>', | |
496 | webpage, 'video title') | |
497 | ||
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 | ||
504 | thumbnail = ( | |
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']) | |
507 | or self._html_search_meta('image', webpage, 'thumbnail', default=None) | |
508 | or video_detail.get('thumbnail')) | |
509 | ||
510 | description = get_video_info_web('description') | |
511 | ||
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 | ||
521 | view_count = int_or_none(get_video_info_web(['view_counter', 'viewCount'])) | |
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 | ||
530 | comment_count = (int_or_none(get_video_info_web('comment_num')) | |
531 | or video_detail.get('commentCount') | |
532 | or try_get(api_data, lambda x: x['thread']['commentCount'])) | |
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(',', '')) | |
539 | ||
540 | duration = (parse_duration( | |
541 | get_video_info_web('length') | |
542 | or self._html_search_meta( | |
543 | 'video:duration', webpage, 'video duration', default=None)) | |
544 | or video_detail.get('length') | |
545 | or get_video_info_web('duration')) | |
546 | ||
547 | webpage_url = get_video_info_web('watch_url') or url | |
548 | ||
549 | # for channel movie and community movie | |
550 | channel_id = try_get( | |
551 | api_data, | |
552 | (lambda x: x['channel']['globalId'], | |
553 | lambda x: x['community']['globalId'])) | |
554 | channel = try_get( | |
555 | api_data, | |
556 | (lambda x: x['channel']['name'], | |
557 | lambda x: x['community']['name'])) | |
558 | ||
559 | # Note: cannot use api_data.get('owner', {}) because owner may be set to "null" | |
560 | # in the JSON, which will cause None to be returned instead of {}. | |
561 | owner = try_get(api_data, lambda x: x.get('owner'), dict) or {} | |
562 | uploader_id = ( | |
563 | get_video_info_web(['ch_id', 'user_id']) | |
564 | or owner.get('id') | |
565 | or channel_id | |
566 | ) | |
567 | uploader = ( | |
568 | get_video_info_web(['ch_name', 'user_nickname']) | |
569 | or owner.get('nickname') | |
570 | or channel | |
571 | ) | |
572 | ||
573 | return { | |
574 | 'id': video_id, | |
575 | 'title': title, | |
576 | 'formats': formats, | |
577 | 'thumbnail': thumbnail, | |
578 | 'description': description, | |
579 | 'uploader': uploader, | |
580 | 'timestamp': timestamp, | |
581 | 'uploader_id': uploader_id, | |
582 | 'channel': channel, | |
583 | 'channel_id': channel_id, | |
584 | 'view_count': view_count, | |
585 | 'comment_count': comment_count, | |
586 | 'duration': duration, | |
587 | 'webpage_url': webpage_url, | |
588 | } | |
589 | ||
590 | ||
591 | class NiconicoPlaylistIE(InfoExtractor): | |
592 | _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/(?:user/\d+/)?mylist/(?P<id>\d+)' | |
593 | ||
594 | _TESTS = [{ | |
595 | 'url': 'http://www.nicovideo.jp/mylist/27411728', | |
596 | 'info_dict': { | |
597 | 'id': '27411728', | |
598 | 'title': 'AKB48のオールナイトニッポン', | |
599 | 'description': 'md5:d89694c5ded4b6c693dea2db6e41aa08', | |
600 | 'uploader': 'のっく', | |
601 | 'uploader_id': '805442', | |
602 | }, | |
603 | 'playlist_mincount': 225, | |
604 | }, { | |
605 | 'url': 'https://www.nicovideo.jp/user/805442/mylist/27411728', | |
606 | 'only_matching': True, | |
607 | }] | |
608 | ||
609 | def _real_extract(self, url): | |
610 | list_id = self._match_id(url) | |
611 | webpage = self._download_webpage(url, list_id) | |
612 | ||
613 | header = self._parse_json(self._html_search_regex( | |
614 | r'data-common-header="([^"]+)"', webpage, | |
615 | 'webpage header'), list_id) | |
616 | frontendId = header.get('initConfig').get('frontendId') | |
617 | frontendVersion = header.get('initConfig').get('frontendVersion') | |
618 | ||
619 | def get_page_data(pagenum, pagesize): | |
620 | return self._download_json( | |
621 | 'http://nvapi.nicovideo.jp/v2/mylists/' + list_id, list_id, | |
622 | query={'page': 1 + pagenum, 'pageSize': pagesize}, | |
623 | headers={ | |
624 | 'X-Frontend-Id': frontendId, | |
625 | 'X-Frontend-Version': frontendVersion, | |
626 | }).get('data').get('mylist') | |
627 | ||
628 | data = get_page_data(0, 1) | |
629 | title = data.get('name') | |
630 | description = data.get('description') | |
631 | uploader = data.get('owner').get('name') | |
632 | uploader_id = data.get('owner').get('id') | |
633 | ||
634 | def pagefunc(pagenum): | |
635 | data = get_page_data(pagenum, 25) | |
636 | return ({ | |
637 | '_type': 'url', | |
638 | 'url': 'http://www.nicovideo.jp/watch/' + item.get('watchId'), | |
639 | } for item in data.get('items')) | |
640 | ||
641 | return { | |
642 | '_type': 'playlist', | |
643 | 'id': list_id, | |
644 | 'title': title, | |
645 | 'description': description, | |
646 | 'uploader': uploader, | |
647 | 'uploader_id': uploader_id, | |
648 | 'entries': OnDemandPagedList(pagefunc, 25), | |
649 | } |