[cleanup] Misc (#8968)
[yt-dlp.git] / yt_dlp / extractor / afreecatv.py
blob3d26d9c25d172f18a903e8f13880c9a6bdac6cae
1 import functools
2 import re
4 from .common import InfoExtractor
5 from ..utils import (
6 ExtractorError,
7 OnDemandPagedList,
8 date_from_str,
9 determine_ext,
10 int_or_none,
11 qualities,
12 traverse_obj,
13 unified_strdate,
14 unified_timestamp,
15 update_url_query,
16 url_or_none,
17 urlencode_postdata,
18 xpath_text,
22 class AfreecaTVIE(InfoExtractor):
23 IE_NAME = 'afreecatv'
24 IE_DESC = 'afreecatv.com'
25 _VALID_URL = r'''(?x)
26 https?://
27 (?:
28 (?:(?:live|afbbs|www)\.)?afreeca(?:tv)?\.com(?::\d+)?
29 (?:
30 /app/(?:index|read_ucc_bbs)\.cgi|
31 /player/[Pp]layer\.(?:swf|html)
32 )\?.*?\bnTitleNo=|
33 vod\.afreecatv\.com/(PLAYER/STATION|player)/
35 (?P<id>\d+)
36 '''
37 _NETRC_MACHINE = 'afreecatv'
38 _TESTS = [{
39 'url': 'http://live.afreecatv.com:8079/app/index.cgi?szType=read_ucc_bbs&szBjId=dailyapril&nStationNo=16711924&nBbsNo=18605867&nTitleNo=36164052&szSkin=',
40 'md5': 'f72c89fe7ecc14c1b5ce506c4996046e',
41 'info_dict': {
42 'id': '36164052',
43 'ext': 'mp4',
44 'title': '데일리 에이프릴 요정들의 시상식!',
45 'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
46 'uploader': 'dailyapril',
47 'uploader_id': 'dailyapril',
48 'upload_date': '20160503',
50 'skip': 'Video is gone',
51 }, {
52 'url': 'http://afbbs.afreecatv.com:8080/app/read_ucc_bbs.cgi?nStationNo=16711924&nTitleNo=36153164&szBjId=dailyapril&nBbsNo=18605867',
53 'info_dict': {
54 'id': '36153164',
55 'title': "BJ유트루와 함께하는 '팅커벨 메이크업!'",
56 'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
57 'uploader': 'dailyapril',
58 'uploader_id': 'dailyapril',
60 'playlist_count': 2,
61 'playlist': [{
62 'md5': 'd8b7c174568da61d774ef0203159bf97',
63 'info_dict': {
64 'id': '36153164_1',
65 'ext': 'mp4',
66 'title': "BJ유트루와 함께하는 '팅커벨 메이크업!'",
67 'upload_date': '20160502',
69 }, {
70 'md5': '58f2ce7f6044e34439ab2d50612ab02b',
71 'info_dict': {
72 'id': '36153164_2',
73 'ext': 'mp4',
74 'title': "BJ유트루와 함께하는 '팅커벨 메이크업!'",
75 'upload_date': '20160502',
77 }],
78 'skip': 'Video is gone',
79 }, {
80 # non standard key
81 'url': 'http://vod.afreecatv.com/PLAYER/STATION/20515605',
82 'info_dict': {
83 'id': '20170411_BE689A0E_190960999_1_2_h',
84 'ext': 'mp4',
85 'title': '혼자사는여자집',
86 'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
87 'uploader': '♥이슬이',
88 'uploader_id': 'dasl8121',
89 'upload_date': '20170411',
90 'duration': 213,
92 'params': {
93 'skip_download': True,
95 }, {
96 # adult content
97 'url': 'https://vod.afreecatv.com/player/97267690',
98 'info_dict': {
99 'id': '20180327_27901457_202289533_1',
100 'ext': 'mp4',
101 'title': '[생]빨개요♥ (part 1)',
102 'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
103 'uploader': '[SA]서아',
104 'uploader_id': 'bjdyrksu',
105 'upload_date': '20180327',
106 'duration': 3601,
108 'params': {
109 'skip_download': True,
111 'skip': 'The VOD does not exist',
112 }, {
113 'url': 'http://www.afreecatv.com/player/Player.swf?szType=szBjId=djleegoon&nStationNo=11273158&nBbsNo=13161095&nTitleNo=36327652',
114 'only_matching': True,
115 }, {
116 'url': 'https://vod.afreecatv.com/player/96753363',
117 'info_dict': {
118 'id': '20230108_9FF5BEE1_244432674_1',
119 'ext': 'mp4',
120 'uploader_id': 'rlantnghks',
121 'uploader': '페이즈으',
122 'duration': 10840,
123 'thumbnail': 'http://videoimg.afreecatv.com/php/SnapshotLoad.php?rowKey=20230108_9FF5BEE1_244432674_1_r',
124 'upload_date': '20230108',
125 'title': '젠지 페이즈',
127 'params': {
128 'skip_download': True,
132 @staticmethod
133 def parse_video_key(key):
134 video_key = {}
135 m = re.match(r'^(?P<upload_date>\d{8})_\w+_(?P<part>\d+)$', key)
136 if m:
137 video_key['upload_date'] = m.group('upload_date')
138 video_key['part'] = int(m.group('part'))
139 return video_key
141 def _perform_login(self, username, password):
142 login_form = {
143 'szWork': 'login',
144 'szType': 'json',
145 'szUid': username,
146 'szPassword': password,
147 'isSaveId': 'false',
148 'szScriptVar': 'oLoginRet',
149 'szAction': '',
152 response = self._download_json(
153 'https://login.afreecatv.com/app/LoginAction.php', None,
154 'Logging in', data=urlencode_postdata(login_form))
156 _ERRORS = {
157 -4: 'Your account has been suspended due to a violation of our terms and policies.',
158 -5: 'https://member.afreecatv.com/app/user_delete_progress.php',
159 -6: 'https://login.afreecatv.com/membership/changeMember.php',
160 -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.",
161 -9: 'https://member.afreecatv.com/app/pop_login_block.php',
162 -11: 'https://login.afreecatv.com/afreeca/second_login.php',
163 -12: 'https://member.afreecatv.com/app/user_security.php',
164 0: 'The username does not exist or you have entered the wrong password.',
165 -1: 'The username does not exist or you have entered the wrong password.',
166 -3: 'You have entered your username/password incorrectly.',
167 -7: 'You cannot use your Global AfreecaTV account to access Korean AfreecaTV.',
168 -10: 'Sorry for the inconvenience. \nYour account has been blocked due to an unauthorized access. \nPlease contact our Help Center for assistance.',
169 -32008: 'You have failed to log in. Please contact our Help Center.',
172 result = int_or_none(response.get('RESULT'))
173 if result != 1:
174 error = _ERRORS.get(result, 'You have failed to log in.')
175 raise ExtractorError(
176 'Unable to login: %s said: %s' % (self.IE_NAME, error),
177 expected=True)
179 def _real_extract(self, url):
180 video_id = self._match_id(url)
182 partial_view = False
183 adult_view = False
184 for _ in range(2):
185 data = self._download_json(
186 'https://api.m.afreecatv.com/station/video/a/view',
187 video_id, headers={'Referer': url}, data=urlencode_postdata({
188 'nTitleNo': video_id,
189 'nApiLevel': 10,
190 }))['data']
191 if traverse_obj(data, ('code', {int})) == -6221:
192 raise ExtractorError('The VOD does not exist', expected=True)
193 query = {
194 'nTitleNo': video_id,
195 'nStationNo': data['station_no'],
196 'nBbsNo': data['bbs_no'],
198 if partial_view:
199 query['partialView'] = 'SKIP_ADULT'
200 if adult_view:
201 query['adultView'] = 'ADULT_VIEW'
202 video_xml = self._download_xml(
203 'http://afbbs.afreecatv.com:8080/api/video/get_video_info.php',
204 video_id, 'Downloading video info XML%s'
205 % (' (skipping adult)' if partial_view else ''),
206 video_id, headers={
207 'Referer': url,
208 }, query=query)
210 flag = xpath_text(video_xml, './track/flag', 'flag', default=None)
211 if flag and flag == 'SUCCEED':
212 break
213 if flag == 'PARTIAL_ADULT':
214 self.report_warning(
215 'In accordance with local laws and regulations, underage users are restricted from watching adult content. '
216 'Only content suitable for all ages will be downloaded. '
217 'Provide account credentials if you wish to download restricted content.')
218 partial_view = True
219 continue
220 elif flag == 'ADULT':
221 if not adult_view:
222 adult_view = True
223 continue
224 error = 'Only users older than 19 are able to watch this video. Provide account credentials to download this content.'
225 else:
226 error = flag
227 raise ExtractorError(
228 '%s said: %s' % (self.IE_NAME, error), expected=True)
229 else:
230 raise ExtractorError('Unable to download video info')
232 video_element = video_xml.findall('./track/video')[-1]
233 if video_element is None or video_element.text is None:
234 raise ExtractorError(
235 'Video %s does not exist' % video_id, expected=True)
237 video_url = video_element.text.strip()
239 title = xpath_text(video_xml, './track/title', 'title', fatal=True)
241 uploader = xpath_text(video_xml, './track/nickname', 'uploader')
242 uploader_id = xpath_text(video_xml, './track/bj_id', 'uploader id')
243 duration = int_or_none(xpath_text(
244 video_xml, './track/duration', 'duration'))
245 thumbnail = xpath_text(video_xml, './track/titleImage', 'thumbnail')
247 common_entry = {
248 'uploader': uploader,
249 'uploader_id': uploader_id,
250 'thumbnail': thumbnail,
253 info = common_entry.copy()
254 info.update({
255 'id': video_id,
256 'title': title,
257 'duration': duration,
260 if not video_url:
261 entries = []
262 file_elements = video_element.findall('./file')
263 one = len(file_elements) == 1
264 for file_num, file_element in enumerate(file_elements, start=1):
265 file_url = url_or_none(file_element.text)
266 if not file_url:
267 continue
268 key = file_element.get('key', '')
269 upload_date = unified_strdate(self._search_regex(
270 r'^(\d{8})_', key, 'upload date', default=None))
271 if upload_date is not None:
272 # sometimes the upload date isn't included in the file name
273 # instead, another random ID is, which may parse as a valid
274 # date but be wildly out of a reasonable range
275 parsed_date = date_from_str(upload_date)
276 if parsed_date.year < 2000 or parsed_date.year >= 2100:
277 upload_date = None
278 file_duration = int_or_none(file_element.get('duration'))
279 format_id = key if key else '%s_%s' % (video_id, file_num)
280 if determine_ext(file_url) == 'm3u8':
281 formats = self._extract_m3u8_formats(
282 file_url, video_id, 'mp4', entry_protocol='m3u8_native',
283 m3u8_id='hls',
284 note='Downloading part %d m3u8 information' % file_num)
285 else:
286 formats = [{
287 'url': file_url,
288 'format_id': 'http',
290 if not formats and not self.get_param('ignore_no_formats'):
291 continue
292 file_info = common_entry.copy()
293 file_info.update({
294 'id': format_id,
295 'title': title if one else '%s (part %d)' % (title, file_num),
296 'upload_date': upload_date,
297 'duration': file_duration,
298 'formats': formats,
300 entries.append(file_info)
301 entries_info = info.copy()
302 entries_info.update({
303 '_type': 'multi_video',
304 'entries': entries,
306 return entries_info
308 info = {
309 'id': video_id,
310 'title': title,
311 'uploader': uploader,
312 'uploader_id': uploader_id,
313 'duration': duration,
314 'thumbnail': thumbnail,
317 if determine_ext(video_url) == 'm3u8':
318 info['formats'] = self._extract_m3u8_formats(
319 video_url, video_id, 'mp4', entry_protocol='m3u8_native',
320 m3u8_id='hls')
321 else:
322 app, playpath = video_url.split('mp4:')
323 info.update({
324 'url': app,
325 'ext': 'flv',
326 'play_path': 'mp4:' + playpath,
327 'rtmp_live': True, # downloading won't end without this
330 return info
333 class AfreecaTVLiveIE(AfreecaTVIE): # XXX: Do not subclass from concrete IE
335 IE_NAME = 'afreecatv:live'
336 _VALID_URL = r'https?://play\.afreeca(?:tv)?\.com/(?P<id>[^/]+)(?:/(?P<bno>\d+))?'
337 _TESTS = [{
338 'url': 'https://play.afreecatv.com/pyh3646/237852185',
339 'info_dict': {
340 'id': '237852185',
341 'ext': 'mp4',
342 'title': '【 우루과이 오늘은 무슨일이? 】',
343 'uploader': '박진우[JINU]',
344 'uploader_id': 'pyh3646',
345 'timestamp': 1640661495,
346 'is_live': True,
348 'skip': 'Livestream has ended',
349 }, {
350 'url': 'http://play.afreeca.com/pyh3646/237852185',
351 'only_matching': True,
352 }, {
353 'url': 'http://play.afreeca.com/pyh3646',
354 'only_matching': True,
357 _LIVE_API_URL = 'https://live.afreecatv.com/afreeca/player_live_api.php'
359 _QUALITIES = ('sd', 'hd', 'hd2k', 'original')
361 def _real_extract(self, url):
362 broadcaster_id, broadcast_no = self._match_valid_url(url).group('id', 'bno')
363 password = self.get_param('videopassword')
365 info = self._download_json(self._LIVE_API_URL, broadcaster_id, fatal=False,
366 data=urlencode_postdata({'bid': broadcaster_id})) or {}
367 channel_info = info.get('CHANNEL') or {}
368 broadcaster_id = channel_info.get('BJID') or broadcaster_id
369 broadcast_no = channel_info.get('BNO') or broadcast_no
370 password_protected = channel_info.get('BPWD')
371 if not broadcast_no:
372 raise ExtractorError(f'Unable to extract broadcast number ({broadcaster_id} may not be live)', expected=True)
373 if password_protected == 'Y' and password is None:
374 raise ExtractorError(
375 'This livestream is protected by a password, use the --video-password option',
376 expected=True)
378 formats = []
379 quality_key = qualities(self._QUALITIES)
380 for quality_str in self._QUALITIES:
381 params = {
382 'bno': broadcast_no,
383 'stream_type': 'common',
384 'type': 'aid',
385 'quality': quality_str,
387 if password is not None:
388 params['pwd'] = password
389 aid_response = self._download_json(
390 self._LIVE_API_URL, broadcast_no, fatal=False,
391 data=urlencode_postdata(params),
392 note=f'Downloading access token for {quality_str} stream',
393 errnote=f'Unable to download access token for {quality_str} stream')
394 aid = traverse_obj(aid_response, ('CHANNEL', 'AID'))
395 if not aid:
396 continue
398 stream_base_url = channel_info.get('RMD') or 'https://livestream-manager.afreecatv.com'
399 stream_info = self._download_json(
400 f'{stream_base_url}/broad_stream_assign.html', broadcast_no, fatal=False,
401 query={
402 'return_type': channel_info.get('CDN', 'gcp_cdn'),
403 'broad_key': f'{broadcast_no}-common-{quality_str}-hls',
405 note=f'Downloading metadata for {quality_str} stream',
406 errnote=f'Unable to download metadata for {quality_str} stream') or {}
408 if stream_info.get('view_url'):
409 formats.append({
410 'format_id': quality_str,
411 'url': update_url_query(stream_info['view_url'], {'aid': aid}),
412 'ext': 'mp4',
413 'protocol': 'm3u8',
414 'quality': quality_key(quality_str),
417 station_info = self._download_json(
418 'https://st.afreecatv.com/api/get_station_status.php', broadcast_no,
419 query={'szBjId': broadcaster_id}, fatal=False,
420 note='Downloading channel metadata', errnote='Unable to download channel metadata') or {}
422 return {
423 'id': broadcast_no,
424 'title': channel_info.get('TITLE') or station_info.get('station_title'),
425 'uploader': channel_info.get('BJNICK') or station_info.get('station_name'),
426 'uploader_id': broadcaster_id,
427 'timestamp': unified_timestamp(station_info.get('broad_start')),
428 'formats': formats,
429 'is_live': True,
433 class AfreecaTVUserIE(InfoExtractor):
434 IE_NAME = 'afreecatv:user'
435 _VALID_URL = r'https?://bj\.afreeca(?:tv)?\.com/(?P<id>[^/]+)/vods/?(?P<slug_type>[^/]+)?'
436 _TESTS = [{
437 'url': 'https://bj.afreecatv.com/ryuryu24/vods/review',
438 'info_dict': {
439 '_type': 'playlist',
440 'id': 'ryuryu24',
441 'title': 'ryuryu24 - review',
443 'playlist_count': 218,
444 }, {
445 'url': 'https://bj.afreecatv.com/parang1995/vods/highlight',
446 'info_dict': {
447 '_type': 'playlist',
448 'id': 'parang1995',
449 'title': 'parang1995 - highlight',
451 'playlist_count': 997,
452 }, {
453 'url': 'https://bj.afreecatv.com/ryuryu24/vods',
454 'info_dict': {
455 '_type': 'playlist',
456 'id': 'ryuryu24',
457 'title': 'ryuryu24 - all',
459 'playlist_count': 221,
460 }, {
461 'url': 'https://bj.afreecatv.com/ryuryu24/vods/balloonclip',
462 'info_dict': {
463 '_type': 'playlist',
464 'id': 'ryuryu24',
465 'title': 'ryuryu24 - balloonclip',
467 'playlist_count': 0,
469 _PER_PAGE = 60
471 def _fetch_page(self, user_id, user_type, page):
472 page += 1
473 info = self._download_json(f'https://bjapi.afreecatv.com/api/{user_id}/vods/{user_type}', user_id,
474 query={'page': page, 'per_page': self._PER_PAGE, 'orderby': 'reg_date'},
475 note=f'Downloading {user_type} video page {page}')
476 for item in info['data']:
477 yield self.url_result(
478 f'https://vod.afreecatv.com/player/{item["title_no"]}/', AfreecaTVIE, item['title_no'])
480 def _real_extract(self, url):
481 user_id, user_type = self._match_valid_url(url).group('id', 'slug_type')
482 user_type = user_type or 'all'
483 entries = OnDemandPagedList(functools.partial(self._fetch_page, user_id, user_type), self._PER_PAGE)
484 return self.playlist_result(entries, user_id, f'{user_id} - {user_type}')