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