]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/brightcove.py
Imported Upstream version 2013.11.11
[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'8eccab865181d29ec2958f32a6a754f5',
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
60 @classmethod
61 def _build_brighcove_url(cls, object_str):
62 """
63 Build a Brightcove url from a xml string containing
64 <object class="BrightcoveExperience">{params}</object>
65 """
66
67 # Fix up some stupid HTML, see https://github.com/rg3/youtube-dl/issues/1553
68 object_str = re.sub(r'(<param name="[^"]+" value="[^"]+")>',
69 lambda m: m.group(1) + '/>', object_str)
70 # Fix up some stupid XML, see https://github.com/rg3/youtube-dl/issues/1608
71 object_str = object_str.replace(u'<--', u'<!--')
72
73 object_doc = xml.etree.ElementTree.fromstring(object_str)
74 assert u'BrightcoveExperience' in object_doc.attrib['class']
75 params = {'flashID': object_doc.attrib['id'],
76 'playerID': find_xpath_attr(object_doc, './param', 'name', 'playerID').attrib['value'],
77 }
78 playerKey = find_xpath_attr(object_doc, './param', 'name', 'playerKey')
79 # Not all pages define this value
80 if playerKey is not None:
81 params['playerKey'] = playerKey.attrib['value']
82 videoPlayer = find_xpath_attr(object_doc, './param', 'name', '@videoPlayer')
83 if videoPlayer is not None:
84 params['@videoPlayer'] = videoPlayer.attrib['value']
85 linkBase = find_xpath_attr(object_doc, './param', 'name', 'linkBaseURL')
86 if linkBase is not None:
87 params['linkBaseURL'] = linkBase.attrib['value']
88 data = compat_urllib_parse.urlencode(params)
89 return cls._FEDERATED_URL_TEMPLATE % data
90
91 @classmethod
92 def _extract_brightcove_url(cls, webpage):
93 """Try to extract the brightcove url from the wepbage, returns None
94 if it can't be found
95 """
96 m_brightcove = re.search(
97 r'<object[^>]+?class=([\'"])[^>]*?BrightcoveExperience.*?\1.+?</object>',
98 webpage, re.DOTALL)
99 if m_brightcove is not None:
100 return cls._build_brighcove_url(m_brightcove.group())
101 else:
102 return None
103
104 def _real_extract(self, url):
105 # Change the 'videoId' and others field to '@videoPlayer'
106 url = re.sub(r'(?<=[?&])(videoI(d|D)|bctid)', '%40videoPlayer', url)
107 # Change bckey (used by bcove.me urls) to playerKey
108 url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
109 mobj = re.match(self._VALID_URL, url)
110 query_str = mobj.group('query')
111 query = compat_urlparse.parse_qs(query_str)
112
113 videoPlayer = query.get('@videoPlayer')
114 if videoPlayer:
115 return self._get_video_info(videoPlayer[0], query_str, query)
116 else:
117 player_key = query['playerKey']
118 return self._get_playlist_info(player_key[0])
119
120 def _get_video_info(self, video_id, query_str, query):
121 request_url = self._FEDERATED_URL_TEMPLATE % query_str
122 req = compat_urllib_request.Request(request_url)
123 linkBase = query.get('linkBaseURL')
124 if linkBase is not None:
125 req.add_header('Referer', linkBase[0])
126 webpage = self._download_webpage(req, video_id)
127
128 self.report_extraction(video_id)
129 info = self._search_regex(r'var experienceJSON = ({.*?});', webpage, 'json')
130 info = json.loads(info)['data']
131 video_info = info['programmedContent']['videoPlayer']['mediaDTO']
132
133 return self._extract_video_info(video_info)
134
135 def _get_playlist_info(self, player_key):
136 playlist_info = self._download_webpage(self._PLAYLIST_URL_TEMPLATE % player_key,
137 player_key, u'Downloading playlist information')
138
139 json_data = json.loads(playlist_info)
140 if 'videoList' not in json_data:
141 raise ExtractorError(u'Empty playlist')
142 playlist_info = json_data['videoList']
143 videos = [self._extract_video_info(video_info) for video_info in playlist_info['mediaCollectionDTO']['videoDTOs']]
144
145 return self.playlist_result(videos, playlist_id=playlist_info['id'],
146 playlist_title=playlist_info['mediaCollectionDTO']['displayName'])
147
148 def _extract_video_info(self, video_info):
149 info = {
150 'id': compat_str(video_info['id']),
151 'title': video_info['displayName'],
152 'description': video_info.get('shortDescription'),
153 'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
154 'uploader': video_info.get('publisherName'),
155 }
156
157 renditions = video_info.get('renditions')
158 if renditions:
159 renditions = sorted(renditions, key=lambda r: r['size'])
160 info['formats'] = [{
161 'url': rend['defaultURL'],
162 'height': rend.get('frameHeight'),
163 'width': rend.get('frameWidth'),
164 } for rend in renditions]
165 elif video_info.get('FLVFullLengthURL') is not None:
166 info.update({
167 'url': video_info['FLVFullLengthURL'],
168 })
169 else:
170 raise ExtractorError(u'Unable to extract video url for %s' % info['id'])
171 return info