[afreecatv] Fix extraction (closes #12706)
[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     xpath_text,
13 )
14
15
16 class AfreecaTVIE(InfoExtractor):
17     IE_NAME = 'afreecatv'
18     IE_DESC = 'afreecatv.com'
19     _VALID_URL = r'''(?x)
20                     https?://
21                         (?:
22                             (?:(?:live|afbbs|www)\.)?afreeca(?:tv)?\.com(?::\d+)?
23                             (?:
24                                 /app/(?:index|read_ucc_bbs)\.cgi|
25                                 /player/[Pp]layer\.(?:swf|html)
26                             )\?.*?\bnTitleNo=|
27                             vod\.afreecatv\.com/PLAYER/STATION/
28                         )
29                         (?P<id>\d+)
30                     '''
31     _TESTS = [{
32         'url': 'http://live.afreecatv.com:8079/app/index.cgi?szType=read_ucc_bbs&szBjId=dailyapril&nStationNo=16711924&nBbsNo=18605867&nTitleNo=36164052&szSkin=',
33         'md5': 'f72c89fe7ecc14c1b5ce506c4996046e',
34         'info_dict': {
35             'id': '36164052',
36             'ext': 'mp4',
37             'title': '데일리 에이프릴 요정들의 시상식!',
38             'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
39             'uploader': 'dailyapril',
40             'uploader_id': 'dailyapril',
41             'upload_date': '20160503',
42         },
43         'skip': 'Video is gone',
44     }, {
45         'url': 'http://afbbs.afreecatv.com:8080/app/read_ucc_bbs.cgi?nStationNo=16711924&nTitleNo=36153164&szBjId=dailyapril&nBbsNo=18605867',
46         'info_dict': {
47             'id': '36153164',
48             'title': "BJ유트루와 함께하는 '팅커벨 메이크업!'",
49             'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
50             'uploader': 'dailyapril',
51             'uploader_id': 'dailyapril',
52         },
53         'playlist_count': 2,
54         'playlist': [{
55             'md5': 'd8b7c174568da61d774ef0203159bf97',
56             'info_dict': {
57                 'id': '36153164_1',
58                 'ext': 'mp4',
59                 'title': "BJ유트루와 함께하는 '팅커벨 메이크업!'",
60                 'upload_date': '20160502',
61             },
62         }, {
63             'md5': '58f2ce7f6044e34439ab2d50612ab02b',
64             'info_dict': {
65                 'id': '36153164_2',
66                 'ext': 'mp4',
67                 'title': "BJ유트루와 함께하는 '팅커벨 메이크업!'",
68                 'upload_date': '20160502',
69             },
70         }],
71         'skip': 'Video is gone',
72     }, {
73         'url': 'http://vod.afreecatv.com/PLAYER/STATION/18650793',
74         'info_dict': {
75             'id': '18650793',
76             'ext': 'mp4',
77             'title': '오늘은 다르다! 쏘님의 우월한 위아래~ 댄스리액션!',
78             'thumbnail': r're:^https?://.*\.jpg$',
79             'uploader': '윈아디',
80             'uploader_id': 'badkids',
81             'duration': 107,
82         },
83         'params': {
84             'skip_download': True,
85         },
86     }, {
87         'url': 'http://vod.afreecatv.com/PLAYER/STATION/10481652',
88         'info_dict': {
89             'id': '10481652',
90             'title': "BJ유트루와 함께하는 '팅커벨 메이크업!'",
91             'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
92             'uploader': 'dailyapril',
93             'uploader_id': 'dailyapril',
94             'duration': 6492,
95         },
96         'playlist_count': 2,
97         'playlist': [{
98             'md5': 'd8b7c174568da61d774ef0203159bf97',
99             'info_dict': {
100                 'id': '10481652_1',
101                 'ext': 'mp4',
102                 'title': "BJ유트루와 함께하는 '팅커벨 메이크업!' (part 1)",
103                 'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
104                 'uploader': 'dailyapril',
105                 'uploader_id': 'dailyapril',
106                 'upload_date': '20160502',
107                 'duration': 3601,
108             },
109         }, {
110             'md5': '58f2ce7f6044e34439ab2d50612ab02b',
111             'info_dict': {
112                 'id': '10481652_2',
113                 'ext': 'mp4',
114                 'title': "BJ유트루와 함께하는 '팅커벨 메이크업!' (part 2)",
115                 'thumbnail': 're:^https?://(?:video|st)img.afreecatv.com/.*$',
116                 'uploader': 'dailyapril',
117                 'uploader_id': 'dailyapril',
118                 'upload_date': '20160502',
119                 'duration': 2891,
120             },
121         }],
122         'params': {
123             'skip_download': True,
124         },
125     }, {
126         'url': 'http://www.afreecatv.com/player/Player.swf?szType=szBjId=djleegoon&nStationNo=11273158&nBbsNo=13161095&nTitleNo=36327652',
127         'only_matching': True,
128     }, {
129         'url': 'http://vod.afreecatv.com/PLAYER/STATION/15055030',
130         'only_matching': True,
131     }]
132
133     @staticmethod
134     def parse_video_key(key):
135         video_key = {}
136         m = re.match(r'^(?P<upload_date>\d{8})_\w+_(?P<part>\d+)$', key)
137         if m:
138             video_key['upload_date'] = m.group('upload_date')
139             video_key['part'] = int(m.group('part'))
140         return video_key
141
142     def _real_extract(self, url):
143         video_id = self._match_id(url)
144
145         video_xml = self._download_xml(
146             'http://afbbs.afreecatv.com:8080/api/video/get_video_info.php',
147             video_id, query={'nTitleNo': video_id})
148
149         video_element = video_xml.findall(compat_xpath('./track/video'))[1]
150         if video_element is None or video_element.text is None:
151             raise ExtractorError('Specified AfreecaTV video does not exist',
152                                  expected=True)
153
154         video_url = video_element.text.strip()
155
156         title = xpath_text(video_xml, './track/title', 'title', fatal=True)
157
158         uploader = xpath_text(video_xml, './track/nickname', 'uploader')
159         uploader_id = xpath_text(video_xml, './track/bj_id', 'uploader id')
160         duration = int_or_none(xpath_text(
161             video_xml, './track/duration', 'duration'))
162         thumbnail = xpath_text(video_xml, './track/titleImage', 'thumbnail')
163
164         common_entry = {
165             'uploader': uploader,
166             'uploader_id': uploader_id,
167             'thumbnail': thumbnail,
168         }
169
170         info = common_entry.copy()
171         info.update({
172             'id': video_id,
173             'title': title,
174             'duration': duration,
175         })
176
177         if not video_url:
178             entries = []
179             for file_num, file_element in enumerate(
180                     video_element.findall(compat_xpath('./file')), start=1):
181                 file_url = file_element.text
182                 if not file_url:
183                     continue
184                 video_key = self.parse_video_key(file_element.get('key', ''))
185                 if not video_key:
186                     continue
187                 file_duration = int_or_none(file_element.get('duration'))
188                 part = video_key.get('part', file_num)
189                 format_id = '%s_%s' % (video_id, part)
190                 formats = self._extract_m3u8_formats(
191                     file_url, video_id, 'mp4', entry_protocol='m3u8_native',
192                     m3u8_id='hls',
193                     note='Downloading part %d m3u8 information' % file_num)
194                 file_info = common_entry.copy()
195                 file_info.update({
196                     'id': format_id,
197                     'title': '%s (part %d)' % (title, part),
198                     'upload_date': video_key.get('upload_date'),
199                     'duration': file_duration,
200                     'formats': formats,
201                 })
202                 entries.append(file_info)
203             entries_info = info.copy()
204             entries_info.update({
205                 '_type': 'multi_video',
206                 'entries': entries,
207             })
208             return entries_info
209
210         info = {
211             'id': video_id,
212             'title': title,
213             'uploader': uploader,
214             'uploader_id': uploader_id,
215             'duration': duration,
216             'thumbnail': thumbnail,
217         }
218
219         if determine_ext(video_url) == 'm3u8':
220             info['formats'] = self._extract_m3u8_formats(
221                 video_url, video_id, 'mp4', entry_protocol='m3u8_native',
222                 m3u8_id='hls')
223         else:
224             app, playpath = video_url.split('mp4:')
225             info.update({
226                 'url': app,
227                 'ext': 'flv',
228                 'play_path': 'mp4:' + playpath,
229                 'rtmp_live': True,  # downloading won't end without this
230             })
231
232         return info
233
234
235 class AfreecaTVGlobalIE(AfreecaTVIE):
236     IE_NAME = 'afreecatv:global'
237     _VALID_URL = r'https?://(?:www\.)?afreeca\.tv/(?P<channel_id>\d+)(?:/v/(?P<video_id>\d+))?'
238     _TESTS = [{
239         'url': 'http://afreeca.tv/36853014/v/58301',
240         'info_dict': {
241             'id': '58301',
242             'title': 'tryhard top100',
243             'uploader_id': '36853014',
244             'uploader': 'makgi Hearthstone Live!',
245         },
246         'playlist_count': 3,
247     }]
248
249     def _real_extract(self, url):
250         channel_id, video_id = re.match(self._VALID_URL, url).groups()
251         video_type = 'video' if video_id else 'live'
252         query = {
253             'pt': 'view',
254             'bid': channel_id,
255         }
256         if video_id:
257             query['vno'] = video_id
258         video_data = self._download_json(
259             'http://api.afreeca.tv/%s/view_%s.php' % (video_type, video_type),
260             video_id or channel_id, query=query)['channel']
261
262         if video_data.get('result') != 1:
263             raise ExtractorError('%s said: %s' % (self.IE_NAME, video_data['remsg']))
264
265         title = video_data['title']
266
267         info = {
268             'thumbnail': video_data.get('thumb'),
269             'view_count': int_or_none(video_data.get('vcnt')),
270             'age_limit': int_or_none(video_data.get('grade')),
271             'uploader_id': channel_id,
272             'uploader': video_data.get('cname'),
273         }
274
275         if video_id:
276             entries = []
277             for i, f in enumerate(video_data.get('flist', [])):
278                 video_key = self.parse_video_key(f.get('key', ''))
279                 f_url = f.get('file')
280                 if not video_key or not f_url:
281                     continue
282                 entries.append({
283                     'id': '%s_%s' % (video_id, video_key.get('part', i + 1)),
284                     'title': title,
285                     'upload_date': video_key.get('upload_date'),
286                     'duration': int_or_none(f.get('length')),
287                     'url': f_url,
288                     'protocol': 'm3u8_native',
289                     'ext': 'mp4',
290                 })
291
292             info.update({
293                 'id': video_id,
294                 'title': title,
295                 'duration': int_or_none(video_data.get('length')),
296             })
297             if len(entries) > 1:
298                 info['_type'] = 'multi_video'
299                 info['entries'] = entries
300             elif len(entries) == 1:
301                 i = entries[0].copy()
302                 i.update(info)
303                 info = i
304         else:
305             formats = []
306             for s in video_data.get('strm', []):
307                 s_url = s.get('purl')
308                 if not s_url:
309                     continue
310                 stype = s.get('stype')
311                 if stype == 'HLS':
312                     formats.extend(self._extract_m3u8_formats(
313                         s_url, channel_id, 'mp4', m3u8_id=stype, fatal=False))
314                 elif stype == 'RTMP':
315                     format_id = [stype]
316                     label = s.get('label')
317                     if label:
318                         format_id.append(label)
319                     formats.append({
320                         'format_id': '-'.join(format_id),
321                         'url': s_url,
322                         'tbr': int_or_none(s.get('bps')),
323                         'height': int_or_none(s.get('brt')),
324                         'ext': 'flv',
325                         'rtmp_live': True,
326                     })
327             self._sort_formats(formats)
328
329             info.update({
330                 'id': channel_id,
331                 'title': self._live_title(title),
332                 'is_live': True,
333                 'formats': formats,
334             })
335
336         return info