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