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.

263 lines
11 KiB

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