]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/bbccouk.py
beb6cfc8ae88a3c40ac2b4ee7f6b0ae2c6ddfc87
[youtubedl] / youtube_dl / extractor / bbccouk.py
1 from __future__ import unicode_literals
2
3 import re
4 import xml.etree.ElementTree
5
6 from .subtitles import SubtitlesInfoExtractor
7 from ..utils import ExtractorError
8 from ..compat import compat_HTTPError
9
10
11 class BBCCoUkIE(SubtitlesInfoExtractor):
12 IE_NAME = 'bbc.co.uk'
13 IE_DESC = 'BBC iPlayer'
14 _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:programmes|iplayer/episode)/(?P<id>[\da-z]{8})'
15
16 _TESTS = [
17 {
18 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
19 'info_dict': {
20 'id': 'b039d07m',
21 'ext': 'flv',
22 'title': 'Kaleidoscope: Leonard Cohen',
23 'description': 'md5:db4755d7a665ae72343779f7dacb402c',
24 'duration': 1740,
25 },
26 'params': {
27 # rtmp download
28 'skip_download': True,
29 }
30 },
31 {
32 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
33 'info_dict': {
34 'id': 'b00yng1d',
35 'ext': 'flv',
36 'title': 'The Man in Black: Series 3: The Printed Name',
37 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
38 'duration': 1800,
39 },
40 'params': {
41 # rtmp download
42 'skip_download': True,
43 },
44 'skip': 'Episode is no longer available on BBC iPlayer Radio',
45 },
46 {
47 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
48 'info_dict': {
49 'id': 'b00yng1d',
50 'ext': 'flv',
51 'title': 'The Voice UK: Series 3: Blind Auditions 5',
52 '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.",
53 'duration': 5100,
54 },
55 'params': {
56 # rtmp download
57 'skip_download': True,
58 },
59 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
60 },
61 {
62 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
63 'info_dict': {
64 'id': 'b03k3pb7',
65 'ext': 'flv',
66 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
67 'description': '2. Invasion',
68 'duration': 3600,
69 },
70 'params': {
71 # rtmp download
72 'skip_download': True,
73 },
74 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
75 },
76 ]
77
78 def _extract_asx_playlist(self, connection, programme_id):
79 asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
80 return [ref.get('href') for ref in asx.findall('./Entry/ref')]
81
82 def _extract_connection(self, connection, programme_id):
83 formats = []
84 protocol = connection.get('protocol')
85 supplier = connection.get('supplier')
86 if protocol == 'http':
87 href = connection.get('href')
88 # ASX playlist
89 if supplier == 'asx':
90 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
91 formats.append({
92 'url': ref,
93 'format_id': 'ref%s_%s' % (i, supplier),
94 })
95 # Direct link
96 else:
97 formats.append({
98 'url': href,
99 'format_id': supplier,
100 })
101 elif protocol == 'rtmp':
102 application = connection.get('application', 'ondemand')
103 auth_string = connection.get('authString')
104 identifier = connection.get('identifier')
105 server = connection.get('server')
106 formats.append({
107 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
108 'play_path': identifier,
109 'app': '%s?%s' % (application, auth_string),
110 'page_url': 'http://www.bbc.co.uk',
111 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
112 'rtmp_live': False,
113 'ext': 'flv',
114 'format_id': supplier,
115 })
116 return formats
117
118 def _extract_items(self, playlist):
119 return playlist.findall('./{http://bbc.co.uk/2008/emp/playlist}item')
120
121 def _extract_medias(self, media_selection):
122 error = media_selection.find('./{http://bbc.co.uk/2008/mp/mediaselection}error')
123 if error is not None:
124 raise ExtractorError(
125 '%s returned error: %s' % (self.IE_NAME, error.get('id')), expected=True)
126 return media_selection.findall('./{http://bbc.co.uk/2008/mp/mediaselection}media')
127
128 def _extract_connections(self, media):
129 return media.findall('./{http://bbc.co.uk/2008/mp/mediaselection}connection')
130
131 def _extract_video(self, media, programme_id):
132 formats = []
133 vbr = int(media.get('bitrate'))
134 vcodec = media.get('encoding')
135 service = media.get('service')
136 width = int(media.get('width'))
137 height = int(media.get('height'))
138 file_size = int(media.get('media_file_size'))
139 for connection in self._extract_connections(media):
140 conn_formats = self._extract_connection(connection, programme_id)
141 for format in conn_formats:
142 format.update({
143 'format_id': '%s_%s' % (service, format['format_id']),
144 'width': width,
145 'height': height,
146 'vbr': vbr,
147 'vcodec': vcodec,
148 'filesize': file_size,
149 })
150 formats.extend(conn_formats)
151 return formats
152
153 def _extract_audio(self, media, programme_id):
154 formats = []
155 abr = int(media.get('bitrate'))
156 acodec = media.get('encoding')
157 service = media.get('service')
158 for connection in self._extract_connections(media):
159 conn_formats = self._extract_connection(connection, programme_id)
160 for format in conn_formats:
161 format.update({
162 'format_id': '%s_%s' % (service, format['format_id']),
163 'abr': abr,
164 'acodec': acodec,
165 })
166 formats.extend(conn_formats)
167 return formats
168
169 def _extract_captions(self, media, programme_id):
170 subtitles = {}
171 for connection in self._extract_connections(media):
172 captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
173 lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
174 ps = captions.findall('./{0}body/{0}div/{0}p'.format('{http://www.w3.org/2006/10/ttaf1}'))
175 srt = ''
176 for pos, p in enumerate(ps):
177 srt += '%s\r\n%s --> %s\r\n%s\r\n\r\n' % (str(pos), p.get('begin'), p.get('end'),
178 p.text.strip() if p.text is not None else '')
179 subtitles[lang] = srt
180 return subtitles
181
182 def _download_media_selector(self, programme_id):
183 try:
184 media_selection = self._download_xml(
185 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s' % programme_id,
186 programme_id, 'Downloading media selection XML')
187 except ExtractorError as ee:
188 if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
189 media_selection = xml.etree.ElementTree.fromstring(ee.cause.read().encode('utf-8'))
190 else:
191 raise
192
193 formats = []
194 subtitles = None
195
196 for media in self._extract_medias(media_selection):
197 kind = media.get('kind')
198 if kind == 'audio':
199 formats.extend(self._extract_audio(media, programme_id))
200 elif kind == 'video':
201 formats.extend(self._extract_video(media, programme_id))
202 elif kind == 'captions':
203 subtitles = self._extract_captions(media, programme_id)
204
205 return formats, subtitles
206
207 def _real_extract(self, url):
208 group_id = self._match_id(url)
209
210 webpage = self._download_webpage(url, group_id, 'Downloading video page')
211
212 programme_id = self._search_regex(
213 r'"vpid"\s*:\s*"([\da-z]{8})"', webpage, 'vpid', fatal=False)
214 if programme_id:
215 player = self._download_json(
216 'http://www.bbc.co.uk/iplayer/episode/%s.json' % group_id,
217 group_id)['jsConf']['player']
218 title = player['title']
219 description = player['subtitle']
220 duration = player['duration']
221 formats, subtitles = self._download_media_selector(programme_id)
222 else:
223 playlist = self._download_xml(
224 'http://www.bbc.co.uk/iplayer/playlist/%s' % group_id,
225 group_id, 'Downloading playlist XML')
226
227 no_items = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}noItems')
228 if no_items is not None:
229 reason = no_items.get('reason')
230 if reason == 'preAvailability':
231 msg = 'Episode %s is not yet available' % group_id
232 elif reason == 'postAvailability':
233 msg = 'Episode %s is no longer available' % group_id
234 elif reason == 'noMedia':
235 msg = 'Episode %s is not currently available' % group_id
236 else:
237 msg = 'Episode %s is not available: %s' % (group_id, reason)
238 raise ExtractorError(msg, expected=True)
239
240 for item in self._extract_items(playlist):
241 kind = item.get('kind')
242 if kind != 'programme' and kind != 'radioProgramme':
243 continue
244 title = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}title').text
245 description = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}summary').text
246 programme_id = item.get('identifier')
247 duration = int(item.get('duration'))
248 formats, subtitles = self._download_media_selector(programme_id)
249
250 if self._downloader.params.get('listsubtitles', False):
251 self._list_available_subtitles(programme_id, subtitles)
252 return
253
254 self._sort_formats(formats)
255
256 return {
257 'id': programme_id,
258 'title': title,
259 'description': description,
260 'duration': duration,
261 'formats': formats,
262 'subtitles': subtitles,
263 }