]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/vlive.py
[panopto] Add extractors (#2908)
[yt-dlp.git] / yt_dlp / extractor / vlive.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import itertools
5 import json
6
7 from .naver import NaverBaseIE
8 from ..compat import (
9 compat_HTTPError,
10 compat_str,
11 )
12 from ..utils import (
13 ExtractorError,
14 int_or_none,
15 LazyList,
16 merge_dicts,
17 str_or_none,
18 strip_or_none,
19 try_get,
20 urlencode_postdata,
21 url_or_none,
22 )
23
24
25 class VLiveBaseIE(NaverBaseIE):
26 _NETRC_MACHINE = 'vlive'
27 _logged_in = False
28
29 def _real_initialize(self):
30 if not self._logged_in:
31 VLiveBaseIE._logged_in = self._login()
32
33 def _login(self):
34 email, password = self._get_login_info()
35 if email is None:
36 return False
37
38 LOGIN_URL = 'https://www.vlive.tv/auth/email/login'
39 self._request_webpage(
40 LOGIN_URL, None, note='Downloading login cookies')
41
42 self._download_webpage(
43 LOGIN_URL, None, note='Logging in',
44 data=urlencode_postdata({'email': email, 'pwd': password}),
45 headers={
46 'Referer': LOGIN_URL,
47 'Content-Type': 'application/x-www-form-urlencoded'
48 })
49
50 login_info = self._download_json(
51 'https://www.vlive.tv/auth/loginInfo', None,
52 note='Checking login status',
53 headers={'Referer': 'https://www.vlive.tv/home'})
54
55 if not try_get(login_info, lambda x: x['message']['login'], bool):
56 raise ExtractorError('Unable to log in', expected=True)
57 return True
58
59 def _call_api(self, path_template, video_id, fields=None, query_add={}, note=None):
60 if note is None:
61 note = 'Downloading %s JSON metadata' % path_template.split('/')[-1].split('-')[0]
62 query = {'appId': '8c6cc7b45d2568fb668be6e05b6e5a3b', 'gcc': 'KR', 'platformType': 'PC'}
63 if fields:
64 query['fields'] = fields
65 if query_add:
66 query.update(query_add)
67 try:
68 return self._download_json(
69 'https://www.vlive.tv/globalv-web/vam-web/' + path_template % video_id, video_id,
70 note, headers={'Referer': 'https://www.vlive.tv/'}, query=query)
71 except ExtractorError as e:
72 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
73 self.raise_login_required(json.loads(e.cause.read().decode('utf-8'))['message'])
74 raise
75
76
77 class VLiveIE(VLiveBaseIE):
78 IE_NAME = 'vlive'
79 _VALID_URL = r'https?://(?:(?:www|m)\.)?vlive\.tv/(?:video|embed)/(?P<id>[0-9]+)'
80 _TESTS = [{
81 'url': 'http://www.vlive.tv/video/1326',
82 'md5': 'cc7314812855ce56de70a06a27314983',
83 'info_dict': {
84 'id': '1326',
85 'ext': 'mp4',
86 'title': "Girl's Day's Broadcast",
87 'creator': "Girl's Day",
88 'view_count': int,
89 'uploader_id': 'muploader_a',
90 'upload_date': '20150817',
91 'thumbnail': r're:^https?://.*\.(?:jpg|png)$',
92 'timestamp': 1439816449,
93 },
94 'params': {
95 'skip_download': True,
96 },
97 }, {
98 'url': 'http://www.vlive.tv/video/16937',
99 'info_dict': {
100 'id': '16937',
101 'ext': 'mp4',
102 'title': '첸백시 걍방',
103 'creator': 'EXO',
104 'view_count': int,
105 'subtitles': 'mincount:12',
106 'uploader_id': 'muploader_j',
107 'upload_date': '20161112',
108 'thumbnail': r're:^https?://.*\.(?:jpg|png)$',
109 'timestamp': 1478923074,
110 },
111 'params': {
112 'skip_download': True,
113 },
114 }, {
115 'url': 'https://www.vlive.tv/video/129100',
116 'md5': 'ca2569453b79d66e5b919e5d308bff6b',
117 'info_dict': {
118 'id': '129100',
119 'ext': 'mp4',
120 'title': '[V LIVE] [BTS+] Run BTS! 2019 - EP.71 :: Behind the scene',
121 'creator': 'BTS+',
122 'view_count': int,
123 'subtitles': 'mincount:10',
124 },
125 'skip': 'This video is only available for CH+ subscribers',
126 }, {
127 'url': 'https://www.vlive.tv/embed/1326',
128 'only_matching': True,
129 }, {
130 # works only with gcc=KR
131 'url': 'https://www.vlive.tv/video/225019',
132 'only_matching': True,
133 }, {
134 'url': 'https://www.vlive.tv/video/223906',
135 'info_dict': {
136 'id': '58',
137 'title': 'RUN BTS!'
138 },
139 'playlist_mincount': 120
140 }]
141
142 def _real_extract(self, url):
143 video_id = self._match_id(url)
144
145 post = self._call_api(
146 'post/v1.0/officialVideoPost-%s', video_id,
147 'author{nickname},channel{channelCode,channelName},officialVideo{commentCount,exposeStatus,likeCount,playCount,playTime,status,title,type,vodId},playlist{playlistSeq,totalCount,name}')
148
149 playlist_id = str_or_none(try_get(post, lambda x: x['playlist']['playlistSeq']))
150 if not self._yes_playlist(playlist_id, video_id):
151 video = post['officialVideo']
152 return self._get_vlive_info(post, video, video_id)
153
154 playlist_name = str_or_none(try_get(post, lambda x: x['playlist']['name']))
155 playlist_count = str_or_none(try_get(post, lambda x: x['playlist']['totalCount']))
156
157 playlist = self._call_api(
158 'playlist/v1.0/playlist-%s/posts', playlist_id, 'data', {'limit': playlist_count})
159
160 entries = []
161 for video_data in playlist['data']:
162 video = video_data.get('officialVideo')
163 video_id = str_or_none(video.get('videoSeq'))
164 entries.append(self._get_vlive_info(video_data, video, video_id))
165
166 return self.playlist_result(entries, playlist_id, playlist_name)
167
168 def _get_vlive_info(self, post, video, video_id):
169 def get_common_fields():
170 channel = post.get('channel') or {}
171 return {
172 'title': video.get('title'),
173 'creator': post.get('author', {}).get('nickname'),
174 'channel': channel.get('channelName'),
175 'channel_id': channel.get('channelCode'),
176 'duration': int_or_none(video.get('playTime')),
177 'view_count': int_or_none(video.get('playCount')),
178 'like_count': int_or_none(video.get('likeCount')),
179 'comment_count': int_or_none(video.get('commentCount')),
180 'timestamp': int_or_none(video.get('createdAt'), scale=1000),
181 'thumbnail': video.get('thumb'),
182 }
183
184 video_type = video.get('type')
185 if video_type == 'VOD':
186 inkey = self._call_api('video/v1.0/vod/%s/inkey', video_id)['inkey']
187 vod_id = video['vodId']
188 info_dict = merge_dicts(
189 get_common_fields(),
190 self._extract_video_info(video_id, vod_id, inkey))
191 thumbnail = video.get('thumb')
192 if thumbnail:
193 if not info_dict.get('thumbnails') and info_dict.get('thumbnail'):
194 info_dict['thumbnails'] = [{'url': info_dict.pop('thumbnail')}]
195 info_dict.setdefault('thumbnails', []).append({'url': thumbnail, 'preference': 1})
196 return info_dict
197 elif video_type == 'LIVE':
198 status = video.get('status')
199 if status == 'ON_AIR':
200 stream_url = self._call_api(
201 'old/v3/live/%s/playInfo',
202 video_id)['result']['adaptiveStreamUrl']
203 formats = self._extract_m3u8_formats(stream_url, video_id, 'mp4')
204 self._sort_formats(formats)
205 info = get_common_fields()
206 info.update({
207 'title': video['title'],
208 'id': video_id,
209 'formats': formats,
210 'is_live': True,
211 })
212 return info
213 elif status == 'ENDED':
214 raise ExtractorError(
215 'Uploading for replay. Please wait...', expected=True)
216 elif status == 'RESERVED':
217 raise ExtractorError('Coming soon!', expected=True)
218 elif video.get('exposeStatus') == 'CANCEL':
219 raise ExtractorError(
220 'We are sorry, but the live broadcast has been canceled.',
221 expected=True)
222 else:
223 raise ExtractorError('Unknown status ' + status)
224
225
226 class VLivePostIE(VLiveBaseIE):
227 IE_NAME = 'vlive:post'
228 _VALID_URL = r'https?://(?:(?:www|m)\.)?vlive\.tv/post/(?P<id>\d-\d+)'
229 _TESTS = [{
230 # uploadType = SOS
231 'url': 'https://www.vlive.tv/post/1-20088044',
232 'info_dict': {
233 'id': '1-20088044',
234 'title': 'Hola estrellitas la tierra les dice hola (si era así no?) Ha...',
235 'description': 'md5:fab8a1e50e6e51608907f46c7fa4b407',
236 },
237 'playlist_count': 3,
238 }, {
239 # uploadType = V
240 'url': 'https://www.vlive.tv/post/1-20087926',
241 'info_dict': {
242 'id': '1-20087926',
243 'title': 'James Corden: And so, the baby becamos the Papa💜😭💪😭',
244 },
245 'playlist_count': 1,
246 }]
247 _FVIDEO_TMPL = 'fvideo/v1.0/fvideo-%%s/%s'
248
249 def _real_extract(self, url):
250 post_id = self._match_id(url)
251
252 post = self._call_api(
253 'post/v1.0/post-%s', post_id,
254 'attachments{video},officialVideo{videoSeq},plainBody,title')
255
256 video_seq = str_or_none(try_get(
257 post, lambda x: x['officialVideo']['videoSeq']))
258 if video_seq:
259 return self.url_result(
260 'http://www.vlive.tv/video/' + video_seq,
261 VLiveIE.ie_key(), video_seq)
262
263 title = post['title']
264 entries = []
265 for idx, video in enumerate(post['attachments']['video'].values()):
266 video_id = video.get('videoId')
267 if not video_id:
268 continue
269 upload_type = video.get('uploadType')
270 upload_info = video.get('uploadInfo') or {}
271 entry = None
272 if upload_type == 'SOS':
273 download = self._call_api(
274 self._FVIDEO_TMPL % 'sosPlayInfo', video_id)['videoUrl']['download']
275 formats = []
276 for f_id, f_url in download.items():
277 formats.append({
278 'format_id': f_id,
279 'url': f_url,
280 'height': int_or_none(f_id[:-1]),
281 })
282 self._sort_formats(formats)
283 entry = {
284 'formats': formats,
285 'id': video_id,
286 'thumbnail': upload_info.get('imageUrl'),
287 }
288 elif upload_type == 'V':
289 vod_id = upload_info.get('videoId')
290 if not vod_id:
291 continue
292 inkey = self._call_api(self._FVIDEO_TMPL % 'inKey', video_id)['inKey']
293 entry = self._extract_video_info(video_id, vod_id, inkey)
294 if entry:
295 entry['title'] = '%s_part%s' % (title, idx)
296 entries.append(entry)
297 return self.playlist_result(
298 entries, post_id, title, strip_or_none(post.get('plainBody')))
299
300
301 class VLiveChannelIE(VLiveBaseIE):
302 IE_NAME = 'vlive:channel'
303 _VALID_URL = r'https?://(?:channels\.vlive\.tv|(?:(?:www|m)\.)?vlive\.tv/channel)/(?P<channel_id>[0-9A-Z]+)(?:/board/(?P<posts_id>\d+))?'
304 _TESTS = [{
305 'url': 'http://channels.vlive.tv/FCD4B',
306 'info_dict': {
307 'id': 'FCD4B',
308 'title': 'MAMAMOO',
309 },
310 'playlist_mincount': 110
311 }, {
312 'url': 'https://www.vlive.tv/channel/FCD4B',
313 'only_matching': True,
314 }, {
315 'url': 'https://www.vlive.tv/channel/FCD4B/board/3546',
316 'info_dict': {
317 'id': 'FCD4B-3546',
318 'title': 'MAMAMOO - Star Board',
319 },
320 'playlist_mincount': 880
321 }]
322
323 def _entries(self, posts_id, board_name):
324 if board_name:
325 posts_path = 'post/v1.0/board-%s/posts'
326 query_add = {'limit': 100, 'sortType': 'LATEST'}
327 else:
328 posts_path = 'post/v1.0/channel-%s/starPosts'
329 query_add = {'limit': 100}
330
331 for page_num in itertools.count(1):
332 video_list = self._call_api(
333 posts_path, posts_id, 'channel{channelName},contentType,postId,title,url', query_add,
334 note=f'Downloading playlist page {page_num}')
335
336 for video in try_get(video_list, lambda x: x['data'], list) or []:
337 video_id = str(video.get('postId'))
338 video_title = str_or_none(video.get('title'))
339 video_url = url_or_none(video.get('url'))
340 if not all((video_id, video_title, video_url)) or video.get('contentType') != 'VIDEO':
341 continue
342 channel_name = try_get(video, lambda x: x['channel']['channelName'], compat_str)
343 yield self.url_result(video_url, VLivePostIE.ie_key(), video_id, video_title, channel=channel_name)
344
345 after = try_get(video_list, lambda x: x['paging']['nextParams']['after'], compat_str)
346 if not after:
347 break
348 query_add['after'] = after
349
350 def _real_extract(self, url):
351 channel_id, posts_id = self._match_valid_url(url).groups()
352
353 board_name = None
354 if posts_id:
355 board = self._call_api(
356 'board/v1.0/board-%s', posts_id, 'title,boardType')
357 board_name = board.get('title') or 'Unknown'
358 if board.get('boardType') not in ('STAR', 'VLIVE_PLUS'):
359 raise ExtractorError(f'Board {board_name!r} is not supported', expected=True)
360
361 entries = LazyList(self._entries(posts_id or channel_id, board_name))
362 channel_name = entries[0]['channel']
363
364 return self.playlist_result(
365 entries,
366 f'{channel_id}-{posts_id}' if posts_id else channel_id,
367 f'{channel_name} - {board_name}' if channel_name and board_name else channel_name)