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