afreecatv.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. import functools
  2. from .common import InfoExtractor
  3. from ..utils import (
  4. ExtractorError,
  5. OnDemandPagedList,
  6. UserNotLive,
  7. determine_ext,
  8. filter_dict,
  9. int_or_none,
  10. orderedSet,
  11. unified_timestamp,
  12. url_or_none,
  13. urlencode_postdata,
  14. urljoin,
  15. )
  16. from ..utils.traversal import traverse_obj
  17. class AfreecaTVBaseIE(InfoExtractor):
  18. _NETRC_MACHINE = 'afreecatv'
  19. def _perform_login(self, username, password):
  20. login_form = {
  21. 'szWork': 'login',
  22. 'szType': 'json',
  23. 'szUid': username,
  24. 'szPassword': password,
  25. 'isSaveId': 'false',
  26. 'szScriptVar': 'oLoginRet',
  27. 'szAction': '',
  28. }
  29. response = self._download_json(
  30. 'https://login.afreecatv.com/app/LoginAction.php', None,
  31. 'Logging in', data=urlencode_postdata(login_form))
  32. _ERRORS = {
  33. -4: 'Your account has been suspended due to a violation of our terms and policies.',
  34. -5: 'https://member.afreecatv.com/app/user_delete_progress.php',
  35. -6: 'https://login.afreecatv.com/membership/changeMember.php',
  36. -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.",
  37. -9: 'https://member.afreecatv.com/app/pop_login_block.php',
  38. -11: 'https://login.afreecatv.com/afreeca/second_login.php',
  39. -12: 'https://member.afreecatv.com/app/user_security.php',
  40. 0: 'The username does not exist or you have entered the wrong password.',
  41. -1: 'The username does not exist or you have entered the wrong password.',
  42. -3: 'You have entered your username/password incorrectly.',
  43. -7: 'You cannot use your Global AfreecaTV account to access Korean AfreecaTV.',
  44. -10: 'Sorry for the inconvenience. \nYour account has been blocked due to an unauthorized access. \nPlease contact our Help Center for assistance.',
  45. -32008: 'You have failed to log in. Please contact our Help Center.',
  46. }
  47. result = int_or_none(response.get('RESULT'))
  48. if result != 1:
  49. error = _ERRORS.get(result, 'You have failed to log in.')
  50. raise ExtractorError(
  51. f'Unable to login: {self.IE_NAME} said: {error}',
  52. expected=True)
  53. class AfreecaTVIE(AfreecaTVBaseIE):
  54. IE_NAME = 'afreecatv'
  55. IE_DESC = 'afreecatv.com'
  56. _VALID_URL = r'''(?x)
  57. https?://
  58. (?:
  59. (?:(?:live|afbbs|www)\.)?afreeca(?:tv)?\.com(?::\d+)?
  60. (?:
  61. /app/(?:index|read_ucc_bbs)\.cgi|
  62. /player/[Pp]layer\.(?:swf|html)
  63. )\?.*?\bnTitleNo=|
  64. vod\.afreecatv\.com/(PLAYER/STATION|player)/
  65. )
  66. (?P<id>\d+)/?(?:$|[?#&])
  67. '''
  68. _TESTS = [{
  69. 'url': 'http://live.afreecatv.com:8079/app/index.cgi?szType=read_ucc_bbs&szBjId=dailyapril&nStationNo=16711924&nBbsNo=18605867&nTitleNo=36164052&szSkin=',
  70. 'md5': 'f72c89fe7ecc14c1b5ce506c4996046e',
  71. 'info_dict': {
  72. 'id': '36164052',
  73. 'ext': 'mp4',
  74. 'title': '데일리 에이프릴 요정들의 시상식!',
  75. 'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
  76. 'uploader': 'dailyapril',
  77. 'uploader_id': 'dailyapril',
  78. 'upload_date': '20160503',
  79. },
  80. 'skip': 'Video is gone',
  81. }, {
  82. 'url': 'http://afbbs.afreecatv.com:8080/app/read_ucc_bbs.cgi?nStationNo=16711924&nTitleNo=36153164&szBjId=dailyapril&nBbsNo=18605867',
  83. 'info_dict': {
  84. 'id': '36153164',
  85. 'title': "BJ유트루와 함께하는 '팅커벨 메이크업!'",
  86. 'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
  87. 'uploader': 'dailyapril',
  88. 'uploader_id': 'dailyapril',
  89. },
  90. 'playlist_count': 2,
  91. 'playlist': [{
  92. 'md5': 'd8b7c174568da61d774ef0203159bf97',
  93. 'info_dict': {
  94. 'id': '36153164_1',
  95. 'ext': 'mp4',
  96. 'title': "BJ유트루와 함께하는 '팅커벨 메이크업!'",
  97. 'upload_date': '20160502',
  98. },
  99. }, {
  100. 'md5': '58f2ce7f6044e34439ab2d50612ab02b',
  101. 'info_dict': {
  102. 'id': '36153164_2',
  103. 'ext': 'mp4',
  104. 'title': "BJ유트루와 함께하는 '팅커벨 메이크업!'",
  105. 'upload_date': '20160502',
  106. },
  107. }],
  108. 'skip': 'Video is gone',
  109. }, {
  110. # non standard key
  111. 'url': 'http://vod.afreecatv.com/PLAYER/STATION/20515605',
  112. 'info_dict': {
  113. 'id': '20170411_BE689A0E_190960999_1_2_h',
  114. 'ext': 'mp4',
  115. 'title': '혼자사는여자집',
  116. 'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
  117. 'uploader': '♥이슬이',
  118. 'uploader_id': 'dasl8121',
  119. 'upload_date': '20170411',
  120. 'timestamp': 1491929865,
  121. 'duration': 213,
  122. },
  123. 'params': {
  124. 'skip_download': True,
  125. },
  126. }, {
  127. # adult content
  128. 'url': 'https://vod.afreecatv.com/player/97267690',
  129. 'info_dict': {
  130. 'id': '20180327_27901457_202289533_1',
  131. 'ext': 'mp4',
  132. 'title': '[생]빨개요♥ (part 1)',
  133. 'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
  134. 'uploader': '[SA]서아',
  135. 'uploader_id': 'bjdyrksu',
  136. 'upload_date': '20180327',
  137. 'duration': 3601,
  138. },
  139. 'params': {
  140. 'skip_download': True,
  141. },
  142. 'skip': 'The VOD does not exist',
  143. }, {
  144. 'url': 'http://www.afreecatv.com/player/Player.swf?szType=szBjId=djleegoon&nStationNo=11273158&nBbsNo=13161095&nTitleNo=36327652',
  145. 'only_matching': True,
  146. }, {
  147. 'url': 'https://vod.afreecatv.com/player/96753363',
  148. 'info_dict': {
  149. 'id': '20230108_9FF5BEE1_244432674_1',
  150. 'ext': 'mp4',
  151. 'uploader_id': 'rlantnghks',
  152. 'uploader': '페이즈으',
  153. 'duration': 10840,
  154. 'thumbnail': r're:https?://videoimg\.afreecatv\.com/.+',
  155. 'upload_date': '20230108',
  156. 'timestamp': 1673218805,
  157. 'title': '젠지 페이즈',
  158. },
  159. 'params': {
  160. 'skip_download': True,
  161. },
  162. }, {
  163. # adult content
  164. 'url': 'https://vod.afreecatv.com/player/70395877',
  165. 'only_matching': True,
  166. }, {
  167. # subscribers only
  168. 'url': 'https://vod.afreecatv.com/player/104647403',
  169. 'only_matching': True,
  170. }, {
  171. # private
  172. 'url': 'https://vod.afreecatv.com/player/81669846',
  173. 'only_matching': True,
  174. }]
  175. def _real_extract(self, url):
  176. video_id = self._match_id(url)
  177. data = self._download_json(
  178. 'https://api.m.afreecatv.com/station/video/a/view', video_id,
  179. headers={'Referer': url}, data=urlencode_postdata({
  180. 'nTitleNo': video_id,
  181. 'nApiLevel': 10,
  182. }), impersonate=True)['data']
  183. error_code = traverse_obj(data, ('code', {int}))
  184. if error_code == -6221:
  185. raise ExtractorError('The VOD does not exist', expected=True)
  186. elif error_code == -6205:
  187. raise ExtractorError('This VOD is private', expected=True)
  188. common_info = traverse_obj(data, {
  189. 'title': ('title', {str}),
  190. 'uploader': ('writer_nick', {str}),
  191. 'uploader_id': ('bj_id', {str}),
  192. 'duration': ('total_file_duration', {functools.partial(int_or_none, scale=1000)}),
  193. 'thumbnail': ('thumb', {url_or_none}),
  194. })
  195. entries = []
  196. for file_num, file_element in enumerate(
  197. traverse_obj(data, ('files', lambda _, v: url_or_none(v['file']))), start=1):
  198. file_url = file_element['file']
  199. if determine_ext(file_url) == 'm3u8':
  200. formats = self._extract_m3u8_formats(
  201. file_url, video_id, 'mp4', m3u8_id='hls',
  202. note=f'Downloading part {file_num} m3u8 information')
  203. else:
  204. formats = [{
  205. 'url': file_url,
  206. 'format_id': 'http',
  207. }]
  208. entries.append({
  209. **common_info,
  210. 'id': file_element.get('file_info_key') or f'{video_id}_{file_num}',
  211. 'title': f'{common_info.get("title") or "Untitled"} (part {file_num})',
  212. 'formats': formats,
  213. **traverse_obj(file_element, {
  214. 'duration': ('duration', {functools.partial(int_or_none, scale=1000)}),
  215. 'timestamp': ('file_start', {unified_timestamp}),
  216. }),
  217. })
  218. if traverse_obj(data, ('adult_status', {str})) == 'notLogin':
  219. if not entries:
  220. self.raise_login_required(
  221. 'Only users older than 19 are able to watch this video', method='password')
  222. self.report_warning(
  223. 'In accordance with local laws and regulations, underage users are '
  224. 'restricted from watching adult content. Only content suitable for all '
  225. f'ages will be downloaded. {self._login_hint("password")}')
  226. if not entries and traverse_obj(data, ('sub_upload_type', {str})):
  227. self.raise_login_required('This VOD is for subscribers only', method='password')
  228. if len(entries) == 1:
  229. return {
  230. **entries[0],
  231. 'title': common_info.get('title'),
  232. }
  233. common_info['timestamp'] = traverse_obj(entries, (..., 'timestamp'), get_all=False)
  234. return self.playlist_result(entries, video_id, multi_video=True, **common_info)
  235. class AfreecaTVCatchStoryIE(AfreecaTVBaseIE):
  236. IE_NAME = 'afreecatv:catchstory'
  237. IE_DESC = 'afreecatv.com catch story'
  238. _VALID_URL = r'https?://vod\.afreecatv\.com/player/(?P<id>\d+)/catchstory'
  239. _TESTS = [{
  240. 'url': 'https://vod.afreecatv.com/player/103247/catchstory',
  241. 'info_dict': {
  242. 'id': '103247',
  243. },
  244. 'playlist_count': 2,
  245. }]
  246. def _real_extract(self, url):
  247. video_id = self._match_id(url)
  248. data = self._download_json(
  249. 'https://api.m.afreecatv.com/catchstory/a/view', video_id, headers={'Referer': url},
  250. query={'aStoryListIdx': '', 'nStoryIdx': video_id}, impersonate=True)
  251. return self.playlist_result(self._entries(data), video_id)
  252. @staticmethod
  253. def _entries(data):
  254. # 'files' is always a list with 1 element
  255. yield from traverse_obj(data, (
  256. 'data', lambda _, v: v['story_type'] == 'catch',
  257. 'catch_list', lambda _, v: v['files'][0]['file'], {
  258. 'id': ('files', 0, 'file_info_key', {str}),
  259. 'url': ('files', 0, 'file', {url_or_none}),
  260. 'duration': ('files', 0, 'duration', {functools.partial(int_or_none, scale=1000)}),
  261. 'title': ('title', {str}),
  262. 'uploader': ('writer_nick', {str}),
  263. 'uploader_id': ('writer_id', {str}),
  264. 'thumbnail': ('thumb', {url_or_none}),
  265. 'timestamp': ('write_timestamp', {int_or_none}),
  266. }))
  267. class AfreecaTVLiveIE(AfreecaTVBaseIE):
  268. IE_NAME = 'afreecatv:live'
  269. IE_DESC = 'afreecatv.com livestreams'
  270. _VALID_URL = r'https?://play\.afreeca(?:tv)?\.com/(?P<id>[^/]+)(?:/(?P<bno>\d+))?'
  271. _TESTS = [{
  272. 'url': 'https://play.afreecatv.com/pyh3646/237852185',
  273. 'info_dict': {
  274. 'id': '237852185',
  275. 'ext': 'mp4',
  276. 'title': '【 우루과이 오늘은 무슨일이? 】',
  277. 'uploader': '박진우[JINU]',
  278. 'uploader_id': 'pyh3646',
  279. 'timestamp': 1640661495,
  280. 'is_live': True,
  281. },
  282. 'skip': 'Livestream has ended',
  283. }, {
  284. 'url': 'https://play.afreecatv.com/pyh3646/237852185',
  285. 'only_matching': True,
  286. }, {
  287. 'url': 'https://play.afreecatv.com/pyh3646',
  288. 'only_matching': True,
  289. }]
  290. _LIVE_API_URL = 'https://live.afreecatv.com/afreeca/player_live_api.php'
  291. _WORKING_CDNS = [
  292. 'gcp_cdn', # live-global-cdn-v02.afreecatv.com
  293. 'gs_cdn_pc_app', # pc-app.stream.afreecatv.com
  294. 'gs_cdn_mobile_web', # mobile-web.stream.afreecatv.com
  295. 'gs_cdn_pc_web', # pc-web.stream.afreecatv.com
  296. ]
  297. _BAD_CDNS = [
  298. 'gs_cdn', # chromecast.afreeca.gscdn.com (cannot resolve)
  299. 'gs_cdn_chromecast', # chromecast.stream.afreecatv.com (HTTP Error 400)
  300. 'azure_cdn', # live-global-cdn-v01.afreecatv.com (cannot resolve)
  301. 'aws_cf', # live-global-cdn-v03.afreecatv.com (cannot resolve)
  302. 'kt_cdn', # kt.stream.afreecatv.com (HTTP Error 400)
  303. ]
  304. def _extract_formats(self, channel_info, broadcast_no, aid):
  305. stream_base_url = channel_info.get('RMD') or 'https://livestream-manager.afreecatv.com'
  306. # If user has not passed CDN IDs, try API-provided CDN ID followed by other working CDN IDs
  307. default_cdn_ids = orderedSet([
  308. *traverse_obj(channel_info, ('CDN', {str}, all, lambda _, v: v not in self._BAD_CDNS)),
  309. *self._WORKING_CDNS,
  310. ])
  311. cdn_ids = self._configuration_arg('cdn', default_cdn_ids)
  312. for attempt, cdn_id in enumerate(cdn_ids, start=1):
  313. m3u8_url = traverse_obj(self._download_json(
  314. urljoin(stream_base_url, 'broad_stream_assign.html'), broadcast_no,
  315. f'Downloading {cdn_id} stream info', f'Unable to download {cdn_id} stream info',
  316. fatal=False, query={
  317. 'return_type': cdn_id,
  318. 'broad_key': f'{broadcast_no}-common-master-hls',
  319. }), ('view_url', {url_or_none}))
  320. try:
  321. return self._extract_m3u8_formats(
  322. m3u8_url, broadcast_no, 'mp4', m3u8_id='hls', query={'aid': aid},
  323. headers={'Referer': 'https://play.afreecatv.com/'})
  324. except ExtractorError as e:
  325. if attempt == len(cdn_ids):
  326. raise
  327. self.report_warning(
  328. f'{e.cause or e.msg}. Retrying... (attempt {attempt} of {len(cdn_ids)})')
  329. def _real_extract(self, url):
  330. broadcaster_id, broadcast_no = self._match_valid_url(url).group('id', 'bno')
  331. channel_info = traverse_obj(self._download_json(
  332. self._LIVE_API_URL, broadcaster_id, data=urlencode_postdata({'bid': broadcaster_id})),
  333. ('CHANNEL', {dict})) or {}
  334. broadcaster_id = channel_info.get('BJID') or broadcaster_id
  335. broadcast_no = channel_info.get('BNO') or broadcast_no
  336. if not broadcast_no:
  337. raise UserNotLive(video_id=broadcaster_id)
  338. password = self.get_param('videopassword')
  339. if channel_info.get('BPWD') == 'Y' and password is None:
  340. raise ExtractorError(
  341. 'This livestream is protected by a password, use the --video-password option',
  342. expected=True)
  343. token_info = traverse_obj(self._download_json(
  344. self._LIVE_API_URL, broadcast_no, 'Downloading access token for stream',
  345. 'Unable to download access token for stream', data=urlencode_postdata(filter_dict({
  346. 'bno': broadcast_no,
  347. 'stream_type': 'common',
  348. 'type': 'aid',
  349. 'quality': 'master',
  350. 'pwd': password,
  351. }))), ('CHANNEL', {dict})) or {}
  352. aid = token_info.get('AID')
  353. if not aid:
  354. result = token_info.get('RESULT')
  355. if result == 0:
  356. raise ExtractorError('This livestream has ended', expected=True)
  357. elif result == -6:
  358. self.raise_login_required('This livestream is for subscribers only', method='password')
  359. raise ExtractorError('Unable to extract access token')
  360. formats = self._extract_formats(channel_info, broadcast_no, aid)
  361. station_info = traverse_obj(self._download_json(
  362. 'https://st.afreecatv.com/api/get_station_status.php', broadcast_no,
  363. 'Downloading channel metadata', 'Unable to download channel metadata',
  364. query={'szBjId': broadcaster_id}, fatal=False), {dict}) or {}
  365. return {
  366. 'id': broadcast_no,
  367. 'title': channel_info.get('TITLE') or station_info.get('station_title'),
  368. 'uploader': channel_info.get('BJNICK') or station_info.get('station_name'),
  369. 'uploader_id': broadcaster_id,
  370. 'timestamp': unified_timestamp(station_info.get('broad_start')),
  371. 'formats': formats,
  372. 'is_live': True,
  373. 'http_headers': {'Referer': url},
  374. }
  375. class AfreecaTVUserIE(InfoExtractor):
  376. IE_NAME = 'afreecatv:user'
  377. _VALID_URL = r'https?://bj\.afreeca(?:tv)?\.com/(?P<id>[^/]+)/vods/?(?P<slug_type>[^/]+)?'
  378. _TESTS = [{
  379. 'url': 'https://bj.afreecatv.com/ryuryu24/vods/review',
  380. 'info_dict': {
  381. '_type': 'playlist',
  382. 'id': 'ryuryu24',
  383. 'title': 'ryuryu24 - review',
  384. },
  385. 'playlist_count': 218,
  386. }, {
  387. 'url': 'https://bj.afreecatv.com/parang1995/vods/highlight',
  388. 'info_dict': {
  389. '_type': 'playlist',
  390. 'id': 'parang1995',
  391. 'title': 'parang1995 - highlight',
  392. },
  393. 'playlist_count': 997,
  394. }, {
  395. 'url': 'https://bj.afreecatv.com/ryuryu24/vods',
  396. 'info_dict': {
  397. '_type': 'playlist',
  398. 'id': 'ryuryu24',
  399. 'title': 'ryuryu24 - all',
  400. },
  401. 'playlist_count': 221,
  402. }, {
  403. 'url': 'https://bj.afreecatv.com/ryuryu24/vods/balloonclip',
  404. 'info_dict': {
  405. '_type': 'playlist',
  406. 'id': 'ryuryu24',
  407. 'title': 'ryuryu24 - balloonclip',
  408. },
  409. 'playlist_count': 0,
  410. }]
  411. _PER_PAGE = 60
  412. def _fetch_page(self, user_id, user_type, page):
  413. page += 1
  414. info = self._download_json(f'https://bjapi.afreecatv.com/api/{user_id}/vods/{user_type}', user_id,
  415. query={'page': page, 'per_page': self._PER_PAGE, 'orderby': 'reg_date'},
  416. note=f'Downloading {user_type} video page {page}')
  417. for item in info['data']:
  418. yield self.url_result(
  419. f'https://vod.afreecatv.com/player/{item["title_no"]}/', AfreecaTVIE, item['title_no'])
  420. def _real_extract(self, url):
  421. user_id, user_type = self._match_valid_url(url).group('id', 'slug_type')
  422. user_type = user_type or 'all'
  423. entries = OnDemandPagedList(functools.partial(self._fetch_page, user_id, user_type), self._PER_PAGE)
  424. return self.playlist_result(entries, user_id, f'{user_id} - {user_type}')