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.

379 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/episode/b05zmgwn/royal-academy-summer-exhibition',
  129. 'info_dict': {
  130. 'id': 'b05zmgw1',
  131. 'ext': 'flv',
  132. '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.',
  133. 'title': 'Royal Academy Summer Exhibition',
  134. 'duration': 3540,
  135. },
  136. 'params': {
  137. # rtmp download
  138. 'skip_download': True,
  139. },
  140. 'skip': 'geolocation',
  141. }, {
  142. 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
  143. 'only_matching': True,
  144. }, {
  145. 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
  146. 'only_matching': True,
  147. }, {
  148. 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
  149. 'only_matching': True,
  150. }
  151. ]
  152. def _extract_asx_playlist(self, connection, programme_id):
  153. asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
  154. return [ref.get('href') for ref in asx.findall('./Entry/ref')]
  155. def _extract_connection(self, connection, programme_id):
  156. formats = []
  157. protocol = connection.get('protocol')
  158. supplier = connection.get('supplier')
  159. if protocol == 'http':
  160. href = connection.get('href')
  161. # ASX playlist
  162. if supplier == 'asx':
  163. for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
  164. formats.append({
  165. 'url': ref,
  166. 'format_id': 'ref%s_%s' % (i, supplier),
  167. })
  168. # Direct link
  169. else:
  170. formats.append({
  171. 'url': href,
  172. 'format_id': supplier,
  173. })
  174. elif protocol == 'rtmp':
  175. application = connection.get('application', 'ondemand')
  176. auth_string = connection.get('authString')
  177. identifier = connection.get('identifier')
  178. server = connection.get('server')
  179. formats.append({
  180. 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
  181. 'play_path': identifier,
  182. 'app': '%s?%s' % (application, auth_string),
  183. 'page_url': 'http://www.bbc.co.uk',
  184. 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
  185. 'rtmp_live': False,
  186. 'ext': 'flv',
  187. 'format_id': supplier,
  188. })
  189. return formats
  190. def _extract_items(self, playlist):
  191. return playlist.findall('./{http://bbc.co.uk/2008/emp/playlist}item')
  192. def _extract_medias(self, media_selection):
  193. error = media_selection.find('./{http://bbc.co.uk/2008/mp/mediaselection}error')
  194. if error is not None:
  195. raise ExtractorError(
  196. '%s returned error: %s' % (self.IE_NAME, error.get('id')), expected=True)
  197. return media_selection.findall('./{http://bbc.co.uk/2008/mp/mediaselection}media')
  198. def _extract_connections(self, media):
  199. return media.findall('./{http://bbc.co.uk/2008/mp/mediaselection}connection')
  200. def _extract_video(self, media, programme_id):
  201. formats = []
  202. vbr = int_or_none(media.get('bitrate'))
  203. vcodec = media.get('encoding')
  204. service = media.get('service')
  205. width = int_or_none(media.get('width'))
  206. height = int_or_none(media.get('height'))
  207. file_size = int_or_none(media.get('media_file_size'))
  208. for connection in self._extract_connections(media):
  209. conn_formats = self._extract_connection(connection, programme_id)
  210. for format in conn_formats:
  211. format.update({
  212. 'format_id': '%s_%s' % (service, format['format_id']),
  213. 'width': width,
  214. 'height': height,
  215. 'vbr': vbr,
  216. 'vcodec': vcodec,
  217. 'filesize': file_size,
  218. })
  219. formats.extend(conn_formats)
  220. return formats
  221. def _extract_audio(self, media, programme_id):
  222. formats = []
  223. abr = int_or_none(media.get('bitrate'))
  224. acodec = media.get('encoding')
  225. service = media.get('service')
  226. for connection in self._extract_connections(media):
  227. conn_formats = self._extract_connection(connection, programme_id)
  228. for format in conn_formats:
  229. format.update({
  230. 'format_id': '%s_%s' % (service, format['format_id']),
  231. 'abr': abr,
  232. 'acodec': acodec,
  233. })
  234. formats.extend(conn_formats)
  235. return formats
  236. def _get_subtitles(self, media, programme_id):
  237. subtitles = {}
  238. for connection in self._extract_connections(media):
  239. captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
  240. lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
  241. subtitles[lang] = [
  242. {
  243. 'url': connection.get('href'),
  244. 'ext': 'ttml',
  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().decode('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_or_none(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_or_none(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. }