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