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.

303 lines
13 KiB

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