]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/naver.py
[extractor/vimeo] Fix `playerConfig` extraction (#6203)
[yt-dlp.git] / yt_dlp / extractor / naver.py
1 import itertools
2 import re
3 from urllib.parse import urlparse, parse_qs
4
5 from .common import InfoExtractor
6 from ..utils import (
7 ExtractorError,
8 clean_html,
9 dict_get,
10 int_or_none,
11 join_nonempty,
12 merge_dicts,
13 parse_duration,
14 traverse_obj,
15 try_get,
16 unified_timestamp,
17 update_url_query,
18 )
19
20
21 class NaverBaseIE(InfoExtractor):
22 _CAPTION_EXT_RE = r'\.(?:ttml|vtt)'
23
24 def _extract_video_info(self, video_id, vid, key):
25 video_data = self._download_json(
26 'http://play.rmcnmv.naver.com/vod/play/v2.0/' + vid,
27 video_id, query={
28 'key': key,
29 })
30 meta = video_data['meta']
31 title = meta['subject']
32 formats = []
33 get_list = lambda x: try_get(video_data, lambda y: y[x + 's']['list'], list) or []
34
35 def extract_formats(streams, stream_type, query={}):
36 for stream in streams:
37 stream_url = stream.get('source')
38 if not stream_url:
39 continue
40 stream_url = update_url_query(stream_url, query)
41 encoding_option = stream.get('encodingOption', {})
42 bitrate = stream.get('bitrate', {})
43 formats.append({
44 'format_id': '%s_%s' % (stream.get('type') or stream_type, dict_get(encoding_option, ('name', 'id'))),
45 'url': stream_url,
46 'ext': 'mp4',
47 'width': int_or_none(encoding_option.get('width')),
48 'height': int_or_none(encoding_option.get('height')),
49 'vbr': int_or_none(bitrate.get('video')),
50 'abr': int_or_none(bitrate.get('audio')),
51 'filesize': int_or_none(stream.get('size')),
52 'protocol': 'm3u8_native' if stream_type == 'HLS' else None,
53 })
54
55 extract_formats(get_list('video'), 'H264')
56 for stream_set in video_data.get('streams', []):
57 query = {}
58 for param in stream_set.get('keys', []):
59 query[param['name']] = param['value']
60 stream_type = stream_set.get('type')
61 videos = stream_set.get('videos')
62 if videos:
63 extract_formats(videos, stream_type, query)
64 elif stream_type == 'HLS':
65 stream_url = stream_set.get('source')
66 if not stream_url:
67 continue
68 formats.extend(self._extract_m3u8_formats(
69 update_url_query(stream_url, query), video_id,
70 'mp4', 'm3u8_native', m3u8_id=stream_type, fatal=False))
71
72 replace_ext = lambda x, y: re.sub(self._CAPTION_EXT_RE, '.' + y, x)
73
74 def get_subs(caption_url):
75 if re.search(self._CAPTION_EXT_RE, caption_url):
76 return [
77 replace_ext(caption_url, 'ttml'),
78 replace_ext(caption_url, 'vtt'),
79 ]
80 return [caption_url]
81
82 automatic_captions = {}
83 subtitles = {}
84 for caption in get_list('caption'):
85 caption_url = caption.get('source')
86 if not caption_url:
87 continue
88 sub_dict = automatic_captions if caption.get('type') == 'auto' else subtitles
89 lang = caption.get('locale') or join_nonempty('language', 'country', from_dict=caption) or 'und'
90 if caption.get('type') == 'fan':
91 lang += '_fan%d' % next(i for i in itertools.count(1) if f'{lang}_fan{i}' not in sub_dict)
92 sub_dict.setdefault(lang, []).extend({
93 'url': sub_url,
94 'name': join_nonempty('label', 'fanName', from_dict=caption, delim=' - '),
95 } for sub_url in get_subs(caption_url))
96
97 user = meta.get('user', {})
98
99 return {
100 'id': video_id,
101 'title': title,
102 'formats': formats,
103 'subtitles': subtitles,
104 'automatic_captions': automatic_captions,
105 'thumbnail': try_get(meta, lambda x: x['cover']['source']),
106 'view_count': int_or_none(meta.get('count')),
107 'uploader_id': user.get('id'),
108 'uploader': user.get('name'),
109 'uploader_url': user.get('url'),
110 }
111
112
113 class NaverIE(NaverBaseIE):
114 _VALID_URL = r'https?://(?:m\.)?tv(?:cast)?\.naver\.com/(?:v|embed)/(?P<id>\d+)'
115 _GEO_BYPASS = False
116 _TESTS = [{
117 'url': 'http://tv.naver.com/v/81652',
118 'info_dict': {
119 'id': '81652',
120 'ext': 'mp4',
121 'title': '[9월 모의고사 해설강의][수학_김상희] 수학 A형 16~20번',
122 'description': '메가스터디 수학 김상희 선생님이 9월 모의고사 수학A형 16번에서 20번까지 해설강의를 공개합니다.',
123 'timestamp': 1378200754,
124 'upload_date': '20130903',
125 'uploader': '메가스터디, 합격불변의 법칙',
126 'uploader_id': 'megastudy',
127 },
128 }, {
129 'url': 'http://tv.naver.com/v/395837',
130 'md5': '8a38e35354d26a17f73f4e90094febd3',
131 'info_dict': {
132 'id': '395837',
133 'ext': 'mp4',
134 'title': '9년이 지나도 아픈 기억, 전효성의 아버지',
135 'description': 'md5:eb6aca9d457b922e43860a2a2b1984d3',
136 'timestamp': 1432030253,
137 'upload_date': '20150519',
138 'uploader': '4가지쇼 시즌2',
139 'uploader_id': 'wrappinguser29',
140 },
141 'skip': 'Georestricted',
142 }, {
143 'url': 'http://tvcast.naver.com/v/81652',
144 'only_matching': True,
145 }]
146
147 def _real_extract(self, url):
148 video_id = self._match_id(url)
149 content = self._download_json(
150 'https://tv.naver.com/api/json/v/' + video_id,
151 video_id, headers=self.geo_verification_headers())
152 player_info_json = content.get('playerInfoJson') or {}
153 current_clip = player_info_json.get('currentClip') or {}
154
155 vid = current_clip.get('videoId')
156 in_key = current_clip.get('inKey')
157
158 if not vid or not in_key:
159 player_auth = try_get(player_info_json, lambda x: x['playerOption']['auth'])
160 if player_auth == 'notCountry':
161 self.raise_geo_restricted(countries=['KR'])
162 elif player_auth == 'notLogin':
163 self.raise_login_required()
164 raise ExtractorError('couldn\'t extract vid and key')
165 info = self._extract_video_info(video_id, vid, in_key)
166 info.update({
167 'description': clean_html(current_clip.get('description')),
168 'timestamp': int_or_none(current_clip.get('firstExposureTime'), 1000),
169 'duration': parse_duration(current_clip.get('displayPlayTime')),
170 'like_count': int_or_none(current_clip.get('recommendPoint')),
171 'age_limit': 19 if current_clip.get('adult') else None,
172 })
173 return info
174
175
176 class NaverLiveIE(InfoExtractor):
177 IE_NAME = 'Naver:live'
178 _VALID_URL = r'https?://(?:m\.)?tv(?:cast)?\.naver\.com/l/(?P<id>\d+)'
179 _GEO_BYPASS = False
180 _TESTS = [{
181 'url': 'https://tv.naver.com/l/52010',
182 'info_dict': {
183 'id': '52010',
184 'ext': 'mp4',
185 'title': '[LIVE] 뉴스특보 : "수도권 거리두기, 2주간 2단계로 조정"',
186 'description': 'md5:df7f0c237a5ed5e786ce5c91efbeaab3',
187 'channel_id': 'NTV-ytnnews24-0',
188 'start_time': 1597026780000,
189 },
190 }, {
191 'url': 'https://tv.naver.com/l/51549',
192 'info_dict': {
193 'id': '51549',
194 'ext': 'mp4',
195 'title': '연합뉴스TV - 코로나19 뉴스특보',
196 'description': 'md5:c655e82091bc21e413f549c0eaccc481',
197 'channel_id': 'NTV-yonhapnewstv-0',
198 'start_time': 1596406380000,
199 },
200 }, {
201 'url': 'https://tv.naver.com/l/54887',
202 'only_matching': True,
203 }]
204
205 def _real_extract(self, url):
206 video_id = self._match_id(url)
207 page = self._download_webpage(url, video_id, 'Downloading Page', 'Unable to download Page')
208 secure_url = self._search_regex(r'sApiF:\s+(?:"|\')([^"\']+)', page, 'secureurl')
209
210 info = self._extract_video_info(video_id, secure_url)
211 info.update({
212 'description': self._og_search_description(page)
213 })
214
215 return info
216
217 def _extract_video_info(self, video_id, url):
218 video_data = self._download_json(url, video_id, headers=self.geo_verification_headers())
219 meta = video_data.get('meta')
220 status = meta.get('status')
221
222 if status == 'CLOSED':
223 raise ExtractorError('Stream is offline.', expected=True)
224 elif status != 'OPENED':
225 raise ExtractorError('Unknown status %s' % status)
226
227 title = meta.get('title')
228 stream_list = video_data.get('streams')
229
230 if stream_list is None:
231 raise ExtractorError('Could not get stream data.', expected=True)
232
233 formats = []
234 for quality in stream_list:
235 if not quality.get('url'):
236 continue
237
238 prop = quality.get('property')
239 if prop.get('abr'): # This abr doesn't mean Average audio bitrate.
240 continue
241
242 formats.extend(self._extract_m3u8_formats(
243 quality.get('url'), video_id, 'mp4',
244 m3u8_id=quality.get('qualityId'), live=True
245 ))
246
247 return {
248 'id': video_id,
249 'title': title,
250 'formats': formats,
251 'channel_id': meta.get('channelId'),
252 'channel_url': meta.get('channelUrl'),
253 'thumbnail': meta.get('imgUrl'),
254 'start_time': meta.get('startTime'),
255 'categories': [meta.get('categoryId')],
256 'is_live': True
257 }
258
259
260 class NaverNowIE(NaverBaseIE):
261 IE_NAME = 'navernow'
262 _VALID_URL = r'https?://now\.naver\.com/s/now\.(?P<id>\w+)'
263 _API_URL = 'https://apis.naver.com/now_web/oldnow_web/v4'
264 _TESTS = [{
265 'url': 'https://now.naver.com/s/now.4759?shareReplayId=26331132#replay=',
266 'md5': 'e05854162c21c221481de16b2944a0bc',
267 'info_dict': {
268 'id': '4759-26331132',
269 'title': '아이키X노제\r\n💖꽁냥꽁냥💖(1)',
270 'ext': 'mp4',
271 'thumbnail': r're:^https?://.*\.jpg',
272 'timestamp': 1650369600,
273 'upload_date': '20220419',
274 'uploader_id': 'now',
275 'view_count': int,
276 'uploader_url': 'https://now.naver.com/show/4759',
277 'uploader': '아이키의 떰즈업',
278 },
279 'params': {
280 'noplaylist': True,
281 }
282 }, {
283 'url': 'https://now.naver.com/s/now.4759?shareHightlight=26601461#highlight=',
284 'md5': '9f6118e398aa0f22b2152f554ea7851b',
285 'info_dict': {
286 'id': '4759-26601461',
287 'title': '아이키: 나 리정한테 흔들렸어,,, 질투 폭발하는 노제 여보😾 [아이키의 떰즈업]ㅣ네이버 NOW.',
288 'ext': 'mp4',
289 'thumbnail': r're:^https?://.*\.jpg',
290 'upload_date': '20220504',
291 'timestamp': 1651648311,
292 'uploader_id': 'now',
293 'view_count': int,
294 'uploader_url': 'https://now.naver.com/show/4759',
295 'uploader': '아이키의 떰즈업',
296 },
297 'params': {
298 'noplaylist': True,
299 },
300 }, {
301 'url': 'https://now.naver.com/s/now.4759',
302 'info_dict': {
303 'id': '4759',
304 'title': '아이키의 떰즈업',
305 },
306 'playlist_mincount': 101
307 }, {
308 'url': 'https://now.naver.com/s/now.4759?shareReplayId=26331132#replay',
309 'info_dict': {
310 'id': '4759',
311 'title': '아이키의 떰즈업',
312 },
313 'playlist_mincount': 101,
314 }, {
315 'url': 'https://now.naver.com/s/now.4759?shareHightlight=26601461#highlight=',
316 'info_dict': {
317 'id': '4759',
318 'title': '아이키의 떰즈업',
319 },
320 'playlist_mincount': 101,
321 }, {
322 'url': 'https://now.naver.com/s/now.kihyunplay?shareReplayId=30573291#replay',
323 'only_matching': True,
324 }]
325
326 def _extract_replay(self, show_id, replay_id):
327 vod_info = self._download_json(f'{self._API_URL}/shows/now.{show_id}/vod/{replay_id}', replay_id)
328 in_key = self._download_json(f'{self._API_URL}/shows/now.{show_id}/vod/{replay_id}/inkey', replay_id)['inKey']
329 return merge_dicts({
330 'id': f'{show_id}-{replay_id}',
331 'title': traverse_obj(vod_info, ('episode', 'title')),
332 'timestamp': unified_timestamp(traverse_obj(vod_info, ('episode', 'start_time'))),
333 'thumbnail': vod_info.get('thumbnail_image_url'),
334 }, self._extract_video_info(replay_id, vod_info['video_id'], in_key))
335
336 def _extract_show_replays(self, show_id):
337 page_size = 15
338 page = 1
339 while True:
340 show_vod_info = self._download_json(
341 f'{self._API_URL}/vod-shows/now.{show_id}', show_id,
342 query={'page': page, 'page_size': page_size},
343 note=f'Downloading JSON vod list for show {show_id} - page {page}'
344 )['response']['result']
345 for v in show_vod_info.get('vod_list') or []:
346 yield self._extract_replay(show_id, v['id'])
347
348 if len(show_vod_info.get('vod_list') or []) < page_size:
349 break
350 page += 1
351
352 def _extract_show_highlights(self, show_id, highlight_id=None):
353 page_size = 10
354 page = 1
355 while True:
356 highlights_videos = self._download_json(
357 f'{self._API_URL}/shows/now.{show_id}/highlights/videos/', show_id,
358 query={'page': page, 'page_size': page_size},
359 note=f'Downloading JSON highlights for show {show_id} - page {page}')
360
361 for highlight in highlights_videos.get('results') or []:
362 if highlight_id and highlight.get('clip_no') != int(highlight_id):
363 continue
364 yield merge_dicts({
365 'id': f'{show_id}-{highlight["clip_no"]}',
366 'title': highlight.get('title'),
367 'timestamp': unified_timestamp(highlight.get('regdate')),
368 'thumbnail': highlight.get('thumbnail_url'),
369 }, self._extract_video_info(highlight['clip_no'], highlight['video_id'], highlight['video_inkey']))
370
371 if len(highlights_videos.get('results') or []) < page_size:
372 break
373 page += 1
374
375 def _extract_highlight(self, show_id, highlight_id):
376 try:
377 return next(self._extract_show_highlights(show_id, highlight_id))
378 except StopIteration:
379 raise ExtractorError(f'Unable to find highlight {highlight_id} for show {show_id}')
380
381 def _real_extract(self, url):
382 show_id = self._match_id(url)
383 qs = parse_qs(urlparse(url).query)
384
385 if not self._yes_playlist(show_id, qs.get('shareHightlight')):
386 return self._extract_highlight(show_id, qs['shareHightlight'][0])
387 elif not self._yes_playlist(show_id, qs.get('shareReplayId')):
388 return self._extract_replay(show_id, qs['shareReplayId'][0])
389
390 show_info = self._download_json(
391 f'{self._API_URL}/shows/now.{show_id}/', show_id,
392 note=f'Downloading JSON vod list for show {show_id}')
393
394 return self.playlist_result(
395 itertools.chain(self._extract_show_replays(show_id), self._extract_show_highlights(show_id)),
396 show_id, show_info.get('title'))