]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/naver.py
[spotify] Detect iframe embeds (#3430)
[yt-dlp.git] / yt_dlp / extractor / naver.py
CommitLineData
c88debff
RA
1import re
2
6b95b065 3from .common import InfoExtractor
1cc79574 4from ..utils import (
c88debff
RA
5 clean_html,
6 dict_get,
6b95b065 7 ExtractorError,
b02b960c 8 int_or_none,
83817163 9 parse_duration,
c88debff 10 try_get,
b02b960c 11 update_url_query,
6b95b065
JMF
12)
13
14
c88debff
RA
15class NaverBaseIE(InfoExtractor):
16 _CAPTION_EXT_RE = r'\.(?:ttml|vtt)'
190f6c93 17
c88debff 18 def _extract_video_info(self, video_id, vid, key):
f65dc41b 19 video_data = self._download_json(
190f6c93 20 'http://play.rmcnmv.naver.com/vod/play/v2.0/' + vid,
f65dc41b 21 video_id, query={
c88debff 22 'key': key,
f65dc41b 23 })
b02b960c
RA
24 meta = video_data['meta']
25 title = meta['subject']
6b95b065 26 formats = []
c88debff 27 get_list = lambda x: try_get(video_data, lambda y: y[x + 's']['list'], list) or []
b02b960c
RA
28
29 def extract_formats(streams, stream_type, query={}):
30 for stream in streams:
31 stream_url = stream.get('source')
32 if not stream_url:
33 continue
34 stream_url = update_url_query(stream_url, query)
35 encoding_option = stream.get('encodingOption', {})
36 bitrate = stream.get('bitrate', {})
37 formats.append({
c88debff 38 'format_id': '%s_%s' % (stream.get('type') or stream_type, dict_get(encoding_option, ('name', 'id'))),
b02b960c 39 'url': stream_url,
652fb0d4 40 'ext': 'mp4',
b02b960c
RA
41 'width': int_or_none(encoding_option.get('width')),
42 'height': int_or_none(encoding_option.get('height')),
43 'vbr': int_or_none(bitrate.get('video')),
44 'abr': int_or_none(bitrate.get('audio')),
45 'filesize': int_or_none(stream.get('size')),
46 'protocol': 'm3u8_native' if stream_type == 'HLS' else None,
087ca2cb 47 })
b02b960c 48
c88debff 49 extract_formats(get_list('video'), 'H264')
b02b960c
RA
50 for stream_set in video_data.get('streams', []):
51 query = {}
52 for param in stream_set.get('keys', []):
53 query[param['name']] = param['value']
54 stream_type = stream_set.get('type')
55 videos = stream_set.get('videos')
56 if videos:
57 extract_formats(videos, stream_type, query)
58 elif stream_type == 'HLS':
59 stream_url = stream_set.get('source')
60 if not stream_url:
61 continue
62 formats.extend(self._extract_m3u8_formats(
63 update_url_query(stream_url, query), video_id,
64 'mp4', 'm3u8_native', m3u8_id=stream_type, fatal=False))
087ca2cb 65 self._sort_formats(formats)
6b95b065 66
c88debff
RA
67 replace_ext = lambda x, y: re.sub(self._CAPTION_EXT_RE, '.' + y, x)
68
69 def get_subs(caption_url):
70 if re.search(self._CAPTION_EXT_RE, caption_url):
71 return [{
72 'url': replace_ext(caption_url, 'ttml'),
73 }, {
74 'url': replace_ext(caption_url, 'vtt'),
75 }]
76 else:
77 return [{'url': caption_url}]
78
79 automatic_captions = {}
b02b960c 80 subtitles = {}
c88debff 81 for caption in get_list('caption'):
b02b960c
RA
82 caption_url = caption.get('source')
83 if not caption_url:
84 continue
c88debff
RA
85 sub_dict = automatic_captions if caption.get('type') == 'auto' else subtitles
86 sub_dict.setdefault(dict_get(caption, ('locale', 'language')), []).extend(get_subs(caption_url))
b02b960c 87
c88debff 88 user = meta.get('user', {})
f65dc41b 89
fb7abb31 90 return {
6b95b065 91 'id': video_id,
b02b960c 92 'title': title,
6b95b065 93 'formats': formats,
b02b960c 94 'subtitles': subtitles,
c88debff
RA
95 'automatic_captions': automatic_captions,
96 'thumbnail': try_get(meta, lambda x: x['cover']['source']),
b02b960c 97 'view_count': int_or_none(meta.get('count')),
c88debff
RA
98 'uploader_id': user.get('id'),
99 'uploader': user.get('name'),
100 'uploader_url': user.get('url'),
6b95b065 101 }
c88debff
RA
102
103
104class NaverIE(NaverBaseIE):
105 _VALID_URL = r'https?://(?:m\.)?tv(?:cast)?\.naver\.com/(?:v|embed)/(?P<id>\d+)'
106 _GEO_BYPASS = False
107 _TESTS = [{
108 'url': 'http://tv.naver.com/v/81652',
109 'info_dict': {
110 'id': '81652',
111 'ext': 'mp4',
112 'title': '[9월 모의고사 해설강의][수학_김상희] 수학 A형 16~20번',
113 'description': '메가스터디 수학 김상희 선생님이 9월 모의고사 수학A형 16번에서 20번까지 해설강의를 공개합니다.',
83817163 114 'timestamp': 1378200754,
c88debff
RA
115 'upload_date': '20130903',
116 'uploader': '메가스터디, 합격불변의 법칙',
117 'uploader_id': 'megastudy',
118 },
119 }, {
120 'url': 'http://tv.naver.com/v/395837',
121 'md5': '8a38e35354d26a17f73f4e90094febd3',
122 'info_dict': {
123 'id': '395837',
124 'ext': 'mp4',
125 'title': '9년이 지나도 아픈 기억, 전효성의 아버지',
126 'description': 'md5:eb6aca9d457b922e43860a2a2b1984d3',
83817163 127 'timestamp': 1432030253,
c88debff
RA
128 'upload_date': '20150519',
129 'uploader': '4가지쇼 시즌2',
130 'uploader_id': 'wrappinguser29',
131 },
132 'skip': 'Georestricted',
133 }, {
134 'url': 'http://tvcast.naver.com/v/81652',
135 'only_matching': True,
136 }]
137
138 def _real_extract(self, url):
139 video_id = self._match_id(url)
140 content = self._download_json(
83817163 141 'https://tv.naver.com/api/json/v/' + video_id,
c88debff 142 video_id, headers=self.geo_verification_headers())
83817163
RA
143 player_info_json = content.get('playerInfoJson') or {}
144 current_clip = player_info_json.get('currentClip') or {}
c88debff 145
83817163
RA
146 vid = current_clip.get('videoId')
147 in_key = current_clip.get('inKey')
c88debff
RA
148
149 if not vid or not in_key:
83817163 150 player_auth = try_get(player_info_json, lambda x: x['playerOption']['auth'])
c88debff
RA
151 if player_auth == 'notCountry':
152 self.raise_geo_restricted(countries=['KR'])
153 elif player_auth == 'notLogin':
154 self.raise_login_required()
155 raise ExtractorError('couldn\'t extract vid and key')
156 info = self._extract_video_info(video_id, vid, in_key)
83817163
RA
157 info.update({
158 'description': clean_html(current_clip.get('description')),
159 'timestamp': int_or_none(current_clip.get('firstExposureTime'), 1000),
160 'duration': parse_duration(current_clip.get('displayPlayTime')),
161 'like_count': int_or_none(current_clip.get('recommendPoint')),
162 'age_limit': 19 if current_clip.get('adult') else None,
163 })
c88debff 164 return info
217e5173
S
165
166
167class NaverLiveIE(InfoExtractor):
168 IE_NAME = 'Naver:live'
169 _VALID_URL = r'https?://(?:m\.)?tv(?:cast)?\.naver\.com/l/(?P<id>\d+)'
170 _GEO_BYPASS = False
171 _TESTS = [{
172 'url': 'https://tv.naver.com/l/52010',
173 'info_dict': {
174 'id': '52010',
652fb0d4 175 'ext': 'mp4',
217e5173
S
176 'title': '[LIVE] 뉴스특보 : "수도권 거리두기, 2주간 2단계로 조정"',
177 'description': 'md5:df7f0c237a5ed5e786ce5c91efbeaab3',
178 'channel_id': 'NTV-ytnnews24-0',
179 'start_time': 1597026780000,
180 },
181 }, {
182 'url': 'https://tv.naver.com/l/51549',
183 'info_dict': {
184 'id': '51549',
652fb0d4 185 'ext': 'mp4',
217e5173
S
186 'title': '연합뉴스TV - 코로나19 뉴스특보',
187 'description': 'md5:c655e82091bc21e413f549c0eaccc481',
188 'channel_id': 'NTV-yonhapnewstv-0',
189 'start_time': 1596406380000,
190 },
191 }, {
192 'url': 'https://tv.naver.com/l/54887',
193 'only_matching': True,
194 }]
195
196 def _real_extract(self, url):
197 video_id = self._match_id(url)
198 page = self._download_webpage(url, video_id, 'Downloading Page', 'Unable to download Page')
199 secure_url = self._search_regex(r'sApiF:\s+(?:"|\')([^"\']+)', page, 'secureurl')
200
201 info = self._extract_video_info(video_id, secure_url)
202 info.update({
203 'description': self._og_search_description(page)
204 })
205
206 return info
207
208 def _extract_video_info(self, video_id, url):
209 video_data = self._download_json(url, video_id, headers=self.geo_verification_headers())
210 meta = video_data.get('meta')
211 status = meta.get('status')
212
213 if status == 'CLOSED':
214 raise ExtractorError('Stream is offline.', expected=True)
215 elif status != 'OPENED':
216 raise ExtractorError('Unknown status %s' % status)
217
218 title = meta.get('title')
219 stream_list = video_data.get('streams')
220
221 if stream_list is None:
222 raise ExtractorError('Could not get stream data.', expected=True)
223
224 formats = []
225 for quality in stream_list:
226 if not quality.get('url'):
227 continue
228
229 prop = quality.get('property')
230 if prop.get('abr'): # This abr doesn't mean Average audio bitrate.
231 continue
232
233 formats.extend(self._extract_m3u8_formats(
652fb0d4 234 quality.get('url'), video_id, 'mp4',
217e5173
S
235 m3u8_id=quality.get('qualityId'), live=True
236 ))
237 self._sort_formats(formats)
238
239 return {
240 'id': video_id,
241 'title': title,
242 'formats': formats,
243 'channel_id': meta.get('channelId'),
244 'channel_url': meta.get('channelUrl'),
245 'thumbnail': meta.get('imgUrl'),
246 'start_time': meta.get('startTime'),
247 'categories': [meta.get('categoryId')],
248 'is_live': True
249 }