]>
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))
71 self
._sort
_formats
(formats
)
73 replace_ext
= lambda x
, y
: re
.sub(self
._CAPTION
_EXT
_RE
, '.' + y
, x
)
75 def get_subs(caption_url
):
76 if re
.search(self
._CAPTION
_EXT
_RE
, caption_url
):
78 'url': replace_ext(caption_url
, 'ttml'),
80 'url': replace_ext(caption_url
, 'vtt'),
83 return [{'url': caption_url}
]
85 automatic_captions
= {}
87 for caption
in get_list('caption'):
88 caption_url
= caption
.get('source')
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
))
94 user
= meta
.get('user', {})
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'),
110 class NaverIE(NaverBaseIE
):
111 _VALID_URL
= r
'https?://(?:m\.)?tv(?:cast)?\.naver\.com/(?:v|embed)/(?P<id>\d+)'
114 'url': 'http://tv.naver.com/v/81652',
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',
126 'url': 'http://tv.naver.com/v/395837',
127 'md5': '8a38e35354d26a17f73f4e90094febd3',
131 'title': '9년이 지나도 아픈 기억, 전효성의 아버지',
132 'description': 'md5:eb6aca9d457b922e43860a2a2b1984d3',
133 'timestamp': 1432030253,
134 'upload_date': '20150519',
135 'uploader': '4가지쇼 시즌2',
136 'uploader_id': 'wrappinguser29',
138 'skip': 'Georestricted',
140 'url': 'http://tvcast.naver.com/v/81652',
141 'only_matching': True,
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 {}
152 vid
= current_clip
.get('videoId')
153 in_key
= current_clip
.get('inKey')
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
)
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,
173 class NaverLiveIE(InfoExtractor
):
174 IE_NAME
= 'Naver:live'
175 _VALID_URL
= r
'https?://(?:m\.)?tv(?:cast)?\.naver\.com/l/(?P<id>\d+)'
178 'url': 'https://tv.naver.com/l/52010',
182 'title': '[LIVE] 뉴스특보 : "수도권 거리두기, 2주간 2단계로 조정"',
183 'description': 'md5:df7f0c237a5ed5e786ce5c91efbeaab3',
184 'channel_id': 'NTV-ytnnews24-0',
185 'start_time': 1597026780000,
188 'url': 'https://tv.naver.com/l/51549',
192 'title': '연합뉴스TV - 코로나19 뉴스특보',
193 'description': 'md5:c655e82091bc21e413f549c0eaccc481',
194 'channel_id': 'NTV-yonhapnewstv-0',
195 'start_time': 1596406380000,
198 'url': 'https://tv.naver.com/l/54887',
199 'only_matching': True,
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')
207 info = self._extract_video_info(video_id, secure_url)
209 'description': self._og_search_description(page)
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')
219 if status == 'CLOSED':
220 raise ExtractorError('Stream is offline.', expected=True)
221 elif status != 'OPENED':
222 raise ExtractorError('Unknown status %s' % status)
224 title = meta.get('title')
225 stream_list = video_data.get('streams')
227 if stream_list is None:
228 raise ExtractorError('Could not get stream data.', expected=True)
231 for quality in stream_list:
232 if not quality.get('url'):
235 prop = quality.get('property')
236 if prop.get('abr'): # This abr doesn't mean Average audio bitrate.
239 formats.extend(self._extract_m3u8_formats(
240 quality.get('url'), video_id, 'mp4',
241 m3u8_id=quality.get('qualityId'), live=True
243 self._sort_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')],
258 class NaverNowIE(NaverBaseIE):
260 _VALID_URL = r'https?://now\.naver\.com/show/(?P<id>[0-9]+)'
262 _API_URL = 'https://apis.naver.com/now_web/nowcms-api-xhmac/cms/v1'
264 'url': 'https://now.naver.com/show/4759?shareReplayId=5901#replay=',
265 'md5': 'e05854162c21c221481de16b2944a0bc',
268 'title': '아이키X노제\r\n💖꽁냥꽁냥💖(1)',
270 'thumbnail': r're:^https?://.*\.jpg',
271 'timestamp': 1650369600,
272 'upload_date': '20220419',
273 'uploader_id': 'now',
280 'url': 'https://now.naver.com/show/4759?shareHightlight=1078#highlight=',
281 'md5': '9f6118e398aa0f22b2152f554ea7851b',
284 'title': '아이키: 나 리정한테 흔들렸어,,, 질투 폭발하는 노제 여보😾 [아이키의 떰즈업]ㅣ네이버 NOW.',
286 'thumbnail': r're:^https?://.*\.jpg',
287 'upload_date': '20220504',
288 'timestamp': 1651648042,
289 'uploader_id': 'now',
296 'url': 'https://now.naver.com/show/4759',
301 'playlist_mincount': 48
303 'url': 'https://now.naver.com/show/4759?shareReplayId=5901#replay',
308 'playlist_mincount': 48,
310 'url': 'https://now.naver.com/show/4759?shareHightlight=1078#highlight=',
315 'playlist_mincount': 48,
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']
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))
328 def _extract_show_replays(self, show_id):
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'])
339 if try_call(lambda: show_vod_info['count'] <= self._PAGE_SIZE * (page + 1)):
343 def _extract_show_highlights(self, show_id, highlight_id=None):
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}')
351 for highlight in highlights_videos.get('results') or []:
352 if highlight_id and highlight.get('id') != int(highlight_id):
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']))
361 if try_call(lambda: highlights_videos['count'] <= self._PAGE_SIZE * (page + 1)):
365 def _extract_highlight(self, show_id, highlight_id):
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}')
371 def _real_extract(self, url):
372 show_id = self._match_id(url)
373 qs = parse_qs(urlparse(url).query)
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])
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}')
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'))