[dcn] make m3u8 formats extraction non fatal
[youtube-dl] / youtube_dl / extractor / livestream.py
1 from __future__ import unicode_literals
2
3 import re
4 import json
5 import itertools
6
7 from .common import InfoExtractor
8 from ..compat import (
9     compat_str,
10     compat_urllib_parse_urlparse,
11     compat_urlparse,
12 )
13 from ..utils import (
14     ExtractorError,
15     find_xpath_attr,
16     int_or_none,
17     orderedSet,
18     xpath_with_ns,
19 )
20
21
22 class LivestreamIE(InfoExtractor):
23     IE_NAME = 'livestream'
24     _VALID_URL = r'https?://(?:new\.)?livestream\.com/.*?/(?P<event_name>.*?)(/videos/(?P<id>[0-9]+)(?:/player)?)?/?(?:$|[?#])'
25     _TESTS = [{
26         'url': 'http://new.livestream.com/CoheedandCambria/WebsterHall/videos/4719370',
27         'md5': '53274c76ba7754fb0e8d072716f2292b',
28         'info_dict': {
29             'id': '4719370',
30             'ext': 'mp4',
31             'title': 'Live from Webster Hall NYC',
32             'upload_date': '20121012',
33             'like_count': int,
34             'view_count': int,
35             'thumbnail': 're:^http://.*\.jpg$'
36         }
37     }, {
38         'url': 'http://new.livestream.com/tedx/cityenglish',
39         'info_dict': {
40             'title': 'TEDCity2.0 (English)',
41             'id': '2245590',
42         },
43         'playlist_mincount': 4,
44     }, {
45         'url': 'http://new.livestream.com/chess24/tatasteelchess',
46         'info_dict': {
47             'title': 'Tata Steel Chess',
48             'id': '3705884',
49         },
50         'playlist_mincount': 60,
51     }, {
52         'url': 'https://new.livestream.com/accounts/362/events/3557232/videos/67864563/player?autoPlay=false&height=360&mute=false&width=640',
53         'only_matching': True,
54     }, {
55         'url': 'http://livestream.com/bsww/concacafbeachsoccercampeonato2015',
56         'only_matching': True,
57     }]
58
59     def _parse_smil(self, video_id, smil_url):
60         formats = []
61         _SWITCH_XPATH = (
62             './/{http://www.w3.org/2001/SMIL20/Language}body/'
63             '{http://www.w3.org/2001/SMIL20/Language}switch')
64         smil_doc = self._download_xml(
65             smil_url, video_id,
66             note='Downloading SMIL information',
67             errnote='Unable to download SMIL information',
68             fatal=False)
69         if smil_doc is False:  # Download failed
70             return formats
71         title_node = find_xpath_attr(
72             smil_doc, './/{http://www.w3.org/2001/SMIL20/Language}meta',
73             'name', 'title')
74         if title_node is None:
75             self.report_warning('Cannot find SMIL id')
76             switch_node = smil_doc.find(_SWITCH_XPATH)
77         else:
78             title_id = title_node.attrib['content']
79             switch_node = find_xpath_attr(
80                 smil_doc, _SWITCH_XPATH, 'id', title_id)
81         if switch_node is None:
82             raise ExtractorError('Cannot find switch node')
83         video_nodes = switch_node.findall(
84             '{http://www.w3.org/2001/SMIL20/Language}video')
85
86         for vn in video_nodes:
87             tbr = int_or_none(vn.attrib.get('system-bitrate'))
88             furl = (
89                 'http://livestream-f.akamaihd.net/%s?v=3.0.3&fp=WIN%%2014,0,0,145' %
90                 (vn.attrib['src']))
91             if 'clipBegin' in vn.attrib:
92                 furl += '&ssek=' + vn.attrib['clipBegin']
93             formats.append({
94                 'url': furl,
95                 'format_id': 'smil_%d' % tbr,
96                 'ext': 'flv',
97                 'tbr': tbr,
98                 'preference': -1000,
99             })
100         return formats
101
102     def _extract_video_info(self, video_data):
103         video_id = compat_str(video_data['id'])
104
105         FORMAT_KEYS = (
106             ('sd', 'progressive_url'),
107             ('hd', 'progressive_url_hd'),
108         )
109         formats = [{
110             'format_id': format_id,
111             'url': video_data[key],
112             'quality': i + 1,
113         } for i, (format_id, key) in enumerate(FORMAT_KEYS)
114             if video_data.get(key)]
115
116         smil_url = video_data.get('smil_url')
117         if smil_url:
118             formats.extend(self._parse_smil(video_id, smil_url))
119         self._sort_formats(formats)
120
121         return {
122             'id': video_id,
123             'formats': formats,
124             'title': video_data['caption'],
125             'thumbnail': video_data.get('thumbnail_url'),
126             'upload_date': video_data['updated_at'].replace('-', '')[:8],
127             'like_count': video_data.get('likes', {}).get('total'),
128             'view_count': video_data.get('views'),
129         }
130
131     def _extract_event(self, info):
132         event_id = compat_str(info['id'])
133         account = compat_str(info['owner_account_id'])
134         root_url = (
135             'https://new.livestream.com/api/accounts/{account}/events/{event}/'
136             'feed.json'.format(account=account, event=event_id))
137
138         def _extract_videos():
139             last_video = None
140             for i in itertools.count(1):
141                 if last_video is None:
142                     info_url = root_url
143                 else:
144                     info_url = '{root}?&id={id}&newer=-1&type=video'.format(
145                         root=root_url, id=last_video)
146                 videos_info = self._download_json(info_url, event_id, 'Downloading page {0}'.format(i))['data']
147                 videos_info = [v['data'] for v in videos_info if v['type'] == 'video']
148                 if not videos_info:
149                     break
150                 for v in videos_info:
151                     yield self._extract_video_info(v)
152                 last_video = videos_info[-1]['id']
153         return self.playlist_result(_extract_videos(), event_id, info['full_name'])
154
155     def _real_extract(self, url):
156         mobj = re.match(self._VALID_URL, url)
157         video_id = mobj.group('id')
158         event_name = mobj.group('event_name')
159         webpage = self._download_webpage(url, video_id or event_name)
160
161         og_video = self._og_search_video_url(
162             webpage, 'player url', fatal=False, default=None)
163         if og_video is not None:
164             query_str = compat_urllib_parse_urlparse(og_video).query
165             query = compat_urlparse.parse_qs(query_str)
166             if 'play_url' in query:
167                 api_url = query['play_url'][0].replace('.smil', '')
168                 info = json.loads(self._download_webpage(
169                     api_url, video_id, 'Downloading video info'))
170                 return self._extract_video_info(info)
171
172         config_json = self._search_regex(
173             r'window.config = ({.*?});', webpage, 'window config')
174         info = json.loads(config_json)['event']
175
176         def is_relevant(vdata, vid):
177             result = vdata['type'] == 'video'
178             if video_id is not None:
179                 result = result and compat_str(vdata['data']['id']) == vid
180             return result
181
182         if video_id is None:
183             # This is an event page:
184             return self._extract_event(info)
185         else:
186             videos = [self._extract_video_info(video_data['data'])
187                       for video_data in info['feed']['data']
188                       if is_relevant(video_data, video_id)]
189             if not videos:
190                 raise ExtractorError('Cannot find video %s' % video_id)
191             return videos[0]
192
193
194 # The original version of Livestream uses a different system
195 class LivestreamOriginalIE(InfoExtractor):
196     IE_NAME = 'livestream:original'
197     _VALID_URL = r'''(?x)https?://original\.livestream\.com/
198         (?P<user>[^/]+)/(?P<type>video|folder)
199         (?:\?.*?Id=|/)(?P<id>.*?)(&|$)
200         '''
201     _TESTS = [{
202         'url': 'http://original.livestream.com/dealbook/video?clipId=pla_8aa4a3f1-ba15-46a4-893b-902210e138fb',
203         'info_dict': {
204             'id': 'pla_8aa4a3f1-ba15-46a4-893b-902210e138fb',
205             'ext': 'mp4',
206             'title': 'Spark 1 (BitCoin) with Cameron Winklevoss & Tyler Winklevoss of Winklevoss Capital',
207         },
208     }, {
209         'url': 'https://original.livestream.com/newplay/folder?dirId=a07bf706-d0e4-4e75-a747-b021d84f2fd3',
210         'info_dict': {
211             'id': 'a07bf706-d0e4-4e75-a747-b021d84f2fd3',
212         },
213         'playlist_mincount': 4,
214     }]
215
216     def _extract_video(self, user, video_id):
217         api_url = 'http://x{0}x.api.channel.livestream.com/2.0/clipdetails?extendedInfo=true&id={1}'.format(user, video_id)
218
219         info = self._download_xml(api_url, video_id)
220         # this url is used on mobile devices
221         stream_url = 'http://x{0}x.api.channel.livestream.com/3.0/getstream.json?id={1}'.format(user, video_id)
222         stream_info = self._download_json(stream_url, video_id)
223         item = info.find('channel').find('item')
224         ns = {'media': 'http://search.yahoo.com/mrss'}
225         thumbnail_url = item.find(xpath_with_ns('media:thumbnail', ns)).attrib['url']
226
227         return {
228             'id': video_id,
229             'title': item.find('title').text,
230             'url': stream_info['progressiveUrl'],
231             'thumbnail': thumbnail_url,
232         }
233
234     def _extract_folder(self, url, folder_id):
235         webpage = self._download_webpage(url, folder_id)
236         paths = orderedSet(re.findall(
237             r'''(?x)(?:
238                 <li\s+class="folder">\s*<a\s+href="|
239                 <a\s+href="(?=https?://livestre\.am/)
240             )([^"]+)"''', webpage))
241
242         return {
243             '_type': 'playlist',
244             'id': folder_id,
245             'entries': [{
246                 '_type': 'url',
247                 'url': compat_urlparse.urljoin(url, p),
248             } for p in paths],
249         }
250
251     def _real_extract(self, url):
252         mobj = re.match(self._VALID_URL, url)
253         id = mobj.group('id')
254         user = mobj.group('user')
255         url_type = mobj.group('type')
256         if url_type == 'folder':
257             return self._extract_folder(url, id)
258         else:
259             return self._extract_video(user, id)
260
261
262 # The server doesn't support HEAD request, the generic extractor can't detect
263 # the redirection
264 class LivestreamShortenerIE(InfoExtractor):
265     IE_NAME = 'livestream:shortener'
266     IE_DESC = False  # Do not list
267     _VALID_URL = r'https?://livestre\.am/(?P<id>.+)'
268
269     def _real_extract(self, url):
270         mobj = re.match(self._VALID_URL, url)
271         id = mobj.group('id')
272         webpage = self._download_webpage(url, id)
273
274         return {
275             '_type': 'url',
276             'url': self._og_search_url(webpage),
277         }