]>
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 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
,
30 meta
= video_data
['meta']
31 title
= meta
['subject']
33 get_list
= lambda x
: try_get(video_data
, lambda y
: y
[x
+ 's']['list'], list) or []
35 def extract_formats(streams
, stream_type
, query
={}):
36 for stream
in streams
:
37 stream_url
= stream
.get('source')
40 stream_url
= update_url_query(stream_url
, query
)
41 encoding_option
= stream
.get('encodingOption', {})
42 bitrate
= stream
.get('bitrate', {})
44 'format_id': '%s_%s' % (stream
.get('type') or stream_type
, dict_get(encoding_option
, ('name', 'id'))),
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,
55 extract_formats(get_list('video'), 'H264')
56 for stream_set
in video_data
.get('streams', []):
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')
63 extract_formats(videos
, stream_type
, query
)
64 elif stream_type
== 'HLS':
65 stream_url
= stream_set
.get('source')
68 formats
.extend(self
._extract
_m
3u8_formats
(
69 update_url_query(stream_url
, query
), video_id
,
70 'mp4', 'm3u8_native', m3u8_id
=stream_type
, fatal
=False))
72 replace_ext
= lambda x
, y
: re
.sub(self
._CAPTION
_EXT
_RE
, '.' + y
, x
)
74 def get_subs(caption_url
):
75 if re
.search(self
._CAPTION
_EXT
_RE
, caption_url
):
77 replace_ext(caption_url
, 'ttml'),
78 replace_ext(caption_url
, 'vtt'),
82 automatic_captions
= {}
84 for caption
in get_list('caption'):
85 caption_url
= caption
.get('source')
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({
94 'name': join_nonempty('label', 'fanName', from_dict
=caption
, delim
=' - '),
95 } for sub_url
in get_subs(caption_url
))
97 user
= meta
.get('user', {})
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'),
113 class NaverIE(NaverBaseIE
):
114 _VALID_URL
= r
'https?://(?:m\.)?tv(?:cast)?\.naver\.com/(?:v|embed)/(?P<id>\d+)'
117 'url': 'http://tv.naver.com/v/81652',
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',
129 'url': 'http://tv.naver.com/v/395837',
130 'md5': '8a38e35354d26a17f73f4e90094febd3',
134 'title': '9년이 지나도 아픈 기억, 전효성의 아버지',
135 'description': 'md5:eb6aca9d457b922e43860a2a2b1984d3',
136 'timestamp': 1432030253,
137 'upload_date': '20150519',
138 'uploader': '4가지쇼 시즌2',
139 'uploader_id': 'wrappinguser29',
141 'skip': 'Georestricted',
143 'url': 'http://tvcast.naver.com/v/81652',
144 'only_matching': True,
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 {}
155 vid
= current_clip
.get('videoId')
156 in_key
= current_clip
.get('inKey')
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
)
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,
176 class NaverLiveIE(InfoExtractor
):
177 IE_NAME
= 'Naver:live'
178 _VALID_URL
= r
'https?://(?:m\.)?tv(?:cast)?\.naver\.com/l/(?P<id>\d+)'
181 'url': 'https://tv.naver.com/l/52010',
185 'title': '[LIVE] 뉴스특보 : "수도권 거리두기, 2주간 2단계로 조정"',
186 'description': 'md5:df7f0c237a5ed5e786ce5c91efbeaab3',
187 'channel_id': 'NTV-ytnnews24-0',
188 'start_time': 1597026780000,
191 'url': 'https://tv.naver.com/l/51549',
195 'title': '연합뉴스TV - 코로나19 뉴스특보',
196 'description': 'md5:c655e82091bc21e413f549c0eaccc481',
197 'channel_id': 'NTV-yonhapnewstv-0',
198 'start_time': 1596406380000,
201 'url': 'https://tv.naver.com/l/54887',
202 'only_matching': True,
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')
210 info = self._extract_video_info(video_id, secure_url)
212 'description': self._og_search_description(page)
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')
222 if status == 'CLOSED':
223 raise ExtractorError('Stream is offline.', expected=True)
224 elif status != 'OPENED':
225 raise ExtractorError('Unknown status %s' % status)
227 title = meta.get('title')
228 stream_list = video_data.get('streams')
230 if stream_list is None:
231 raise ExtractorError('Could not get stream data.', expected=True)
234 for quality in stream_list:
235 if not quality.get('url'):
238 prop = quality.get('property')
239 if prop.get('abr'): # This abr doesn't mean Average audio bitrate.
242 formats.extend(self._extract_m3u8_formats(
243 quality.get('url'), video_id, 'mp4',
244 m3u8_id=quality.get('qualityId'), live=True
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')],
260 class NaverNowIE(NaverBaseIE):
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'
265 'url': 'https://now.naver.com/s/now.4759?shareReplayId=26331132#replay=',
266 'md5': 'e05854162c21c221481de16b2944a0bc',
268 'id': '4759-26331132',
269 'title': '아이키X노제\r\n💖꽁냥꽁냥💖(1)',
271 'thumbnail': r're:^https?://.*\.jpg',
272 'timestamp': 1650369600,
273 'upload_date': '20220419',
274 'uploader_id': 'now',
276 'uploader_url': 'https://now.naver.com/show/4759',
277 'uploader': '아이키의 떰즈업',
283 'url': 'https://now.naver.com/s/now.4759?shareHightlight=26601461#highlight=',
284 'md5': '9f6118e398aa0f22b2152f554ea7851b',
286 'id': '4759-26601461',
287 'title': '아이키: 나 리정한테 흔들렸어,,, 질투 폭발하는 노제 여보😾 [아이키의 떰즈업]ㅣ네이버 NOW.',
289 'thumbnail': r're:^https?://.*\.jpg',
290 'upload_date': '20220504',
291 'timestamp': 1651648311,
292 'uploader_id': 'now',
294 'uploader_url': 'https://now.naver.com/show/4759',
295 'uploader': '아이키의 떰즈업',
301 'url': 'https://now.naver.com/s/now.4759',
306 'playlist_mincount': 101
308 'url': 'https://now.naver.com/s/now.4759?shareReplayId=26331132#replay',
313 'playlist_mincount': 101,
315 'url': 'https://now.naver.com/s/now.4759?shareHightlight=26601461#highlight=',
320 'playlist_mincount': 101,
322 'url': 'https://now.naver.com/s/now.kihyunplay?shareReplayId=30573291#replay',
323 'only_matching': True,
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']
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))
336 def _extract_show_replays(self, show_id):
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'])
348 if len(show_vod_info.get('vod_list') or []) < page_size:
352 def _extract_show_highlights(self, show_id, highlight_id=None):
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}')
361 for highlight in highlights_videos.get('results') or []:
362 if highlight_id and highlight.get('clip_no') != int(highlight_id):
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']))
371 if len(highlights_videos.get('results') or []) < page_size:
375 def _extract_highlight(self, show_id, highlight_id):
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}')
381 def _real_extract(self, url):
382 show_id = self._match_id(url)
383 qs = parse_qs(urlparse(url).query)
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])
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}')
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'))