]>
jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/naver.py
3 from urllib
.parse
import urlparse
, parse_qs
5 from .common
import InfoExtractor
21 class NaverBaseIE(InfoExtractor
):
22 _CAPTION_EXT_RE
= r
'\.(?:ttml|vtt)'
24 @staticmethod # NB: Used in VLiveWebArchiveIE
25 def process_subtitles(vod_data
, process_url
):
26 ret
= {'subtitles': {}
, 'automatic_captions': {}}
27 for caption
in traverse_obj(vod_data
, ('captions', 'list', ...)):
28 caption_url
= caption
.get('source')
31 type_
= 'automatic_captions' if caption
.get('type') == 'auto' else 'subtitles'
32 lang
= caption
.get('locale') or join_nonempty('language', 'country', from_dict
=caption
) or 'und'
33 if caption
.get('type') == 'fan':
34 lang
+= '_fan%d' % next(i
for i
in itertools
.count(1) if f
'{lang}_fan{i}' not in ret
[type_
])
35 ret
[type_
].setdefault(lang
, []).extend({
37 'name': join_nonempty('label', 'fanName', from_dict
=caption
, delim
=' - '),
38 } for sub_url
in process_url(caption_url
))
41 def _extract_video_info(self
, video_id
, vid
, key
):
42 video_data
= self
._download
_json
(
43 'http://play.rmcnmv.naver.com/vod/play/v2.0/' + vid
,
47 meta
= video_data
['meta']
48 title
= meta
['subject']
50 get_list
= lambda x
: try_get(video_data
, lambda y
: y
[x
+ 's']['list'], list) or []
52 def extract_formats(streams
, stream_type
, query
={}):
53 for stream
in streams
:
54 stream_url
= stream
.get('source')
57 stream_url
= update_url_query(stream_url
, query
)
58 encoding_option
= stream
.get('encodingOption', {})
59 bitrate
= stream
.get('bitrate', {})
61 'format_id': '%s_%s' % (stream
.get('type') or stream_type
, dict_get(encoding_option
, ('name', 'id'))),
64 'width': int_or_none(encoding_option
.get('width')),
65 'height': int_or_none(encoding_option
.get('height')),
66 'vbr': int_or_none(bitrate
.get('video')),
67 'abr': int_or_none(bitrate
.get('audio')),
68 'filesize': int_or_none(stream
.get('size')),
69 'protocol': 'm3u8_native' if stream_type
== 'HLS' else None,
72 extract_formats(get_list('video'), 'H264')
73 for stream_set
in video_data
.get('streams', []):
75 for param
in stream_set
.get('keys', []):
76 query
[param
['name']] = param
['value']
77 stream_type
= stream_set
.get('type')
78 videos
= stream_set
.get('videos')
80 extract_formats(videos
, stream_type
, query
)
81 elif stream_type
== 'HLS':
82 stream_url
= stream_set
.get('source')
85 formats
.extend(self
._extract
_m
3u8_formats
(
86 update_url_query(stream_url
, query
), video_id
,
87 'mp4', 'm3u8_native', m3u8_id
=stream_type
, fatal
=False))
89 replace_ext
= lambda x
, y
: re
.sub(self
._CAPTION
_EXT
_RE
, '.' + y
, x
)
91 def get_subs(caption_url
):
92 if re
.search(self
._CAPTION
_EXT
_RE
, caption_url
):
94 replace_ext(caption_url
, 'ttml'),
95 replace_ext(caption_url
, 'vtt'),
99 user
= meta
.get('user', {})
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 **self
.process_subtitles(video_data
, get_subs
),
114 class NaverIE(NaverBaseIE
):
115 _VALID_URL
= r
'https?://(?:m\.)?tv(?:cast)?\.naver\.com/(?:v|embed)/(?P<id>\d+)'
118 'url': 'http://tv.naver.com/v/81652',
122 'title': '[9월 모의고사 해설강의][수학_김상희] 수학 A형 16~20번',
123 'description': '메가스터디 수학 김상희 선생님이 9월 모의고사 수학A형 16번에서 20번까지 해설강의를 공개합니다.',
124 'timestamp': 1378200754,
125 'upload_date': '20130903',
126 'uploader': '메가스터디, 합격불변의 법칙',
127 'uploader_id': 'megastudy',
130 'url': 'http://tv.naver.com/v/395837',
131 'md5': '8a38e35354d26a17f73f4e90094febd3',
135 'title': '9년이 지나도 아픈 기억, 전효성의 아버지',
136 'description': 'md5:eb6aca9d457b922e43860a2a2b1984d3',
137 'timestamp': 1432030253,
138 'upload_date': '20150519',
139 'uploader': '4가지쇼 시즌2',
140 'uploader_id': 'wrappinguser29',
142 'skip': 'Georestricted',
144 'url': 'http://tvcast.naver.com/v/81652',
145 'only_matching': True,
148 def _real_extract(self
, url
):
149 video_id
= self
._match
_id
(url
)
150 content
= self
._download
_json
(
151 'https://tv.naver.com/api/json/v/' + video_id
,
152 video_id
, headers
=self
.geo_verification_headers())
153 player_info_json
= content
.get('playerInfoJson') or {}
154 current_clip
= player_info_json
.get('currentClip') or {}
156 vid
= current_clip
.get('videoId')
157 in_key
= current_clip
.get('inKey')
159 if not vid
or not in_key
:
160 player_auth
= try_get(player_info_json
, lambda x
: x
['playerOption']['auth'])
161 if player_auth
== 'notCountry':
162 self
.raise_geo_restricted(countries
=['KR'])
163 elif player_auth
== 'notLogin':
164 self
.raise_login_required()
165 raise ExtractorError('couldn\'t extract vid and key')
166 info
= self
._extract
_video
_info
(video_id
, vid
, in_key
)
168 'description': clean_html(current_clip
.get('description')),
169 'timestamp': int_or_none(current_clip
.get('firstExposureTime'), 1000),
170 'duration': parse_duration(current_clip
.get('displayPlayTime')),
171 'like_count': int_or_none(current_clip
.get('recommendPoint')),
172 'age_limit': 19 if current_clip
.get('adult') else None,
177 class NaverLiveIE(InfoExtractor
):
178 IE_NAME
= 'Naver:live'
179 _VALID_URL
= r
'https?://(?:m\.)?tv(?:cast)?\.naver\.com/l/(?P<id>\d+)'
182 'url': 'https://tv.naver.com/l/52010',
186 'title': '[LIVE] 뉴스특보 : "수도권 거리두기, 2주간 2단계로 조정"',
187 'description': 'md5:df7f0c237a5ed5e786ce5c91efbeaab3',
188 'channel_id': 'NTV-ytnnews24-0',
189 'start_time': 1597026780000,
192 'url': 'https://tv.naver.com/l/51549',
196 'title': '연합뉴스TV - 코로나19 뉴스특보',
197 'description': 'md5:c655e82091bc21e413f549c0eaccc481',
198 'channel_id': 'NTV-yonhapnewstv-0',
199 'start_time': 1596406380000,
202 'url': 'https://tv.naver.com/l/54887',
203 'only_matching': True,
206 def _real_extract(self
, url
):
207 video_id
= self
._match
_id
(url
)
208 page
= self
._download
_webpage
(url
, video_id
, 'Downloading Page', 'Unable to download Page')
209 secure_url
= self
._search
_regex
(r
'sApiF:\s+(?:"|\')([^
"\']+)', page, 'secureurl')
211 info = self._extract_video_info(video_id, secure_url)
213 'description': self._og_search_description(page)
218 def _extract_video_info(self, video_id, url):
219 video_data = self._download_json(url, video_id, headers=self.geo_verification_headers())
220 meta = video_data.get('meta')
221 status = meta.get('status')
223 if status == 'CLOSED':
224 raise ExtractorError('Stream is offline.', expected=True)
225 elif status != 'OPENED':
226 raise ExtractorError('Unknown status %s' % status)
228 title = meta.get('title')
229 stream_list = video_data.get('streams')
231 if stream_list is None:
232 raise ExtractorError('Could not get stream data.', expected=True)
235 for quality in stream_list:
236 if not quality.get('url'):
239 prop = quality.get('property')
240 if prop.get('abr'): # This abr doesn't mean Average audio bitrate.
243 formats.extend(self._extract_m3u8_formats(
244 quality.get('url'), video_id, 'mp4',
245 m3u8_id=quality.get('qualityId'), live=True
252 'channel_id': meta.get('channelId'),
253 'channel_url': meta.get('channelUrl'),
254 'thumbnail': meta.get('imgUrl'),
255 'start_time': meta.get('startTime'),
256 'categories': [meta.get('categoryId')],
261 class NaverNowIE(NaverBaseIE):
263 _VALID_URL = r'https?://now\.naver\.com/s/now\.(?P<id>\w+)'
264 _API_URL = 'https://apis.naver.com/now_web/oldnow_web/v4'
266 'url': 'https://now.naver.com/s/now.4759?shareReplayId=26331132#replay=',
267 'md5': 'e05854162c21c221481de16b2944a0bc',
269 'id': '4759-26331132',
270 'title': '아이키X노제\r\n💖꽁냥꽁냥💖(1)',
272 'thumbnail': r're:^https?://.*\.jpg',
273 'timestamp': 1650369600,
274 'upload_date': '20220419',
275 'uploader_id': 'now',
277 'uploader_url': 'https://now.naver.com/show/4759',
278 'uploader': '아이키의 떰즈업',
284 'url': 'https://now.naver.com/s/now.4759?shareHightlight=26601461#highlight=',
285 'md5': '9f6118e398aa0f22b2152f554ea7851b',
287 'id': '4759-26601461',
288 'title': '아이키: 나 리정한테 흔들렸어,,, 질투 폭발하는 노제 여보😾 [아이키의 떰즈업]ㅣ네이버 NOW.',
290 'thumbnail': r're:^https?://.*\.jpg',
291 'upload_date': '20220504',
292 'timestamp': 1651648311,
293 'uploader_id': 'now',
295 'uploader_url': 'https://now.naver.com/show/4759',
296 'uploader': '아이키의 떰즈업',
302 'url': 'https://now.naver.com/s/now.4759',
307 'playlist_mincount': 101
309 'url': 'https://now.naver.com/s/now.4759?shareReplayId=26331132#replay',
314 'playlist_mincount': 101,
316 'url': 'https://now.naver.com/s/now.4759?shareHightlight=26601461#highlight=',
321 'playlist_mincount': 101,
323 'url': 'https://now.naver.com/s/now.kihyunplay?shareReplayId=30573291#replay',
324 'only_matching': True,
327 def _extract_replay(self, show_id, replay_id):
328 vod_info = self._download_json(f'{self._API_URL}/shows/now.{show_id}/vod/{replay_id}', replay_id)
329 in_key = self._download_json(f'{self._API_URL}/shows/now.{show_id}/vod/{replay_id}/inkey', replay_id)['inKey']
331 'id': f'{show_id}-{replay_id}',
332 'title': traverse_obj(vod_info, ('episode', 'title')),
333 'timestamp': unified_timestamp(traverse_obj(vod_info, ('episode', 'start_time'))),
334 'thumbnail': vod_info.get('thumbnail_image_url'),
335 }, self._extract_video_info(replay_id, vod_info['video_id'], in_key))
337 def _extract_show_replays(self, show_id):
341 show_vod_info = self._download_json(
342 f'{self._API_URL}/vod-shows/now.{show_id}', show_id,
343 query={'page': page, 'page_size': page_size},
344 note=f'Downloading JSON vod list for show {show_id} - page {page}'
345 )['response']['result']
346 for v in show_vod_info.get('vod_list') or []:
347 yield self._extract_replay(show_id, v['id'])
349 if len(show_vod_info.get('vod_list') or []) < page_size:
353 def _extract_show_highlights(self, show_id, highlight_id=None):
357 highlights_videos = self._download_json(
358 f'{self._API_URL}/shows/now.{show_id}/highlights/videos/', show_id,
359 query={'page': page, 'page_size': page_size},
360 note=f'Downloading JSON highlights for show {show_id} - page {page}')
362 for highlight in highlights_videos.get('results') or []:
363 if highlight_id and highlight.get('clip_no') != int(highlight_id):
366 'id': f'{show_id}-{highlight["clip_no"]}',
367 'title': highlight.get('title'),
368 'timestamp': unified_timestamp(highlight.get('regdate')),
369 'thumbnail': highlight.get('thumbnail_url'),
370 }, self._extract_video_info(highlight['clip_no'], highlight['video_id'], highlight['video_inkey']))
372 if len(highlights_videos.get('results') or []) < page_size:
376 def _extract_highlight(self, show_id, highlight_id):
378 return next(self._extract_show_highlights(show_id, highlight_id))
379 except StopIteration:
380 raise ExtractorError(f'Unable to find highlight {highlight_id} for show {show_id}')
382 def _real_extract(self, url):
383 show_id = self._match_id(url)
384 qs = parse_qs(urlparse(url).query)
386 if not self._yes_playlist(show_id, qs.get('shareHightlight')):
387 return self._extract_highlight(show_id, qs['shareHightlight'][0])
388 elif not self._yes_playlist(show_id, qs.get('shareReplayId')):
389 return self._extract_replay(show_id, qs['shareReplayId'][0])
391 show_info = self._download_json(
392 f'{self._API_URL}/shows/now.{show_id}/', show_id,
393 note=f'Downloading JSON vod list for show {show_id}')
395 return self.playlist_result(
396 itertools.chain(self._extract_show_replays(show_id), self._extract_show_highlights(show_id)),
397 show_id, show_info.get('title'))