[livestream] Parse SMIL (#2713)
[youtube-dl] / 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 _extract_video_info(self, video_data):
37         video_id = compat_str(video_data['id'])
38
39         FORMAT_KEYS = (
40             ('sd', 'progressive_url'),
41             ('hd', 'progressive_url_hd'),
42         )
43         formats = [{
44             'format_id': format_id,
45             'url': video_data[key],
46             'quality': i + 1,
47         } for i, (format_id, key) in enumerate(FORMAT_KEYS)
48             if video_data.get(key)]
49
50         smil_url = video_data.get('smil_url')
51         if smil_url:
52             _SWITCH_XPATH = (
53                 './/{http://www.w3.org/2001/SMIL20/Language}body/'
54                 '{http://www.w3.org/2001/SMIL20/Language}switch')
55             smil_doc = self._download_xml(
56                 smil_url, video_id, note='Downloading SMIL information')
57
58             title_node = find_xpath_attr(
59                 smil_doc, './/{http://www.w3.org/2001/SMIL20/Language}meta',
60                 'name', 'title')
61             if title_node is None:
62                 self.report_warning('Cannot find SMIL id')
63                 switch_node = smil_doc.find(_SWITCH_XPATH)
64             else:
65                 title_id = title_node.attrib['content']
66                 switch_node = find_xpath_attr(
67                     smil_doc, _SWITCH_XPATH, 'id', title_id)
68             if switch_node is None:
69                 raise ExtractorError('Cannot find switch node')
70             video_nodes = switch_node.findall(
71                 '{http://www.w3.org/2001/SMIL20/Language}video')
72
73             for vn in video_nodes:
74                 tbr = int_or_none(vn.attrib.get('system-bitrate'))
75                 furl = (
76                     'http://livestream-f.akamaihd.net/%s?v=3.0.3&fp=WIN%%2014,0,0,145&seek=%s' %
77                     (vn.attrib['src'], 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         self._sort_formats(formats)
86
87         return {
88             'id': video_id,
89             'formats': formats,
90             'title': video_data['caption'],
91             'thumbnail': video_data.get('thumbnail_url'),
92             'upload_date': video_data['updated_at'].replace('-', '')[:8],
93             'like_count': video_data.get('likes', {}).get('total'),
94             'view_count': video_data.get('views'),
95         }
96
97     def _real_extract(self, url):
98         mobj = re.match(self._VALID_URL, url)
99         video_id = mobj.group('id')
100         event_name = mobj.group('event_name')
101         webpage = self._download_webpage(url, video_id or event_name)
102
103         if video_id is None:
104             # This is an event page:
105             config_json = self._search_regex(
106                 r'window.config = ({.*?});', webpage, 'window config')
107             info = json.loads(config_json)['event']
108             videos = [self._extract_video_info(video_data['data'])
109                 for video_data in info['feed']['data']
110                 if video_data['type'] == 'video']
111             return self.playlist_result(videos, info['id'], info['full_name'])
112         else:
113             og_video = self._og_search_video_url(webpage, 'player url')
114             query_str = compat_urllib_parse_urlparse(og_video).query
115             query = compat_urlparse.parse_qs(query_str)
116             api_url = query['play_url'][0].replace('.smil', '')
117             info = json.loads(self._download_webpage(
118                 api_url, video_id, 'Downloading video info'))
119             return self._extract_video_info(info)
120
121
122 # The original version of Livestream uses a different system
123 class LivestreamOriginalIE(InfoExtractor):
124     IE_NAME = 'livestream:original'
125     _VALID_URL = r'''(?x)https?://www\.livestream\.com/
126         (?P<user>[^/]+)/(?P<type>video|folder)
127         (?:\?.*?Id=|/)(?P<id>.*?)(&|$)
128         '''
129     _TEST = {
130         'url': 'http://www.livestream.com/dealbook/video?clipId=pla_8aa4a3f1-ba15-46a4-893b-902210e138fb',
131         'info_dict': {
132             'id': 'pla_8aa4a3f1-ba15-46a4-893b-902210e138fb',
133             'ext': 'flv',
134             'title': 'Spark 1 (BitCoin) with Cameron Winklevoss & Tyler Winklevoss of Winklevoss Capital',
135         },
136         'params': {
137             # rtmp
138             'skip_download': True,
139         },
140     }
141
142     def _extract_video(self, user, video_id):
143         api_url = 'http://x{0}x.api.channel.livestream.com/2.0/clipdetails?extendedInfo=true&id={1}'.format(user, video_id)
144
145         info = self._download_xml(api_url, video_id)
146         item = info.find('channel').find('item')
147         ns = {'media': 'http://search.yahoo.com/mrss'}
148         thumbnail_url = item.find(xpath_with_ns('media:thumbnail', ns)).attrib['url']
149         # Remove the extension and number from the path (like 1.jpg)
150         path = self._search_regex(r'(user-files/.+)_.*?\.jpg$', thumbnail_url, 'path')
151
152         return {
153             'id': video_id,
154             'title': item.find('title').text,
155             'url': 'rtmp://extondemand.livestream.com/ondemand',
156             'play_path': 'mp4:trans/dv15/mogulus-{0}.mp4'.format(path),
157             'ext': 'flv',
158             'thumbnail': thumbnail_url,
159         }
160
161     def _extract_folder(self, url, folder_id):
162         webpage = self._download_webpage(url, folder_id)
163         urls = orderedSet(re.findall(r'<a href="(https?://livestre\.am/.*?)"', webpage))
164
165         return {
166             '_type': 'playlist',
167             'id': folder_id,
168             'entries': [{
169                 '_type': 'url',
170                 'url': video_url,
171             } for video_url in urls],
172         }
173
174     def _real_extract(self, url):
175         mobj = re.match(self._VALID_URL, url)
176         id = mobj.group('id')
177         user = mobj.group('user')
178         url_type = mobj.group('type')
179         if url_type == 'folder':
180             return self._extract_folder(url, id)
181         else:
182             return self._extract_video(user, id)
183
184
185 # The server doesn't support HEAD request, the generic extractor can't detect
186 # the redirection
187 class LivestreamShortenerIE(InfoExtractor):
188     IE_NAME = 'livestream:shortener'
189     IE_DESC = False  # Do not list
190     _VALID_URL = r'https?://livestre\.am/(?P<id>.+)'
191
192     def _real_extract(self, url):
193         mobj = re.match(self._VALID_URL, url)
194         id = mobj.group('id')
195         webpage = self._download_webpage(url, id)
196
197         return {
198             '_type': 'url',
199             'url': self._og_search_url(webpage),
200         }