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