[livestream] improve extraction, add support for live streams and extract more info...
[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(smil, self._xpath_ns('.//meta', namespace), 'name', 'httpBase')
66         base = base_ele.get('content') if base_ele else 'http://livestreamvod-f.akamaihd.net/'
67
68         formats = []
69         video_nodes = smil.findall(self._xpath_ns('.//video', namespace))
70
71         for vn in video_nodes:
72             tbr = int_or_none(vn.attrib.get('system-bitrate'), 1000)
73             furl = (
74                 '%s%s?v=3.0.3&fp=WIN%%2014,0,0,145' % (base, vn.attrib['src']))
75             if 'clipBegin' in vn.attrib:
76                 furl += '&ssek=' + vn.attrib['clipBegin']
77             formats.append({
78                 'url': furl,
79                 'format_id': 'smil_%d' % tbr,
80                 'ext': 'flv',
81                 'tbr': tbr,
82                 'preference': -1000,
83             })
84         return formats
85
86     def _extract_video_info(self, video_data):
87         video_id = compat_str(video_data['id'])
88
89         FORMAT_KEYS = (
90             ('sd', 'progressive_url'),
91             ('hd', 'progressive_url_hd'),
92         )
93
94         formats = []
95         for format_id, key in FORMAT_KEYS:
96             video_url = video_data.get(key)
97             if video_url:
98                 ext = determine_ext(video_url)
99                 bitrate = int_or_none(self._search_regex(r'(\d+)\.%s' % ext, video_url, 'bitrate', default=None))
100                 formats.append({
101                     'url': video_url,
102                     'format_id': format_id,
103                     'tbr': bitrate,
104                     'ext': ext,
105                 })
106
107         smil_url = video_data.get('smil_url')
108         if smil_url:
109             smil_formats = self._extract_smil_formats(smil_url, video_id)
110             if smil_formats:
111                 formats.extend(smil_formats)
112
113         m3u8_url = video_data.get('m3u8_url')
114         if m3u8_url:
115             m3u8_formats = self._extract_m3u8_formats(
116                 m3u8_url, video_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False)
117             if m3u8_formats:
118                 formats.extend(m3u8_formats)
119
120         f4m_url = video_data.get('f4m_url')
121         if f4m_url:
122             f4m_formats = self._extract_f4m_formats(f4m_url, video_id, f4m_id='hds', fatal=False)
123             if f4m_formats:
124                 formats.extend(f4m_formats)
125         self._sort_formats(formats)
126
127         comments = [{
128             'author_id': comment.get('author_id'),
129             'author': comment.get('author', {}).get('full_name'),
130             'id': comment.get('id'),
131             'text': comment['text'],
132             'timestamp': parse_iso8601(comment.get('created_at')),
133         } for comment in video_data.get('comments', {}).get('data', [])]
134
135         return {
136             'id': video_id,
137             'formats': formats,
138             'title': video_data['caption'],
139             'description': video_data.get('description'),
140             'thumbnail': video_data.get('thumbnail_url'),
141             'duration': float_or_none(video_data.get('duration'), 1000),
142             'timestamp': parse_iso8601(video_data.get('publish_at')),
143             'like_count': video_data.get('likes', {}).get('total'),
144             'comment_count': video_data.get('comments', {}).get('total'),
145             'view_count': video_data.get('views'),
146             'comments': comments,
147         }
148
149     def _extract_stream_info(self, stream_info):
150         broadcast_id = stream_info['broadcast_id']
151         is_live = stream_info.get('is_live')
152
153         formats = []
154         smil_url = stream_info.get('play_url')
155         if smil_url:
156             smil_formats = self._extract_smil_formats(smil_url, broadcast_id)
157             if smil_formats:
158                 formats.extend(smil_formats)
159
160         m3u8_url = stream_info.get('m3u8_url')
161         if m3u8_url:
162             m3u8_formats = self._extract_m3u8_formats(
163                 m3u8_url, broadcast_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False)
164             if m3u8_formats:
165                 formats.extend(m3u8_formats)
166
167         rtsp_url = stream_info.get('rtsp_url')
168         if rtsp_url:
169             formats.append({
170                 'url': rtsp_url,
171                 'format_id': 'rtsp',
172             })
173         self._sort_formats(formats)
174
175         return {
176             'id': broadcast_id,
177             'formats': formats,
178             'title': self._live_title(stream_info['stream_title']) if is_live else stream_info['stream_title'],
179             'thumbnail': stream_info.get('thumbnail_url'),
180             'is_live': is_live,
181         }
182
183     def _extract_event(self, event_data):
184         event_id = compat_str(event_data['id'])
185         account_id = compat_str(event_data['owner_account_id'])
186         feed_root_url = self._API_URL_TEMPLATE % (account_id, event_id) + '/feed.json'
187
188         stream_info = event_data.get('stream_info')
189         if stream_info:
190             return self._extract_stream_info(stream_info)
191
192         last_video = None
193         entries = []
194         for i in itertools.count(1):
195             if last_video is None:
196                 info_url = feed_root_url
197             else:
198                 info_url = '{root}?&id={id}&newer=-1&type=video'.format(
199                     root=feed_root_url, id=last_video)
200             videos_info = self._download_json(info_url, event_id, 'Downloading page {0}'.format(i))['data']
201             videos_info = [v['data'] for v in videos_info if v['type'] == 'video']
202             if not videos_info:
203                 break
204             for v in videos_info:
205                 entries.append(self.url_result(
206                     'http://livestream.com/accounts/%s/events/%s/videos/%s' % (account_id, event_id, v['id']),
207                     'Livestream', v['id'], v['caption']))
208             last_video = videos_info[-1]['id']
209         return self.playlist_result(entries, event_id, event_data['full_name'])
210
211     def _real_extract(self, url):
212         mobj = re.match(self._VALID_URL, url)
213         video_id = mobj.group('id')
214         event = mobj.group('event_id') or mobj.group('event_name')
215         account = mobj.group('account_id') or mobj.group('account_name')
216         api_url = self._API_URL_TEMPLATE % (account, event)
217         if video_id:
218             video_data = self._download_json(api_url + '/videos/%s' % video_id, video_id)
219             return self._extract_video_info(video_data)
220         else:
221             event_data = self._download_json(api_url, video_id)
222             return self._extract_event(event_data)
223
224
225 # The original version of Livestream uses a different system
226 class LivestreamOriginalIE(InfoExtractor):
227     IE_NAME = 'livestream:original'
228     _VALID_URL = r'''(?x)https?://original\.livestream\.com/
229         (?P<user>[^/]+)/(?P<type>video|folder)
230         (?:\?.*?Id=|/)(?P<id>.*?)(&|$)
231         '''
232     _TESTS = [{
233         'url': 'http://original.livestream.com/dealbook/video?clipId=pla_8aa4a3f1-ba15-46a4-893b-902210e138fb',
234         'info_dict': {
235             'id': 'pla_8aa4a3f1-ba15-46a4-893b-902210e138fb',
236             'ext': 'mp4',
237             'title': 'Spark 1 (BitCoin) with Cameron Winklevoss & Tyler Winklevoss of Winklevoss Capital',
238             'duration': 771.301,
239             'view_count': int,
240         },
241     }, {
242         'url': 'https://original.livestream.com/newplay/folder?dirId=a07bf706-d0e4-4e75-a747-b021d84f2fd3',
243         'info_dict': {
244             'id': 'a07bf706-d0e4-4e75-a747-b021d84f2fd3',
245         },
246         'playlist_mincount': 4,
247     }]
248
249     def _extract_video(self, user, video_id):
250         api_url = 'http://x{0}x.api.channel.livestream.com/2.0/clipdetails?extendedInfo=true&id={1}'.format(user, video_id)
251
252         info = self._download_xml(api_url, video_id)
253         # this url is used on mobile devices
254         stream_url = 'http://x{0}x.api.channel.livestream.com/3.0/getstream.json?id={1}'.format(user, video_id)
255         stream_info = self._download_json(stream_url, video_id)
256         is_live = stream_info.get('isLive')
257         item = info.find('channel').find('item')
258         media_ns = {'media': 'http://search.yahoo.com/mrss'}
259         thumbnail_url = xpath_attr(item, xpath_with_ns('media:thumbnail', media_ns), 'url')
260         duration = float_or_none(xpath_attr(item, xpath_with_ns('media:content', media_ns), 'duration'))
261         ls_ns = {'ls': 'http://api.channel.livestream.com/2.0'}
262         view_count = int_or_none(xpath_text(item, xpath_with_ns('ls:viewsCount', ls_ns)))
263
264         formats = [{
265             'url': stream_info['progressiveUrl'],
266             'format_id': 'http',
267         }]
268
269         m3u8_url = stream_info.get('httpUrl')
270         if m3u8_url:
271             m3u8_formats = self._extract_m3u8_formats(
272                 m3u8_url, video_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False)
273             if m3u8_formats:
274                 formats.extend(m3u8_formats)
275
276         rtsp_url = stream_info.get('rtspUrl')
277         if rtsp_url:
278             formats.append({
279                 'url': rtsp_url,
280                 'format_id': 'rtsp',
281             })
282         self._sort_formats(formats)
283
284         return {
285             'id': video_id,
286             'title': self._live_title(xpath_text(item, 'title')) if is_live else xpath_text(item, 'title'),
287             'formats': formats,
288             'thumbnail': thumbnail_url,
289             'duration': duration,
290             'view_count': view_count,
291             'is_live': is_live,
292         }
293
294     def _extract_folder(self, url, folder_id):
295         webpage = self._download_webpage(url, folder_id)
296         paths = orderedSet(re.findall(
297             r'''(?x)(?:
298                 <li\s+class="folder">\s*<a\s+href="|
299                 <a\s+href="(?=https?://livestre\.am/)
300             )([^"]+)"''', webpage))
301
302         entries = [{
303             '_type': 'url',
304             'url': compat_urlparse.urljoin(url, p),
305         } for p in paths]
306
307         return self.playlist_result(entries, folder_id)
308
309     def _real_extract(self, url):
310         mobj = re.match(self._VALID_URL, url)
311         id = mobj.group('id')
312         user = mobj.group('user')
313         url_type = mobj.group('type')
314         if url_type == 'folder':
315             return self._extract_folder(url, id)
316         else:
317             return self._extract_video(user, id)
318
319
320 # The server doesn't support HEAD request, the generic extractor can't detect
321 # the redirection
322 class LivestreamShortenerIE(InfoExtractor):
323     IE_NAME = 'livestream:shortener'
324     IE_DESC = False  # Do not list
325     _VALID_URL = r'https?://livestre\.am/(?P<id>.+)'
326
327     def _real_extract(self, url):
328         mobj = re.match(self._VALID_URL, url)
329         id = mobj.group('id')
330         webpage = self._download_webpage(url, id)
331
332         return {
333             '_type': 'url',
334             'url': self._og_search_url(webpage),
335         }