]> gitweb @ CieloNegro.org - youtube-dl.git/blob - youtube_dl/extractor/livestream.py
[generic] Remove debug statement
[youtube-dl.git] / youtube_dl / extractor / livestream.py
1 from __future__ import unicode_literals
2
3 import re
4 import json
5
6 from .common import InfoExtractor
7 from ..utils import (
8     compat_str,
9     compat_urllib_parse_urlparse,
10     compat_urlparse,
11     ExtractorError,
12     find_xpath_attr,
13     int_or_none,
14     orderedSet,
15     xpath_with_ns,
16 )
17
18
19 class LivestreamIE(InfoExtractor):
20     IE_NAME = 'livestream'
21     _VALID_URL = r'http://new\.livestream\.com/.*?/(?P<event_name>.*?)(/videos/(?P<id>\d+))?/?$'
22     _TEST = {
23         'url': 'http://new.livestream.com/CoheedandCambria/WebsterHall/videos/4719370',
24         'md5': '53274c76ba7754fb0e8d072716f2292b',
25         'info_dict': {
26             'id': '4719370',
27             'ext': 'mp4',
28             'title': 'Live from Webster Hall NYC',
29             'upload_date': '20121012',
30             'like_count': int,
31             'view_count': int,
32             'thumbnail': 're:^http://.*\.jpg$'
33         }
34     }
35
36     def _parse_smil(self, video_id, smil_url):
37         formats = []
38         _SWITCH_XPATH = (
39             './/{http://www.w3.org/2001/SMIL20/Language}body/'
40             '{http://www.w3.org/2001/SMIL20/Language}switch')
41         smil_doc = self._download_xml(
42             smil_url, video_id,
43             note='Downloading SMIL information',
44             errnote='Unable to download SMIL information',
45             fatal=False)
46         if smil_doc is False:  # Download failed
47             return formats
48         title_node = find_xpath_attr(
49             smil_doc, './/{http://www.w3.org/2001/SMIL20/Language}meta',
50             'name', 'title')
51         if title_node is None:
52             self.report_warning('Cannot find SMIL id')
53             switch_node = smil_doc.find(_SWITCH_XPATH)
54         else:
55             title_id = title_node.attrib['content']
56             switch_node = find_xpath_attr(
57                 smil_doc, _SWITCH_XPATH, 'id', title_id)
58         if switch_node is None:
59             raise ExtractorError('Cannot find switch node')
60         video_nodes = switch_node.findall(
61             '{http://www.w3.org/2001/SMIL20/Language}video')
62
63         for vn in video_nodes:
64             tbr = int_or_none(vn.attrib.get('system-bitrate'))
65             furl = (
66                 'http://livestream-f.akamaihd.net/%s?v=3.0.3&fp=WIN%%2014,0,0,145' %
67                 (vn.attrib['src']))
68             if 'clipBegin' in vn.attrib:
69                 furl += '&ssek=' + vn.attrib['clipBegin']
70             formats.append({
71                 'url': furl,
72                 'format_id': 'smil_%d' % tbr,
73                 'ext': 'flv',
74                 'tbr': tbr,
75                 'preference': -1000,
76             })
77         return formats
78
79     def _extract_video_info(self, video_data):
80         video_id = compat_str(video_data['id'])
81
82         FORMAT_KEYS = (
83             ('sd', 'progressive_url'),
84             ('hd', 'progressive_url_hd'),
85         )
86         formats = [{
87             'format_id': format_id,
88             'url': video_data[key],
89             'quality': i + 1,
90         } for i, (format_id, key) in enumerate(FORMAT_KEYS)
91             if video_data.get(key)]
92
93         smil_url = video_data.get('smil_url')
94         if smil_url:
95             formats.extend(self._parse_smil(video_id, smil_url))
96         self._sort_formats(formats)
97
98         return {
99             'id': video_id,
100             'formats': formats,
101             'title': video_data['caption'],
102             'thumbnail': video_data.get('thumbnail_url'),
103             'upload_date': video_data['updated_at'].replace('-', '')[:8],
104             'like_count': video_data.get('likes', {}).get('total'),
105             'view_count': video_data.get('views'),
106         }
107
108     def _real_extract(self, url):
109         mobj = re.match(self._VALID_URL, url)
110         video_id = mobj.group('id')
111         event_name = mobj.group('event_name')
112         webpage = self._download_webpage(url, video_id or event_name)
113
114         og_video = self._og_search_video_url(webpage, 'player url', fatal=False, default=None)
115         if og_video is None:
116             config_json = self._search_regex(
117                 r'window.config = ({.*?});', webpage, 'window config')
118             info = json.loads(config_json)['event']
119
120             def is_relevant(vdata, vid):
121                 result = vdata['type'] == 'video'
122                 if video_id is not None:
123                     result = result and compat_str(vdata['data']['id']) == vid
124                 return result
125
126             videos = [self._extract_video_info(video_data['data'])
127                       for video_data in info['feed']['data']
128                       if is_relevant(video_data, video_id)]
129             if video_id is None:
130                 # This is an event page:
131                 return self.playlist_result(videos, info['id'], info['full_name'])
132             else:
133                 if videos:
134                     return videos[0]
135         else:
136             query_str = compat_urllib_parse_urlparse(og_video).query
137             query = compat_urlparse.parse_qs(query_str)
138             api_url = query['play_url'][0].replace('.smil', '')
139             info = json.loads(self._download_webpage(
140                 api_url, video_id, 'Downloading video info'))
141             return self._extract_video_info(info)
142
143
144 # The original version of Livestream uses a different system
145 class LivestreamOriginalIE(InfoExtractor):
146     IE_NAME = 'livestream:original'
147     _VALID_URL = r'''(?x)https?://www\.livestream\.com/
148         (?P<user>[^/]+)/(?P<type>video|folder)
149         (?:\?.*?Id=|/)(?P<id>.*?)(&|$)
150         '''
151     _TEST = {
152         'url': 'http://www.livestream.com/dealbook/video?clipId=pla_8aa4a3f1-ba15-46a4-893b-902210e138fb',
153         'info_dict': {
154             'id': 'pla_8aa4a3f1-ba15-46a4-893b-902210e138fb',
155             'ext': 'flv',
156             'title': 'Spark 1 (BitCoin) with Cameron Winklevoss & Tyler Winklevoss of Winklevoss Capital',
157         },
158         'params': {
159             # rtmp
160             'skip_download': True,
161         },
162     }
163
164     def _extract_video(self, user, video_id):
165         api_url = 'http://x{0}x.api.channel.livestream.com/2.0/clipdetails?extendedInfo=true&id={1}'.format(user, video_id)
166
167         info = self._download_xml(api_url, video_id)
168         item = info.find('channel').find('item')
169         ns = {'media': 'http://search.yahoo.com/mrss'}
170         thumbnail_url = item.find(xpath_with_ns('media:thumbnail', ns)).attrib['url']
171         # Remove the extension and number from the path (like 1.jpg)
172         path = self._search_regex(r'(user-files/.+)_.*?\.jpg$', thumbnail_url, 'path')
173
174         return {
175             'id': video_id,
176             'title': item.find('title').text,
177             'url': 'rtmp://extondemand.livestream.com/ondemand',
178             'play_path': 'mp4:trans/dv15/mogulus-{0}.mp4'.format(path),
179             'ext': 'flv',
180             'thumbnail': thumbnail_url,
181         }
182
183     def _extract_folder(self, url, folder_id):
184         webpage = self._download_webpage(url, folder_id)
185         urls = orderedSet(re.findall(r'<a href="(https?://livestre\.am/.*?)"', webpage))
186
187         return {
188             '_type': 'playlist',
189             'id': folder_id,
190             'entries': [{
191                 '_type': 'url',
192                 'url': video_url,
193             } for video_url in urls],
194         }
195
196     def _real_extract(self, url):
197         mobj = re.match(self._VALID_URL, url)
198         id = mobj.group('id')
199         user = mobj.group('user')
200         url_type = mobj.group('type')
201         if url_type == 'folder':
202             return self._extract_folder(url, id)
203         else:
204             return self._extract_video(user, id)
205
206
207 # The server doesn't support HEAD request, the generic extractor can't detect
208 # the redirection
209 class LivestreamShortenerIE(InfoExtractor):
210     IE_NAME = 'livestream:shortener'
211     IE_DESC = False  # Do not list
212     _VALID_URL = r'https?://livestre\.am/(?P<id>.+)'
213
214     def _real_extract(self, url):
215         mobj = re.match(self._VALID_URL, url)
216         id = mobj.group('id')
217         webpage = self._download_webpage(url, id)
218
219         return {
220             '_type': 'url',
221             'url': self._og_search_url(webpage),
222         }