[brightcove] Add the extraction of the url from generic
[youtube-dl] / 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
14     ExtractorError,
15 )
16
17 class BrightcoveIE(InfoExtractor):
18     _VALID_URL = r'https?://.*brightcove\.com/(services|viewer).*\?(?P<query>.*)'
19     _FEDERATED_URL_TEMPLATE = 'http://c.brightcove.com/services/viewer/htmlFederated?%s'
20     _PLAYLIST_URL_TEMPLATE = 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=%s'
21
22     _TESTS = [
23         {
24             # From http://www.8tv.cat/8aldia/videos/xavier-sala-i-martin-aquesta-tarda-a-8-al-dia/
25             u'url': u'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1654948606001&flashID=myExperience&%40videoPlayer=2371591881001',
26             u'file': u'2371591881001.mp4',
27             u'md5': u'8eccab865181d29ec2958f32a6a754f5',
28             u'note': u'Test Brightcove downloads and detection in GenericIE',
29             u'info_dict': {
30                 u'title': u'Xavier Sala i Martín: “Un banc que no presta és un banc zombi que no serveix per a res”',
31                 u'uploader': u'8TV',
32                 u'description': u'md5:a950cc4285c43e44d763d036710cd9cd',
33             }
34         },
35         {
36             # From http://medianetwork.oracle.com/video/player/1785452137001
37             u'url': u'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1217746023001&flashID=myPlayer&%40videoPlayer=1785452137001',
38             u'file': u'1785452137001.flv',
39             u'info_dict': {
40                 u'title': u'JVMLS 2012: Arrays 2.0 - Opportunities and Challenges',
41                 u'description': u'John Rose speaks at the JVM Language Summit, August 1, 2012.',
42                 u'uploader': u'Oracle',
43             },
44         },
45     ]
46
47     @classmethod
48     def _build_brighcove_url(cls, object_str):
49         """
50         Build a Brightcove url from a xml string containing
51         <object class="BrightcoveExperience">{params}</object>
52         """
53
54         # Fix up some stupid HTML, see https://github.com/rg3/youtube-dl/issues/1553
55         object_str = re.sub(r'(<param name="[^"]+" value="[^"]+")>',
56                             lambda m: m.group(1) + '/>', object_str)
57         # Fix up some stupid XML, see https://github.com/rg3/youtube-dl/issues/1608
58         object_str = object_str.replace(u'<--', u'<!--')
59
60         object_doc = xml.etree.ElementTree.fromstring(object_str)
61         assert u'BrightcoveExperience' in object_doc.attrib['class']
62         params = {'flashID': object_doc.attrib['id'],
63                   'playerID': find_xpath_attr(object_doc, './param', 'name', 'playerID').attrib['value'],
64                   }
65         playerKey = find_xpath_attr(object_doc, './param', 'name', 'playerKey')
66         # Not all pages define this value
67         if playerKey is not None:
68             params['playerKey'] = playerKey.attrib['value']
69         videoPlayer = find_xpath_attr(object_doc, './param', 'name', '@videoPlayer')
70         if videoPlayer is not None:
71             params['@videoPlayer'] = videoPlayer.attrib['value']
72         data = compat_urllib_parse.urlencode(params)
73         return cls._FEDERATED_URL_TEMPLATE % data
74
75     @classmethod
76     def _extract_brightcove_url(cls, webpage):
77         """Try to extract the brightcove url from the wepbage, returns None
78         if it can't be found
79         """
80         m_brightcove = re.search(
81             r'<object[^>]+?class=([\'"])[^>]*?BrightcoveExperience.*?\1.+?</object>',
82             webpage, re.DOTALL)
83         if m_brightcove is not None:
84             return cls._build_brighcove_url(m_brightcove.group())
85         else:
86             return None
87
88     def _real_extract(self, url):
89         mobj = re.match(self._VALID_URL, url)
90         query_str = mobj.group('query')
91         query = compat_urlparse.parse_qs(query_str)
92
93         videoPlayer = query.get('@videoPlayer')
94         if videoPlayer:
95             return self._get_video_info(videoPlayer[0], query_str)
96         else:
97             player_key = query['playerKey']
98             return self._get_playlist_info(player_key[0])
99
100     def _get_video_info(self, video_id, query):
101         request_url = self._FEDERATED_URL_TEMPLATE % query
102         webpage = self._download_webpage(request_url, video_id)
103
104         self.report_extraction(video_id)
105         info = self._search_regex(r'var experienceJSON = ({.*?});', webpage, 'json')
106         info = json.loads(info)['data']
107         video_info = info['programmedContent']['videoPlayer']['mediaDTO']
108
109         return self._extract_video_info(video_info)
110
111     def _get_playlist_info(self, player_key):
112         playlist_info = self._download_webpage(self._PLAYLIST_URL_TEMPLATE % player_key,
113                                                player_key, u'Downloading playlist information')
114
115         json_data = json.loads(playlist_info)
116         if 'videoList' not in json_data:
117             raise ExtractorError(u'Empty playlist')
118         playlist_info = json_data['videoList']
119         videos = [self._extract_video_info(video_info) for video_info in playlist_info['mediaCollectionDTO']['videoDTOs']]
120
121         return self.playlist_result(videos, playlist_id=playlist_info['id'],
122                                     playlist_title=playlist_info['mediaCollectionDTO']['displayName'])
123
124     def _extract_video_info(self, video_info):
125         info = {
126             'id': compat_str(video_info['id']),
127             'title': video_info['displayName'],
128             'description': video_info.get('shortDescription'),
129             'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
130             'uploader': video_info.get('publisherName'),
131         }
132
133         renditions = video_info.get('renditions')
134         if renditions:
135             renditions = sorted(renditions, key=lambda r: r['size'])
136             best_format = renditions[-1]
137             info.update({
138                 'url': best_format['defaultURL'],
139             })
140         elif video_info.get('FLVFullLengthURL') is not None:
141             info.update({
142                 'url': video_info['FLVFullLengthURL'],
143             })
144         else:
145             raise ExtractorError(u'Unable to extract video url for %s' % info['id'])
146         return info