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