Merge pull request #3927 from qrtt1/master
[youtube-dl] / 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)/(?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': 'md5:db4755d7a665ae72343779f7dacb402c',
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     ]
76
77     def _extract_asx_playlist(self, connection, programme_id):
78         asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
79         return [ref.get('href') for ref in asx.findall('./Entry/ref')]
80
81     def _extract_connection(self, connection, programme_id):
82         formats = []
83         protocol = connection.get('protocol')
84         supplier = connection.get('supplier')
85         if protocol == 'http':
86             href = connection.get('href')
87             # ASX playlist
88             if supplier == 'asx':
89                 for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
90                     formats.append({
91                         'url': ref,
92                         'format_id': 'ref%s_%s' % (i, supplier),
93                     })
94             # Direct link
95             else:
96                 formats.append({
97                     'url': href,
98                     'format_id': supplier,
99                 })
100         elif protocol == 'rtmp':
101             application = connection.get('application', 'ondemand')
102             auth_string = connection.get('authString')
103             identifier = connection.get('identifier')
104             server = connection.get('server')
105             formats.append({
106                 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
107                 'play_path': identifier,
108                 'app': '%s?%s' % (application, auth_string),
109                 'page_url': 'http://www.bbc.co.uk',
110                 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
111                 'rtmp_live': False,
112                 'ext': 'flv',
113                 'format_id': supplier,
114             })
115         return formats
116
117     def _extract_items(self, playlist):
118         return playlist.findall('./{http://bbc.co.uk/2008/emp/playlist}item')
119
120     def _extract_medias(self, media_selection):
121         error = media_selection.find('./{http://bbc.co.uk/2008/mp/mediaselection}error')
122         if error is not None:
123             raise ExtractorError(
124                 '%s returned error: %s' % (self.IE_NAME, error.get('id')), expected=True)
125         return media_selection.findall('./{http://bbc.co.uk/2008/mp/mediaselection}media')
126
127     def _extract_connections(self, media):
128         return media.findall('./{http://bbc.co.uk/2008/mp/mediaselection}connection')
129
130     def _extract_video(self, media, programme_id):
131         formats = []
132         vbr = int(media.get('bitrate'))
133         vcodec = media.get('encoding')
134         service = media.get('service')
135         width = int(media.get('width'))
136         height = int(media.get('height'))
137         file_size = int(media.get('media_file_size'))
138         for connection in self._extract_connections(media):
139             conn_formats = self._extract_connection(connection, programme_id)
140             for format in conn_formats:
141                 format.update({
142                     'format_id': '%s_%s' % (service, format['format_id']),
143                     'width': width,
144                     'height': height,
145                     'vbr': vbr,
146                     'vcodec': vcodec,
147                     'filesize': file_size,
148                 })
149             formats.extend(conn_formats)
150         return formats
151
152     def _extract_audio(self, media, programme_id):
153         formats = []
154         abr = int(media.get('bitrate'))
155         acodec = media.get('encoding')
156         service = media.get('service')
157         for connection in self._extract_connections(media):
158             conn_formats = self._extract_connection(connection, programme_id)
159             for format in conn_formats:
160                 format.update({
161                     'format_id': '%s_%s' % (service, format['format_id']),
162                     'abr': abr,
163                     'acodec': acodec,
164                 })
165             formats.extend(conn_formats)
166         return formats
167
168     def _extract_captions(self, media, programme_id):
169         subtitles = {}
170         for connection in self._extract_connections(media):
171             captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
172             lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
173             ps = captions.findall('./{0}body/{0}div/{0}p'.format('{http://www.w3.org/2006/10/ttaf1}'))
174             srt = ''
175             for pos, p in enumerate(ps):
176                 srt += '%s\r\n%s --> %s\r\n%s\r\n\r\n' % (str(pos), p.get('begin'), p.get('end'),
177                                                           p.text.strip() if p.text is not None else '')
178             subtitles[lang] = srt
179         return subtitles
180
181     def _download_media_selector(self, programme_id):
182         try:
183             media_selection = self._download_xml(
184                 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s' % programme_id,
185                 programme_id, 'Downloading media selection XML')
186         except ExtractorError as ee:
187             if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
188                 media_selection = xml.etree.ElementTree.fromstring(ee.cause.read().encode('utf-8'))
189             else:
190                 raise
191
192         formats = []
193         subtitles = None
194
195         for media in self._extract_medias(media_selection):
196             kind = media.get('kind')
197             if kind == 'audio':
198                 formats.extend(self._extract_audio(media, programme_id))
199             elif kind == 'video':
200                 formats.extend(self._extract_video(media, programme_id))
201             elif kind == 'captions':
202                 subtitles = self._extract_captions(media, programme_id)
203
204         return formats, subtitles
205
206     def _real_extract(self, url):
207         group_id = self._match_id(url)
208
209         webpage = self._download_webpage(url, group_id, 'Downloading video page')
210
211         programme_id = self._search_regex(
212             r'"vpid"\s*:\s*"([\da-z]{8})"', webpage, 'vpid', fatal=False)
213         if programme_id:
214             player = self._download_json(
215                 'http://www.bbc.co.uk/iplayer/episode/%s.json' % group_id,
216                 group_id)['jsConf']['player']
217             title = player['title']
218             description = player['subtitle']
219             duration = player['duration']
220             formats, subtitles = self._download_media_selector(programme_id)
221         else:
222             playlist = self._download_xml(
223                 'http://www.bbc.co.uk/iplayer/playlist/%s' % group_id,
224                 group_id, 'Downloading playlist XML')
225
226             no_items = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}noItems')
227             if no_items is not None:
228                 reason = no_items.get('reason')
229                 if reason == 'preAvailability':
230                     msg = 'Episode %s is not yet available' % group_id
231                 elif reason == 'postAvailability':
232                     msg = 'Episode %s is no longer available' % group_id
233                 elif reason == 'noMedia':
234                     msg = 'Episode %s is not currently available' % group_id
235                 else:
236                     msg = 'Episode %s is not available: %s' % (group_id, reason)
237                 raise ExtractorError(msg, expected=True)
238
239             for item in self._extract_items(playlist):
240                 kind = item.get('kind')
241                 if kind != 'programme' and kind != 'radioProgramme':
242                     continue
243                 title = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}title').text
244                 description = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}summary').text
245                 programme_id = item.get('identifier')
246                 duration = int(item.get('duration'))
247                 formats, subtitles = self._download_media_selector(programme_id)
248
249         if self._downloader.params.get('listsubtitles', False):
250             self._list_available_subtitles(programme_id, subtitles)
251             return
252
253         self._sort_formats(formats)
254
255         return {
256             'id': programme_id,
257             'title': title,
258             'description': description,
259             'duration': duration,
260             'formats': formats,
261             'subtitles': subtitles,
262         }