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.

262 lines
11 KiB

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