afreecatv.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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 AfreecaTVLiveIE(AfreecaTVBaseIE):
  236. IE_NAME = 'afreecatv:live'
  237. IE_DESC = 'afreecatv.com livestreams'
  238. _VALID_URL = r'https?://play\.afreeca(?:tv)?\.com/(?P<id>[^/]+)(?:/(?P<bno>\d+))?'
  239. _TESTS = [{
  240. 'url': 'https://play.afreecatv.com/pyh3646/237852185',
  241. 'info_dict': {
  242. 'id': '237852185',
  243. 'ext': 'mp4',
  244. 'title': '【 우루과이 오늘은 무슨일이? 】',
  245. 'uploader': '박진우[JINU]',
  246. 'uploader_id': 'pyh3646',
  247. 'timestamp': 1640661495,
  248. 'is_live': True,
  249. },
  250. 'skip': 'Livestream has ended',
  251. }, {
  252. 'url': 'https://play.afreecatv.com/pyh3646/237852185',
  253. 'only_matching': True,
  254. }, {
  255. 'url': 'https://play.afreecatv.com/pyh3646',
  256. 'only_matching': True,
  257. }]
  258. _LIVE_API_URL = 'https://live.afreecatv.com/afreeca/player_live_api.php'
  259. _WORKING_CDNS = [
  260. 'gcp_cdn', # live-global-cdn-v02.afreecatv.com
  261. 'gs_cdn_pc_app', # pc-app.stream.afreecatv.com
  262. 'gs_cdn_mobile_web', # mobile-web.stream.afreecatv.com
  263. 'gs_cdn_pc_web', # pc-web.stream.afreecatv.com
  264. ]
  265. _BAD_CDNS = [
  266. 'gs_cdn', # chromecast.afreeca.gscdn.com (cannot resolve)
  267. 'gs_cdn_chromecast', # chromecast.stream.afreecatv.com (HTTP Error 400)
  268. 'azure_cdn', # live-global-cdn-v01.afreecatv.com (cannot resolve)
  269. 'aws_cf', # live-global-cdn-v03.afreecatv.com (cannot resolve)
  270. 'kt_cdn', # kt.stream.afreecatv.com (HTTP Error 400)
  271. ]
  272. def _extract_formats(self, channel_info, broadcast_no, aid):
  273. stream_base_url = channel_info.get('RMD') or 'https://livestream-manager.afreecatv.com'
  274. # If user has not passed CDN IDs, try API-provided CDN ID followed by other working CDN IDs
  275. default_cdn_ids = orderedSet([
  276. *traverse_obj(channel_info, ('CDN', {str}, all, lambda _, v: v not in self._BAD_CDNS)),
  277. *self._WORKING_CDNS,
  278. ])
  279. cdn_ids = self._configuration_arg('cdn', default_cdn_ids)
  280. for attempt, cdn_id in enumerate(cdn_ids, start=1):
  281. m3u8_url = traverse_obj(self._download_json(
  282. urljoin(stream_base_url, 'broad_stream_assign.html'), broadcast_no,
  283. f'Downloading {cdn_id} stream info', f'Unable to download {cdn_id} stream info',
  284. fatal=False, query={
  285. 'return_type': cdn_id,
  286. 'broad_key': f'{broadcast_no}-common-master-hls',
  287. }), ('view_url', {url_or_none}))
  288. try:
  289. return self._extract_m3u8_formats(
  290. m3u8_url, broadcast_no, 'mp4', m3u8_id='hls', query={'aid': aid},
  291. headers={'Referer': 'https://play.afreecatv.com/'})
  292. except ExtractorError as e:
  293. if attempt == len(cdn_ids):
  294. raise
  295. self.report_warning(
  296. f'{e.cause or e.msg}. Retrying... (attempt {attempt} of {len(cdn_ids)})')
  297. def _real_extract(self, url):
  298. broadcaster_id, broadcast_no = self._match_valid_url(url).group('id', 'bno')
  299. channel_info = traverse_obj(self._download_json(
  300. self._LIVE_API_URL, broadcaster_id, data=urlencode_postdata({'bid': broadcaster_id})),
  301. ('CHANNEL', {dict})) or {}
  302. broadcaster_id = channel_info.get('BJID') or broadcaster_id
  303. broadcast_no = channel_info.get('BNO') or broadcast_no
  304. if not broadcast_no:
  305. raise UserNotLive(video_id=broadcaster_id)
  306. password = self.get_param('videopassword')
  307. if channel_info.get('BPWD') == 'Y' and password is None:
  308. raise ExtractorError(
  309. 'This livestream is protected by a password, use the --video-password option',
  310. expected=True)
  311. token_info = traverse_obj(self._download_json(
  312. self._LIVE_API_URL, broadcast_no, 'Downloading access token for stream',
  313. 'Unable to download access token for stream', data=urlencode_postdata(filter_dict({
  314. 'bno': broadcast_no,
  315. 'stream_type': 'common',
  316. 'type': 'aid',
  317. 'quality': 'master',
  318. 'pwd': password,
  319. }))), ('CHANNEL', {dict})) or {}
  320. aid = token_info.get('AID')
  321. if not aid:
  322. result = token_info.get('RESULT')
  323. if result == 0:
  324. raise ExtractorError('This livestream has ended', expected=True)
  325. elif result == -6:
  326. self.raise_login_required('This livestream is for subscribers only', method='password')
  327. raise ExtractorError('Unable to extract access token')
  328. formats = self._extract_formats(channel_info, broadcast_no, aid)
  329. station_info = traverse_obj(self._download_json(
  330. 'https://st.afreecatv.com/api/get_station_status.php', broadcast_no,
  331. 'Downloading channel metadata', 'Unable to download channel metadata',
  332. query={'szBjId': broadcaster_id}, fatal=False), {dict}) or {}
  333. return {
  334. 'id': broadcast_no,
  335. 'title': channel_info.get('TITLE') or station_info.get('station_title'),
  336. 'uploader': channel_info.get('BJNICK') or station_info.get('station_name'),
  337. 'uploader_id': broadcaster_id,
  338. 'timestamp': unified_timestamp(station_info.get('broad_start')),
  339. 'formats': formats,
  340. 'is_live': True,
  341. 'http_headers': {'Referer': url},
  342. }
  343. class AfreecaTVUserIE(InfoExtractor):
  344. IE_NAME = 'afreecatv:user'
  345. _VALID_URL = r'https?://bj\.afreeca(?:tv)?\.com/(?P<id>[^/]+)/vods/?(?P<slug_type>[^/]+)?'
  346. _TESTS = [{
  347. 'url': 'https://bj.afreecatv.com/ryuryu24/vods/review',
  348. 'info_dict': {
  349. '_type': 'playlist',
  350. 'id': 'ryuryu24',
  351. 'title': 'ryuryu24 - review',
  352. },
  353. 'playlist_count': 218,
  354. }, {
  355. 'url': 'https://bj.afreecatv.com/parang1995/vods/highlight',
  356. 'info_dict': {
  357. '_type': 'playlist',
  358. 'id': 'parang1995',
  359. 'title': 'parang1995 - highlight',
  360. },
  361. 'playlist_count': 997,
  362. }, {
  363. 'url': 'https://bj.afreecatv.com/ryuryu24/vods',
  364. 'info_dict': {
  365. '_type': 'playlist',
  366. 'id': 'ryuryu24',
  367. 'title': 'ryuryu24 - all',
  368. },
  369. 'playlist_count': 221,
  370. }, {
  371. 'url': 'https://bj.afreecatv.com/ryuryu24/vods/balloonclip',
  372. 'info_dict': {
  373. '_type': 'playlist',
  374. 'id': 'ryuryu24',
  375. 'title': 'ryuryu24 - balloonclip',
  376. },
  377. 'playlist_count': 0,
  378. }]
  379. _PER_PAGE = 60
  380. def _fetch_page(self, user_id, user_type, page):
  381. page += 1
  382. info = self._download_json(f'https://bjapi.afreecatv.com/api/{user_id}/vods/{user_type}', user_id,
  383. query={'page': page, 'per_page': self._PER_PAGE, 'orderby': 'reg_date'},
  384. note=f'Downloading {user_type} video page {page}')
  385. for item in info['data']:
  386. yield self.url_result(
  387. f'https://vod.afreecatv.com/player/{item["title_no"]}/', AfreecaTVIE, item['title_no'])
  388. def _real_extract(self, url):
  389. user_id, user_type = self._match_valid_url(url).group('id', 'slug_type')
  390. user_type = user_type or 'all'
  391. entries = OnDemandPagedList(functools.partial(self._fetch_page, user_id, user_type), self._PER_PAGE)
  392. return self.playlist_result(entries, user_id, f'{user_id} - {user_type}')