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