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