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