]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/brightcove.py
Imported Upstream version 2013.12.23
[youtubedl] / youtube_dl / extractor / brightcove.py
1 # encoding: utf-8
2
3 import re
4 import json
5 import xml.etree.ElementTree
6
7 from .common import InfoExtractor
8 from ..utils import (
9 compat_urllib_parse,
10 find_xpath_attr,
11 compat_urlparse,
12 compat_str,
13 compat_urllib_request,
14
15 ExtractorError,
16 )
17
18
19 class BrightcoveIE(InfoExtractor):
20 _VALID_URL = r'https?://.*brightcove\.com/(services|viewer).*\?(?P<query>.*)'
21 _FEDERATED_URL_TEMPLATE = 'http://c.brightcove.com/services/viewer/htmlFederated?%s'
22 _PLAYLIST_URL_TEMPLATE = 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=%s'
23
24 _TESTS = [
25 {
26 # From http://www.8tv.cat/8aldia/videos/xavier-sala-i-martin-aquesta-tarda-a-8-al-dia/
27 u'url': u'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1654948606001&flashID=myExperience&%40videoPlayer=2371591881001',
28 u'file': u'2371591881001.mp4',
29 u'md5': u'5423e113865d26e40624dce2e4b45d95',
30 u'note': u'Test Brightcove downloads and detection in GenericIE',
31 u'info_dict': {
32 u'title': u'Xavier Sala i Martín: “Un banc que no presta és un banc zombi que no serveix per a res”',
33 u'uploader': u'8TV',
34 u'description': u'md5:a950cc4285c43e44d763d036710cd9cd',
35 }
36 },
37 {
38 # From http://medianetwork.oracle.com/video/player/1785452137001
39 u'url': u'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1217746023001&flashID=myPlayer&%40videoPlayer=1785452137001',
40 u'file': u'1785452137001.flv',
41 u'info_dict': {
42 u'title': u'JVMLS 2012: Arrays 2.0 - Opportunities and Challenges',
43 u'description': u'John Rose speaks at the JVM Language Summit, August 1, 2012.',
44 u'uploader': u'Oracle',
45 },
46 },
47 {
48 # From http://mashable.com/2013/10/26/thermoelectric-bracelet-lets-you-control-your-body-temperature/
49 u'url': u'http://c.brightcove.com/services/viewer/federated_f9?&playerID=1265504713001&publisherID=AQ%7E%7E%2CAAABBzUwv1E%7E%2CxP-xFHVUstiMFlNYfvF4G9yFnNaqCw_9&videoID=2750934548001',
50 u'info_dict': {
51 u'id': u'2750934548001',
52 u'ext': u'mp4',
53 u'title': u'This Bracelet Acts as a Personal Thermostat',
54 u'description': u'md5:547b78c64f4112766ccf4e151c20b6a0',
55 u'uploader': u'Mashable',
56 },
57 },
58 {
59 # test that the default referer works
60 # from http://national.ballet.ca/interact/video/Lost_in_Motion_II/
61 u'url': u'http://link.brightcove.com/services/player/bcpid756015033001?bckey=AQ~~,AAAApYJi_Ck~,GxhXCegT1Dp39ilhXuxMJxasUhVNZiil&bctid=2878862109001',
62 u'info_dict': {
63 u'id': u'2878862109001',
64 u'ext': u'mp4',
65 u'title': u'Lost in Motion II',
66 u'description': u'md5:363109c02998fee92ec02211bd8000df',
67 u'uploader': u'National Ballet of Canada',
68 },
69 },
70 ]
71
72 @classmethod
73 def _build_brighcove_url(cls, object_str):
74 """
75 Build a Brightcove url from a xml string containing
76 <object class="BrightcoveExperience">{params}</object>
77 """
78
79 # Fix up some stupid HTML, see https://github.com/rg3/youtube-dl/issues/1553
80 object_str = re.sub(r'(<param name="[^"]+" value="[^"]+")>',
81 lambda m: m.group(1) + '/>', object_str)
82 # Fix up some stupid XML, see https://github.com/rg3/youtube-dl/issues/1608
83 object_str = object_str.replace(u'<--', u'<!--')
84
85 object_doc = xml.etree.ElementTree.fromstring(object_str)
86 assert u'BrightcoveExperience' in object_doc.attrib['class']
87 params = {'flashID': object_doc.attrib['id'],
88 'playerID': find_xpath_attr(object_doc, './param', 'name', 'playerID').attrib['value'],
89 }
90 def find_param(name):
91 node = find_xpath_attr(object_doc, './param', 'name', name)
92 if node is not None:
93 return node.attrib['value']
94 return None
95 playerKey = find_param('playerKey')
96 # Not all pages define this value
97 if playerKey is not None:
98 params['playerKey'] = playerKey
99 # The three fields hold the id of the video
100 videoPlayer = find_param('@videoPlayer') or find_param('videoId') or find_param('videoID')
101 if videoPlayer is not None:
102 params['@videoPlayer'] = videoPlayer
103 linkBase = find_param('linkBaseURL')
104 if linkBase is not None:
105 params['linkBaseURL'] = linkBase
106 data = compat_urllib_parse.urlencode(params)
107 return cls._FEDERATED_URL_TEMPLATE % data
108
109 @classmethod
110 def _extract_brightcove_url(cls, webpage):
111 """Try to extract the brightcove url from the wepbage, returns None
112 if it can't be found
113 """
114 m_brightcove = re.search(
115 r'<object[^>]+?class=([\'"])[^>]*?BrightcoveExperience.*?\1.+?</object>',
116 webpage, re.DOTALL)
117 if m_brightcove is not None:
118 return cls._build_brighcove_url(m_brightcove.group())
119 else:
120 return None
121
122 def _real_extract(self, url):
123 # Change the 'videoId' and others field to '@videoPlayer'
124 url = re.sub(r'(?<=[?&])(videoI(d|D)|bctid)', '%40videoPlayer', url)
125 # Change bckey (used by bcove.me urls) to playerKey
126 url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
127 mobj = re.match(self._VALID_URL, url)
128 query_str = mobj.group('query')
129 query = compat_urlparse.parse_qs(query_str)
130
131 videoPlayer = query.get('@videoPlayer')
132 if videoPlayer:
133 return self._get_video_info(videoPlayer[0], query_str, query,
134 # We set the original url as the default 'Referer' header
135 referer=url)
136 else:
137 player_key = query['playerKey']
138 return self._get_playlist_info(player_key[0])
139
140 def _get_video_info(self, video_id, query_str, query, referer=None):
141 request_url = self._FEDERATED_URL_TEMPLATE % query_str
142 req = compat_urllib_request.Request(request_url)
143 linkBase = query.get('linkBaseURL')
144 if linkBase is not None:
145 referer = linkBase[0]
146 if referer is not None:
147 req.add_header('Referer', referer)
148 webpage = self._download_webpage(req, video_id)
149
150 self.report_extraction(video_id)
151 info = self._search_regex(r'var experienceJSON = ({.*?});', webpage, 'json')
152 info = json.loads(info)['data']
153 video_info = info['programmedContent']['videoPlayer']['mediaDTO']
154
155 return self._extract_video_info(video_info)
156
157 def _get_playlist_info(self, player_key):
158 playlist_info = self._download_webpage(self._PLAYLIST_URL_TEMPLATE % player_key,
159 player_key, u'Downloading playlist information')
160
161 json_data = json.loads(playlist_info)
162 if 'videoList' not in json_data:
163 raise ExtractorError(u'Empty playlist')
164 playlist_info = json_data['videoList']
165 videos = [self._extract_video_info(video_info) for video_info in playlist_info['mediaCollectionDTO']['videoDTOs']]
166
167 return self.playlist_result(videos, playlist_id=playlist_info['id'],
168 playlist_title=playlist_info['mediaCollectionDTO']['displayName'])
169
170 def _extract_video_info(self, video_info):
171 info = {
172 'id': compat_str(video_info['id']),
173 'title': video_info['displayName'],
174 'description': video_info.get('shortDescription'),
175 'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
176 'uploader': video_info.get('publisherName'),
177 }
178
179 renditions = video_info.get('renditions')
180 if renditions:
181 renditions = sorted(renditions, key=lambda r: r['size'])
182 info['formats'] = [{
183 'url': rend['defaultURL'],
184 'height': rend.get('frameHeight'),
185 'width': rend.get('frameWidth'),
186 } for rend in renditions]
187 elif video_info.get('FLVFullLengthURL') is not None:
188 info.update({
189 'url': video_info['FLVFullLengthURL'],
190 })
191 else:
192 raise ExtractorError(u'Unable to extract video url for %s' % info['id'])
193 return info