bbccouk.py 16 KB

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