You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

380 lines
16 KiB

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