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.

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