]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/bbccouk.py
[canalplus] Modernize
[yt-dlp.git] / youtube_dl / extractor / bbccouk.py
CommitLineData
082c6c86
S
1from __future__ import unicode_literals
2
c056efa2 3import xml.etree.ElementTree
082c6c86 4
f13b1e7d 5from .common import InfoExtractor
8683b4d8
S
6from ..utils import (
7 ExtractorError,
8 int_or_none,
9)
c056efa2 10from ..compat import compat_HTTPError
082c6c86
S
11
12
f13b1e7d 13class BBCCoUkIE(InfoExtractor):
082c6c86 14 IE_NAME = 'bbc.co.uk'
2e3fd9ec 15 IE_DESC = 'BBC iPlayer'
0692ef86 16 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:(?:(?:programmes|iplayer(?:/[^/]+)?/(?:episode|playlist))/)|music/clips[/#])(?P<id>[\da-z]{8})'
082c6c86 17
2e3fd9ec
S
18 _TESTS = [
19 {
f2d0fc68 20 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
2e3fd9ec 21 'info_dict': {
f2d0fc68 22 'id': 'b039d07m',
2e3fd9ec 23 'ext': 'flv',
c4914185
S
24 'title': 'Kaleidoscope, Leonard Cohen',
25 'description': 'The Canadian poet and songwriter reflects on his musical career.',
f2d0fc68 26 'duration': 1740,
2e3fd9ec
S
27 },
28 'params': {
29 # rtmp download
30 'skip_download': True,
31 }
082c6c86 32 },
2e3fd9ec
S
33 {
34 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
35 'info_dict': {
36 'id': 'b00yng1d',
37 'ext': 'flv',
38 'title': 'The Man in Black: Series 3: The Printed Name',
39 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
40 'duration': 1800,
41 },
42 'params': {
43 # rtmp download
44 'skip_download': True,
c7f0177f
S
45 },
46 'skip': 'Episode is no longer available on BBC iPlayer Radio',
2e3fd9ec
S
47 },
48 {
49 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
50 'info_dict': {
51 'id': 'b00yng1d',
52 'ext': 'flv',
17968e44
S
53 'title': 'The Voice UK: Series 3: Blind Auditions 5',
54 '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.",
55 'duration': 5100,
2e3fd9ec
S
56 },
57 'params': {
58 # rtmp download
59 'skip_download': True,
60 },
61 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
c056efa2
S
62 },
63 {
64 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
65 'info_dict': {
66 'id': 'b03k3pb7',
67 'ext': 'flv',
68 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
69 'description': '2. Invasion',
70 'duration': 3600,
71 },
72 'params': {
73 # rtmp download
74 'skip_download': True,
75 },
76 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
ae6986fb
S
77 }, {
78 'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
79 'info_dict': {
80 'id': 'b04v209v',
81 'ext': 'flv',
82 'title': 'Pete Tong, The Essential New Tune Special',
83 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
84 'duration': 10800,
85 },
86 'params': {
87 # rtmp download
88 'skip_download': True,
89 }
c7e67594
S
90 }, {
91 'url': 'http://www.bbc.co.uk/music/clips/p02frcc3',
92 'note': 'Audio',
93 'info_dict': {
94 'id': 'p02frcch',
95 'ext': 'flv',
96 'title': 'Pete Tong, Past, Present and Future Special, Madeon - After Hours mix',
97 'description': 'French house superstar Madeon takes us out of the club and onto the after party.',
98 'duration': 3507,
99 },
100 'params': {
101 # rtmp download
102 'skip_download': True,
103 }
104 }, {
105 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
106 'note': 'Video',
107 'info_dict': {
108 'id': 'p025c103',
109 'ext': 'flv',
110 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
111 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
112 'duration': 226,
113 },
114 'params': {
115 # rtmp download
116 'skip_download': True,
117 }
e68ae99a
S
118 }, {
119 'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
120 'info_dict': {
121 'id': 'p02n76xf',
122 'ext': 'flv',
123 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
124 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
125 'duration': 3540,
126 },
127 'params': {
128 # rtmp download
129 'skip_download': True,
130 },
131 'skip': 'geolocation',
25fa8d66
YCH
132 }, {
133 'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
134 'info_dict': {
135 'id': 'b05zmgw1',
136 'ext': 'flv',
137 'description': 'Kirsty Wark and Morgan Quaintance visit the Royal Academy as it prepares for its annual artistic extravaganza, meeting people who have come together to make the show unique.',
138 'title': 'Royal Academy Summer Exhibition',
139 'duration': 3540,
140 },
141 'params': {
142 # rtmp download
143 'skip_download': True,
144 },
145 'skip': 'geolocation',
31763975
S
146 }, {
147 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
148 'only_matching': True,
c7e67594
S
149 }, {
150 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
151 'only_matching': True,
0692ef86
S
152 }, {
153 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
154 'only_matching': True,
ae6986fb 155 }
2e3fd9ec
S
156 ]
157
158 def _extract_asx_playlist(self, connection, programme_id):
159 asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
160 return [ref.get('href') for ref in asx.findall('./Entry/ref')]
161
162 def _extract_connection(self, connection, programme_id):
163 formats = []
164 protocol = connection.get('protocol')
165 supplier = connection.get('supplier')
166 if protocol == 'http':
167 href = connection.get('href')
168 # ASX playlist
169 if supplier == 'asx':
170 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
171 formats.append({
172 'url': ref,
173 'format_id': 'ref%s_%s' % (i, supplier),
174 })
175 # Direct link
176 else:
177 formats.append({
178 'url': href,
179 'format_id': supplier,
180 })
181 elif protocol == 'rtmp':
182 application = connection.get('application', 'ondemand')
183 auth_string = connection.get('authString')
184 identifier = connection.get('identifier')
185 server = connection.get('server')
186 formats.append({
187 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
188 'play_path': identifier,
189 'app': '%s?%s' % (application, auth_string),
190 'page_url': 'http://www.bbc.co.uk',
191 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
192 'rtmp_live': False,
193 'ext': 'flv',
194 'format_id': supplier,
195 })
196 return formats
197
198 def _extract_items(self, playlist):
199 return playlist.findall('./{http://bbc.co.uk/2008/emp/playlist}item')
200
201 def _extract_medias(self, media_selection):
c056efa2
S
202 error = media_selection.find('./{http://bbc.co.uk/2008/mp/mediaselection}error')
203 if error is not None:
204 raise ExtractorError(
205 '%s returned error: %s' % (self.IE_NAME, error.get('id')), expected=True)
2e3fd9ec
S
206 return media_selection.findall('./{http://bbc.co.uk/2008/mp/mediaselection}media')
207
208 def _extract_connections(self, media):
209 return media.findall('./{http://bbc.co.uk/2008/mp/mediaselection}connection')
210
211 def _extract_video(self, media, programme_id):
212 formats = []
213 vbr = int(media.get('bitrate'))
214 vcodec = media.get('encoding')
215 service = media.get('service')
216 width = int(media.get('width'))
217 height = int(media.get('height'))
218 file_size = int(media.get('media_file_size'))
219 for connection in self._extract_connections(media):
220 conn_formats = self._extract_connection(connection, programme_id)
221 for format in conn_formats:
222 format.update({
223 'format_id': '%s_%s' % (service, format['format_id']),
224 'width': width,
225 'height': height,
226 'vbr': vbr,
227 'vcodec': vcodec,
228 'filesize': file_size,
229 })
230 formats.extend(conn_formats)
231 return formats
232
233 def _extract_audio(self, media, programme_id):
234 formats = []
235 abr = int(media.get('bitrate'))
236 acodec = media.get('encoding')
237 service = media.get('service')
238 for connection in self._extract_connections(media):
239 conn_formats = self._extract_connection(connection, programme_id)
240 for format in conn_formats:
241 format.update({
242 'format_id': '%s_%s' % (service, format['format_id']),
243 'abr': abr,
244 'acodec': acodec,
245 })
246 formats.extend(conn_formats)
247 return formats
248
f13b1e7d 249 def _get_subtitles(self, media, programme_id):
2e3fd9ec
S
250 subtitles = {}
251 for connection in self._extract_connections(media):
252 captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
253 lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
f13b1e7d
JMF
254 subtitles[lang] = [
255 {
256 'url': connection.get('href'),
257 'ext': 'ttml',
258 },
f13b1e7d 259 ]
2e3fd9ec 260 return subtitles
082c6c86 261
c056efa2
S
262 def _download_media_selector(self, programme_id):
263 try:
264 media_selection = self._download_xml(
265 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s' % programme_id,
266 programme_id, 'Downloading media selection XML')
267 except ExtractorError as ee:
268 if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
974a6146 269 media_selection = xml.etree.ElementTree.fromstring(ee.cause.read().decode('utf-8'))
2e3fd9ec 270 else:
c056efa2 271 raise
082c6c86
S
272
273 formats = []
2e3fd9ec
S
274 subtitles = None
275
c056efa2
S
276 for media in self._extract_medias(media_selection):
277 kind = media.get('kind')
278 if kind == 'audio':
279 formats.extend(self._extract_audio(media, programme_id))
280 elif kind == 'video':
281 formats.extend(self._extract_video(media, programme_id))
282 elif kind == 'captions':
f13b1e7d 283 subtitles = self.extract_subtitles(media, programme_id)
2e3fd9ec 284
c056efa2 285 return formats, subtitles
2e3fd9ec 286
ae6986fb
S
287 def _download_playlist(self, playlist_id):
288 try:
289 playlist = self._download_json(
290 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
291 playlist_id, 'Downloading playlist JSON')
292
293 version = playlist.get('defaultAvailableVersion')
294 if version:
295 smp_config = version['smpConfig']
296 title = smp_config['title']
297 description = smp_config['summary']
298 for item in smp_config['items']:
299 kind = item['kind']
300 if kind != 'programme' and kind != 'radioProgramme':
301 continue
302 programme_id = item.get('vpid')
303 duration = int(item.get('duration'))
304 formats, subtitles = self._download_media_selector(programme_id)
305 return programme_id, title, description, duration, formats, subtitles
306 except ExtractorError as ee:
f813928e 307 if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
ae6986fb
S
308 raise
309
310 # fallback to legacy playlist
311 playlist = self._download_xml(
931e2d1d
PH
312 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id,
313 playlist_id, 'Downloading legacy playlist XML')
ae6986fb
S
314
315 no_items = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}noItems')
316 if no_items is not None:
317 reason = no_items.get('reason')
318 if reason == 'preAvailability':
319 msg = 'Episode %s is not yet available' % playlist_id
320 elif reason == 'postAvailability':
321 msg = 'Episode %s is no longer available' % playlist_id
322 elif reason == 'noMedia':
323 msg = 'Episode %s is not currently available' % playlist_id
324 else:
325 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
326 raise ExtractorError(msg, expected=True)
327
328 for item in self._extract_items(playlist):
329 kind = item.get('kind')
330 if kind != 'programme' and kind != 'radioProgramme':
331 continue
332 title = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}title').text
333 description = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}summary').text
334 programme_id = item.get('identifier')
335 duration = int(item.get('duration'))
336 formats, subtitles = self._download_media_selector(programme_id)
337
338 return programme_id, title, description, duration, formats, subtitles
339
c056efa2
S
340 def _real_extract(self, url):
341 group_id = self._match_id(url)
342
343 webpage = self._download_webpage(url, group_id, 'Downloading video page')
344
8683b4d8
S
345 programme_id = None
346
347 tviplayer = self._search_regex(
348 r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
349 webpage, 'player', default=None)
350
351 if tviplayer:
352 player = self._parse_json(tviplayer, group_id).get('player', {})
353 duration = int_or_none(player.get('duration'))
354 programme_id = player.get('vpid')
355
356 if not programme_id:
357 programme_id = self._search_regex(
358 r'"vpid"\s*:\s*"([\da-z]{8})"', webpage, 'vpid', fatal=False, default=None)
359
c056efa2 360 if programme_id:
c056efa2 361 formats, subtitles = self._download_media_selector(programme_id)
8683b4d8
S
362 title = self._og_search_title(webpage)
363 description = self._search_regex(
25fa8d66 364 r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
8683b4d8 365 webpage, 'description', fatal=False)
c056efa2 366 else:
ae6986fb 367 programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
2e3fd9ec 368
082c6c86
S
369 self._sort_formats(formats)
370
371 return {
2e3fd9ec 372 'id': programme_id,
082c6c86
S
373 'title': title,
374 'description': description,
650cfd0c 375 'thumbnail': self._og_search_thumbnail(webpage, default=None),
082c6c86
S
376 'duration': duration,
377 'formats': formats,
2e3fd9ec 378 'subtitles': subtitles,
5f6a1245 379 }