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