]>
Commit | Line | Data |
---|---|---|
fb198a8a | 1 | import datetime |
f494ddad | 2 | import functools |
7bdcb4a4 | 3 | import itertools |
abafce59 | 4 | import json |
5 | import re | |
7bdcb4a4 | 6 | import time |
52ad14ae | 7 | |
f8f9250f L |
8 | from urllib.parse import urlparse |
9 | ||
abafce59 | 10 | from .common import InfoExtractor, SearchInfoExtractor |
ccfd70f4 | 11 | from ..networking import Request |
3d2623a8 | 12 | from ..networking.exceptions import HTTPError |
1cc79574 | 13 | from ..utils import ( |
6110bbbf | 14 | ExtractorError, |
7bdcb4a4 LNO |
15 | OnDemandPagedList, |
16 | bug_reports_message, | |
17 | clean_html, | |
fb198a8a | 18 | float_or_none, |
b868936c | 19 | int_or_none, |
7bdcb4a4 | 20 | join_nonempty, |
1cc79574 | 21 | parse_duration, |
7bdcb4a4 | 22 | parse_filesize, |
bb865f3a | 23 | parse_iso8601, |
5d45484c LNO |
24 | parse_resolution, |
25 | qualities, | |
ee6a6116 | 26 | remove_start, |
5d45484c | 27 | str_or_none, |
f494ddad | 28 | traverse_obj, |
463e7216 | 29 | try_get, |
f494ddad | 30 | unescapeHTML, |
7bdcb4a4 LNO |
31 | update_url_query, |
32 | url_or_none, | |
6e6bc8da | 33 | urlencode_postdata, |
83bfb5e2 | 34 | urljoin, |
52ad14ae TT |
35 | ) |
36 | ||
13ebea79 | 37 | |
52ad14ae | 38 | class NiconicoIE(InfoExtractor): |
214c22c7 JMF |
39 | IE_NAME = 'niconico' |
40 | IE_DESC = 'ニコニコ動画' | |
52ad14ae | 41 | |
1c9a1457 | 42 | _TESTS = [{ |
214c22c7 | 43 | 'url': 'http://www.nicovideo.jp/watch/sm22312215', |
7bdcb4a4 | 44 | 'md5': 'd1a75c0823e2f629128c43e1212760f9', |
214c22c7 JMF |
45 | 'info_dict': { |
46 | 'id': 'sm22312215', | |
47 | 'ext': 'mp4', | |
48 | 'title': 'Big Buck Bunny', | |
463e7216 | 49 | 'thumbnail': r're:https?://.*', |
214c22c7 JMF |
50 | 'uploader': 'takuya0301', |
51 | 'uploader_id': '2698420', | |
52 | 'upload_date': '20131123', | |
aaab8c5e | 53 | 'timestamp': int, # timestamp is unstable |
214c22c7 | 54 | 'description': '(c) copyright 2008, Blender Foundation / www.bigbuckbunny.org', |
15ce1338 | 55 | 'duration': 33, |
463e7216 YCH |
56 | 'view_count': int, |
57 | 'comment_count': int, | |
52ad14ae | 58 | }, |
8e4988f1 | 59 | 'skip': 'Requires an account', |
1c9a1457 | 60 | }, { |
59d814f7 YCH |
61 | # File downloaded with and without credentials are different, so omit |
62 | # the md5 field | |
1c9a1457 | 63 | 'url': 'http://www.nicovideo.jp/watch/nm14296458', |
1c9a1457 S |
64 | 'info_dict': { |
65 | 'id': 'nm14296458', | |
66 | 'ext': 'swf', | |
67 | 'title': '【鏡音リン】Dance on media【オリジナル】take2!', | |
bb865f3a | 68 | 'description': 'md5:689f066d74610b3b22e0f1739add0f58', |
463e7216 | 69 | 'thumbnail': r're:https?://.*', |
1c9a1457 S |
70 | 'uploader': 'りょうた', |
71 | 'uploader_id': '18822557', | |
72 | 'upload_date': '20110429', | |
bb865f3a | 73 | 'timestamp': 1304065916, |
1c9a1457 S |
74 | 'duration': 209, |
75 | }, | |
8e4988f1 | 76 | 'skip': 'Requires an account', |
bb865f3a YCH |
77 | }, { |
78 | # 'video exists but is marked as "deleted" | |
b2e8e7da | 79 | # md5 is unstable |
bb865f3a | 80 | 'url': 'http://www.nicovideo.jp/watch/sm10000', |
bb865f3a YCH |
81 | 'info_dict': { |
82 | 'id': 'sm10000', | |
83 | 'ext': 'unknown_video', | |
84 | 'description': 'deleted', | |
85 | 'title': 'ドラえもんエターナル第3話「決戦第3新東京市」<前編>', | |
463e7216 | 86 | 'thumbnail': r're:https?://.*', |
b2e8e7da | 87 | 'upload_date': '20071224', |
8e4988f1 | 88 | 'timestamp': int, # timestamp field has different value if logged in |
b2e8e7da | 89 | 'duration': 304, |
463e7216 | 90 | 'view_count': int, |
bb865f3a | 91 | }, |
8e4988f1 | 92 | 'skip': 'Requires an account', |
621ffe7b YCH |
93 | }, { |
94 | 'url': 'http://www.nicovideo.jp/watch/so22543406', | |
95 | 'info_dict': { | |
96 | 'id': '1388129933', | |
97 | 'ext': 'mp4', | |
98 | 'title': '【第1回】RADIOアニメロミックス ラブライブ!~のぞえりRadio Garden~', | |
99 | 'description': 'md5:b27d224bb0ff53d3c8269e9f8b561cf1', | |
463e7216 | 100 | 'thumbnail': r're:https?://.*', |
621ffe7b YCH |
101 | 'timestamp': 1388851200, |
102 | 'upload_date': '20140104', | |
103 | 'uploader': 'アニメロチャンネル', | |
104 | 'uploader_id': '312', | |
8e4988f1 YCH |
105 | }, |
106 | 'skip': 'The viewing period of the video you were searching for has expired.', | |
463e7216 | 107 | }, { |
ee6a6116 | 108 | # video not available via `getflv`; "old" HTML5 video |
463e7216 | 109 | 'url': 'http://www.nicovideo.jp/watch/sm1151009', |
ee6a6116 | 110 | 'md5': '8fa81c364eb619d4085354eab075598a', |
463e7216 YCH |
111 | 'info_dict': { |
112 | 'id': 'sm1151009', | |
ee6a6116 | 113 | 'ext': 'mp4', |
463e7216 YCH |
114 | 'title': 'マスターシステム本体内蔵のスペハリのメインテーマ(PSG版)', |
115 | 'description': 'md5:6ee077e0581ff5019773e2e714cdd0b7', | |
116 | 'thumbnail': r're:https?://.*', | |
117 | 'duration': 184, | |
118 | 'timestamp': 1190868283, | |
119 | 'upload_date': '20070927', | |
120 | 'uploader': 'denden2', | |
121 | 'uploader_id': '1392194', | |
122 | 'view_count': int, | |
123 | 'comment_count': int, | |
124 | }, | |
125 | 'skip': 'Requires an account', | |
ee6a6116 YCH |
126 | }, { |
127 | # "New" HTML5 video | |
aaab8c5e | 128 | # md5 is unstable |
ee6a6116 | 129 | 'url': 'http://www.nicovideo.jp/watch/sm31464864', |
ee6a6116 YCH |
130 | 'info_dict': { |
131 | 'id': 'sm31464864', | |
132 | 'ext': 'mp4', | |
133 | 'title': '新作TVアニメ「戦姫絶唱シンフォギアAXZ」PV 最高画質', | |
134 | 'description': 'md5:e52974af9a96e739196b2c1ca72b5feb', | |
135 | 'timestamp': 1498514060, | |
136 | 'upload_date': '20170626', | |
aaab8c5e | 137 | 'uploader': 'ゲスト', |
ee6a6116 YCH |
138 | 'uploader_id': '40826363', |
139 | 'thumbnail': r're:https?://.*', | |
140 | 'duration': 198, | |
141 | 'view_count': int, | |
142 | 'comment_count': int, | |
143 | }, | |
144 | 'skip': 'Requires an account', | |
aaab8c5e PP |
145 | }, { |
146 | # Video without owner | |
147 | 'url': 'http://www.nicovideo.jp/watch/sm18238488', | |
148 | 'md5': 'd265680a1f92bdcbbd2a507fc9e78a9e', | |
149 | 'info_dict': { | |
150 | 'id': 'sm18238488', | |
151 | 'ext': 'mp4', | |
152 | 'title': '【実写版】ミュータントタートルズ', | |
153 | 'description': 'md5:15df8988e47a86f9e978af2064bf6d8e', | |
154 | 'timestamp': 1341160408, | |
155 | 'upload_date': '20120701', | |
156 | 'uploader': None, | |
157 | 'uploader_id': None, | |
158 | 'thumbnail': r're:https?://.*', | |
159 | 'duration': 5271, | |
160 | 'view_count': int, | |
161 | 'comment_count': int, | |
162 | }, | |
163 | 'skip': 'Requires an account', | |
4a87de72 LS |
164 | }, { |
165 | 'url': 'http://sp.nicovideo.jp/watch/sm28964488?ss_pos=1&cp_in=wt_tg', | |
166 | 'only_matching': True, | |
7bdcb4a4 LNO |
167 | }, { |
168 | 'note': 'a video that is only served as an ENCRYPTED HLS.', | |
169 | 'url': 'https://www.nicovideo.jp/watch/so38016254', | |
170 | 'only_matching': True, | |
1c9a1457 | 171 | }] |
52ad14ae | 172 | |
7bdcb4a4 | 173 | _VALID_URL = r'https?://(?:(?:www\.|secure\.|sp\.)?nicovideo\.jp/watch|nico\.ms)/(?P<id>(?:[a-z]{2})?[0-9]+)' |
52ad14ae | 174 | _NETRC_MACHINE = 'niconico' |
7bdcb4a4 LNO |
175 | _COMMENT_API_ENDPOINTS = ( |
176 | 'https://nvcomment.nicovideo.jp/legacy/api.json', | |
177 | 'https://nmsg.nicovideo.jp/api.json',) | |
2291dbce | 178 | _API_HEADERS = { |
179 | 'X-Frontend-ID': '6', | |
7bdcb4a4 LNO |
180 | 'X-Frontend-Version': '0', |
181 | 'X-Niconico-Language': 'en-us', | |
182 | 'Referer': 'https://www.nicovideo.jp/', | |
183 | 'Origin': 'https://www.nicovideo.jp', | |
2291dbce | 184 | } |
185 | ||
52efa4b3 | 186 | def _perform_login(self, username, password): |
bb139491 | 187 | login_ok = True |
52ad14ae | 188 | login_form_strs = { |
bb139491 | 189 | 'mail_tel': username, |
214c22c7 | 190 | 'password': password, |
52ad14ae | 191 | } |
7bdcb4a4 LNO |
192 | self._request_webpage( |
193 | 'https://account.nicovideo.jp/login', None, | |
194 | note='Acquiring Login session') | |
83bfb5e2 | 195 | page = self._download_webpage( |
7bdcb4a4 | 196 | 'https://account.nicovideo.jp/login/redirector?show_button_twitter=1&site=niconico&show_button_facebook=1', None, |
bb139491 | 197 | note='Logging in', errnote='Unable to log in', |
7bdcb4a4 LNO |
198 | data=urlencode_postdata(login_form_strs), |
199 | headers={ | |
200 | 'Referer': 'https://account.nicovideo.jp/login', | |
201 | 'Content-Type': 'application/x-www-form-urlencoded', | |
202 | }) | |
83bfb5e2 | 203 | if 'oneTimePw' in page: |
204 | post_url = self._search_regex( | |
205 | r'<form[^>]+action=(["\'])(?P<url>.+?)\1', page, 'post url', group='url') | |
206 | page = self._download_webpage( | |
207 | urljoin('https://account.nicovideo.jp', post_url), None, | |
208 | note='Performing MFA', errnote='Unable to complete MFA', | |
209 | data=urlencode_postdata({ | |
210 | 'otp': self._get_tfa_info('6 digits code') | |
211 | }), headers={ | |
212 | 'Content-Type': 'application/x-www-form-urlencoded', | |
213 | }) | |
214 | if 'oneTimePw' in page or 'formError' in page: | |
215 | err_msg = self._html_search_regex( | |
216 | r'formError["\']+>(.*?)</div>', page, 'form_error', | |
217 | default='There\'s an error but the message can\'t be parsed.', | |
218 | flags=re.DOTALL) | |
219 | self.report_warning(f'Unable to log in: MFA challenge failed, "{err_msg}"') | |
220 | return False | |
221 | login_ok = 'class="notice error"' not in page | |
bb139491 | 222 | if not login_ok: |
83bfb5e2 | 223 | self.report_warning('Unable to log in: bad username or password') |
bb139491 | 224 | return login_ok |
52ad14ae | 225 | |
fb198a8a | 226 | def _get_heartbeat_info(self, info_dict): |
fb198a8a | 227 | video_id, video_src_id, audio_src_id = info_dict['url'].split(':')[1].split('/') |
2e25ce3a | 228 | dmc_protocol = info_dict['expected_protocol'] |
ee6a6116 | 229 | |
2291dbce | 230 | api_data = ( |
231 | info_dict.get('_api_data') | |
232 | or self._parse_json( | |
233 | self._html_search_regex( | |
234 | 'data-api-data="([^"]+)"', | |
c7e4ab27 | 235 | self._download_webpage('https://www.nicovideo.jp/watch/' + video_id, video_id), |
2291dbce | 236 | 'API data', default='{}'), |
237 | video_id)) | |
fb198a8a | 238 | |
7978e172 | 239 | session_api_data = try_get(api_data, lambda x: x['media']['delivery']['movie']['session']) |
fb198a8a | 240 | session_api_endpoint = try_get(session_api_data, lambda x: x['urls'][0]) |
241 | ||
2291dbce | 242 | def ping(): |
7bdcb4a4 LNO |
243 | tracking_id = traverse_obj(api_data, ('media', 'delivery', 'trackingId')) |
244 | if tracking_id: | |
245 | tracking_url = update_url_query('https://nvapi.nicovideo.jp/v1/2ab0cbaa/watch', {'t': tracking_id}) | |
246 | watch_request_response = self._download_json( | |
247 | tracking_url, video_id, | |
248 | note='Acquiring permission for downloading video', fatal=False, | |
249 | headers=self._API_HEADERS) | |
250 | if traverse_obj(watch_request_response, ('meta', 'status')) != 200: | |
251 | self.report_warning('Failed to acquire permission for playing video. Video download may fail.') | |
fb198a8a | 252 | |
253 | yesno = lambda x: 'yes' if x else 'no' | |
254 | ||
7bdcb4a4 LNO |
255 | if dmc_protocol == 'http': |
256 | protocol = 'http' | |
257 | protocol_parameters = { | |
258 | 'http_output_download_parameters': { | |
259 | 'use_ssl': yesno(session_api_data['urls'][0]['isSsl']), | |
260 | 'use_well_known_port': yesno(session_api_data['urls'][0]['isWellKnownPort']), | |
261 | } | |
262 | } | |
263 | elif dmc_protocol == 'hls': | |
fb198a8a | 264 | protocol = 'm3u8' |
7bdcb4a4 LNO |
265 | segment_duration = try_get(self._configuration_arg('segment_duration'), lambda x: int(x[0])) or 6000 |
266 | parsed_token = self._parse_json(session_api_data['token'], video_id) | |
267 | encryption = traverse_obj(api_data, ('media', 'delivery', 'encryption')) | |
268 | protocol_parameters = { | |
269 | 'hls_parameters': { | |
270 | 'segment_duration': segment_duration, | |
271 | 'transfer_preset': '', | |
272 | 'use_ssl': yesno(session_api_data['urls'][0]['isSsl']), | |
273 | 'use_well_known_port': yesno(session_api_data['urls'][0]['isWellKnownPort']), | |
fb198a8a | 274 | } |
275 | } | |
7bdcb4a4 LNO |
276 | if 'hls_encryption' in parsed_token and encryption: |
277 | protocol_parameters['hls_parameters']['encryption'] = { | |
278 | parsed_token['hls_encryption']: { | |
279 | 'encrypted_key': encryption['encryptedKey'], | |
280 | 'key_uri': encryption['keyUri'], | |
fb198a8a | 281 | } |
282 | } | |
7bdcb4a4 LNO |
283 | else: |
284 | protocol = 'm3u8_native' | |
285 | else: | |
286 | raise ExtractorError(f'Unsupported DMC protocol: {dmc_protocol}') | |
ee6a6116 YCH |
287 | |
288 | session_response = self._download_json( | |
289 | session_api_endpoint['url'], video_id, | |
290 | query={'_format': 'json'}, | |
291 | headers={'Content-Type': 'application/json'}, | |
fb198a8a | 292 | note='Downloading JSON metadata for %s' % info_dict['format_id'], |
ee6a6116 YCH |
293 | data=json.dumps({ |
294 | 'session': { | |
295 | 'client_info': { | |
7978e172 | 296 | 'player_id': session_api_data.get('playerId'), |
ee6a6116 YCH |
297 | }, |
298 | 'content_auth': { | |
7978e172 | 299 | 'auth_type': try_get(session_api_data, lambda x: x['authTypes'][session_api_data['protocols'][0]]), |
300 | 'content_key_timeout': session_api_data.get('contentKeyTimeout'), | |
ee6a6116 | 301 | 'service_id': 'nicovideo', |
7978e172 | 302 | 'service_user_id': session_api_data.get('serviceUserId') |
ee6a6116 | 303 | }, |
7978e172 | 304 | 'content_id': session_api_data.get('contentId'), |
ee6a6116 YCH |
305 | 'content_src_id_sets': [{ |
306 | 'content_src_ids': [{ | |
307 | 'src_id_to_mux': { | |
fb198a8a | 308 | 'audio_src_ids': [audio_src_id], |
309 | 'video_src_ids': [video_src_id], | |
ee6a6116 YCH |
310 | } |
311 | }] | |
312 | }], | |
313 | 'content_type': 'movie', | |
314 | 'content_uri': '', | |
315 | 'keep_method': { | |
316 | 'heartbeat': { | |
7978e172 | 317 | 'lifetime': session_api_data.get('heartbeatLifetime') |
ee6a6116 YCH |
318 | } |
319 | }, | |
7bdcb4a4 | 320 | 'priority': session_api_data['priority'], |
ee6a6116 YCH |
321 | 'protocol': { |
322 | 'name': 'http', | |
323 | 'parameters': { | |
7bdcb4a4 LNO |
324 | 'http_parameters': { |
325 | 'parameters': protocol_parameters | |
326 | } | |
ee6a6116 YCH |
327 | } |
328 | }, | |
7978e172 | 329 | 'recipe_id': session_api_data.get('recipeId'), |
ee6a6116 YCH |
330 | 'session_operation_auth': { |
331 | 'session_operation_auth_by_signature': { | |
fb198a8a | 332 | 'signature': session_api_data.get('signature'), |
333 | 'token': session_api_data.get('token'), | |
ee6a6116 YCH |
334 | } |
335 | }, | |
336 | 'timing_constraint': 'unlimited' | |
337 | } | |
4d59db5b | 338 | }).encode()) |
ee6a6116 | 339 | |
fb198a8a | 340 | info_dict['url'] = session_response['data']['session']['content_uri'] |
341 | info_dict['protocol'] = protocol | |
342 | ||
343 | # get heartbeat info | |
344 | heartbeat_info_dict = { | |
345 | 'url': session_api_endpoint['url'] + '/' + session_response['data']['session']['id'] + '?_format=json&_method=PUT', | |
346 | 'data': json.dumps(session_response['data']), | |
347 | # interval, convert milliseconds to seconds, then halve to make a buffer. | |
2291dbce | 348 | 'interval': float_or_none(session_api_data.get('heartbeatLifetime'), scale=3000), |
349 | 'ping': ping | |
fb198a8a | 350 | } |
351 | ||
352 | return info_dict, heartbeat_info_dict | |
353 | ||
7bdcb4a4 LNO |
354 | def _extract_format_for_quality(self, video_id, audio_quality, video_quality, dmc_protocol): |
355 | ||
356 | if not audio_quality.get('isAvailable') or not video_quality.get('isAvailable'): | |
357 | return None | |
358 | ||
359 | def extract_video_quality(video_quality): | |
360 | return parse_filesize('%sB' % self._search_regex( | |
361 | r'\| ([0-9]*\.?[0-9]*[MK])', video_quality, 'vbr', default='')) | |
362 | ||
363 | format_id = '-'.join( | |
364 | [remove_start(s['id'], 'archive_') for s in (video_quality, audio_quality)] + [dmc_protocol]) | |
365 | ||
366 | vid_qual_label = traverse_obj(video_quality, ('metadata', 'label')) | |
367 | vid_quality = traverse_obj(video_quality, ('metadata', 'bitrate')) | |
ee6a6116 YCH |
368 | |
369 | return { | |
7bdcb4a4 | 370 | 'url': 'niconico_dmc:%s/%s/%s' % (video_id, video_quality['id'], audio_quality['id']), |
ee6a6116 | 371 | 'format_id': format_id, |
7bdcb4a4 | 372 | 'format_note': join_nonempty('DMC', vid_qual_label, dmc_protocol.upper(), delim=' '), |
ee6a6116 | 373 | 'ext': 'mp4', # Session API are used in HTML5, which always serves mp4 |
7bdcb4a4 LNO |
374 | 'acodec': 'aac', |
375 | 'vcodec': 'h264', | |
376 | 'abr': float_or_none(traverse_obj(audio_quality, ('metadata', 'bitrate')), 1000), | |
377 | 'vbr': float_or_none(vid_quality if vid_quality > 0 else extract_video_quality(vid_qual_label), 1000), | |
378 | 'height': traverse_obj(video_quality, ('metadata', 'resolution', 'height')), | |
379 | 'width': traverse_obj(video_quality, ('metadata', 'resolution', 'width')), | |
380 | 'quality': -2 if 'low' in video_quality['id'] else None, | |
381 | 'protocol': 'niconico_dmc', | |
2e25ce3a | 382 | 'expected_protocol': dmc_protocol, # XXX: This is not a documented field |
fb198a8a | 383 | 'http_headers': { |
384 | 'Origin': 'https://www.nicovideo.jp', | |
385 | 'Referer': 'https://www.nicovideo.jp/watch/' + video_id, | |
386 | } | |
ee6a6116 YCH |
387 | } |
388 | ||
52ad14ae | 389 | def _real_extract(self, url): |
937daef4 | 390 | video_id = self._match_id(url) |
52ad14ae | 391 | |
7bdcb4a4 LNO |
392 | try: |
393 | webpage, handle = self._download_webpage_handle( | |
c7e4ab27 | 394 | 'https://www.nicovideo.jp/watch/' + video_id, video_id) |
7bdcb4a4 | 395 | if video_id.startswith('so'): |
3d2623a8 | 396 | video_id = self._match_id(handle.url) |
fb198a8a | 397 | |
7bdcb4a4 LNO |
398 | api_data = self._parse_json(self._html_search_regex( |
399 | 'data-api-data="([^"]+)"', webpage, | |
400 | 'API data', default='{}'), video_id) | |
401 | except ExtractorError as e: | |
402 | try: | |
403 | api_data = self._download_json( | |
404 | 'https://www.nicovideo.jp/api/watch/v3/%s?_frontendId=6&_frontendVersion=0&actionTrackId=AAAAAAAAAA_%d' % (video_id, round(time.time() * 1000)), video_id, | |
405 | note='Downloading API JSON', errnote='Unable to fetch data')['data'] | |
406 | except ExtractorError: | |
3d2623a8 | 407 | if not isinstance(e.cause, HTTPError): |
7bdcb4a4 | 408 | raise |
3d2623a8 | 409 | webpage = e.cause.response.read().decode('utf-8', 'replace') |
7bdcb4a4 LNO |
410 | error_msg = self._html_search_regex( |
411 | r'(?s)<section\s+class="(?:(?:ErrorMessage|WatchExceptionPage-message)\s*)+">(.+?)</section>', | |
412 | webpage, 'error reason', default=None) | |
413 | if not error_msg: | |
414 | raise | |
415 | raise ExtractorError(re.sub(r'\s+', ' ', error_msg), expected=True) | |
7978e172 | 416 | |
7bdcb4a4 | 417 | formats = [] |
7978e172 | 418 | |
7bdcb4a4 LNO |
419 | def get_video_info(*items, get_first=True, **kwargs): |
420 | return traverse_obj(api_data, ('video', *items), get_all=not get_first, **kwargs) | |
7978e172 | 421 | |
7bdcb4a4 LNO |
422 | quality_info = api_data['media']['delivery']['movie'] |
423 | session_api_data = quality_info['session'] | |
424 | for (audio_quality, video_quality, protocol) in itertools.product(quality_info['audios'], quality_info['videos'], session_api_data['protocols']): | |
425 | fmt = self._extract_format_for_quality(video_id, audio_quality, video_quality, protocol) | |
426 | if fmt: | |
427 | formats.append(fmt) | |
fb198a8a | 428 | |
52ad14ae | 429 | # Start extracting information |
7bdcb4a4 LNO |
430 | tags = None |
431 | if webpage: | |
432 | # use og:video:tag (not logged in) | |
433 | og_video_tags = re.finditer(r'<meta\s+property="og:video:tag"\s*content="(.*?)">', webpage) | |
434 | tags = list(filter(None, (clean_html(x.group(1)) for x in og_video_tags))) | |
435 | if not tags: | |
436 | # use keywords and split with comma (not logged in) | |
437 | kwds = self._html_search_meta('keywords', webpage, default=None) | |
438 | if kwds: | |
439 | tags = [x for x in kwds.split(',') if x] | |
440 | if not tags: | |
441 | # find in json (logged in) | |
442 | tags = traverse_obj(api_data, ('tag', 'items', ..., 'name')) | |
52ad14ae | 443 | |
5d45484c LNO |
444 | thumb_prefs = qualities(['url', 'middleUrl', 'largeUrl', 'player', 'ogp']) |
445 | ||
b2e8e7da | 446 | return { |
214c22c7 | 447 | 'id': video_id, |
2291dbce | 448 | '_api_data': api_data, |
7bdcb4a4 | 449 | 'title': get_video_info(('originalTitle', 'title')) or self._og_search_title(webpage, default=None), |
ee6a6116 | 450 | 'formats': formats, |
5d45484c LNO |
451 | 'thumbnails': [{ |
452 | 'id': key, | |
453 | 'url': url, | |
454 | 'ext': 'jpg', | |
455 | 'preference': thumb_prefs(key), | |
456 | **parse_resolution(url, lenient=True), | |
457 | } for key, url in (get_video_info('thumbnail') or {}).items() if url], | |
7bdcb4a4 | 458 | 'description': clean_html(get_video_info('description')), |
5d45484c LNO |
459 | 'uploader': traverse_obj(api_data, ('owner', 'nickname'), ('channel', 'name'), ('community', 'name')), |
460 | 'uploader_id': str_or_none(traverse_obj(api_data, ('owner', 'id'), ('channel', 'id'), ('community', 'id'))), | |
7bdcb4a4 LNO |
461 | 'timestamp': parse_iso8601(get_video_info('registeredAt')) or parse_iso8601( |
462 | self._html_search_meta('video:release_date', webpage, 'date published', default=None)), | |
7bdcb4a4 LNO |
463 | 'channel': traverse_obj(api_data, ('channel', 'name'), ('community', 'name')), |
464 | 'channel_id': traverse_obj(api_data, ('channel', 'id'), ('community', 'id')), | |
465 | 'view_count': int_or_none(get_video_info('count', 'view')), | |
466 | 'tags': tags, | |
467 | 'genre': traverse_obj(api_data, ('genre', 'label'), ('genre', 'key')), | |
468 | 'comment_count': get_video_info('count', 'comment', expected_type=int), | |
469 | 'duration': ( | |
470 | parse_duration(self._html_search_meta('video:duration', webpage, 'video duration', default=None)) | |
471 | or get_video_info('duration')), | |
472 | 'webpage_url': url_or_none(url) or f'https://www.nicovideo.jp/watch/{video_id}', | |
473 | 'subtitles': self.extract_subtitles(video_id, api_data, session_api_data), | |
52ad14ae | 474 | } |
a9bad429 | 475 | |
7bdcb4a4 LNO |
476 | def _get_subtitles(self, video_id, api_data, session_api_data): |
477 | comment_user_key = traverse_obj(api_data, ('comment', 'keys', 'userKey')) | |
478 | user_id_str = session_api_data.get('serviceUserId') | |
479 | ||
a44ca5a4 | 480 | thread_ids = traverse_obj(api_data, ('comment', 'threads', lambda _, v: v['isActive'])) |
52ecc33e L |
481 | legacy_danmaku = self._extract_legacy_comments(video_id, thread_ids, user_id_str, comment_user_key) or [] |
482 | ||
483 | new_comments = traverse_obj(api_data, ('comment', 'nvComment')) | |
484 | new_danmaku = self._extract_new_comments( | |
485 | new_comments.get('server'), video_id, | |
486 | new_comments.get('params'), new_comments.get('threadKey')) | |
487 | ||
488 | if not legacy_danmaku and not new_danmaku: | |
7bdcb4a4 LNO |
489 | self.report_warning(f'Failed to get comments. {bug_reports_message()}') |
490 | return | |
52ecc33e | 491 | |
7bdcb4a4 LNO |
492 | return { |
493 | 'comments': [{ | |
494 | 'ext': 'json', | |
52ecc33e | 495 | 'data': json.dumps(legacy_danmaku + new_danmaku), |
7bdcb4a4 LNO |
496 | }], |
497 | } | |
498 | ||
52ecc33e | 499 | def _extract_legacy_comments(self, video_id, threads, user_id, user_key): |
7bdcb4a4 LNO |
500 | auth_data = { |
501 | 'user_id': user_id, | |
502 | 'userkey': user_key, | |
503 | } if user_id and user_key else {'user_id': ''} | |
504 | ||
52ecc33e L |
505 | api_url = traverse_obj(threads, (..., 'server'), get_all=False) |
506 | ||
7bdcb4a4 LNO |
507 | # Request Start |
508 | post_data = [{'ping': {'content': 'rs:0'}}] | |
509 | for i, thread in enumerate(threads): | |
510 | thread_id = thread['id'] | |
511 | thread_fork = thread['fork'] | |
512 | # Post Start (2N) | |
513 | post_data.append({'ping': {'content': f'ps:{i * 2}'}}) | |
514 | post_data.append({'thread': { | |
515 | 'fork': thread_fork, | |
516 | 'language': 0, | |
517 | 'nicoru': 3, | |
518 | 'scores': 1, | |
519 | 'thread': thread_id, | |
520 | 'version': '20090904', | |
521 | 'with_global': 1, | |
522 | **auth_data, | |
523 | }}) | |
524 | # Post Final (2N) | |
525 | post_data.append({'ping': {'content': f'pf:{i * 2}'}}) | |
526 | ||
527 | # Post Start (2N+1) | |
528 | post_data.append({'ping': {'content': f'ps:{i * 2 + 1}'}}) | |
529 | post_data.append({'thread_leaves': { | |
530 | # format is '<bottom of minute range>-<top of minute range>:<comments per minute>,<total last comments' | |
531 | # unfortunately NND limits (deletes?) comment returns this way, so you're only able to grab the last 1000 per language | |
532 | 'content': '0-999999:999999,999999,nicoru:999999', | |
533 | 'fork': thread_fork, | |
534 | 'language': 0, | |
535 | 'nicoru': 3, | |
536 | 'scores': 1, | |
537 | 'thread': thread_id, | |
538 | **auth_data, | |
539 | }}) | |
540 | # Post Final (2N+1) | |
541 | post_data.append({'ping': {'content': f'pf:{i * 2 + 1}'}}) | |
542 | # Request Final | |
543 | post_data.append({'ping': {'content': 'rf:0'}}) | |
544 | ||
52ecc33e L |
545 | return self._download_json( |
546 | f'{api_url}/api.json', video_id, data=json.dumps(post_data).encode(), fatal=False, | |
547 | headers={ | |
548 | 'Referer': f'https://www.nicovideo.jp/watch/{video_id}', | |
549 | 'Origin': 'https://www.nicovideo.jp', | |
550 | 'Content-Type': 'text/plain;charset=UTF-8', | |
551 | }, | |
552 | note='Downloading comments', errnote=f'Failed to access endpoint {api_url}') | |
553 | ||
554 | def _extract_new_comments(self, endpoint, video_id, params, thread_key): | |
555 | comments = self._download_json( | |
556 | f'{endpoint}/v1/threads', video_id, data=json.dumps({ | |
557 | 'additionals': {}, | |
558 | 'params': params, | |
559 | 'threadKey': thread_key, | |
560 | }).encode(), fatal=False, | |
561 | headers={ | |
562 | 'Referer': 'https://www.nicovideo.jp/', | |
563 | 'Origin': 'https://www.nicovideo.jp', | |
564 | 'Content-Type': 'text/plain;charset=UTF-8', | |
565 | 'x-client-os-type': 'others', | |
566 | 'x-frontend-id': '6', | |
567 | 'x-frontend-version': '0', | |
568 | }, | |
569 | note='Downloading comments (new)', errnote='Failed to download comments (new)') | |
570 | return traverse_obj(comments, ('data', 'threads', ..., 'comments', ...)) | |
7bdcb4a4 | 571 | |
a9bad429 | 572 | |
f494ddad LNO |
573 | class NiconicoPlaylistBaseIE(InfoExtractor): |
574 | _PAGE_SIZE = 100 | |
575 | ||
576 | _API_HEADERS = { | |
577 | 'X-Frontend-ID': '6', | |
578 | 'X-Frontend-Version': '0', | |
579 | 'X-Niconico-Language': 'en-us' | |
580 | } | |
581 | ||
582 | def _call_api(self, list_id, resource, query): | |
2fa669f7 | 583 | raise NotImplementedError('Must be implemented in subclasses') |
f494ddad LNO |
584 | |
585 | @staticmethod | |
586 | def _parse_owner(item): | |
587 | return { | |
588 | 'uploader': traverse_obj(item, ('owner', 'name')), | |
589 | 'uploader_id': traverse_obj(item, ('owner', 'id')), | |
590 | } | |
591 | ||
592 | def _fetch_page(self, list_id, page): | |
593 | page += 1 | |
594 | resp = self._call_api(list_id, 'page %d' % page, { | |
595 | 'page': page, | |
596 | 'pageSize': self._PAGE_SIZE, | |
597 | }) | |
598 | # this is needed to support both mylist and user | |
599 | for video in traverse_obj(resp, ('items', ..., ('video', None))) or []: | |
600 | video_id = video.get('id') | |
601 | if not video_id: | |
602 | # skip {"video": {"id": "blablabla", ...}} | |
603 | continue | |
604 | count = video.get('count') or {} | |
605 | get_count = lambda x: int_or_none(count.get(x)) | |
606 | yield { | |
607 | '_type': 'url', | |
608 | 'id': video_id, | |
609 | 'title': video.get('title'), | |
610 | 'url': f'https://www.nicovideo.jp/watch/{video_id}', | |
611 | 'description': video.get('shortDescription'), | |
612 | 'duration': int_or_none(video.get('duration')), | |
613 | 'view_count': get_count('view'), | |
614 | 'comment_count': get_count('comment'), | |
615 | 'thumbnail': traverse_obj(video, ('thumbnail', ('nHdUrl', 'largeUrl', 'listingUrl', 'url'))), | |
616 | 'ie_key': NiconicoIE.ie_key(), | |
617 | **self._parse_owner(video), | |
618 | } | |
619 | ||
620 | def _entries(self, list_id): | |
621 | return OnDemandPagedList(functools.partial(self._fetch_page, list_id), self._PAGE_SIZE) | |
622 | ||
623 | ||
624 | class NiconicoPlaylistIE(NiconicoPlaylistBaseIE): | |
625 | IE_NAME = 'niconico:playlist' | |
626 | _VALID_URL = r'https?://(?:(?:www\.|sp\.)?nicovideo\.jp|nico\.ms)/(?:user/\d+/)?(?:my/)?mylist/(?:#/)?(?P<id>\d+)' | |
a9bad429 | 627 | |
29f7c58a | 628 | _TESTS = [{ |
a9bad429 JMF |
629 | 'url': 'http://www.nicovideo.jp/mylist/27411728', |
630 | 'info_dict': { | |
631 | 'id': '27411728', | |
632 | 'title': 'AKB48のオールナイトニッポン', | |
29f7c58a | 633 | 'description': 'md5:d89694c5ded4b6c693dea2db6e41aa08', |
634 | 'uploader': 'のっく', | |
635 | 'uploader_id': '805442', | |
a9bad429 | 636 | }, |
f494ddad | 637 | 'playlist_mincount': 291, |
29f7c58a | 638 | }, { |
639 | 'url': 'https://www.nicovideo.jp/user/805442/mylist/27411728', | |
640 | 'only_matching': True, | |
f494ddad LNO |
641 | }, { |
642 | 'url': 'https://www.nicovideo.jp/my/mylist/#/68048635', | |
643 | 'only_matching': True, | |
29f7c58a | 644 | }] |
a9bad429 | 645 | |
f494ddad LNO |
646 | def _call_api(self, list_id, resource, query): |
647 | return self._download_json( | |
648 | f'https://nvapi.nicovideo.jp/v2/mylists/{list_id}', list_id, | |
649 | f'Downloading {resource}', query=query, | |
650 | headers=self._API_HEADERS)['data']['mylist'] | |
2291dbce | 651 | |
a9bad429 JMF |
652 | def _real_extract(self, url): |
653 | list_id = self._match_id(url) | |
f494ddad LNO |
654 | mylist = self._call_api(list_id, 'list', { |
655 | 'pageSize': 1, | |
656 | }) | |
657 | return self.playlist_result( | |
658 | self._entries(list_id), list_id, | |
659 | mylist.get('name'), mylist.get('description'), **self._parse_owner(mylist)) | |
fb198a8a | 660 | |
fb198a8a | 661 | |
f494ddad LNO |
662 | class NiconicoSeriesIE(InfoExtractor): |
663 | IE_NAME = 'niconico:series' | |
c86e433c | 664 | _VALID_URL = r'https?://(?:(?:www\.|sp\.)?nicovideo\.jp(?:/user/\d+)?|nico\.ms)/series/(?P<id>\d+)' |
f494ddad LNO |
665 | |
666 | _TESTS = [{ | |
c86e433c | 667 | 'url': 'https://www.nicovideo.jp/user/44113208/series/110226', |
f494ddad LNO |
668 | 'info_dict': { |
669 | 'id': '110226', | |
670 | 'title': 'ご立派ァ!のシリーズ', | |
671 | }, | |
ac05fb93 | 672 | 'playlist_mincount': 10, |
f494ddad LNO |
673 | }, { |
674 | 'url': 'https://www.nicovideo.jp/series/12312/', | |
675 | 'info_dict': { | |
676 | 'id': '12312', | |
677 | 'title': 'バトルスピリッツ お勧めカード紹介(調整中)', | |
678 | }, | |
ac05fb93 | 679 | 'playlist_mincount': 103, |
f494ddad LNO |
680 | }, { |
681 | 'url': 'https://nico.ms/series/203559', | |
682 | 'only_matching': True, | |
683 | }] | |
684 | ||
685 | def _real_extract(self, url): | |
686 | list_id = self._match_id(url) | |
c86e433c | 687 | webpage = self._download_webpage(url, list_id) |
f494ddad LNO |
688 | |
689 | title = self._search_regex( | |
690 | (r'<title>「(.+)(全', | |
691 | r'<div class="TwitterShareButton"\s+data-text="(.+)\s+https:'), | |
692 | webpage, 'title', fatal=False) | |
693 | if title: | |
694 | title = unescapeHTML(title) | |
c86e433c | 695 | json_data = next(self._yield_json_ld(webpage, None, fatal=False)) |
696 | return self.playlist_from_matches( | |
697 | traverse_obj(json_data, ('itemListElement', ..., 'url')), list_id, title, ie=NiconicoIE) | |
f494ddad LNO |
698 | |
699 | ||
700 | class NiconicoHistoryIE(NiconicoPlaylistBaseIE): | |
701 | IE_NAME = 'niconico:history' | |
3b161265 M |
702 | IE_DESC = 'NicoNico user history or likes. Requires cookies.' |
703 | _VALID_URL = r'https?://(?:www\.|sp\.)?nicovideo\.jp/my/(?P<id>history(?:/like)?)' | |
f494ddad LNO |
704 | |
705 | _TESTS = [{ | |
706 | 'note': 'PC page, with /video', | |
707 | 'url': 'https://www.nicovideo.jp/my/history/video', | |
708 | 'only_matching': True, | |
709 | }, { | |
710 | 'note': 'PC page, without /video', | |
711 | 'url': 'https://www.nicovideo.jp/my/history', | |
712 | 'only_matching': True, | |
713 | }, { | |
714 | 'note': 'mobile page, with /video', | |
715 | 'url': 'https://sp.nicovideo.jp/my/history/video', | |
716 | 'only_matching': True, | |
717 | }, { | |
718 | 'note': 'mobile page, without /video', | |
719 | 'url': 'https://sp.nicovideo.jp/my/history', | |
720 | 'only_matching': True, | |
3b161265 M |
721 | }, { |
722 | 'note': 'PC page', | |
723 | 'url': 'https://www.nicovideo.jp/my/history/like', | |
724 | 'only_matching': True, | |
725 | }, { | |
726 | 'note': 'Mobile page', | |
727 | 'url': 'https://sp.nicovideo.jp/my/history/like', | |
728 | 'only_matching': True, | |
f494ddad LNO |
729 | }] |
730 | ||
731 | def _call_api(self, list_id, resource, query): | |
3b161265 | 732 | path = 'likes' if list_id == 'history/like' else 'watch/history' |
f494ddad | 733 | return self._download_json( |
3b161265 M |
734 | f'https://nvapi.nicovideo.jp/v1/users/me/{path}', list_id, |
735 | f'Downloading {resource}', query=query, headers=self._API_HEADERS)['data'] | |
f494ddad LNO |
736 | |
737 | def _real_extract(self, url): | |
3b161265 | 738 | list_id = self._match_id(url) |
f494ddad | 739 | try: |
3b161265 | 740 | mylist = self._call_api(list_id, 'list', {'pageSize': 1}) |
f494ddad | 741 | except ExtractorError as e: |
3d2623a8 | 742 | if isinstance(e.cause, HTTPError) and e.cause.status == 401: |
3b161265 | 743 | self.raise_login_required('You have to be logged in to get your history') |
f494ddad LNO |
744 | raise |
745 | return self.playlist_result(self._entries(list_id), list_id, **self._parse_owner(mylist)) | |
c1d3a4a8 | 746 | |
747 | ||
63ccf4ff | 748 | class NicovideoSearchBaseIE(InfoExtractor): |
9a5b0125 LNO |
749 | _SEARCH_TYPE = 'search' |
750 | ||
63ccf4ff | 751 | def _entries(self, url, item_id, query=None, note='Downloading page %(page)s'): |
752 | query = query or {} | |
753 | pages = [query['page']] if 'page' in query else itertools.count(1) | |
754 | for page_num in pages: | |
755 | query['page'] = str(page_num) | |
756 | webpage = self._download_webpage(url, item_id, query=query, note=note % {'page': page_num}) | |
757 | results = re.findall(r'(?<=data-video-id=)["\']?(?P<videoid>.*?)(?=["\'])', webpage) | |
758 | for item in results: | |
c7e4ab27 | 759 | yield self.url_result(f'https://www.nicovideo.jp/watch/{item}', 'Niconico', item) |
63ccf4ff | 760 | if not results: |
761 | break | |
762 | ||
146cc411 | 763 | def _search_results(self, query): |
764 | return self._entries( | |
9a5b0125 | 765 | self._proto_relative_url(f'//www.nicovideo.jp/{self._SEARCH_TYPE}/{query}'), query) |
146cc411 | 766 | |
63ccf4ff | 767 | |
768 | class NicovideoSearchIE(NicovideoSearchBaseIE, SearchInfoExtractor): | |
769 | IE_DESC = 'Nico video search' | |
770 | IE_NAME = 'nicovideo:search' | |
771 | _SEARCH_KEY = 'nicosearch' | |
abafce59 | 772 | |
63ccf4ff | 773 | |
774 | class NicovideoSearchURLIE(NicovideoSearchBaseIE): | |
775 | IE_NAME = f'{NicovideoSearchIE.IE_NAME}_url' | |
abafce59 | 776 | IE_DESC = 'Nico video search URLs' |
777 | _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/search/(?P<id>[^?#&]+)?' | |
778 | _TESTS = [{ | |
779 | 'url': 'http://www.nicovideo.jp/search/sm9', | |
780 | 'info_dict': { | |
781 | 'id': 'sm9', | |
782 | 'title': 'sm9' | |
783 | }, | |
784 | 'playlist_mincount': 40, | |
785 | }, { | |
786 | 'url': 'https://www.nicovideo.jp/search/sm9?sort=h&order=d&end=2020-12-31&start=2020-01-01', | |
787 | 'info_dict': { | |
788 | 'id': 'sm9', | |
789 | 'title': 'sm9' | |
790 | }, | |
791 | 'playlist_count': 31, | |
792 | }] | |
793 | ||
abafce59 | 794 | def _real_extract(self, url): |
795 | query = self._match_id(url) | |
796 | return self.playlist_result(self._entries(url, query), query, query) | |
797 | ||
798 | ||
63ccf4ff | 799 | class NicovideoSearchDateIE(NicovideoSearchBaseIE, SearchInfoExtractor): |
f304da8a | 800 | IE_DESC = 'Nico video search, newest first' |
63ccf4ff | 801 | IE_NAME = f'{NicovideoSearchIE.IE_NAME}:date' |
abafce59 | 802 | _SEARCH_KEY = 'nicosearchdate' |
803 | _TESTS = [{ | |
804 | 'url': 'nicosearchdateall:a', | |
805 | 'info_dict': { | |
806 | 'id': 'a', | |
807 | 'title': 'a' | |
808 | }, | |
809 | 'playlist_mincount': 1610, | |
810 | }] | |
811 | ||
812 | _START_DATE = datetime.date(2007, 1, 1) | |
813 | _RESULTS_PER_PAGE = 32 | |
814 | _MAX_PAGES = 50 | |
815 | ||
816 | def _entries(self, url, item_id, start_date=None, end_date=None): | |
817 | start_date, end_date = start_date or self._START_DATE, end_date or datetime.datetime.now().date() | |
818 | ||
819 | # If the last page has a full page of videos, we need to break down the query interval further | |
820 | last_page_len = len(list(self._get_entries_for_date( | |
821 | url, item_id, start_date, end_date, self._MAX_PAGES, | |
822 | note=f'Checking number of videos from {start_date} to {end_date}'))) | |
823 | if (last_page_len == self._RESULTS_PER_PAGE and start_date != end_date): | |
824 | midpoint = start_date + ((end_date - start_date) // 2) | |
825 | yield from self._entries(url, item_id, midpoint, end_date) | |
826 | yield from self._entries(url, item_id, start_date, midpoint) | |
827 | else: | |
828 | self.to_screen(f'{item_id}: Downloading results from {start_date} to {end_date}') | |
829 | yield from self._get_entries_for_date( | |
830 | url, item_id, start_date, end_date, note=' Downloading page %(page)s') | |
831 | ||
832 | def _get_entries_for_date(self, url, item_id, start_date, end_date=None, page_num=None, note=None): | |
833 | query = { | |
834 | 'start': str(start_date), | |
835 | 'end': str(end_date or start_date), | |
836 | 'sort': 'f', | |
837 | 'order': 'd', | |
838 | } | |
839 | if page_num: | |
840 | query['page'] = str(page_num) | |
841 | ||
63ccf4ff | 842 | yield from super()._entries(url, item_id, query=query, note=note) |
abafce59 | 843 | |
844 | ||
9a5b0125 LNO |
845 | class NicovideoTagURLIE(NicovideoSearchBaseIE): |
846 | IE_NAME = 'niconico:tag' | |
847 | IE_DESC = 'NicoNico video tag URLs' | |
848 | _SEARCH_TYPE = 'tag' | |
849 | _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/tag/(?P<id>[^?#&]+)?' | |
850 | _TESTS = [{ | |
851 | 'url': 'https://www.nicovideo.jp/tag/ドキュメンタリー淫夢', | |
852 | 'info_dict': { | |
853 | 'id': 'ドキュメンタリー淫夢', | |
854 | 'title': 'ドキュメンタリー淫夢' | |
855 | }, | |
856 | 'playlist_mincount': 400, | |
857 | }] | |
858 | ||
859 | def _real_extract(self, url): | |
860 | query = self._match_id(url) | |
861 | return self.playlist_result(self._entries(url, query), query, query) | |
862 | ||
863 | ||
c1d3a4a8 | 864 | class NiconicoUserIE(InfoExtractor): |
865 | _VALID_URL = r'https?://(?:www\.)?nicovideo\.jp/user/(?P<id>\d+)/?(?:$|[#?])' | |
866 | _TEST = { | |
867 | 'url': 'https://www.nicovideo.jp/user/419948', | |
868 | 'info_dict': { | |
869 | 'id': '419948', | |
870 | }, | |
871 | 'playlist_mincount': 101, | |
872 | } | |
873 | _API_URL = "https://nvapi.nicovideo.jp/v1/users/%s/videos?sortKey=registeredAt&sortOrder=desc&pageSize=%s&page=%s" | |
2291dbce | 874 | _PAGE_SIZE = 100 |
875 | ||
876 | _API_HEADERS = { | |
c1d3a4a8 | 877 | 'X-Frontend-ID': '6', |
2291dbce | 878 | 'X-Frontend-Version': '0' |
c1d3a4a8 | 879 | } |
c1d3a4a8 | 880 | |
abafce59 | 881 | def _entries(self, list_id): |
c1d3a4a8 | 882 | total_count = 1 |
883 | count = page_num = 0 | |
884 | while count < total_count: | |
885 | json_parsed = self._download_json( | |
886 | self._API_URL % (list_id, self._PAGE_SIZE, page_num + 1), list_id, | |
2291dbce | 887 | headers=self._API_HEADERS, |
c1d3a4a8 | 888 | note='Downloading JSON metadata%s' % (' page %d' % page_num if page_num else '')) |
889 | if not page_num: | |
890 | total_count = int_or_none(json_parsed['data'].get('totalCount')) | |
891 | for entry in json_parsed["data"]["items"]: | |
892 | count += 1 | |
893 | yield self.url_result('https://www.nicovideo.jp/watch/%s' % entry['id']) | |
894 | page_num += 1 | |
895 | ||
896 | def _real_extract(self, url): | |
897 | list_id = self._match_id(url) | |
898 | return self.playlist_result(self._entries(list_id), list_id, ie=NiconicoIE.ie_key()) | |
f8f9250f L |
899 | |
900 | ||
901 | class NiconicoLiveIE(InfoExtractor): | |
902 | IE_NAME = 'niconico:live' | |
903 | IE_DESC = 'ニコニコ生放送' | |
904 | _VALID_URL = r'https?://(?:sp\.)?live2?\.nicovideo\.jp/(?:watch|gate)/(?P<id>lv\d+)' | |
905 | _TESTS = [{ | |
906 | 'note': 'this test case includes invisible characters for title, pasting them as-is', | |
907 | 'url': 'https://live.nicovideo.jp/watch/lv339533123', | |
908 | 'info_dict': { | |
909 | 'id': 'lv339533123', | |
910 | 'title': '激辛ペヤング食べます( ;ᯅ; )(歌枠オーディション参加中)', | |
911 | 'view_count': 1526, | |
912 | 'comment_count': 1772, | |
913 | 'description': '初めましてもかって言います❕\nのんびり自由に適当に暮らしてます', | |
914 | 'uploader': 'もか', | |
915 | 'channel': 'ゲストさんのコミュニティ', | |
916 | 'channel_id': 'co5776900', | |
917 | 'channel_url': 'https://com.nicovideo.jp/community/co5776900', | |
918 | 'timestamp': 1670677328, | |
919 | 'is_live': True, | |
920 | }, | |
921 | 'skip': 'livestream', | |
922 | }, { | |
923 | 'url': 'https://live2.nicovideo.jp/watch/lv339533123', | |
924 | 'only_matching': True, | |
925 | }, { | |
926 | 'url': 'https://sp.live.nicovideo.jp/watch/lv339533123', | |
927 | 'only_matching': True, | |
928 | }, { | |
929 | 'url': 'https://sp.live2.nicovideo.jp/watch/lv339533123', | |
930 | 'only_matching': True, | |
931 | }] | |
932 | ||
933 | _KNOWN_LATENCY = ('high', 'low') | |
934 | ||
935 | def _real_extract(self, url): | |
f8f9250f L |
936 | video_id = self._match_id(url) |
937 | webpage, urlh = self._download_webpage_handle(f'https://live.nicovideo.jp/watch/{video_id}', video_id) | |
938 | ||
939 | embedded_data = self._parse_json(unescapeHTML(self._search_regex( | |
940 | r'<script\s+id="embedded-data"\s*data-props="(.+?)"', webpage, 'embedded data')), video_id) | |
941 | ||
942 | ws_url = traverse_obj(embedded_data, ('site', 'relive', 'webSocketUrl')) | |
943 | if not ws_url: | |
944 | raise ExtractorError('The live hasn\'t started yet or already ended.', expected=True) | |
945 | ws_url = update_url_query(ws_url, { | |
946 | 'frontend_id': traverse_obj(embedded_data, ('site', 'frontendId')) or '9', | |
947 | }) | |
948 | ||
3d2623a8 | 949 | hostname = remove_start(urlparse(urlh.url).hostname, 'sp.') |
f8f9250f L |
950 | latency = try_get(self._configuration_arg('latency'), lambda x: x[0]) |
951 | if latency not in self._KNOWN_LATENCY: | |
952 | latency = 'high' | |
953 | ||
ccfd70f4 | 954 | ws = self._request_webpage( |
955 | Request(ws_url, headers={'Origin': f'https://{hostname}'}), | |
956 | video_id=video_id, note='Connecting to WebSocket server') | |
f8f9250f L |
957 | |
958 | self.write_debug('[debug] Sending HLS server request') | |
959 | ws.send(json.dumps({ | |
960 | 'type': 'startWatching', | |
961 | 'data': { | |
962 | 'stream': { | |
963 | 'quality': 'abr', | |
964 | 'protocol': 'hls+fmp4', | |
965 | 'latency': latency, | |
966 | 'chasePlay': False | |
967 | }, | |
968 | 'room': { | |
969 | 'protocol': 'webSocket', | |
970 | 'commentable': True | |
971 | }, | |
972 | 'reconnect': False, | |
973 | } | |
974 | })) | |
975 | ||
976 | while True: | |
977 | recv = ws.recv() | |
978 | if not recv: | |
979 | continue | |
980 | data = json.loads(recv) | |
981 | if not isinstance(data, dict): | |
982 | continue | |
983 | if data.get('type') == 'stream': | |
984 | m3u8_url = data['data']['uri'] | |
985 | qualities = data['data']['availableQualities'] | |
986 | break | |
987 | elif data.get('type') == 'disconnect': | |
988 | self.write_debug(recv) | |
989 | raise ExtractorError('Disconnected at middle of extraction') | |
990 | elif data.get('type') == 'error': | |
991 | self.write_debug(recv) | |
992 | message = traverse_obj(data, ('body', 'code')) or recv | |
993 | raise ExtractorError(message) | |
994 | elif self.get_param('verbose', False): | |
995 | if len(recv) > 100: | |
996 | recv = recv[:100] + '...' | |
997 | self.write_debug('Server said: %s' % recv) | |
998 | ||
999 | title = traverse_obj(embedded_data, ('program', 'title')) or self._html_search_meta( | |
1000 | ('og:title', 'twitter:title'), webpage, 'live title', fatal=False) | |
1001 | ||
1002 | raw_thumbs = traverse_obj(embedded_data, ('program', 'thumbnail')) or {} | |
1003 | thumbnails = [] | |
1004 | for name, value in raw_thumbs.items(): | |
1005 | if not isinstance(value, dict): | |
1006 | thumbnails.append({ | |
1007 | 'id': name, | |
1008 | 'url': value, | |
1009 | **parse_resolution(value, lenient=True), | |
1010 | }) | |
1011 | continue | |
1012 | ||
1013 | for k, img_url in value.items(): | |
1014 | res = parse_resolution(k, lenient=True) or parse_resolution(img_url, lenient=True) | |
1015 | width, height = res.get('width'), res.get('height') | |
1016 | ||
1017 | thumbnails.append({ | |
1018 | 'id': f'{name}_{width}x{height}', | |
1019 | 'url': img_url, | |
1020 | **res, | |
1021 | }) | |
1022 | ||
1023 | formats = self._extract_m3u8_formats(m3u8_url, video_id, ext='mp4', live=True) | |
1024 | for fmt, q in zip(formats, reversed(qualities[1:])): | |
1025 | fmt.update({ | |
1026 | 'format_id': q, | |
1027 | 'protocol': 'niconico_live', | |
1028 | 'ws': ws, | |
1029 | 'video_id': video_id, | |
f8f9250f L |
1030 | 'live_latency': latency, |
1031 | 'origin': hostname, | |
1032 | }) | |
1033 | ||
1034 | return { | |
1035 | 'id': video_id, | |
1036 | 'title': title, | |
1037 | **traverse_obj(embedded_data, { | |
1038 | 'view_count': ('program', 'statistics', 'watchCount'), | |
1039 | 'comment_count': ('program', 'statistics', 'commentCount'), | |
1040 | 'uploader': ('program', 'supplier', 'name'), | |
1041 | 'channel': ('socialGroup', 'name'), | |
1042 | 'channel_id': ('socialGroup', 'id'), | |
1043 | 'channel_url': ('socialGroup', 'socialGroupPageUrl'), | |
1044 | }), | |
1045 | 'description': clean_html(traverse_obj(embedded_data, ('program', 'description'))), | |
1046 | 'timestamp': int_or_none(traverse_obj(embedded_data, ('program', 'openTime'))), | |
1047 | 'is_live': True, | |
1048 | 'thumbnails': thumbnails, | |
1049 | 'formats': formats, | |
1050 | } |