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