Merge branch 'dcn' of github.com:remitamine/youtube-dl into remitamine-dcn
[youtube-dl] / youtube_dl / extractor / livestream.py
1 from __future__ import unicode_literals
2
3 import re
4 import itertools
5
6 from .common import InfoExtractor
7 from ..compat import (
8     compat_str,
9     compat_urlparse,
10 )
11 from ..utils import (
12     find_xpath_attr,
13     xpath_attr,
14     xpath_with_ns,
15     xpath_text,
16     orderedSet,
17     int_or_none,
18     float_or_none,
19     parse_iso8601,
20     determine_ext,
21 )
22
23
24 class LivestreamIE(InfoExtractor):
25     IE_NAME = 'livestream'
26     _VALID_URL = r'https?://(?:new\.)?livestream\.com/(?:accounts/(?P<account_id>\d+)|(?P<account_name>[^/]+))/(?:events/(?P<event_id>\d+)|(?P<event_name>[^/]+))(?:/videos/(?P<id>\d+))?'
27     _TESTS = [{
28         'url': 'http://new.livestream.com/CoheedandCambria/WebsterHall/videos/4719370',
29         'md5': '53274c76ba7754fb0e8d072716f2292b',
30         'info_dict': {
31             'id': '4719370',
32             'ext': 'mp4',
33             'title': 'Live from Webster Hall NYC',
34             'timestamp': 1350008072,
35             'upload_date': '20121012',
36             'duration': 5968.0,
37             'like_count': int,
38             'view_count': int,
39             'thumbnail': 're:^http://.*\.jpg$'
40         }
41     }, {
42         'url': 'http://new.livestream.com/tedx/cityenglish',
43         'info_dict': {
44             'title': 'TEDCity2.0 (English)',
45             'id': '2245590',
46         },
47         'playlist_mincount': 4,
48     }, {
49         'url': 'http://new.livestream.com/chess24/tatasteelchess',
50         'info_dict': {
51             'title': 'Tata Steel Chess',
52             'id': '3705884',
53         },
54         'playlist_mincount': 60,
55     }, {
56         'url': 'https://new.livestream.com/accounts/362/events/3557232/videos/67864563/player?autoPlay=false&height=360&mute=false&width=640',
57         'only_matching': True,
58     }, {
59         'url': 'http://livestream.com/bsww/concacafbeachsoccercampeonato2015',
60         'only_matching': True,
61     }]
62     _API_URL_TEMPLATE = 'http://livestream.com/api/accounts/%s/events/%s'
63
64     def _parse_smil_formats(self, smil, smil_url, video_id, namespace=None, f4m_params=None, transform_rtmp_url=None):
65         base_ele = find_xpath_attr(
66             smil, self._xpath_ns('.//meta', namespace), 'name', 'httpBase')
67         base = base_ele.get('content') if base_ele else 'http://livestreamvod-f.akamaihd.net/'
68
69         formats = []
70         video_nodes = smil.findall(self._xpath_ns('.//video', namespace))
71
72         for vn in video_nodes:
73             tbr = int_or_none(vn.attrib.get('system-bitrate'), 1000)
74             furl = (
75                 '%s%s?v=3.0.3&fp=WIN%%2014,0,0,145' % (base, vn.attrib['src']))
76             if 'clipBegin' in vn.attrib:
77                 furl += '&ssek=' + vn.attrib['clipBegin']
78             formats.append({
79                 'url': furl,
80                 'format_id': 'smil_%d' % tbr,
81                 'ext': 'flv',
82                 'tbr': tbr,
83                 'preference': -1000,
84             })
85         return formats
86
87     def _extract_video_info(self, video_data):
88         video_id = compat_str(video_data['id'])
89
90         FORMAT_KEYS = (
91             ('sd', 'progressive_url'),
92             ('hd', 'progressive_url_hd'),
93         )
94
95         formats = []
96         for format_id, key in FORMAT_KEYS:
97             video_url = video_data.get(key)
98             if video_url:
99                 ext = determine_ext(video_url)
100                 if ext == 'm3u8':
101                     continue
102                 bitrate = int_or_none(self._search_regex(
103                     r'(\d+)\.%s' % ext, video_url, 'bitrate', default=None))
104                 formats.append({
105                     'url': video_url,
106                     'format_id': format_id,
107                     'tbr': bitrate,
108                     'ext': ext,
109                 })
110
111         smil_url = video_data.get('smil_url')
112         if smil_url:
113             smil_formats = self._extract_smil_formats(smil_url, video_id)
114             if smil_formats:
115                 formats.extend(smil_formats)
116
117         m3u8_url = video_data.get('m3u8_url')
118         if m3u8_url:
119             m3u8_formats = self._extract_m3u8_formats(
120                 m3u8_url, video_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False)
121             if m3u8_formats:
122                 formats.extend(m3u8_formats)
123
124         f4m_url = video_data.get('f4m_url')
125         if f4m_url:
126             f4m_formats = self._extract_f4m_formats(
127                 f4m_url, video_id, f4m_id='hds', fatal=False)
128             if f4m_formats:
129                 formats.extend(f4m_formats)
130         self._sort_formats(formats)
131
132         comments = [{
133             'author_id': comment.get('author_id'),
134             'author': comment.get('author', {}).get('full_name'),
135             'id': comment.get('id'),
136             'text': comment['text'],
137             'timestamp': parse_iso8601(comment.get('created_at')),
138         } for comment in video_data.get('comments', {}).get('data', [])]
139
140         return {
141             'id': video_id,
142             'formats': formats,
143             'title': video_data['caption'],
144             'description': video_data.get('description'),
145             'thumbnail': video_data.get('thumbnail_url'),
146             'duration': float_or_none(video_data.get('duration'), 1000),
147             'timestamp': parse_iso8601(video_data.get('publish_at')),
148             'like_count': video_data.get('likes', {}).get('total'),
149             'comment_count': video_data.get('comments', {}).get('total'),
150             'view_count': video_data.get('views'),
151             'comments': comments,
152         }
153
154     def _extract_stream_info(self, stream_info):
155         broadcast_id = stream_info['broadcast_id']
156         is_live = stream_info.get('is_live')
157
158         formats = []
159         smil_url = stream_info.get('play_url')
160         if smil_url:
161             smil_formats = self._extract_smil_formats(smil_url, broadcast_id)
162             if smil_formats:
163                 formats.extend(smil_formats)
164
165         entry_protocol = 'm3u8' if is_live else 'm3u8_native'
166         m3u8_url = stream_info.get('m3u8_url')
167         if m3u8_url:
168             m3u8_formats = self._extract_m3u8_formats(
169                 m3u8_url, broadcast_id, 'mp4', entry_protocol, m3u8_id='hls', fatal=False)
170             if m3u8_formats:
171                 formats.extend(m3u8_formats)
172
173         rtsp_url = stream_info.get('rtsp_url')
174         if rtsp_url:
175             formats.append({
176                 'url': rtsp_url,
177                 'format_id': 'rtsp',
178             })
179         self._sort_formats(formats)
180
181         return {
182             'id': broadcast_id,
183             'formats': formats,
184             'title': self._live_title(stream_info['stream_title']) if is_live else stream_info['stream_title'],
185             'thumbnail': stream_info.get('thumbnail_url'),
186             'is_live': is_live,
187         }
188
189     def _extract_event(self, event_data):
190         event_id = compat_str(event_data['id'])
191         account_id = compat_str(event_data['owner_account_id'])
192         feed_root_url = self._API_URL_TEMPLATE % (account_id, event_id) + '/feed.json'
193
194         stream_info = event_data.get('stream_info')
195         if stream_info:
196             return self._extract_stream_info(stream_info)
197
198         last_video = None
199         entries = []
200         for i in itertools.count(1):
201             if last_video is None:
202                 info_url = feed_root_url
203             else:
204                 info_url = '{root}?&id={id}&newer=-1&type=video'.format(
205                     root=feed_root_url, id=last_video)
206             videos_info = self._download_json(
207                 info_url, event_id, 'Downloading page {0}'.format(i))['data']
208             videos_info = [v['data'] for v in videos_info if v['type'] == 'video']
209             if not videos_info:
210                 break
211             for v in videos_info:
212                 entries.append(self.url_result(
213                     'http://livestream.com/accounts/%s/events/%s/videos/%s' % (account_id, event_id, v['id']),
214                     'Livestream', v['id'], v['caption']))
215             last_video = videos_info[-1]['id']
216         return self.playlist_result(entries, event_id, event_data['full_name'])
217
218     def _real_extract(self, url):
219         mobj = re.match(self._VALID_URL, url)
220         video_id = mobj.group('id')
221         event = mobj.group('event_id') or mobj.group('event_name')
222         account = mobj.group('account_id') or mobj.group('account_name')
223         api_url = self._API_URL_TEMPLATE % (account, event)
224         if video_id:
225             video_data = self._download_json(
226                 api_url + '/videos/%s' % video_id, video_id)
227             return self._extract_video_info(video_data)
228         else:
229             event_data = self._download_json(api_url, video_id)
230             return self._extract_event(event_data)
231
232
233 # The original version of Livestream uses a different system
234 class LivestreamOriginalIE(InfoExtractor):
235     IE_NAME = 'livestream:original'
236     _VALID_URL = r'''(?x)https?://original\.livestream\.com/
237         (?P<user>[^/\?#]+)(?:/(?P<type>video|folder)
238         (?:(?:\?.*?Id=|/)(?P<id>.*?)(&|$))?)?
239         '''
240     _TESTS = [{
241         'url': 'http://original.livestream.com/dealbook/video?clipId=pla_8aa4a3f1-ba15-46a4-893b-902210e138fb',
242         'info_dict': {
243             'id': 'pla_8aa4a3f1-ba15-46a4-893b-902210e138fb',
244             'ext': 'mp4',
245             'title': 'Spark 1 (BitCoin) with Cameron Winklevoss & Tyler Winklevoss of Winklevoss Capital',
246             'duration': 771.301,
247             'view_count': int,
248         },
249     }, {
250         'url': 'https://original.livestream.com/newplay/folder?dirId=a07bf706-d0e4-4e75-a747-b021d84f2fd3',
251         'info_dict': {
252             'id': 'a07bf706-d0e4-4e75-a747-b021d84f2fd3',
253         },
254         'playlist_mincount': 4,
255     }, {
256         # live stream
257         'url': 'http://original.livestream.com/znsbahamas',
258         'only_matching': True,
259     }]
260
261     def _extract_video_info(self, user, video_id):
262         api_url = 'http://x%sx.api.channel.livestream.com/2.0/clipdetails?extendedInfo=true&id=%s' % (user, video_id)
263         info = self._download_xml(api_url, video_id)
264
265         item = info.find('channel').find('item')
266         title = xpath_text(item, 'title')
267         media_ns = {'media': 'http://search.yahoo.com/mrss'}
268         thumbnail_url = xpath_attr(
269             item, xpath_with_ns('media:thumbnail', media_ns), 'url')
270         duration = float_or_none(xpath_attr(
271             item, xpath_with_ns('media:content', media_ns), 'duration'))
272         ls_ns = {'ls': 'http://api.channel.livestream.com/2.0'}
273         view_count = int_or_none(xpath_text(
274             item, xpath_with_ns('ls:viewsCount', ls_ns)))
275
276         return {
277             'id': video_id,
278             'title': title,
279             'thumbnail': thumbnail_url,
280             'duration': duration,
281             'view_count': view_count,
282         }
283
284     def _extract_video_formats(self, video_data, video_id, entry_protocol):
285         formats = []
286
287         progressive_url = video_data.get('progressiveUrl')
288         if progressive_url:
289             formats.append({
290                 'url': progressive_url,
291                 'format_id': 'http',
292             })
293
294         m3u8_url = video_data.get('httpUrl')
295         if m3u8_url:
296             m3u8_formats = self._extract_m3u8_formats(
297                 m3u8_url, video_id, 'mp4', entry_protocol, m3u8_id='hls', fatal=False)
298             if m3u8_formats:
299                 formats.extend(m3u8_formats)
300
301         rtsp_url = video_data.get('rtspUrl')
302         if rtsp_url:
303             formats.append({
304                 'url': rtsp_url,
305                 'format_id': 'rtsp',
306             })
307
308         self._sort_formats(formats)
309         return formats
310
311     def _extract_folder(self, url, folder_id):
312         webpage = self._download_webpage(url, folder_id)
313         paths = orderedSet(re.findall(
314             r'''(?x)(?:
315                 <li\s+class="folder">\s*<a\s+href="|
316                 <a\s+href="(?=https?://livestre\.am/)
317             )([^"]+)"''', webpage))
318
319         entries = [{
320             '_type': 'url',
321             'url': compat_urlparse.urljoin(url, p),
322         } for p in paths]
323
324         return self.playlist_result(entries, folder_id)
325
326     def _real_extract(self, url):
327         mobj = re.match(self._VALID_URL, url)
328         user = mobj.group('user')
329         url_type = mobj.group('type')
330         content_id = mobj.group('id')
331         if url_type == 'folder':
332             return self._extract_folder(url, content_id)
333         else:
334             # this url is used on mobile devices
335             stream_url = 'http://x%sx.api.channel.livestream.com/3.0/getstream.json' % user
336             info = {}
337             if content_id:
338                 stream_url += '?id=%s' % content_id
339                 info = self._extract_video_info(user, content_id)
340             else:
341                 content_id = user
342                 webpage = self._download_webpage(url, content_id)
343                 info = {
344                     'title': self._og_search_title(webpage),
345                     'description': self._og_search_description(webpage),
346                     'thumbnail': self._search_regex(r'channelLogo.src\s*=\s*"([^"]+)"', webpage, 'thumbnail', None),
347                 }
348             video_data = self._download_json(stream_url, content_id)
349             is_live = video_data.get('isLive')
350             entry_protocol = 'm3u8' if is_live else 'm3u8_native'
351             info.update({
352                 'id': content_id,
353                 'title': self._live_title(info['title']) if is_live else info['title'],
354                 'formats': self._extract_video_formats(video_data, content_id, entry_protocol),
355                 'is_live': is_live,
356             })
357             return info
358
359
360 # The server doesn't support HEAD request, the generic extractor can't detect
361 # the redirection
362 class LivestreamShortenerIE(InfoExtractor):
363     IE_NAME = 'livestream:shortener'
364     IE_DESC = False  # Do not list
365     _VALID_URL = r'https?://livestre\.am/(?P<id>.+)'
366
367     def _real_extract(self, url):
368         mobj = re.match(self._VALID_URL, url)
369         id = mobj.group('id')
370         webpage = self._download_webpage(url, id)
371
372         return {
373             '_type': 'url',
374             'url': self._og_search_url(webpage),
375         }