]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/bbccouk.py
Merge tag 'upstream/2015.01.16'
[youtubedl] / youtube_dl / extractor / bbccouk.py
1 from __future__ import unicode_literals
2
3 import xml.etree.ElementTree
4
5 from .subtitles import SubtitlesInfoExtractor
6 from ..utils import ExtractorError
7 from ..compat import compat_HTTPError
8
9
10 class BBCCoUkIE(SubtitlesInfoExtractor):
11 IE_NAME = 'bbc.co.uk'
12 IE_DESC = 'BBC iPlayer'
13 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:(?:(?:programmes|iplayer/(?:episode|playlist))/)|music/clips[/#])(?P<id>[\da-z]{8})'
14
15 _TESTS = [
16 {
17 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
18 'info_dict': {
19 'id': 'b039d07m',
20 'ext': 'flv',
21 'title': 'Kaleidoscope, Leonard Cohen',
22 'description': 'The Canadian poet and songwriter reflects on his musical career.',
23 'duration': 1740,
24 },
25 'params': {
26 # rtmp download
27 'skip_download': True,
28 }
29 },
30 {
31 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
32 'info_dict': {
33 'id': 'b00yng1d',
34 'ext': 'flv',
35 'title': 'The Man in Black: Series 3: The Printed Name',
36 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
37 'duration': 1800,
38 },
39 'params': {
40 # rtmp download
41 'skip_download': True,
42 },
43 'skip': 'Episode is no longer available on BBC iPlayer Radio',
44 },
45 {
46 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
47 'info_dict': {
48 'id': 'b00yng1d',
49 'ext': 'flv',
50 'title': 'The Voice UK: Series 3: Blind Auditions 5',
51 'description': "Emma Willis and Marvin Humes present the fifth set of blind auditions in the singing competition, as the coaches continue to build their teams based on voice alone.",
52 'duration': 5100,
53 },
54 'params': {
55 # rtmp download
56 'skip_download': True,
57 },
58 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
59 },
60 {
61 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
62 'info_dict': {
63 'id': 'b03k3pb7',
64 'ext': 'flv',
65 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
66 'description': '2. Invasion',
67 'duration': 3600,
68 },
69 'params': {
70 # rtmp download
71 'skip_download': True,
72 },
73 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
74 }, {
75 'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
76 'info_dict': {
77 'id': 'b04v209v',
78 'ext': 'flv',
79 'title': 'Pete Tong, The Essential New Tune Special',
80 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
81 'duration': 10800,
82 },
83 'params': {
84 # rtmp download
85 'skip_download': True,
86 }
87 }, {
88 'url': 'http://www.bbc.co.uk/music/clips/p02frcc3',
89 'note': 'Audio',
90 'info_dict': {
91 'id': 'p02frcch',
92 'ext': 'flv',
93 'title': 'Pete Tong, Past, Present and Future Special, Madeon - After Hours mix',
94 'description': 'French house superstar Madeon takes us out of the club and onto the after party.',
95 'duration': 3507,
96 },
97 'params': {
98 # rtmp download
99 'skip_download': True,
100 }
101 }, {
102 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
103 'note': 'Video',
104 'info_dict': {
105 'id': 'p025c103',
106 'ext': 'flv',
107 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
108 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
109 'duration': 226,
110 },
111 'params': {
112 # rtmp download
113 'skip_download': True,
114 }
115 }, {
116 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
117 'only_matching': True,
118 }, {
119 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
120 'only_matching': True,
121 }
122 ]
123
124 def _extract_asx_playlist(self, connection, programme_id):
125 asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
126 return [ref.get('href') for ref in asx.findall('./Entry/ref')]
127
128 def _extract_connection(self, connection, programme_id):
129 formats = []
130 protocol = connection.get('protocol')
131 supplier = connection.get('supplier')
132 if protocol == 'http':
133 href = connection.get('href')
134 # ASX playlist
135 if supplier == 'asx':
136 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
137 formats.append({
138 'url': ref,
139 'format_id': 'ref%s_%s' % (i, supplier),
140 })
141 # Direct link
142 else:
143 formats.append({
144 'url': href,
145 'format_id': supplier,
146 })
147 elif protocol == 'rtmp':
148 application = connection.get('application', 'ondemand')
149 auth_string = connection.get('authString')
150 identifier = connection.get('identifier')
151 server = connection.get('server')
152 formats.append({
153 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
154 'play_path': identifier,
155 'app': '%s?%s' % (application, auth_string),
156 'page_url': 'http://www.bbc.co.uk',
157 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
158 'rtmp_live': False,
159 'ext': 'flv',
160 'format_id': supplier,
161 })
162 return formats
163
164 def _extract_items(self, playlist):
165 return playlist.findall('./{http://bbc.co.uk/2008/emp/playlist}item')
166
167 def _extract_medias(self, media_selection):
168 error = media_selection.find('./{http://bbc.co.uk/2008/mp/mediaselection}error')
169 if error is not None:
170 raise ExtractorError(
171 '%s returned error: %s' % (self.IE_NAME, error.get('id')), expected=True)
172 return media_selection.findall('./{http://bbc.co.uk/2008/mp/mediaselection}media')
173
174 def _extract_connections(self, media):
175 return media.findall('./{http://bbc.co.uk/2008/mp/mediaselection}connection')
176
177 def _extract_video(self, media, programme_id):
178 formats = []
179 vbr = int(media.get('bitrate'))
180 vcodec = media.get('encoding')
181 service = media.get('service')
182 width = int(media.get('width'))
183 height = int(media.get('height'))
184 file_size = int(media.get('media_file_size'))
185 for connection in self._extract_connections(media):
186 conn_formats = self._extract_connection(connection, programme_id)
187 for format in conn_formats:
188 format.update({
189 'format_id': '%s_%s' % (service, format['format_id']),
190 'width': width,
191 'height': height,
192 'vbr': vbr,
193 'vcodec': vcodec,
194 'filesize': file_size,
195 })
196 formats.extend(conn_formats)
197 return formats
198
199 def _extract_audio(self, media, programme_id):
200 formats = []
201 abr = int(media.get('bitrate'))
202 acodec = media.get('encoding')
203 service = media.get('service')
204 for connection in self._extract_connections(media):
205 conn_formats = self._extract_connection(connection, programme_id)
206 for format in conn_formats:
207 format.update({
208 'format_id': '%s_%s' % (service, format['format_id']),
209 'abr': abr,
210 'acodec': acodec,
211 })
212 formats.extend(conn_formats)
213 return formats
214
215 def _extract_captions(self, media, programme_id):
216 subtitles = {}
217 for connection in self._extract_connections(media):
218 captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
219 lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
220 ps = captions.findall('./{0}body/{0}div/{0}p'.format('{http://www.w3.org/2006/10/ttaf1}'))
221 srt = ''
222 for pos, p in enumerate(ps):
223 srt += '%s\r\n%s --> %s\r\n%s\r\n\r\n' % (str(pos), p.get('begin'), p.get('end'),
224 p.text.strip() if p.text is not None else '')
225 subtitles[lang] = srt
226 return subtitles
227
228 def _download_media_selector(self, programme_id):
229 try:
230 media_selection = self._download_xml(
231 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s' % programme_id,
232 programme_id, 'Downloading media selection XML')
233 except ExtractorError as ee:
234 if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
235 media_selection = xml.etree.ElementTree.fromstring(ee.cause.read().encode('utf-8'))
236 else:
237 raise
238
239 formats = []
240 subtitles = None
241
242 for media in self._extract_medias(media_selection):
243 kind = media.get('kind')
244 if kind == 'audio':
245 formats.extend(self._extract_audio(media, programme_id))
246 elif kind == 'video':
247 formats.extend(self._extract_video(media, programme_id))
248 elif kind == 'captions':
249 subtitles = self._extract_captions(media, programme_id)
250
251 return formats, subtitles
252
253 def _download_playlist(self, playlist_id):
254 try:
255 playlist = self._download_json(
256 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
257 playlist_id, 'Downloading playlist JSON')
258
259 version = playlist.get('defaultAvailableVersion')
260 if version:
261 smp_config = version['smpConfig']
262 title = smp_config['title']
263 description = smp_config['summary']
264 for item in smp_config['items']:
265 kind = item['kind']
266 if kind != 'programme' and kind != 'radioProgramme':
267 continue
268 programme_id = item.get('vpid')
269 duration = int(item.get('duration'))
270 formats, subtitles = self._download_media_selector(programme_id)
271 return programme_id, title, description, duration, formats, subtitles
272 except ExtractorError as ee:
273 if not isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404:
274 raise
275
276 # fallback to legacy playlist
277 playlist = self._download_xml(
278 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id,
279 playlist_id, 'Downloading legacy playlist XML')
280
281 no_items = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}noItems')
282 if no_items is not None:
283 reason = no_items.get('reason')
284 if reason == 'preAvailability':
285 msg = 'Episode %s is not yet available' % playlist_id
286 elif reason == 'postAvailability':
287 msg = 'Episode %s is no longer available' % playlist_id
288 elif reason == 'noMedia':
289 msg = 'Episode %s is not currently available' % playlist_id
290 else:
291 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
292 raise ExtractorError(msg, expected=True)
293
294 for item in self._extract_items(playlist):
295 kind = item.get('kind')
296 if kind != 'programme' and kind != 'radioProgramme':
297 continue
298 title = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}title').text
299 description = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}summary').text
300 programme_id = item.get('identifier')
301 duration = int(item.get('duration'))
302 formats, subtitles = self._download_media_selector(programme_id)
303
304 return programme_id, title, description, duration, formats, subtitles
305
306 def _real_extract(self, url):
307 group_id = self._match_id(url)
308
309 webpage = self._download_webpage(url, group_id, 'Downloading video page')
310
311 programme_id = self._search_regex(
312 r'"vpid"\s*:\s*"([\da-z]{8})"', webpage, 'vpid', fatal=False, default=None)
313 if programme_id:
314 player = self._download_json(
315 'http://www.bbc.co.uk/iplayer/episode/%s.json' % group_id,
316 group_id)['jsConf']['player']
317 title = player['title']
318 description = player['subtitle']
319 duration = player['duration']
320 formats, subtitles = self._download_media_selector(programme_id)
321 else:
322 programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
323
324 if self._downloader.params.get('listsubtitles', False):
325 self._list_available_subtitles(programme_id, subtitles)
326 return
327
328 self._sort_formats(formats)
329
330 return {
331 'id': programme_id,
332 'title': title,
333 'description': description,
334 'duration': duration,
335 'formats': formats,
336 'subtitles': subtitles,
337 }