afreecatv.py 21 KB

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