10 from .common
import InfoExtractor
26 class NaverBaseIE(InfoExtractor
):
27 _CAPTION_EXT_RE
= r
'\.(?:ttml|vtt)'
29 @staticmethod # NB: Used in WeverseIE
30 def process_subtitles(vod_data
, process_url
):
31 ret
= {'subtitles': {}, 'automatic_captions': {}}
32 for caption
in traverse_obj(vod_data
, ('captions', 'list', ...)):
33 caption_url
= caption
.get('source')
36 type_
= 'automatic_captions' if caption
.get('type') == 'auto' else 'subtitles'
37 lang
= caption
.get('locale') or join_nonempty('language', 'country', from_dict
=caption
) or 'und'
38 if caption
.get('type') == 'fan':
39 lang
+= '_fan{}'.format(next(i
for i
in itertools
.count(1) if f
'{lang}_fan{i}' not in ret
[type_
]))
40 ret
[type_
].setdefault(lang
, []).extend({
42 'name': join_nonempty('label', 'fanName', from_dict
=caption
, delim
=' - '),
43 } for sub_url
in process_url(caption_url
))
46 def _extract_video_info(self
, video_id
, vid
, key
):
47 video_data
= self
._download
_json
(
48 'http://play.rmcnmv.naver.com/vod/play/v2.0/' + vid
,
52 meta
= video_data
['meta']
53 title
= meta
['subject']
55 get_list
= lambda x
: try_get(video_data
, lambda y
: y
[x
+ 's']['list'], list) or []
57 def extract_formats(streams
, stream_type
, query
={}):
58 for stream
in streams
:
59 stream_url
= stream
.get('source')
62 stream_url
= update_url_query(stream_url
, query
)
63 encoding_option
= stream
.get('encodingOption', {})
64 bitrate
= stream
.get('bitrate', {})
66 'format_id': '{}_{}'.format(stream
.get('type') or stream_type
, dict_get(encoding_option
, ('name', 'id'))),
69 'width': int_or_none(encoding_option
.get('width')),
70 'height': int_or_none(encoding_option
.get('height')),
71 'vbr': int_or_none(bitrate
.get('video')),
72 'abr': int_or_none(bitrate
.get('audio')),
73 'filesize': int_or_none(stream
.get('size')),
74 'protocol': 'm3u8_native' if stream_type
== 'HLS' else None,
77 extract_formats(get_list('video'), 'H264')
78 for stream_set
in video_data
.get('streams', []):
80 for param
in stream_set
.get('keys', []):
81 query
[param
['name']] = param
['value']
82 stream_type
= stream_set
.get('type')
83 videos
= stream_set
.get('videos')
85 extract_formats(videos
, stream_type
, query
)
86 elif stream_type
== 'HLS':
87 stream_url
= stream_set
.get('source')
90 formats
.extend(self
._extract
_m
3u8_formats
(
91 update_url_query(stream_url
, query
), video_id
,
92 'mp4', 'm3u8_native', m3u8_id
=stream_type
, fatal
=False))
94 replace_ext
= lambda x
, y
: re
.sub(self
._CAPTION
_EXT
_RE
, '.' + y
, x
)
96 def get_subs(caption_url
):
97 if re
.search(self
._CAPTION
_EXT
_RE
, caption_url
):
99 replace_ext(caption_url
, 'ttml'),
100 replace_ext(caption_url
, 'vtt'),
104 user
= meta
.get('user', {})
110 'thumbnail': try_get(meta
, lambda x
: x
['cover']['source']),
111 'view_count': int_or_none(meta
.get('count')),
112 'uploader_id': user
.get('id'),
113 'uploader': user
.get('name'),
114 'uploader_url': user
.get('url'),
115 **self
.process_subtitles(video_data
, get_subs
),
118 def _call_api(self
, path
, video_id
):
119 api_endpoint
= f
'https://apis.naver.com/now_web2/now_web_api/v1{path}'
120 key
= b
'nbxvs5nwNG9QKEWK0ADjYA4JZoujF4gHcIwvoCxFTPAeamq5eemvt5IWAYXxrbYM'
121 msgpad
= int(time
.time() * 1000)
122 md
= base64
.b64encode(hmac
.HMAC(
123 key
, f
'{api_endpoint[:255]}{msgpad}'.encode(), digestmod
=hashlib
.sha1
).digest()).decode()
125 return self
._download
_json
(api_endpoint
, video_id
=video_id
, headers
=self
.geo_verification_headers(), query
={
131 class NaverIE(NaverBaseIE
):
132 _VALID_URL
= r
'https?://(?:m\.)?tv(?:cast)?\.naver\.com/(?:v|embed)/(?P<id>\d+)'
135 'url': 'http://tv.naver.com/v/81652',
139 'title': '[9월 모의고사 해설강의][수학_김상희] 수학 A형 16~20번',
140 'description': '메가스터디 수학 김상희 선생님이 9월 모의고사 수학A형 16번에서 20번까지 해설강의를 공개합니다.',
141 'timestamp': 1378200754,
142 'upload_date': '20130903',
143 'uploader': '메가스터디, 합격불변의 법칙',
144 'uploader_id': 'megastudy',
145 'uploader_url': 'https://tv.naver.com/megastudy',
148 'comment_count': int,
150 'thumbnail': r
're:^https?://.*\.jpg',
153 'url': 'http://tv.naver.com/v/395837',
154 'md5': '7791205fa89dbed2f5e3eb16d287ff05',
158 'title': '9년이 지나도 아픈 기억, 전효성의 아버지',
159 'description': 'md5:c76be23e21403a6473d8119678cdb5cb',
160 'timestamp': 1432030253,
161 'upload_date': '20150519',
163 'uploader_id': '4show',
164 'uploader_url': 'https://tv.naver.com/4show',
167 'comment_count': int,
169 'thumbnail': r
're:^https?://.*\.jpg',
172 'url': 'http://tvcast.naver.com/v/81652',
173 'only_matching': True,
176 def _real_extract(self
, url
):
177 video_id
= self
._match
_id
(url
)
178 data
= self
._call
_api
(f
'/clips/{video_id}/play-info', video_id
)
180 vid
= traverse_obj(data
, ('clip', 'videoId', {str}
))
181 in_key
= traverse_obj(data
, ('play', 'inKey', {str}
))
183 if not vid
or not in_key
:
184 raise ExtractorError('Unable to extract video info')
186 info
= self
._extract
_video
_info
(video_id
, vid
, in_key
)
187 info
.update(traverse_obj(data
, ('clip', {
189 'description': 'description',
190 'timestamp': ('firstExposureDatetime', {parse_iso8601}
),
191 'duration': ('playTime', {int_or_none}
),
192 'like_count': ('likeItCount', {int_or_none}
),
193 'view_count': ('playCount', {int_or_none}
),
194 'comment_count': ('commentCount', {int_or_none}
),
195 'thumbnail': ('thumbnailImageUrl', {url_or_none}
),
196 'uploader': 'channelName',
197 'uploader_id': 'channelId',
198 'uploader_url': ('channelUrl', {url_or_none}
),
199 'age_limit': ('adultVideo', {lambda x
: 19 if x
else None}),
204 class NaverLiveIE(NaverBaseIE
):
205 IE_NAME
= 'Naver:live'
206 _VALID_URL
= r
'https?://(?:m\.)?tv(?:cast)?\.naver\.com/l/(?P<id>\d+)'
209 'url': 'https://tv.naver.com/l/127062',
213 'live_status': 'is_live',
214 'channel': '뉴스는 YTN',
215 'channel_id': 'ytnnews24',
216 'title': 're:^대한민국 24시간 뉴스 채널 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
217 'description': 'md5:f938b5956711beab6f882314ffadf4d5',
218 'start_time': 1677752280,
219 'thumbnail': r
're:^https?://.*\.(jpg|jpeg|png)',
223 'url': 'https://tv.naver.com/l/140535',
227 'live_status': 'is_live',
229 'channel_id': 'kbsnews',
230 'start_time': 1696867320,
231 'title': 're:^언제 어디서나! KBS 뉴스 24 [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
232 'description': 'md5:6ad419c0bf2f332829bda3f79c295284',
233 'thumbnail': r
're:^https?://.*\.(jpg|jpeg|png)',
237 'url': 'https://tv.naver.com/l/54887',
238 'only_matching': True,
241 def _real_extract(self
, url
):
242 video_id
= self
._match
_id
(url
)
243 data
= self
._call
_api
(f
'/live-end/normal/{video_id}/play-info?renewLastPlayDate=true', video_id
)
245 status
= traverse_obj(data
, ('live', 'liveStatus'))
246 if status
== 'CLOSED':
247 raise ExtractorError('Stream is offline.', expected
=True)
248 elif status
!= 'OPENED':
249 raise ExtractorError(f
'Unknown status {status!r}')
253 'formats': self
._extract
_m
3u8_formats
(
254 traverse_obj(data
, ('playbackBody', {json
.loads
}, 'media', 0, 'path')), video_id
, live
=True),
255 **traverse_obj(data
, ('live', {
257 'channel': 'channelName',
258 'channel_id': 'channelId',
259 'description': 'description',
260 'like_count': (('likeCount', 'likeItCount'), {int_or_none}
),
261 'thumbnail': ('thumbnailImageUrl', {url_or_none}
),
262 'start_time': (('startTime', 'startDateTime', 'startYmdt'), {parse_iso8601}
),
268 class NaverNowIE(NaverBaseIE
):
270 _VALID_URL
= r
'https?://now\.naver\.com/s/now\.(?P<id>\w+)'
271 _API_URL
= 'https://apis.naver.com/now_web/oldnow_web/v4'
273 'url': 'https://now.naver.com/s/now.4759?shareReplayId=26331132#replay=',
274 'md5': 'e05854162c21c221481de16b2944a0bc',
276 'id': '4759-26331132',
277 'title': '아이키X노제\r\n💖꽁냥꽁냥💖(1)',
279 'thumbnail': r
're:^https?://.*\.jpg',
280 'timestamp': 1650369600,
281 'upload_date': '20220419',
282 'uploader_id': 'now',
284 'uploader_url': 'https://now.naver.com/show/4759',
285 'uploader': '아이키의 떰즈업',
291 'url': 'https://now.naver.com/s/now.4759?shareHightlight=26601461#highlight=',
292 'md5': '9f6118e398aa0f22b2152f554ea7851b',
294 'id': '4759-26601461',
295 'title': '아이키: 나 리정한테 흔들렸어,,, 질투 폭발하는 노제 여보😾 [아이키의 떰즈업]ㅣ네이버 NOW.',
297 'thumbnail': r
're:^https?://.*\.jpg',
298 'upload_date': '20220504',
299 'timestamp': 1651648311,
300 'uploader_id': 'now',
302 'uploader_url': 'https://now.naver.com/show/4759',
303 'uploader': '아이키의 떰즈업',
309 'url': 'https://now.naver.com/s/now.4759',
314 'playlist_mincount': 101,
316 'url': 'https://now.naver.com/s/now.4759?shareReplayId=26331132#replay',
321 'playlist_mincount': 101,
323 'url': 'https://now.naver.com/s/now.4759?shareHightlight=26601461#highlight=',
328 'playlist_mincount': 101,
330 'url': 'https://now.naver.com/s/now.kihyunplay?shareReplayId=30573291#replay',
331 'only_matching': True,
334 def _extract_replay(self
, show_id
, replay_id
):
335 vod_info
= self
._download
_json
(f
'{self._API_URL}/shows/now.{show_id}/vod/{replay_id}', replay_id
)
336 in_key
= self
._download
_json
(f
'{self._API_URL}/shows/now.{show_id}/vod/{replay_id}/inkey', replay_id
)['inKey']
338 'id': f
'{show_id}-{replay_id}',
339 'title': traverse_obj(vod_info
, ('episode', 'title')),
340 'timestamp': unified_timestamp(traverse_obj(vod_info
, ('episode', 'start_time'))),
341 'thumbnail': vod_info
.get('thumbnail_image_url'),
342 }, self
._extract
_video
_info
(replay_id
, vod_info
['video_id'], in_key
))
344 def _extract_show_replays(self
, show_id
):
348 show_vod_info
= self
._download
_json
(
349 f
'{self._API_URL}/vod-shows/now.{show_id}', show_id
,
350 query
={'page': page
, 'page_size': page_size
},
351 note
=f
'Downloading JSON vod list for show {show_id} - page {page}',
352 )['response']['result']
353 for v
in show_vod_info
.get('vod_list') or []:
354 yield self
._extract
_replay
(show_id
, v
['id'])
356 if len(show_vod_info
.get('vod_list') or []) < page_size
:
360 def _extract_show_highlights(self
, show_id
, highlight_id
=None):
364 highlights_videos
= self
._download
_json
(
365 f
'{self._API_URL}/shows/now.{show_id}/highlights/videos/', show_id
,
366 query
={'page': page
, 'page_size': page_size
},
367 note
=f
'Downloading JSON highlights for show {show_id} - page {page}')
369 for highlight
in highlights_videos
.get('results') or []:
370 if highlight_id
and highlight
.get('clip_no') != int(highlight_id
):
373 'id': f
'{show_id}-{highlight["clip_no"]}',
374 'title': highlight
.get('title'),
375 'timestamp': unified_timestamp(highlight
.get('regdate')),
376 'thumbnail': highlight
.get('thumbnail_url'),
377 }, self
._extract
_video
_info
(highlight
['clip_no'], highlight
['video_id'], highlight
['video_inkey']))
379 if len(highlights_videos
.get('results') or []) < page_size
:
383 def _extract_highlight(self
, show_id
, highlight_id
):
385 return next(self
._extract
_show
_highlights
(show_id
, highlight_id
))
386 except StopIteration:
387 raise ExtractorError(f
'Unable to find highlight {highlight_id} for show {show_id}')
389 def _real_extract(self
, url
):
390 show_id
= self
._match
_id
(url
)
391 qs
= urllib
.parse
.parse_qs(urllib
.parse
.urlparse(url
).query
)
393 if not self
._yes
_playlist
(show_id
, qs
.get('shareHightlight')):
394 return self
._extract
_highlight
(show_id
, qs
['shareHightlight'][0])
395 elif not self
._yes
_playlist
(show_id
, qs
.get('shareReplayId')):
396 return self
._extract
_replay
(show_id
, qs
['shareReplayId'][0])
398 show_info
= self
._download
_json
(
399 f
'{self._API_URL}/shows/now.{show_id}/', show_id
,
400 note
=f
'Downloading JSON vod list for show {show_id}')
402 return self
.playlist_result(
403 itertools
.chain(self
._extract
_show
_replays
(show_id
), self
._extract
_show
_highlights
(show_id
)),
404 show_id
, show_info
.get('title'))