Merge pull request #7892 from remitamine/livestream
[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                 bitrate = int_or_none(self._search_regex(
101                     r'(\d+)\.%s' % ext, video_url, 'bitrate', default=None))
102                 formats.append({
103                     'url': video_url,
104                     'format_id': format_id,
105                     'tbr': bitrate,
106                     'ext': ext,
107                 })
108
109         smil_url = video_data.get('smil_url')
110         if smil_url:
111             smil_formats = self._extract_smil_formats(smil_url, video_id)
112             if smil_formats:
113                 formats.extend(smil_formats)
114
115         m3u8_url = video_data.get('m3u8_url')
116         if m3u8_url:
117             m3u8_formats = self._extract_m3u8_formats(
118                 m3u8_url, video_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False)
119             if m3u8_formats:
120                 formats.extend(m3u8_formats)
121
122         f4m_url = video_data.get('f4m_url')
123         if f4m_url:
124             f4m_formats = self._extract_f4m_formats(
125                 f4m_url, video_id, f4m_id='hds', fatal=False)
126             if f4m_formats:
127                 formats.extend(f4m_formats)
128         self._sort_formats(formats)
129
130         comments = [{
131             'author_id': comment.get('author_id'),
132             'author': comment.get('author', {}).get('full_name'),
133             'id': comment.get('id'),
134             'text': comment['text'],
135             'timestamp': parse_iso8601(comment.get('created_at')),
136         } for comment in video_data.get('comments', {}).get('data', [])]
137
138         return {
139             'id': video_id,
140             'formats': formats,
141             'title': video_data['caption'],
142             'description': video_data.get('description'),
143             'thumbnail': video_data.get('thumbnail_url'),
144             'duration': float_or_none(video_data.get('duration'), 1000),
145             'timestamp': parse_iso8601(video_data.get('publish_at')),
146             'like_count': video_data.get('likes', {}).get('total'),
147             'comment_count': video_data.get('comments', {}).get('total'),
148             'view_count': video_data.get('views'),
149             'comments': comments,
150         }
151
152     def _extract_stream_info(self, stream_info):
153         broadcast_id = stream_info['broadcast_id']
154         is_live = stream_info.get('is_live')
155
156         formats = []
157         smil_url = stream_info.get('play_url')
158         if smil_url:
159             smil_formats = self._extract_smil_formats(smil_url, broadcast_id)
160             if smil_formats:
161                 formats.extend(smil_formats)
162
163         entry_protocol = 'm3u8' if is_live else 'm3u8_native'
164         m3u8_url = stream_info.get('m3u8_url')
165         if m3u8_url:
166             m3u8_formats = self._extract_m3u8_formats(
167                 m3u8_url, broadcast_id, 'mp4', entry_protocol, m3u8_id='hls', fatal=False)
168             if m3u8_formats:
169                 formats.extend(m3u8_formats)
170
171         rtsp_url = stream_info.get('rtsp_url')
172         if rtsp_url:
173             formats.append({
174                 'url': rtsp_url,
175                 'format_id': 'rtsp',
176             })
177         self._sort_formats(formats)
178
179         return {
180             'id': broadcast_id,
181             'formats': formats,
182             'title': self._live_title(stream_info['stream_title']) if is_live else stream_info['stream_title'],
183             'thumbnail': stream_info.get('thumbnail_url'),
184             'is_live': is_live,
185         }
186
187     def _extract_event(self, event_data):
188         event_id = compat_str(event_data['id'])
189         account_id = compat_str(event_data['owner_account_id'])
190         feed_root_url = self._API_URL_TEMPLATE % (account_id, event_id) + '/feed.json'
191
192         stream_info = event_data.get('stream_info')
193         if stream_info:
194             return self._extract_stream_info(stream_info)
195
196         last_video = None
197         entries = []
198         for i in itertools.count(1):
199             if last_video is None:
200                 info_url = feed_root_url
201             else:
202                 info_url = '{root}?&id={id}&newer=-1&type=video'.format(
203                     root=feed_root_url, id=last_video)
204             videos_info = self._download_json(
205                 info_url, event_id, 'Downloading page {0}'.format(i))['data']
206             videos_info = [v['data'] for v in videos_info if v['type'] == 'video']
207             if not videos_info:
208                 break
209             for v in videos_info:
210                 entries.append(self.url_result(
211                     'http://livestream.com/accounts/%s/events/%s/videos/%s' % (account_id, event_id, v['id']),
212                     'Livestream', v['id'], v['caption']))
213             last_video = videos_info[-1]['id']
214         return self.playlist_result(entries, event_id, event_data['full_name'])
215
216     def _real_extract(self, url):
217         mobj = re.match(self._VALID_URL, url)
218         video_id = mobj.group('id')
219         event = mobj.group('event_id') or mobj.group('event_name')
220         account = mobj.group('account_id') or mobj.group('account_name')
221         api_url = self._API_URL_TEMPLATE % (account, event)
222         if video_id:
223             video_data = self._download_json(
224                 api_url + '/videos/%s' % video_id, video_id)
225             return self._extract_video_info(video_data)
226         else:
227             event_data = self._download_json(api_url, video_id)
228             return self._extract_event(event_data)
229
230
231 # The original version of Livestream uses a different system
232 class LivestreamOriginalIE(InfoExtractor):
233     IE_NAME = 'livestream:original'
234     _VALID_URL = r'''(?x)https?://original\.livestream\.com/
235         (?P<user>[^/\?#]+)(?:/(?P<type>video|folder)
236         (?:(?:\?.*?Id=|/)(?P<id>.*?)(&|$))?)?
237         '''
238     _TESTS = [{
239         'url': 'http://original.livestream.com/dealbook/video?clipId=pla_8aa4a3f1-ba15-46a4-893b-902210e138fb',
240         'info_dict': {
241             'id': 'pla_8aa4a3f1-ba15-46a4-893b-902210e138fb',
242             'ext': 'mp4',
243             'title': 'Spark 1 (BitCoin) with Cameron Winklevoss & Tyler Winklevoss of Winklevoss Capital',
244             'duration': 771.301,
245             'view_count': int,
246         },
247     }, {
248         'url': 'https://original.livestream.com/newplay/folder?dirId=a07bf706-d0e4-4e75-a747-b021d84f2fd3',
249         'info_dict': {
250             'id': 'a07bf706-d0e4-4e75-a747-b021d84f2fd3',
251         },
252         'playlist_mincount': 4,
253     }, {
254         # live stream
255         'url': 'http://www.livestream.com/znsbahamas',
256         'only_matching': True,
257     }]
258
259     def _extract_video_info(self, user, video_id):
260         api_url = 'http://x%sx.api.channel.livestream.com/2.0/clipdetails?extendedInfo=true&id=%s' % (user, video_id)
261         info = self._download_xml(api_url, video_id)
262
263         item = info.find('channel').find('item')
264         title = xpath_text(item, 'title')
265         media_ns = {'media': 'http://search.yahoo.com/mrss'}
266         thumbnail_url = xpath_attr(
267             item, xpath_with_ns('media:thumbnail', media_ns), 'url')
268         duration = float_or_none(xpath_attr(
269             item, xpath_with_ns('media:content', media_ns), 'duration'))
270         ls_ns = {'ls': 'http://api.channel.livestream.com/2.0'}
271         view_count = int_or_none(xpath_text(
272             item, xpath_with_ns('ls:viewsCount', ls_ns)))
273
274         return {
275             'id': video_id,
276             'title': title,
277             'thumbnail': thumbnail_url,
278             'duration': duration,
279             'view_count': view_count,
280         }
281
282     def _extract_video_formats(self, video_data, video_id, entry_protocol):
283         formats = []
284
285         progressive_url = video_data.get('progressiveUrl')
286         if progressive_url:
287             formats.append({
288                 'url': progressive_url,
289                 'format_id': 'http',
290             })
291
292         m3u8_url = video_data.get('httpUrl')
293         if m3u8_url:
294             m3u8_formats = self._extract_m3u8_formats(
295                 m3u8_url, video_id, 'mp4', entry_protocol, m3u8_id='hls', fatal=False)
296             if m3u8_formats:
297                 formats.extend(m3u8_formats)
298
299         rtsp_url = video_data.get('rtspUrl')
300         if rtsp_url:
301             formats.append({
302                 'url': rtsp_url,
303                 'format_id': 'rtsp',
304             })
305
306         self._sort_formats(formats)
307         return formats
308
309     def _extract_folder(self, url, folder_id):
310         webpage = self._download_webpage(url, folder_id)
311         paths = orderedSet(re.findall(
312             r'''(?x)(?:
313                 <li\s+class="folder">\s*<a\s+href="|
314                 <a\s+href="(?=https?://livestre\.am/)
315             )([^"]+)"''', webpage))
316
317         entries = [{
318             '_type': 'url',
319             'url': compat_urlparse.urljoin(url, p),
320         } for p in paths]
321
322         return self.playlist_result(entries, folder_id)
323
324     def _real_extract(self, url):
325         mobj = re.match(self._VALID_URL, url)
326         user = mobj.group('user')
327         url_type = mobj.group('type')
328         content_id = mobj.group('id')
329         if url_type == 'folder':
330             return self._extract_folder(url, content_id)
331         else:
332             # this url is used on mobile devices
333             stream_url = 'http://x%sx.api.channel.livestream.com/3.0/getstream.json' % user
334             info = {}
335             if content_id:
336                 stream_url += '?id=%s' % content_id
337                 info = self._extract_video_info(user, content_id)
338             else:
339                 content_id = user
340                 webpage = self._download_webpage(url, content_id)
341                 info = {
342                     'title': self._og_search_title(webpage),
343                     'description': self._og_search_description(webpage),
344                     'thumbnail': self._search_regex(r'channelLogo.src\s*=\s*"([^"]+)"', webpage, 'thumbnail', None),
345                 }
346             video_data = self._download_json(stream_url, content_id)
347             is_live = video_data.get('isLive')
348             entry_protocol = 'm3u8' if is_live else 'm3u8_native'
349             info.update({
350                 'id': content_id,
351                 'title': self._live_title(info['title']) if is_live else info['title'],
352                 'formats': self._extract_video_formats(video_data, content_id, entry_protocol),
353                 'is_live': is_live,
354             })
355             return info
356
357
358 # The server doesn't support HEAD request, the generic extractor can't detect
359 # the redirection
360 class LivestreamShortenerIE(InfoExtractor):
361     IE_NAME = 'livestream:shortener'
362     IE_DESC = False  # Do not list
363     _VALID_URL = r'https?://livestre\.am/(?P<id>.+)'
364
365     def _real_extract(self, url):
366         mobj = re.match(self._VALID_URL, url)
367         id = mobj.group('id')
368         webpage = self._download_webpage(url, id)
369
370         return {
371             '_type': 'url',
372             'url': self._og_search_url(webpage),
373         }