[ie/wistia] Support password-protected videos (#11100)
[yt-dlp3.git] / yt_dlp / extractor / afreecatv.py
blob815d20537fa42616caae8172182cb41b6fdf88d9
1 import functools
3 from .common import InfoExtractor
4 from ..networking import Request
5 from ..utils import (
6 ExtractorError,
7 OnDemandPagedList,
8 UserNotLive,
9 determine_ext,
10 filter_dict,
11 int_or_none,
12 orderedSet,
13 unified_timestamp,
14 url_or_none,
15 urlencode_postdata,
16 urljoin,
18 from ..utils.traversal import traverse_obj
21 class AfreecaTVBaseIE(InfoExtractor):
22 _NETRC_MACHINE = 'afreecatv'
24 def _perform_login(self, username, password):
25 login_form = {
26 'szWork': 'login',
27 'szType': 'json',
28 'szUid': username,
29 'szPassword': password,
30 'isSaveId': 'false',
31 'szScriptVar': 'oLoginRet',
32 'szAction': '',
35 response = self._download_json(
36 'https://login.afreecatv.com/app/LoginAction.php', None,
37 'Logging in', data=urlencode_postdata(login_form))
39 _ERRORS = {
40 -4: 'Your account has been suspended due to a violation of our terms and policies.',
41 -5: 'https://member.afreecatv.com/app/user_delete_progress.php',
42 -6: 'https://login.afreecatv.com/membership/changeMember.php',
43 -8: "Hello! AfreecaTV here.\nThe username you have entered belongs to \n an account that requires a legal guardian's consent. \nIf you wish to use our services without restriction, \nplease make sure to go through the necessary verification process.",
44 -9: 'https://member.afreecatv.com/app/pop_login_block.php',
45 -11: 'https://login.afreecatv.com/afreeca/second_login.php',
46 -12: 'https://member.afreecatv.com/app/user_security.php',
47 0: 'The username does not exist or you have entered the wrong password.',
48 -1: 'The username does not exist or you have entered the wrong password.',
49 -3: 'You have entered your username/password incorrectly.',
50 -7: 'You cannot use your Global AfreecaTV account to access Korean AfreecaTV.',
51 -10: 'Sorry for the inconvenience. \nYour account has been blocked due to an unauthorized access. \nPlease contact our Help Center for assistance.',
52 -32008: 'You have failed to log in. Please contact our Help Center.',
55 result = int_or_none(response.get('RESULT'))
56 if result != 1:
57 error = _ERRORS.get(result, 'You have failed to log in.')
58 raise ExtractorError(
59 f'Unable to login: {self.IE_NAME} said: {error}',
60 expected=True)
62 def _call_api(self, endpoint, display_id, data=None, headers=None, query=None):
63 return self._download_json(Request(
64 f'https://api.m.afreecatv.com/{endpoint}',
65 data=data, headers=headers, query=query,
66 extensions={'legacy_ssl': True}), display_id,
67 'Downloading API JSON', 'Unable to download API JSON')
70 class AfreecaTVIE(AfreecaTVBaseIE):
71 IE_NAME = 'afreecatv'
72 IE_DESC = 'afreecatv.com'
73 _VALID_URL = r'''(?x)
74 https?://
75 (?:
76 (?:(?:live|afbbs|www)\.)?afreeca(?:tv)?\.com(?::\d+)?
77 (?:
78 /app/(?:index|read_ucc_bbs)\.cgi|
79 /player/[Pp]layer\.(?:swf|html)
80 )\?.*?\bnTitleNo=|
81 vod\.afreecatv\.com/(PLAYER/STATION|player)/
83 (?P<id>\d+)/?(?:$|[?#&])
84 '''
85 _TESTS = [{
86 'url': 'http://live.afreecatv.com:8079/app/index.cgi?szType=read_ucc_bbs&szBjId=dailyapril&nStationNo=16711924&nBbsNo=18605867&nTitleNo=36164052&szSkin=',
87 'md5': 'f72c89fe7ecc14c1b5ce506c4996046e',
88 'info_dict': {
89 'id': '36164052',
90 'ext': 'mp4',
91 'title': '데일리 에이프릴 요정들의 시상식!',
92 'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
93 'uploader': 'dailyapril',
94 'uploader_id': 'dailyapril',
95 'upload_date': '20160503',
97 'skip': 'Video is gone',
98 }, {
99 'url': 'http://afbbs.afreecatv.com:8080/app/read_ucc_bbs.cgi?nStationNo=16711924&nTitleNo=36153164&szBjId=dailyapril&nBbsNo=18605867',
100 'info_dict': {
101 'id': '36153164',
102 'title': "BJ유트루와 함께하는 '팅커벨 메이크업!'",
103 'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
104 'uploader': 'dailyapril',
105 'uploader_id': 'dailyapril',
107 'playlist_count': 2,
108 'playlist': [{
109 'md5': 'd8b7c174568da61d774ef0203159bf97',
110 'info_dict': {
111 'id': '36153164_1',
112 'ext': 'mp4',
113 'title': "BJ유트루와 함께하는 '팅커벨 메이크업!'",
114 'upload_date': '20160502',
116 }, {
117 'md5': '58f2ce7f6044e34439ab2d50612ab02b',
118 'info_dict': {
119 'id': '36153164_2',
120 'ext': 'mp4',
121 'title': "BJ유트루와 함께하는 '팅커벨 메이크업!'",
122 'upload_date': '20160502',
125 'skip': 'Video is gone',
126 }, {
127 # non standard key
128 'url': 'http://vod.afreecatv.com/PLAYER/STATION/20515605',
129 'info_dict': {
130 'id': '20170411_BE689A0E_190960999_1_2_h',
131 'ext': 'mp4',
132 'title': '혼자사는여자집',
133 'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
134 'uploader': '♥이슬이',
135 'uploader_id': 'dasl8121',
136 'upload_date': '20170411',
137 'timestamp': 1491929865,
138 'duration': 213,
140 'params': {
141 'skip_download': True,
143 }, {
144 # adult content
145 'url': 'https://vod.afreecatv.com/player/97267690',
146 'info_dict': {
147 'id': '20180327_27901457_202289533_1',
148 'ext': 'mp4',
149 'title': '[생]빨개요♥ (part 1)',
150 'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
151 'uploader': '[SA]서아',
152 'uploader_id': 'bjdyrksu',
153 'upload_date': '20180327',
154 'duration': 3601,
156 'params': {
157 'skip_download': True,
159 'skip': 'The VOD does not exist',
160 }, {
161 'url': 'http://www.afreecatv.com/player/Player.swf?szType=szBjId=djleegoon&nStationNo=11273158&nBbsNo=13161095&nTitleNo=36327652',
162 'only_matching': True,
163 }, {
164 'url': 'https://vod.afreecatv.com/player/96753363',
165 'info_dict': {
166 'id': '20230108_9FF5BEE1_244432674_1',
167 'ext': 'mp4',
168 'uploader_id': 'rlantnghks',
169 'uploader': '페이즈으',
170 'duration': 10840,
171 'thumbnail': r're:https?://videoimg\.afreecatv\.com/.+',
172 'upload_date': '20230108',
173 'timestamp': 1673218805,
174 'title': '젠지 페이즈',
176 'params': {
177 'skip_download': True,
179 }, {
180 # adult content
181 'url': 'https://vod.afreecatv.com/player/70395877',
182 'only_matching': True,
183 }, {
184 # subscribers only
185 'url': 'https://vod.afreecatv.com/player/104647403',
186 'only_matching': True,
187 }, {
188 # private
189 'url': 'https://vod.afreecatv.com/player/81669846',
190 'only_matching': True,
193 def _real_extract(self, url):
194 video_id = self._match_id(url)
195 data = self._call_api(
196 'station/video/a/view', video_id, headers={'Referer': url},
197 data=urlencode_postdata({
198 'nTitleNo': video_id,
199 'nApiLevel': 10,
200 }))['data']
202 error_code = traverse_obj(data, ('code', {int}))
203 if error_code == -6221:
204 raise ExtractorError('The VOD does not exist', expected=True)
205 elif error_code == -6205:
206 raise ExtractorError('This VOD is private', expected=True)
208 common_info = traverse_obj(data, {
209 'title': ('title', {str}),
210 'uploader': ('writer_nick', {str}),
211 'uploader_id': ('bj_id', {str}),
212 'duration': ('total_file_duration', {functools.partial(int_or_none, scale=1000)}),
213 'thumbnail': ('thumb', {url_or_none}),
216 entries = []
217 for file_num, file_element in enumerate(
218 traverse_obj(data, ('files', lambda _, v: url_or_none(v['file']))), start=1):
219 file_url = file_element['file']
220 if determine_ext(file_url) == 'm3u8':
221 formats = self._extract_m3u8_formats(
222 file_url, video_id, 'mp4', m3u8_id='hls',
223 note=f'Downloading part {file_num} m3u8 information')
224 else:
225 formats = [{
226 'url': file_url,
227 'format_id': 'http',
230 entries.append({
231 **common_info,
232 'id': file_element.get('file_info_key') or f'{video_id}_{file_num}',
233 'title': f'{common_info.get("title") or "Untitled"} (part {file_num})',
234 'formats': formats,
235 **traverse_obj(file_element, {
236 'duration': ('duration', {functools.partial(int_or_none, scale=1000)}),
237 'timestamp': ('file_start', {unified_timestamp}),
241 if traverse_obj(data, ('adult_status', {str})) == 'notLogin':
242 if not entries:
243 self.raise_login_required(
244 'Only users older than 19 are able to watch this video', method='password')
245 self.report_warning(
246 'In accordance with local laws and regulations, underage users are '
247 'restricted from watching adult content. Only content suitable for all '
248 f'ages will be downloaded. {self._login_hint("password")}')
250 if not entries and traverse_obj(data, ('sub_upload_type', {str})):
251 self.raise_login_required('This VOD is for subscribers only', method='password')
253 if len(entries) == 1:
254 return {
255 **entries[0],
256 'title': common_info.get('title'),
259 common_info['timestamp'] = traverse_obj(entries, (..., 'timestamp'), get_all=False)
261 return self.playlist_result(entries, video_id, multi_video=True, **common_info)
264 class AfreecaTVCatchStoryIE(AfreecaTVBaseIE):
265 IE_NAME = 'afreecatv:catchstory'
266 IE_DESC = 'afreecatv.com catch story'
267 _VALID_URL = r'https?://vod\.afreecatv\.com/player/(?P<id>\d+)/catchstory'
268 _TESTS = [{
269 'url': 'https://vod.afreecatv.com/player/103247/catchstory',
270 'info_dict': {
271 'id': '103247',
273 'playlist_count': 2,
276 def _real_extract(self, url):
277 video_id = self._match_id(url)
278 data = self._call_api(
279 'catchstory/a/view', video_id, headers={'Referer': url},
280 query={'aStoryListIdx': '', 'nStoryIdx': video_id})
282 return self.playlist_result(self._entries(data), video_id)
284 @staticmethod
285 def _entries(data):
286 # 'files' is always a list with 1 element
287 yield from traverse_obj(data, (
288 'data', lambda _, v: v['story_type'] == 'catch',
289 'catch_list', lambda _, v: v['files'][0]['file'], {
290 'id': ('files', 0, 'file_info_key', {str}),
291 'url': ('files', 0, 'file', {url_or_none}),
292 'duration': ('files', 0, 'duration', {functools.partial(int_or_none, scale=1000)}),
293 'title': ('title', {str}),
294 'uploader': ('writer_nick', {str}),
295 'uploader_id': ('writer_id', {str}),
296 'thumbnail': ('thumb', {url_or_none}),
297 'timestamp': ('write_timestamp', {int_or_none}),
301 class AfreecaTVLiveIE(AfreecaTVBaseIE):
302 IE_NAME = 'afreecatv:live'
303 IE_DESC = 'afreecatv.com livestreams'
304 _VALID_URL = r'https?://play\.afreeca(?:tv)?\.com/(?P<id>[^/]+)(?:/(?P<bno>\d+))?'
305 _TESTS = [{
306 'url': 'https://play.afreecatv.com/pyh3646/237852185',
307 'info_dict': {
308 'id': '237852185',
309 'ext': 'mp4',
310 'title': '【 우루과이 오늘은 무슨일이? 】',
311 'uploader': '박진우[JINU]',
312 'uploader_id': 'pyh3646',
313 'timestamp': 1640661495,
314 'is_live': True,
316 'skip': 'Livestream has ended',
317 }, {
318 'url': 'https://play.afreecatv.com/pyh3646/237852185',
319 'only_matching': True,
320 }, {
321 'url': 'https://play.afreecatv.com/pyh3646',
322 'only_matching': True,
325 _LIVE_API_URL = 'https://live.afreecatv.com/afreeca/player_live_api.php'
326 _WORKING_CDNS = [
327 'gcp_cdn', # live-global-cdn-v02.afreecatv.com
328 'gs_cdn_pc_app', # pc-app.stream.afreecatv.com
329 'gs_cdn_mobile_web', # mobile-web.stream.afreecatv.com
330 'gs_cdn_pc_web', # pc-web.stream.afreecatv.com
332 _BAD_CDNS = [
333 'gs_cdn', # chromecast.afreeca.gscdn.com (cannot resolve)
334 'gs_cdn_chromecast', # chromecast.stream.afreecatv.com (HTTP Error 400)
335 'azure_cdn', # live-global-cdn-v01.afreecatv.com (cannot resolve)
336 'aws_cf', # live-global-cdn-v03.afreecatv.com (cannot resolve)
337 'kt_cdn', # kt.stream.afreecatv.com (HTTP Error 400)
340 def _extract_formats(self, channel_info, broadcast_no, aid):
341 stream_base_url = channel_info.get('RMD') or 'https://livestream-manager.afreecatv.com'
343 # If user has not passed CDN IDs, try API-provided CDN ID followed by other working CDN IDs
344 default_cdn_ids = orderedSet([
345 *traverse_obj(channel_info, ('CDN', {str}, all, lambda _, v: v not in self._BAD_CDNS)),
346 *self._WORKING_CDNS,
348 cdn_ids = self._configuration_arg('cdn', default_cdn_ids)
350 for attempt, cdn_id in enumerate(cdn_ids, start=1):
351 m3u8_url = traverse_obj(self._download_json(
352 urljoin(stream_base_url, 'broad_stream_assign.html'), broadcast_no,
353 f'Downloading {cdn_id} stream info', f'Unable to download {cdn_id} stream info',
354 fatal=False, query={
355 'return_type': cdn_id,
356 'broad_key': f'{broadcast_no}-common-master-hls',
357 }), ('view_url', {url_or_none}))
358 try:
359 return self._extract_m3u8_formats(
360 m3u8_url, broadcast_no, 'mp4', m3u8_id='hls', query={'aid': aid},
361 headers={'Referer': 'https://play.afreecatv.com/'})
362 except ExtractorError as e:
363 if attempt == len(cdn_ids):
364 raise
365 self.report_warning(
366 f'{e.cause or e.msg}. Retrying... (attempt {attempt} of {len(cdn_ids)})')
368 def _real_extract(self, url):
369 broadcaster_id, broadcast_no = self._match_valid_url(url).group('id', 'bno')
370 channel_info = traverse_obj(self._download_json(
371 self._LIVE_API_URL, broadcaster_id, data=urlencode_postdata({'bid': broadcaster_id})),
372 ('CHANNEL', {dict})) or {}
374 broadcaster_id = channel_info.get('BJID') or broadcaster_id
375 broadcast_no = channel_info.get('BNO') or broadcast_no
376 if not broadcast_no:
377 raise UserNotLive(video_id=broadcaster_id)
379 password = self.get_param('videopassword')
380 if channel_info.get('BPWD') == 'Y' and password is None:
381 raise ExtractorError(
382 'This livestream is protected by a password, use the --video-password option',
383 expected=True)
385 token_info = traverse_obj(self._download_json(
386 self._LIVE_API_URL, broadcast_no, 'Downloading access token for stream',
387 'Unable to download access token for stream', data=urlencode_postdata(filter_dict({
388 'bno': broadcast_no,
389 'stream_type': 'common',
390 'type': 'aid',
391 'quality': 'master',
392 'pwd': password,
393 }))), ('CHANNEL', {dict})) or {}
394 aid = token_info.get('AID')
395 if not aid:
396 result = token_info.get('RESULT')
397 if result == 0:
398 raise ExtractorError('This livestream has ended', expected=True)
399 elif result == -6:
400 self.raise_login_required('This livestream is for subscribers only', method='password')
401 raise ExtractorError('Unable to extract access token')
403 formats = self._extract_formats(channel_info, broadcast_no, aid)
405 station_info = traverse_obj(self._download_json(
406 'https://st.afreecatv.com/api/get_station_status.php', broadcast_no,
407 'Downloading channel metadata', 'Unable to download channel metadata',
408 query={'szBjId': broadcaster_id}, fatal=False), {dict}) or {}
410 return {
411 'id': broadcast_no,
412 'title': channel_info.get('TITLE') or station_info.get('station_title'),
413 'uploader': channel_info.get('BJNICK') or station_info.get('station_name'),
414 'uploader_id': broadcaster_id,
415 'timestamp': unified_timestamp(station_info.get('broad_start')),
416 'formats': formats,
417 'is_live': True,
418 'http_headers': {'Referer': url},
422 class AfreecaTVUserIE(InfoExtractor):
423 IE_NAME = 'afreecatv:user'
424 _VALID_URL = r'https?://bj\.afreeca(?:tv)?\.com/(?P<id>[^/]+)/vods/?(?P<slug_type>[^/]+)?'
425 _TESTS = [{
426 'url': 'https://bj.afreecatv.com/ryuryu24/vods/review',
427 'info_dict': {
428 '_type': 'playlist',
429 'id': 'ryuryu24',
430 'title': 'ryuryu24 - review',
432 'playlist_count': 218,
433 }, {
434 'url': 'https://bj.afreecatv.com/parang1995/vods/highlight',
435 'info_dict': {
436 '_type': 'playlist',
437 'id': 'parang1995',
438 'title': 'parang1995 - highlight',
440 'playlist_count': 997,
441 }, {
442 'url': 'https://bj.afreecatv.com/ryuryu24/vods',
443 'info_dict': {
444 '_type': 'playlist',
445 'id': 'ryuryu24',
446 'title': 'ryuryu24 - all',
448 'playlist_count': 221,
449 }, {
450 'url': 'https://bj.afreecatv.com/ryuryu24/vods/balloonclip',
451 'info_dict': {
452 '_type': 'playlist',
453 'id': 'ryuryu24',
454 'title': 'ryuryu24 - balloonclip',
456 'playlist_count': 0,
458 _PER_PAGE = 60
460 def _fetch_page(self, user_id, user_type, page):
461 page += 1
462 info = self._download_json(f'https://bjapi.afreecatv.com/api/{user_id}/vods/{user_type}', user_id,
463 query={'page': page, 'per_page': self._PER_PAGE, 'orderby': 'reg_date'},
464 note=f'Downloading {user_type} video page {page}')
465 for item in info['data']:
466 yield self.url_result(
467 f'https://vod.afreecatv.com/player/{item["title_no"]}/', AfreecaTVIE, item['title_no'])
469 def _real_extract(self, url):
470 user_id, user_type = self._match_valid_url(url).group('id', 'slug_type')
471 user_type = user_type or 'all'
472 entries = OnDemandPagedList(functools.partial(self._fetch_page, user_id, user_type), self._PER_PAGE)
473 return self.playlist_result(entries, user_id, f'{user_id} - {user_type}')