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