]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/afreecatv.py
[ie/dailymotion] Support search (#8292)
[yt-dlp.git] / yt_dlp / extractor / afreecatv.py
CommitLineData
bd4073c5 1import functools
1dbfd787
PR
2import re
3
57cf9b7f 4from .common import InfoExtractor
57cf9b7f 5from ..utils import (
bd4073c5
HTL
6 ExtractorError,
7 OnDemandPagedList,
b2eeee0c 8 date_from_str,
6b9466de 9 determine_ext,
57cf9b7f 10 int_or_none,
f76ca2dd
LR
11 qualities,
12 traverse_obj,
b2eeee0c 13 unified_strdate,
f76ca2dd
LR
14 unified_timestamp,
15 update_url_query,
3052a30d 16 url_or_none,
e51762be 17 urlencode_postdata,
833b644f 18 xpath_text,
57cf9b7f
PR
19)
20
21
22class AfreecaTVIE(InfoExtractor):
c60089c0 23 IE_NAME = 'afreecatv'
57cf9b7f 24 IE_DESC = 'afreecatv.com'
e58609b2
S
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=|
028f6437 33 vod\.afreecatv\.com/(PLAYER/STATION|player)/
e58609b2
S
34 )
35 (?P<id>\d+)
36 '''
e51762be 37 _NETRC_MACHINE = 'afreecatv'
8d93c214 38 _TESTS = [{
57cf9b7f
PR
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': '데일리 에이프릴 요정들의 시상식!',
3452c3a2 45 'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
57cf9b7f
PR
46 'uploader': 'dailyapril',
47 'uploader_id': 'dailyapril',
8d93c214 48 'upload_date': '20160503',
51ef4919
YCH
49 },
50 'skip': 'Video is gone',
8d93c214
PR
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유트루와 함께하는 '팅커벨 메이크업!'",
3452c3a2 56 'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
8d93c214
PR
57 'uploader': 'dailyapril',
58 'uploader_id': 'dailyapril',
59 },
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',
68 },
69 }, {
70 'md5': '58f2ce7f6044e34439ab2d50612ab02b',
71 'info_dict': {
72 'id': '36153164_2',
73 'ext': 'mp4',
74 'title': "BJ유트루와 함께하는 '팅커벨 메이크업!'",
75 'upload_date': '20160502',
76 },
77 }],
51ef4919 78 'skip': 'Video is gone',
e109f1ff
S
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,
91 },
92 'params': {
93 'skip_download': True,
94 },
839728f5 95 }, {
fdd69db3
JH
96 # adult content
97 'url': 'https://vod.afreecatv.com/player/97267690',
839728f5 98 'info_dict': {
86693c49 99 'id': '20180327_27901457_202289533_1',
839728f5 100 'ext': 'mp4',
86693c49 101 'title': '[생]빨개요♥ (part 1)',
839728f5 102 'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
86693c49 103 'uploader': '[SA]서아',
839728f5 104 'uploader_id': 'bjdyrksu',
86693c49
S
105 'upload_date': '20180327',
106 'duration': 3601,
839728f5
S
107 },
108 'params': {
109 'skip_download': True,
110 },
fdd69db3 111 'skip': 'The VOD does not exist',
3452c3a2
PR
112 }, {
113 'url': 'http://www.afreecatv.com/player/Player.swf?szType=szBjId=djleegoon&nStationNo=11273158&nBbsNo=13161095&nTitleNo=36327652',
114 'only_matching': True,
e58609b2 115 }, {
fdd69db3
JH
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': '젠지 페이즈',
126 },
127 'params': {
128 'skip_download': True,
129 },
8d93c214 130 }]
57cf9b7f 131
1dbfd787
PR
132 @staticmethod
133 def parse_video_key(key):
0fdbe314 134 video_key = {}
1dbfd787
PR
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')
6b9466de 138 video_key['part'] = int(m.group('part'))
1dbfd787
PR
139 return video_key
140
52efa4b3 141 def _perform_login(self, username, password):
e51762be
S
142 login_form = {
143 'szWork': 'login',
144 'szType': 'json',
145 'szUid': username,
146 'szPassword': password,
147 'isSaveId': 'false',
148 'szScriptVar': 'oLoginRet',
149 'szAction': '',
150 }
151
152 response = self._download_json(
153 'https://login.afreecatv.com/app/LoginAction.php', None,
154 'Logging in', data=urlencode_postdata(login_form))
155
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.',
170 }
171
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)
178
57cf9b7f
PR
179 def _real_extract(self, url):
180 video_id = self._match_id(url)
e58609b2 181
86693c49 182 partial_view = False
875cfb8c 183 adult_view = False
86693c49 184 for _ in range(2):
fdd69db3
JH
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)
86693c49 193 query = {
839728f5 194 'nTitleNo': video_id,
fdd69db3
JH
195 'nStationNo': data['station_no'],
196 'nBbsNo': data['bbs_no'],
86693c49
S
197 }
198 if partial_view:
199 query['partialView'] = 'SKIP_ADULT'
875cfb8c
LR
200 if adult_view:
201 query['adultView'] = 'ADULT_VIEW'
86693c49
S
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)
839728f5 209
86693c49
S
210 flag = xpath_text(video_xml, './track/flag', 'flag', default=None)
211 if flag and flag == 'SUCCEED':
212 break
213 if flag == 'PARTIAL_ADULT':
6a39ee13 214 self.report_warning(
86693c49
S
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':
875cfb8c
LR
221 if not adult_view:
222 adult_view = True
223 continue
86693c49
S
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
839728f5 227 raise ExtractorError(
86693c49
S
228 '%s said: %s' % (self.IE_NAME, error), expected=True)
229 else:
230 raise ExtractorError('Unable to download video info')
57cf9b7f 231
f9934b96 232 video_element = video_xml.findall('./track/video')[-1]
51ef4919 233 if video_element is None or video_element.text is None:
f9f10268 234 raise ExtractorError(
8bdd16b4 235 'Video %s does not exist' % video_id, expected=True)
e7d85c4e 236
6b9466de 237 video_url = video_element.text.strip()
51ef4919
YCH
238
239 title = xpath_text(video_xml, './track/title', 'title', fatal=True)
6b9466de 240
833b644f
PR
241 uploader = xpath_text(video_xml, './track/nickname', 'uploader')
242 uploader_id = xpath_text(video_xml, './track/bj_id', 'uploader id')
6b9466de
S
243 duration = int_or_none(xpath_text(
244 video_xml, './track/duration', 'duration'))
833b644f 245 thumbnail = xpath_text(video_xml, './track/titleImage', 'thumbnail')
57cf9b7f 246
6b9466de
S
247 common_entry = {
248 'uploader': uploader,
249 'uploader_id': uploader_id,
250 'thumbnail': thumbnail,
251 }
252
253 info = common_entry.copy()
254 info.update({
255 'id': video_id,
256 'title': title,
257 'duration': duration,
258 })
259
260 if not video_url:
261 entries = []
f9934b96 262 file_elements = video_element.findall('./file')
e109f1ff
S
263 one = len(file_elements) == 1
264 for file_num, file_element in enumerate(file_elements, start=1):
3052a30d 265 file_url = url_or_none(file_element.text)
6b9466de
S
266 if not file_url:
267 continue
e109f1ff 268 key = file_element.get('key', '')
b2eeee0c
LR
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
6b9466de 278 file_duration = int_or_none(file_element.get('duration'))
e109f1ff 279 format_id = key if key else '%s_%s' % (video_id, file_num)
4a109f81
S
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',
289 }]
a06916d9 290 if not formats and not self.get_param('ignore_no_formats'):
4a109f81 291 continue
6b9466de
S
292 file_info = common_entry.copy()
293 file_info.update({
294 'id': format_id,
6b4ddd33 295 'title': title if one else '%s (part %d)' % (title, file_num),
e109f1ff 296 'upload_date': upload_date,
6b9466de
S
297 'duration': file_duration,
298 'formats': formats,
299 })
300 entries.append(file_info)
301 entries_info = info.copy()
302 entries_info.update({
303 '_type': 'multi_video',
304 'entries': entries,
305 })
306 return entries_info
307
308 info = {
57cf9b7f
PR
309 'id': video_id,
310 'title': title,
311 'uploader': uploader,
312 'uploader_id': uploader_id,
313 'duration': duration,
314 'thumbnail': thumbnail,
315 }
316
6b9466de
S
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
328 })
329
330 return info
f76ca2dd
LR
331
332
6368e2e6 333class AfreecaTVLiveIE(AfreecaTVIE): # XXX: Do not subclass from concrete IE
f76ca2dd
LR
334
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,
347 },
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,
355 }]
356
357 _LIVE_API_URL = 'https://live.afreecatv.com/afreeca/player_live_api.php'
358
359 _QUALITIES = ('sd', 'hd', 'hd2k', 'original')
360
361 def _real_extract(self, url):
362 broadcaster_id, broadcast_no = self._match_valid_url(url).group('id', 'bno')
5dee3ad0 363 password = self.get_param('videopassword')
f76ca2dd
LR
364
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
5dee3ad0 370 password_protected = channel_info.get('BPWD')
f76ca2dd
LR
371 if not broadcast_no:
372 raise ExtractorError(f'Unable to extract broadcast number ({broadcaster_id} may not be live)', expected=True)
5dee3ad0
LR
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)
f76ca2dd
LR
377
378 formats = []
379 quality_key = qualities(self._QUALITIES)
380 for quality_str in self._QUALITIES:
5dee3ad0
LR
381 params = {
382 'bno': broadcast_no,
383 'stream_type': 'common',
384 'type': 'aid',
385 'quality': quality_str,
386 }
387 if password is not None:
388 params['pwd'] = password
f76ca2dd
LR
389 aid_response = self._download_json(
390 self._LIVE_API_URL, broadcast_no, fatal=False,
5dee3ad0 391 data=urlencode_postdata(params),
f76ca2dd
LR
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
397
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',
404 },
405 note=f'Downloading metadata for {quality_str} stream',
406 errnote=f'Unable to download metadata for {quality_str} stream') or {}
407
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),
415 })
416
f76ca2dd
LR
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 {}
421
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,
430 }
bd4073c5
HTL
431
432
433class 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',
442 },
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',
450 },
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',
458 },
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',
466 },
467 'playlist_count': 0,
468 }]
469 _PER_PAGE = 60
470
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'])
479
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}')