]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/bbccouk.py
[history] Add extractor (Closes #4934)
[yt-dlp.git] / youtube_dl / extractor / bbccouk.py
CommitLineData
082c6c86
S
1from __future__ import unicode_literals
2
c056efa2 3import xml.etree.ElementTree
082c6c86 4
2e3fd9ec 5from .subtitles import SubtitlesInfoExtractor
082c6c86 6from ..utils import ExtractorError
c056efa2 7from ..compat import compat_HTTPError
082c6c86
S
8
9
2e3fd9ec 10class BBCCoUkIE(SubtitlesInfoExtractor):
082c6c86 11 IE_NAME = 'bbc.co.uk'
2e3fd9ec 12 IE_DESC = 'BBC iPlayer'
0692ef86 13 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:(?:(?:programmes|iplayer(?:/[^/]+)?/(?:episode|playlist))/)|music/clips[/#])(?P<id>[\da-z]{8})'
082c6c86 14
2e3fd9ec
S
15 _TESTS = [
16 {
f2d0fc68 17 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
2e3fd9ec 18 'info_dict': {
f2d0fc68 19 'id': 'b039d07m',
2e3fd9ec 20 'ext': 'flv',
c4914185
S
21 'title': 'Kaleidoscope, Leonard Cohen',
22 'description': 'The Canadian poet and songwriter reflects on his musical career.',
f2d0fc68 23 'duration': 1740,
2e3fd9ec
S
24 },
25 'params': {
26 # rtmp download
27 'skip_download': True,
28 }
082c6c86 29 },
2e3fd9ec
S
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,
c7f0177f
S
42 },
43 'skip': 'Episode is no longer available on BBC iPlayer Radio',
2e3fd9ec
S
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',
17968e44
S
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,
2e3fd9ec
S
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',
c056efa2
S
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',
ae6986fb
S
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 }
c7e67594
S
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 }
31763975
S
115 }, {
116 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
117 'only_matching': True,
c7e67594
S
118 }, {
119 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
120 'only_matching': True,
0692ef86
S
121 }, {
122 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
123 'only_matching': True,
ae6986fb 124 }
2e3fd9ec
S
125 ]
126
127 def _extract_asx_playlist(self, connection, programme_id):
128 asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
129 return [ref.get('href') for ref in asx.findall('./Entry/ref')]
130
131 def _extract_connection(self, connection, programme_id):
132 formats = []
133 protocol = connection.get('protocol')
134 supplier = connection.get('supplier')
135 if protocol == 'http':
136 href = connection.get('href')
137 # ASX playlist
138 if supplier == 'asx':
139 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
140 formats.append({
141 'url': ref,
142 'format_id': 'ref%s_%s' % (i, supplier),
143 })
144 # Direct link
145 else:
146 formats.append({
147 'url': href,
148 'format_id': supplier,
149 })
150 elif protocol == 'rtmp':
151 application = connection.get('application', 'ondemand')
152 auth_string = connection.get('authString')
153 identifier = connection.get('identifier')
154 server = connection.get('server')
155 formats.append({
156 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
157 'play_path': identifier,
158 'app': '%s?%s' % (application, auth_string),
159 'page_url': 'http://www.bbc.co.uk',
160 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
161 'rtmp_live': False,
162 'ext': 'flv',
163 'format_id': supplier,
164 })
165 return formats
166
167 def _extract_items(self, playlist):
168 return playlist.findall('./{http://bbc.co.uk/2008/emp/playlist}item')
169
170 def _extract_medias(self, media_selection):
c056efa2
S
171 error = media_selection.find('./{http://bbc.co.uk/2008/mp/mediaselection}error')
172 if error is not None:
173 raise ExtractorError(
174 '%s returned error: %s' % (self.IE_NAME, error.get('id')), expected=True)
2e3fd9ec
S
175 return media_selection.findall('./{http://bbc.co.uk/2008/mp/mediaselection}media')
176
177 def _extract_connections(self, media):
178 return media.findall('./{http://bbc.co.uk/2008/mp/mediaselection}connection')
179
180 def _extract_video(self, media, programme_id):
181 formats = []
182 vbr = int(media.get('bitrate'))
183 vcodec = media.get('encoding')
184 service = media.get('service')
185 width = int(media.get('width'))
186 height = int(media.get('height'))
187 file_size = int(media.get('media_file_size'))
188 for connection in self._extract_connections(media):
189 conn_formats = self._extract_connection(connection, programme_id)
190 for format in conn_formats:
191 format.update({
192 'format_id': '%s_%s' % (service, format['format_id']),
193 'width': width,
194 'height': height,
195 'vbr': vbr,
196 'vcodec': vcodec,
197 'filesize': file_size,
198 })
199 formats.extend(conn_formats)
200 return formats
201
202 def _extract_audio(self, media, programme_id):
203 formats = []
204 abr = int(media.get('bitrate'))
205 acodec = media.get('encoding')
206 service = media.get('service')
207 for connection in self._extract_connections(media):
208 conn_formats = self._extract_connection(connection, programme_id)
209 for format in conn_formats:
210 format.update({
211 'format_id': '%s_%s' % (service, format['format_id']),
212 'abr': abr,
213 'acodec': acodec,
214 })
215 formats.extend(conn_formats)
216 return formats
217
218 def _extract_captions(self, media, programme_id):
219 subtitles = {}
220 for connection in self._extract_connections(media):
221 captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
222 lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
223 ps = captions.findall('./{0}body/{0}div/{0}p'.format('{http://www.w3.org/2006/10/ttaf1}'))
224 srt = ''
225 for pos, p in enumerate(ps):
226 srt += '%s\r\n%s --> %s\r\n%s\r\n\r\n' % (str(pos), p.get('begin'), p.get('end'),
227 p.text.strip() if p.text is not None else '')
228 subtitles[lang] = srt
229 return subtitles
082c6c86 230
c056efa2
S
231 def _download_media_selector(self, programme_id):
232 try:
233 media_selection = self._download_xml(
234 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s' % programme_id,
235 programme_id, 'Downloading media selection XML')
236 except ExtractorError as ee:
237 if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
238 media_selection = xml.etree.ElementTree.fromstring(ee.cause.read().encode('utf-8'))
2e3fd9ec 239 else:
c056efa2 240 raise
082c6c86
S
241
242 formats = []
2e3fd9ec
S
243 subtitles = None
244
c056efa2
S
245 for media in self._extract_medias(media_selection):
246 kind = media.get('kind')
247 if kind == 'audio':
248 formats.extend(self._extract_audio(media, programme_id))
249 elif kind == 'video':
250 formats.extend(self._extract_video(media, programme_id))
251 elif kind == 'captions':
252 subtitles = self._extract_captions(media, programme_id)
2e3fd9ec 253
c056efa2 254 return formats, subtitles
2e3fd9ec 255
ae6986fb
S
256 def _download_playlist(self, playlist_id):
257 try:
258 playlist = self._download_json(
259 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
260 playlist_id, 'Downloading playlist JSON')
261
262 version = playlist.get('defaultAvailableVersion')
263 if version:
264 smp_config = version['smpConfig']
265 title = smp_config['title']
266 description = smp_config['summary']
267 for item in smp_config['items']:
268 kind = item['kind']
269 if kind != 'programme' and kind != 'radioProgramme':
270 continue
271 programme_id = item.get('vpid')
272 duration = int(item.get('duration'))
273 formats, subtitles = self._download_media_selector(programme_id)
274 return programme_id, title, description, duration, formats, subtitles
275 except ExtractorError as ee:
276 if not isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404:
277 raise
278
279 # fallback to legacy playlist
280 playlist = self._download_xml(
931e2d1d
PH
281 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id,
282 playlist_id, 'Downloading legacy playlist XML')
ae6986fb
S
283
284 no_items = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}noItems')
285 if no_items is not None:
286 reason = no_items.get('reason')
287 if reason == 'preAvailability':
288 msg = 'Episode %s is not yet available' % playlist_id
289 elif reason == 'postAvailability':
290 msg = 'Episode %s is no longer available' % playlist_id
291 elif reason == 'noMedia':
292 msg = 'Episode %s is not currently available' % playlist_id
293 else:
294 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
295 raise ExtractorError(msg, expected=True)
296
297 for item in self._extract_items(playlist):
298 kind = item.get('kind')
299 if kind != 'programme' and kind != 'radioProgramme':
300 continue
301 title = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}title').text
302 description = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}summary').text
303 programme_id = item.get('identifier')
304 duration = int(item.get('duration'))
305 formats, subtitles = self._download_media_selector(programme_id)
306
307 return programme_id, title, description, duration, formats, subtitles
308
c056efa2
S
309 def _real_extract(self, url):
310 group_id = self._match_id(url)
311
312 webpage = self._download_webpage(url, group_id, 'Downloading video page')
313
314 programme_id = self._search_regex(
da4d4191 315 r'"vpid"\s*:\s*"([\da-z]{8})"', webpage, 'vpid', fatal=False, default=None)
c056efa2
S
316 if programme_id:
317 player = self._download_json(
318 'http://www.bbc.co.uk/iplayer/episode/%s.json' % group_id,
319 group_id)['jsConf']['player']
320 title = player['title']
321 description = player['subtitle']
322 duration = player['duration']
323 formats, subtitles = self._download_media_selector(programme_id)
324 else:
ae6986fb 325 programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
2e3fd9ec
S
326
327 if self._downloader.params.get('listsubtitles', False):
328 self._list_available_subtitles(programme_id, subtitles)
329 return
082c6c86
S
330
331 self._sort_formats(formats)
332
333 return {
2e3fd9ec 334 'id': programme_id,
082c6c86
S
335 'title': title,
336 'description': description,
337 'duration': duration,
338 'formats': formats,
2e3fd9ec 339 'subtitles': subtitles,
5f6a1245 340 }