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