[afreecatv] Add support for authentication (#14450)
[youtube-dl] / youtube_dl / 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     determine_ext,
10     ExtractorError,
11     int_or_none,
12     urlencode_postdata,
13     xpath_text,
14 )
15
16
17 class AfreecaTVIE(InfoExtractor):
18     IE_NAME = 'afreecatv'
19     IE_DESC = 'afreecatv.com'
20     _VALID_URL = r'''(?x)
21                     https?://
22                         (?:
23                             (?:(?:live|afbbs|www)\.)?afreeca(?:tv)?\.com(?::\d+)?
24                             (?:
25                                 /app/(?:index|read_ucc_bbs)\.cgi|
26                                 /player/[Pp]layer\.(?:swf|html)
27                             )\?.*?\bnTitleNo=|
28                             vod\.afreecatv\.com/PLAYER/STATION/
29                         )
30                         (?P<id>\d+)
31                     '''
32     _NETRC_MACHINE = 'afreecatv'
33     _TESTS = [{
34         'url': 'http://live.afreecatv.com:8079/app/index.cgi?szType=read_ucc_bbs&szBjId=dailyapril&nStationNo=16711924&nBbsNo=18605867&nTitleNo=36164052&szSkin=',
35         'md5': 'f72c89fe7ecc14c1b5ce506c4996046e',
36         'info_dict': {
37             'id': '36164052',
38             'ext': 'mp4',
39             'title': '데일리 에이프릴 요정들의 시상식!',
40             'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
41             'uploader': 'dailyapril',
42             'uploader_id': 'dailyapril',
43             'upload_date': '20160503',
44         },
45         'skip': 'Video is gone',
46     }, {
47         'url': 'http://afbbs.afreecatv.com:8080/app/read_ucc_bbs.cgi?nStationNo=16711924&nTitleNo=36153164&szBjId=dailyapril&nBbsNo=18605867',
48         'info_dict': {
49             'id': '36153164',
50             'title': "BJ유트루와 함께하는 '팅커벨 메이크업!'",
51             'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
52             'uploader': 'dailyapril',
53             'uploader_id': 'dailyapril',
54         },
55         'playlist_count': 2,
56         'playlist': [{
57             'md5': 'd8b7c174568da61d774ef0203159bf97',
58             'info_dict': {
59                 'id': '36153164_1',
60                 'ext': 'mp4',
61                 'title': "BJ유트루와 함께하는 '팅커벨 메이크업!'",
62                 'upload_date': '20160502',
63             },
64         }, {
65             'md5': '58f2ce7f6044e34439ab2d50612ab02b',
66             'info_dict': {
67                 'id': '36153164_2',
68                 'ext': 'mp4',
69                 'title': "BJ유트루와 함께하는 '팅커벨 메이크업!'",
70                 'upload_date': '20160502',
71             },
72         }],
73         'skip': 'Video is gone',
74     }, {
75         'url': 'http://vod.afreecatv.com/PLAYER/STATION/18650793',
76         'info_dict': {
77             'id': '18650793',
78             'ext': 'mp4',
79             'title': '오늘은 다르다! 쏘님의 우월한 위아래~ 댄스리액션!',
80             'thumbnail': r're:^https?://.*\.jpg$',
81             'uploader': '윈아디',
82             'uploader_id': 'badkids',
83             'duration': 107,
84         },
85         'params': {
86             'skip_download': True,
87         },
88     }, {
89         'url': 'http://vod.afreecatv.com/PLAYER/STATION/10481652',
90         'info_dict': {
91             'id': '10481652',
92             'title': "BJ유트루와 함께하는 '팅커벨 메이크업!'",
93             'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
94             'uploader': 'dailyapril',
95             'uploader_id': 'dailyapril',
96             'duration': 6492,
97         },
98         'playlist_count': 2,
99         'playlist': [{
100             'md5': 'd8b7c174568da61d774ef0203159bf97',
101             'info_dict': {
102                 'id': '20160502_c4c62b9d_174361386_1',
103                 'ext': 'mp4',
104                 'title': "BJ유트루와 함께하는 '팅커벨 메이크업!' (part 1)",
105                 'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
106                 'uploader': 'dailyapril',
107                 'uploader_id': 'dailyapril',
108                 'upload_date': '20160502',
109                 'duration': 3601,
110             },
111         }, {
112             'md5': '58f2ce7f6044e34439ab2d50612ab02b',
113             'info_dict': {
114                 'id': '20160502_39e739bb_174361386_2',
115                 'ext': 'mp4',
116                 'title': "BJ유트루와 함께하는 '팅커벨 메이크업!' (part 2)",
117                 'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
118                 'uploader': 'dailyapril',
119                 'uploader_id': 'dailyapril',
120                 'upload_date': '20160502',
121                 'duration': 2891,
122             },
123         }],
124         'params': {
125             'skip_download': True,
126         },
127     }, {
128         # non standard key
129         'url': 'http://vod.afreecatv.com/PLAYER/STATION/20515605',
130         'info_dict': {
131             'id': '20170411_BE689A0E_190960999_1_2_h',
132             'ext': 'mp4',
133             'title': '혼자사는여자집',
134             'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
135             'uploader': '♥이슬이',
136             'uploader_id': 'dasl8121',
137             'upload_date': '20170411',
138             'duration': 213,
139         },
140         'params': {
141             'skip_download': True,
142         },
143     }, {
144         # adult video
145         'url': 'http://vod.afreecatv.com/PLAYER/STATION/26542731',
146         'info_dict': {
147             'id': '20171001_F1AE1711_196617479_1',
148             'ext': 'mp4',
149             'title': '[생]서아 초심 찾기 방송 (part 1)',
150             'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
151             'uploader': 'BJ서아',
152             'uploader_id': 'bjdyrksu',
153             'upload_date': '20171001',
154             'duration': 3600,
155             'age_limit': 18,
156         },
157         'params': {
158             'skip_download': True,
159         },
160     }, {
161         'url': 'http://www.afreecatv.com/player/Player.swf?szType=szBjId=djleegoon&nStationNo=11273158&nBbsNo=13161095&nTitleNo=36327652',
162         'only_matching': True,
163     }, {
164         'url': 'http://vod.afreecatv.com/PLAYER/STATION/15055030',
165         'only_matching': True,
166     }]
167
168     @staticmethod
169     def parse_video_key(key):
170         video_key = {}
171         m = re.match(r'^(?P<upload_date>\d{8})_\w+_(?P<part>\d+)$', key)
172         if m:
173             video_key['upload_date'] = m.group('upload_date')
174             video_key['part'] = int(m.group('part'))
175         return video_key
176
177     def _real_initialize(self):
178         self._login()
179
180     def _login(self):
181         username, password = self._get_login_info()
182         if username is None:
183             return
184
185         login_form = {
186             'szWork': 'login',
187             'szType': 'json',
188             'szUid': username,
189             'szPassword': password,
190             'isSaveId': 'false',
191             'szScriptVar': 'oLoginRet',
192             'szAction': '',
193         }
194
195         response = self._download_json(
196             'https://login.afreecatv.com/app/LoginAction.php', None,
197             'Logging in', data=urlencode_postdata(login_form))
198
199         _ERRORS = {
200             -4: 'Your account has been suspended due to a violation of our terms and policies.',
201             -5: 'https://member.afreecatv.com/app/user_delete_progress.php',
202             -6: 'https://login.afreecatv.com/membership/changeMember.php',
203             -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.",
204             -9: 'https://member.afreecatv.com/app/pop_login_block.php',
205             -11: 'https://login.afreecatv.com/afreeca/second_login.php',
206             -12: 'https://member.afreecatv.com/app/user_security.php',
207             0: 'The username does not exist or you have entered the wrong password.',
208             -1: 'The username does not exist or you have entered the wrong password.',
209             -3: 'You have entered your username/password incorrectly.',
210             -7: 'You cannot use your Global AfreecaTV account to access Korean AfreecaTV.',
211             -10: 'Sorry for the inconvenience. \nYour account has been blocked due to an unauthorized access. \nPlease contact our Help Center for assistance.',
212             -32008: 'You have failed to log in. Please contact our Help Center.',
213         }
214
215         result = int_or_none(response.get('RESULT'))
216         if result != 1:
217             error = _ERRORS.get(result, 'You have failed to log in.')
218             raise ExtractorError(
219                 'Unable to login: %s said: %s' % (self.IE_NAME, error),
220                 expected=True)
221
222     def _real_extract(self, url):
223         video_id = self._match_id(url)
224
225         webpage = self._download_webpage(url, video_id)
226
227         if re.search(r'alert\(["\']This video has been deleted', webpage):
228             raise ExtractorError(
229                 'Video %s has been deleted' % video_id, expected=True)
230
231         station_id = self._search_regex(
232             r'nStationNo\s*=\s*(\d+)', webpage, 'station')
233         bbs_id = self._search_regex(
234             r'nBbsNo\s*=\s*(\d+)', webpage, 'bbs')
235         video_id = self._search_regex(
236             r'nTitleNo\s*=\s*(\d+)', webpage, 'title', default=video_id)
237         print(video_id, station_id, bbs_id)
238         video_xml = self._download_xml(
239             'http://afbbs.afreecatv.com:8080/api/video/get_video_info.php',
240             video_id, headers={
241                 'Referer': url,
242             }, query={
243                 'nTitleNo': video_id,
244                 'nStationNo': station_id,
245                 'nBbsNo': bbs_id,
246                 'partialView': 'SKIP_ADULT',
247             })
248
249         flag = xpath_text(video_xml, './track/flag', 'flag', default=None)
250         if flag and flag != 'SUCCEED':
251             raise ExtractorError(
252                 '%s said: %s' % (self.IE_NAME, flag), expected=True)
253
254         video_element = video_xml.findall(compat_xpath('./track/video'))[-1]
255         if video_element is None or video_element.text is None:
256             raise ExtractorError(
257                 'Video %s video does not exist' % video_id, expected=True)
258
259         video_url = video_element.text.strip()
260
261         title = xpath_text(video_xml, './track/title', 'title', fatal=True)
262
263         uploader = xpath_text(video_xml, './track/nickname', 'uploader')
264         uploader_id = xpath_text(video_xml, './track/bj_id', 'uploader id')
265         duration = int_or_none(xpath_text(
266             video_xml, './track/duration', 'duration'))
267         thumbnail = xpath_text(video_xml, './track/titleImage', 'thumbnail')
268
269         common_entry = {
270             'uploader': uploader,
271             'uploader_id': uploader_id,
272             'thumbnail': thumbnail,
273         }
274
275         info = common_entry.copy()
276         info.update({
277             'id': video_id,
278             'title': title,
279             'duration': duration,
280         })
281
282         if not video_url:
283             entries = []
284             file_elements = video_element.findall(compat_xpath('./file'))
285             one = len(file_elements) == 1
286             for file_num, file_element in enumerate(file_elements, start=1):
287                 file_url = file_element.text
288                 if not file_url:
289                     continue
290                 key = file_element.get('key', '')
291                 upload_date = self._search_regex(
292                     r'^(\d{8})_', key, 'upload date', default=None)
293                 file_duration = int_or_none(file_element.get('duration'))
294                 format_id = key if key else '%s_%s' % (video_id, file_num)
295                 if determine_ext(file_url) == 'm3u8':
296                     formats = self._extract_m3u8_formats(
297                         file_url, video_id, 'mp4', entry_protocol='m3u8_native',
298                         m3u8_id='hls',
299                         note='Downloading part %d m3u8 information' % file_num)
300                 else:
301                     formats = [{
302                         'url': file_url,
303                         'format_id': 'http',
304                     }]
305                 if not formats:
306                     continue
307                 self._sort_formats(formats)
308                 file_info = common_entry.copy()
309                 file_info.update({
310                     'id': format_id,
311                     'title': title if one else '%s (part %d)' % (title, file_num),
312                     'upload_date': upload_date,
313                     'duration': file_duration,
314                     'formats': formats,
315                 })
316                 entries.append(file_info)
317             entries_info = info.copy()
318             entries_info.update({
319                 '_type': 'multi_video',
320                 'entries': entries,
321             })
322             return entries_info
323
324         info = {
325             'id': video_id,
326             'title': title,
327             'uploader': uploader,
328             'uploader_id': uploader_id,
329             'duration': duration,
330             'thumbnail': thumbnail,
331         }
332
333         if determine_ext(video_url) == 'm3u8':
334             info['formats'] = self._extract_m3u8_formats(
335                 video_url, video_id, 'mp4', entry_protocol='m3u8_native',
336                 m3u8_id='hls')
337         else:
338             app, playpath = video_url.split('mp4:')
339             info.update({
340                 'url': app,
341                 'ext': 'flv',
342                 'play_path': 'mp4:' + playpath,
343                 'rtmp_live': True,  # downloading won't end without this
344             })
345
346         return info