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