bbc.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. from .common import InfoExtractor
  5. from ..utils import (
  6. ExtractorError,
  7. float_or_none,
  8. int_or_none,
  9. parse_duration,
  10. parse_iso8601,
  11. remove_end,
  12. unescapeHTML,
  13. )
  14. from ..compat import (
  15. compat_etree_fromstring,
  16. compat_HTTPError,
  17. )
  18. class BBCCoUkIE(InfoExtractor):
  19. IE_NAME = 'bbc.co.uk'
  20. IE_DESC = 'BBC iPlayer'
  21. _ID_REGEX = r'[pb][\da-z]{7}'
  22. _VALID_URL = r'''(?x)
  23. https?://
  24. (?:www\.)?bbc\.co\.uk/
  25. (?:
  26. programmes/(?!articles/)|
  27. iplayer(?:/[^/]+)?/(?:episode/|playlist/)|
  28. music/clips[/#]|
  29. radio/player/
  30. )
  31. (?P<id>%s)
  32. ''' % _ID_REGEX
  33. _MEDIASELECTOR_URLS = [
  34. # Provides HQ HLS streams with even better quality that pc mediaset but fails
  35. # with geolocation in some cases when it's even not geo restricted at all (e.g.
  36. # http://www.bbc.co.uk/programmes/b06bp7lf). Also may fail with selectionunavailable.
  37. 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
  38. 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s',
  39. ]
  40. _MEDIASELECTION_NS = 'http://bbc.co.uk/2008/mp/mediaselection'
  41. _EMP_PLAYLIST_NS = 'http://bbc.co.uk/2008/emp/playlist'
  42. _NAMESPACES = (
  43. _MEDIASELECTION_NS,
  44. _EMP_PLAYLIST_NS,
  45. )
  46. _TESTS = [
  47. {
  48. 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
  49. 'info_dict': {
  50. 'id': 'b039d07m',
  51. 'ext': 'flv',
  52. 'title': 'Leonard Cohen, Kaleidoscope - BBC Radio 4',
  53. 'description': 'The Canadian poet and songwriter reflects on his musical career.',
  54. },
  55. 'params': {
  56. # rtmp download
  57. 'skip_download': True,
  58. }
  59. },
  60. {
  61. 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
  62. 'info_dict': {
  63. 'id': 'b00yng1d',
  64. 'ext': 'flv',
  65. 'title': 'The Man in Black: Series 3: The Printed Name',
  66. 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
  67. 'duration': 1800,
  68. },
  69. 'params': {
  70. # rtmp download
  71. 'skip_download': True,
  72. },
  73. 'skip': 'Episode is no longer available on BBC iPlayer Radio',
  74. },
  75. {
  76. 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
  77. 'info_dict': {
  78. 'id': 'b00yng1d',
  79. 'ext': 'flv',
  80. 'title': 'The Voice UK: Series 3: Blind Auditions 5',
  81. '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.",
  82. 'duration': 5100,
  83. },
  84. 'params': {
  85. # rtmp download
  86. 'skip_download': True,
  87. },
  88. 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
  89. },
  90. {
  91. 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
  92. 'info_dict': {
  93. 'id': 'b03k3pb7',
  94. 'ext': 'flv',
  95. 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
  96. 'description': '2. Invasion',
  97. 'duration': 3600,
  98. },
  99. 'params': {
  100. # rtmp download
  101. 'skip_download': True,
  102. },
  103. 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
  104. }, {
  105. 'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
  106. 'info_dict': {
  107. 'id': 'b04v209v',
  108. 'ext': 'flv',
  109. 'title': 'Pete Tong, The Essential New Tune Special',
  110. 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
  111. 'duration': 10800,
  112. },
  113. 'params': {
  114. # rtmp download
  115. 'skip_download': True,
  116. },
  117. 'skip': 'Episode is no longer available on BBC iPlayer Radio',
  118. }, {
  119. 'url': 'http://www.bbc.co.uk/music/clips/p022h44b',
  120. 'note': 'Audio',
  121. 'info_dict': {
  122. 'id': 'p022h44j',
  123. 'ext': 'flv',
  124. 'title': 'BBC Proms Music Guides, Rachmaninov: Symphonic Dances',
  125. 'description': "In this Proms Music Guide, Andrew McGregor looks at Rachmaninov's Symphonic Dances.",
  126. 'duration': 227,
  127. },
  128. 'params': {
  129. # rtmp download
  130. 'skip_download': True,
  131. }
  132. }, {
  133. 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
  134. 'note': 'Video',
  135. 'info_dict': {
  136. 'id': 'p025c103',
  137. 'ext': 'flv',
  138. 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
  139. 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
  140. 'duration': 226,
  141. },
  142. 'params': {
  143. # rtmp download
  144. 'skip_download': True,
  145. }
  146. }, {
  147. 'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
  148. 'info_dict': {
  149. 'id': 'p02n76xf',
  150. 'ext': 'flv',
  151. 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
  152. 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
  153. 'duration': 3540,
  154. },
  155. 'params': {
  156. # rtmp download
  157. 'skip_download': True,
  158. },
  159. 'skip': 'geolocation',
  160. }, {
  161. 'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
  162. 'info_dict': {
  163. 'id': 'b05zmgw1',
  164. 'ext': 'flv',
  165. '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.',
  166. 'title': 'Royal Academy Summer Exhibition',
  167. 'duration': 3540,
  168. },
  169. 'params': {
  170. # rtmp download
  171. 'skip_download': True,
  172. },
  173. 'skip': 'geolocation',
  174. }, {
  175. # iptv-all mediaset fails with geolocation however there is no geo restriction
  176. # for this programme at all
  177. 'url': 'http://www.bbc.co.uk/programmes/b06rkn85',
  178. 'info_dict': {
  179. 'id': 'b06rkms3',
  180. 'ext': 'flv',
  181. 'title': "Best of the Mini-Mixes 2015: Part 3, Annie Mac's Friday Night - BBC Radio 1",
  182. 'description': "Annie has part three in the Best of the Mini-Mixes 2015, plus the year's Most Played!",
  183. },
  184. 'params': {
  185. # rtmp download
  186. 'skip_download': True,
  187. },
  188. }, {
  189. 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
  190. 'only_matching': True,
  191. }, {
  192. 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
  193. 'only_matching': True,
  194. }, {
  195. 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
  196. 'only_matching': True,
  197. }, {
  198. 'url': 'http://www.bbc.co.uk/radio/player/p03cchwf',
  199. 'only_matching': True,
  200. }
  201. ]
  202. class MediaSelectionError(Exception):
  203. def __init__(self, id):
  204. self.id = id
  205. def _extract_asx_playlist(self, connection, programme_id):
  206. asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
  207. return [ref.get('href') for ref in asx.findall('./Entry/ref')]
  208. def _extract_connection(self, connection, programme_id):
  209. formats = []
  210. kind = connection.get('kind')
  211. protocol = connection.get('protocol')
  212. supplier = connection.get('supplier')
  213. if protocol == 'http':
  214. href = connection.get('href')
  215. transfer_format = connection.get('transferFormat')
  216. # ASX playlist
  217. if supplier == 'asx':
  218. for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
  219. formats.append({
  220. 'url': ref,
  221. 'format_id': 'ref%s_%s' % (i, supplier),
  222. })
  223. # Skip DASH until supported
  224. elif transfer_format == 'dash':
  225. pass
  226. elif transfer_format == 'hls':
  227. formats.extend(self._extract_m3u8_formats(
  228. href, programme_id, ext='mp4', entry_protocol='m3u8_native',
  229. m3u8_id=supplier, fatal=False))
  230. # Direct link
  231. else:
  232. formats.append({
  233. 'url': href,
  234. 'format_id': supplier or kind or protocol,
  235. })
  236. elif protocol == 'rtmp':
  237. application = connection.get('application', 'ondemand')
  238. auth_string = connection.get('authString')
  239. identifier = connection.get('identifier')
  240. server = connection.get('server')
  241. formats.append({
  242. 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
  243. 'play_path': identifier,
  244. 'app': '%s?%s' % (application, auth_string),
  245. 'page_url': 'http://www.bbc.co.uk',
  246. 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
  247. 'rtmp_live': False,
  248. 'ext': 'flv',
  249. 'format_id': supplier,
  250. })
  251. return formats
  252. def _extract_items(self, playlist):
  253. return playlist.findall('./{%s}item' % self._EMP_PLAYLIST_NS)
  254. def _findall_ns(self, element, xpath):
  255. elements = []
  256. for ns in self._NAMESPACES:
  257. elements.extend(element.findall(xpath % ns))
  258. return elements
  259. def _extract_medias(self, media_selection):
  260. error = media_selection.find('./{%s}error' % self._MEDIASELECTION_NS)
  261. if error is None:
  262. media_selection.find('./{%s}error' % self._EMP_PLAYLIST_NS)
  263. if error is not None:
  264. raise BBCCoUkIE.MediaSelectionError(error.get('id'))
  265. return self._findall_ns(media_selection, './{%s}media')
  266. def _extract_connections(self, media):
  267. return self._findall_ns(media, './{%s}connection')
  268. def _extract_video(self, media, programme_id):
  269. formats = []
  270. vbr = int_or_none(media.get('bitrate'))
  271. vcodec = media.get('encoding')
  272. service = media.get('service')
  273. width = int_or_none(media.get('width'))
  274. height = int_or_none(media.get('height'))
  275. file_size = int_or_none(media.get('media_file_size'))
  276. for connection in self._extract_connections(media):
  277. conn_formats = self._extract_connection(connection, programme_id)
  278. for format in conn_formats:
  279. format.update({
  280. 'width': width,
  281. 'height': height,
  282. 'vbr': vbr,
  283. 'vcodec': vcodec,
  284. 'filesize': file_size,
  285. })
  286. if service:
  287. format['format_id'] = '%s_%s' % (service, format['format_id'])
  288. formats.extend(conn_formats)
  289. return formats
  290. def _extract_audio(self, media, programme_id):
  291. formats = []
  292. abr = int_or_none(media.get('bitrate'))
  293. acodec = media.get('encoding')
  294. service = media.get('service')
  295. for connection in self._extract_connections(media):
  296. conn_formats = self._extract_connection(connection, programme_id)
  297. for format in conn_formats:
  298. format.update({
  299. 'format_id': '%s_%s' % (service, format['format_id']),
  300. 'abr': abr,
  301. 'acodec': acodec,
  302. })
  303. formats.extend(conn_formats)
  304. return formats
  305. def _get_subtitles(self, media, programme_id):
  306. subtitles = {}
  307. for connection in self._extract_connections(media):
  308. captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
  309. lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
  310. subtitles[lang] = [
  311. {
  312. 'url': connection.get('href'),
  313. 'ext': 'ttml',
  314. },
  315. ]
  316. return subtitles
  317. def _raise_extractor_error(self, media_selection_error):
  318. raise ExtractorError(
  319. '%s returned error: %s' % (self.IE_NAME, media_selection_error.id),
  320. expected=True)
  321. def _download_media_selector(self, programme_id):
  322. last_exception = None
  323. for mediaselector_url in self._MEDIASELECTOR_URLS:
  324. try:
  325. return self._download_media_selector_url(
  326. mediaselector_url % programme_id, programme_id)
  327. except BBCCoUkIE.MediaSelectionError as e:
  328. if e.id in ('notukerror', 'geolocation', 'selectionunavailable'):
  329. last_exception = e
  330. continue
  331. self._raise_extractor_error(e)
  332. self._raise_extractor_error(last_exception)
  333. def _download_media_selector_url(self, url, programme_id=None):
  334. try:
  335. media_selection = self._download_xml(
  336. url, programme_id, 'Downloading media selection XML')
  337. except ExtractorError as ee:
  338. if isinstance(ee.cause, compat_HTTPError) and ee.cause.code in (403, 404):
  339. media_selection = compat_etree_fromstring(ee.cause.read().decode('utf-8'))
  340. else:
  341. raise
  342. return self._process_media_selector(media_selection, programme_id)
  343. def _process_media_selector(self, media_selection, programme_id):
  344. formats = []
  345. subtitles = None
  346. for media in self._extract_medias(media_selection):
  347. kind = media.get('kind')
  348. if kind == 'audio':
  349. formats.extend(self._extract_audio(media, programme_id))
  350. elif kind == 'video':
  351. formats.extend(self._extract_video(media, programme_id))
  352. elif kind == 'captions':
  353. subtitles = self.extract_subtitles(media, programme_id)
  354. return formats, subtitles
  355. def _download_playlist(self, playlist_id):
  356. try:
  357. playlist = self._download_json(
  358. 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
  359. playlist_id, 'Downloading playlist JSON')
  360. version = playlist.get('defaultAvailableVersion')
  361. if version:
  362. smp_config = version['smpConfig']
  363. title = smp_config['title']
  364. description = smp_config['summary']
  365. for item in smp_config['items']:
  366. kind = item['kind']
  367. if kind != 'programme' and kind != 'radioProgramme':
  368. continue
  369. programme_id = item.get('vpid')
  370. duration = int_or_none(item.get('duration'))
  371. formats, subtitles = self._download_media_selector(programme_id)
  372. return programme_id, title, description, duration, formats, subtitles
  373. except ExtractorError as ee:
  374. if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
  375. raise
  376. # fallback to legacy playlist
  377. return self._process_legacy_playlist(playlist_id)
  378. def _process_legacy_playlist_url(self, url, display_id):
  379. playlist = self._download_legacy_playlist_url(url, display_id)
  380. return self._extract_from_legacy_playlist(playlist, display_id)
  381. def _process_legacy_playlist(self, playlist_id):
  382. return self._process_legacy_playlist_url(
  383. 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
  384. def _download_legacy_playlist_url(self, url, playlist_id=None):
  385. return self._download_xml(
  386. url, playlist_id, 'Downloading legacy playlist XML')
  387. def _extract_from_legacy_playlist(self, playlist, playlist_id):
  388. no_items = playlist.find('./{%s}noItems' % self._EMP_PLAYLIST_NS)
  389. if no_items is not None:
  390. reason = no_items.get('reason')
  391. if reason == 'preAvailability':
  392. msg = 'Episode %s is not yet available' % playlist_id
  393. elif reason == 'postAvailability':
  394. msg = 'Episode %s is no longer available' % playlist_id
  395. elif reason == 'noMedia':
  396. msg = 'Episode %s is not currently available' % playlist_id
  397. else:
  398. msg = 'Episode %s is not available: %s' % (playlist_id, reason)
  399. raise ExtractorError(msg, expected=True)
  400. for item in self._extract_items(playlist):
  401. kind = item.get('kind')
  402. if kind != 'programme' and kind != 'radioProgramme':
  403. continue
  404. title = playlist.find('./{%s}title' % self._EMP_PLAYLIST_NS).text
  405. description_el = playlist.find('./{%s}summary' % self._EMP_PLAYLIST_NS)
  406. description = description_el.text if description_el is not None else None
  407. def get_programme_id(item):
  408. def get_from_attributes(item):
  409. for p in('identifier', 'group'):
  410. value = item.get(p)
  411. if value and re.match(r'^[pb][\da-z]{7}$', value):
  412. return value
  413. get_from_attributes(item)
  414. mediator = item.find('./{%s}mediator' % self._EMP_PLAYLIST_NS)
  415. if mediator is not None:
  416. return get_from_attributes(mediator)
  417. programme_id = get_programme_id(item)
  418. duration = int_or_none(item.get('duration'))
  419. if programme_id:
  420. formats, subtitles = self._download_media_selector(programme_id)
  421. else:
  422. formats, subtitles = self._process_media_selector(item, playlist_id)
  423. programme_id = playlist_id
  424. return programme_id, title, description, duration, formats, subtitles
  425. def _real_extract(self, url):
  426. group_id = self._match_id(url)
  427. webpage = self._download_webpage(url, group_id, 'Downloading video page')
  428. programme_id = None
  429. duration = None
  430. tviplayer = self._search_regex(
  431. r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
  432. webpage, 'player', default=None)
  433. if tviplayer:
  434. player = self._parse_json(tviplayer, group_id).get('player', {})
  435. duration = int_or_none(player.get('duration'))
  436. programme_id = player.get('vpid')
  437. if not programme_id:
  438. programme_id = self._search_regex(
  439. r'"vpid"\s*:\s*"(%s)"' % self._ID_REGEX, webpage, 'vpid', fatal=False, default=None)
  440. if programme_id:
  441. formats, subtitles = self._download_media_selector(programme_id)
  442. title = self._og_search_title(webpage, default=None) or self._html_search_regex(
  443. (r'<h2[^>]+id="parent-title"[^>]*>(.+?)</h2>',
  444. r'<div[^>]+class="info"[^>]*>\s*<h1>(.+?)</h1>'), webpage, 'title')
  445. description = self._search_regex(
  446. r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
  447. webpage, 'description', default=None)
  448. if not description:
  449. description = self._html_search_meta('description', webpage)
  450. else:
  451. programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
  452. self._sort_formats(formats)
  453. return {
  454. 'id': programme_id,
  455. 'title': title,
  456. 'description': description,
  457. 'thumbnail': self._og_search_thumbnail(webpage, default=None),
  458. 'duration': duration,
  459. 'formats': formats,
  460. 'subtitles': subtitles,
  461. }
  462. class BBCIE(BBCCoUkIE):
  463. IE_NAME = 'bbc'
  464. IE_DESC = 'BBC'
  465. _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
  466. _MEDIASELECTOR_URLS = [
  467. # Provides HQ HLS streams but fails with geolocation in some cases when it's
  468. # even not geo restricted at all
  469. 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
  470. # Provides more formats, namely direct mp4 links, but fails on some videos with
  471. # notukerror for non UK (?) users (e.g.
  472. # http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
  473. 'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s',
  474. # Provides fewer formats, but works everywhere for everybody (hopefully)
  475. 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s',
  476. ]
  477. _TESTS = [{
  478. # article with multiple videos embedded with data-playable containing vpids
  479. 'url': 'http://www.bbc.com/news/world-europe-32668511',
  480. 'info_dict': {
  481. 'id': 'world-europe-32668511',
  482. 'title': 'Russia stages massive WW2 parade despite Western boycott',
  483. 'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
  484. },
  485. 'playlist_count': 2,
  486. }, {
  487. # article with multiple videos embedded with data-playable (more videos)
  488. 'url': 'http://www.bbc.com/news/business-28299555',
  489. 'info_dict': {
  490. 'id': 'business-28299555',
  491. 'title': 'Farnborough Airshow: Video highlights',
  492. 'description': 'BBC reports and video highlights at the Farnborough Airshow.',
  493. },
  494. 'playlist_count': 9,
  495. 'skip': 'Save time',
  496. }, {
  497. # article with multiple videos embedded with `new SMP()`
  498. # broken
  499. 'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
  500. 'info_dict': {
  501. 'id': '3662a707-0af9-3149-963f-47bea720b460',
  502. 'title': 'BBC Blogs - Adam Curtis - BUGGER',
  503. },
  504. 'playlist_count': 18,
  505. }, {
  506. # single video embedded with data-playable containing vpid
  507. 'url': 'http://www.bbc.com/news/world-europe-32041533',
  508. 'info_dict': {
  509. 'id': 'p02mprgb',
  510. 'ext': 'mp4',
  511. 'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
  512. 'description': 'md5:2868290467291b37feda7863f7a83f54',
  513. 'duration': 47,
  514. 'timestamp': 1427219242,
  515. 'upload_date': '20150324',
  516. },
  517. 'params': {
  518. # rtmp download
  519. 'skip_download': True,
  520. }
  521. }, {
  522. # article with single video embedded with data-playable containing XML playlist
  523. # with direct video links as progressiveDownloadUrl (for now these are extracted)
  524. # and playlist with f4m and m3u8 as streamingUrl
  525. 'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
  526. 'info_dict': {
  527. 'id': '150615_telabyad_kentin_cogu',
  528. 'ext': 'mp4',
  529. 'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
  530. 'timestamp': 1434397334,
  531. 'upload_date': '20150615',
  532. },
  533. 'params': {
  534. 'skip_download': True,
  535. }
  536. }, {
  537. # single video embedded with data-playable containing XML playlists (regional section)
  538. 'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
  539. 'info_dict': {
  540. 'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
  541. 'ext': 'mp4',
  542. 'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
  543. 'timestamp': 1434713142,
  544. 'upload_date': '20150619',
  545. },
  546. 'params': {
  547. 'skip_download': True,
  548. }
  549. }, {
  550. # single video from video playlist embedded with vxp-playlist-data JSON
  551. 'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
  552. 'info_dict': {
  553. 'id': 'p02w6qjc',
  554. 'ext': 'mp4',
  555. 'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
  556. 'duration': 56,
  557. 'description': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
  558. },
  559. 'params': {
  560. 'skip_download': True,
  561. }
  562. }, {
  563. # single video story with digitalData
  564. 'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
  565. 'info_dict': {
  566. 'id': 'p02q6gc4',
  567. 'ext': 'flv',
  568. 'title': 'Sri Lanka’s spicy secret',
  569. 'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
  570. 'timestamp': 1437674293,
  571. 'upload_date': '20150723',
  572. },
  573. 'params': {
  574. # rtmp download
  575. 'skip_download': True,
  576. }
  577. }, {
  578. # single video story without digitalData
  579. 'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
  580. 'info_dict': {
  581. 'id': 'p018zqqg',
  582. 'ext': 'mp4',
  583. 'title': 'Hyundai Santa Fe Sport: Rock star',
  584. 'description': 'md5:b042a26142c4154a6e472933cf20793d',
  585. 'timestamp': 1415867444,
  586. 'upload_date': '20141113',
  587. },
  588. 'params': {
  589. # rtmp download
  590. 'skip_download': True,
  591. }
  592. }, {
  593. # single video with playlist.sxml URL in playlist param
  594. 'url': 'http://www.bbc.com/sport/0/football/33653409',
  595. 'info_dict': {
  596. 'id': 'p02xycnp',
  597. 'ext': 'mp4',
  598. 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
  599. 'description': 'BBC Sport\'s David Ornstein has the latest transfer gossip, including rumours of a Manchester United return for Cristiano Ronaldo.',
  600. 'duration': 140,
  601. },
  602. 'params': {
  603. # rtmp download
  604. 'skip_download': True,
  605. }
  606. }, {
  607. # article with multiple videos embedded with playlist.sxml in playlist param
  608. 'url': 'http://www.bbc.com/sport/0/football/34475836',
  609. 'info_dict': {
  610. 'id': '34475836',
  611. 'title': 'What Liverpool can expect from Klopp',
  612. },
  613. 'playlist_count': 3,
  614. }, {
  615. # single video with playlist URL from weather section
  616. 'url': 'http://www.bbc.com/weather/features/33601775',
  617. 'only_matching': True,
  618. }, {
  619. # custom redirection to www.bbc.com
  620. 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
  621. 'only_matching': True,
  622. }]
  623. @classmethod
  624. def suitable(cls, url):
  625. return False if BBCCoUkIE.suitable(url) or BBCCoUkArticleIE.suitable(url) else super(BBCIE, cls).suitable(url)
  626. def _extract_from_media_meta(self, media_meta, video_id):
  627. # Direct links to media in media metadata (e.g.
  628. # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
  629. # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
  630. source_files = media_meta.get('sourceFiles')
  631. if source_files:
  632. return [{
  633. 'url': f['url'],
  634. 'format_id': format_id,
  635. 'ext': f.get('encoding'),
  636. 'tbr': float_or_none(f.get('bitrate'), 1000),
  637. 'filesize': int_or_none(f.get('filesize')),
  638. } for format_id, f in source_files.items() if f.get('url')], []
  639. programme_id = media_meta.get('externalId')
  640. if programme_id:
  641. return self._download_media_selector(programme_id)
  642. # Process playlist.sxml as legacy playlist
  643. href = media_meta.get('href')
  644. if href:
  645. playlist = self._download_legacy_playlist_url(href)
  646. _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
  647. return formats, subtitles
  648. return [], []
  649. def _extract_from_playlist_sxml(self, url, playlist_id, timestamp):
  650. programme_id, title, description, duration, formats, subtitles = \
  651. self._process_legacy_playlist_url(url, playlist_id)
  652. self._sort_formats(formats)
  653. return {
  654. 'id': programme_id,
  655. 'title': title,
  656. 'description': description,
  657. 'duration': duration,
  658. 'timestamp': timestamp,
  659. 'formats': formats,
  660. 'subtitles': subtitles,
  661. }
  662. def _real_extract(self, url):
  663. playlist_id = self._match_id(url)
  664. webpage = self._download_webpage(url, playlist_id)
  665. json_ld_info = self._search_json_ld(webpage, playlist_id, default=None)
  666. timestamp = json_ld_info.get('timestamp')
  667. playlist_title = json_ld_info.get('title')
  668. playlist_description = json_ld_info.get('description')
  669. if not timestamp:
  670. timestamp = parse_iso8601(self._search_regex(
  671. [r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
  672. r'itemprop="datePublished"[^>]+datetime="([^"]+)"',
  673. r'"datePublished":\s*"([^"]+)'],
  674. webpage, 'date', default=None))
  675. entries = []
  676. # article with multiple videos embedded with playlist.sxml (e.g.
  677. # http://www.bbc.com/sport/0/football/34475836)
  678. playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
  679. playlists.extend(re.findall(r'data-media-id="([^"]+/playlist\.sxml)"', webpage))
  680. if playlists:
  681. entries = [
  682. self._extract_from_playlist_sxml(playlist_url, playlist_id, timestamp)
  683. for playlist_url in playlists]
  684. # news article with multiple videos embedded with data-playable
  685. data_playables = re.findall(r'data-playable=(["\'])({.+?})\1', webpage)
  686. if data_playables:
  687. for _, data_playable_json in data_playables:
  688. data_playable = self._parse_json(
  689. unescapeHTML(data_playable_json), playlist_id, fatal=False)
  690. if not data_playable:
  691. continue
  692. settings = data_playable.get('settings', {})
  693. if settings:
  694. # data-playable with video vpid in settings.playlistObject.items (e.g.
  695. # http://www.bbc.com/news/world-us-canada-34473351)
  696. playlist_object = settings.get('playlistObject', {})
  697. if playlist_object:
  698. items = playlist_object.get('items')
  699. if items and isinstance(items, list):
  700. title = playlist_object['title']
  701. description = playlist_object.get('summary')
  702. duration = int_or_none(items[0].get('duration'))
  703. programme_id = items[0].get('vpid')
  704. formats, subtitles = self._download_media_selector(programme_id)
  705. self._sort_formats(formats)
  706. entries.append({
  707. 'id': programme_id,
  708. 'title': title,
  709. 'description': description,
  710. 'timestamp': timestamp,
  711. 'duration': duration,
  712. 'formats': formats,
  713. 'subtitles': subtitles,
  714. })
  715. else:
  716. # data-playable without vpid but with a playlist.sxml URLs
  717. # in otherSettings.playlist (e.g.
  718. # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
  719. playlist = data_playable.get('otherSettings', {}).get('playlist', {})
  720. if playlist:
  721. entries.append(self._extract_from_playlist_sxml(
  722. playlist.get('progressiveDownloadUrl'), playlist_id, timestamp))
  723. if entries:
  724. playlist_title = playlist_title or remove_end(self._og_search_title(webpage), ' - BBC News')
  725. playlist_description = playlist_description or self._og_search_description(webpage, default=None)
  726. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
  727. # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
  728. programme_id = self._search_regex(
  729. [r'data-video-player-vpid="(%s)"' % self._ID_REGEX,
  730. r'<param[^>]+name="externalIdentifier"[^>]+value="(%s)"' % self._ID_REGEX,
  731. r'videoId\s*:\s*["\'](%s)["\']' % self._ID_REGEX],
  732. webpage, 'vpid', default=None)
  733. if programme_id:
  734. formats, subtitles = self._download_media_selector(programme_id)
  735. self._sort_formats(formats)
  736. # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
  737. digital_data = self._parse_json(
  738. self._search_regex(
  739. r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
  740. programme_id, fatal=False)
  741. page_info = digital_data.get('page', {}).get('pageInfo', {})
  742. title = page_info.get('pageName') or self._og_search_title(webpage)
  743. description = page_info.get('description') or self._og_search_description(webpage)
  744. timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
  745. return {
  746. 'id': programme_id,
  747. 'title': title,
  748. 'description': description,
  749. 'timestamp': timestamp,
  750. 'formats': formats,
  751. 'subtitles': subtitles,
  752. }
  753. playlist_title = self._html_search_regex(
  754. r'<title>(.*?)(?:\s*-\s*BBC [^ ]+)?</title>', webpage, 'playlist title')
  755. playlist_description = self._og_search_description(webpage, default=None)
  756. def extract_all(pattern):
  757. return list(filter(None, map(
  758. lambda s: self._parse_json(s, playlist_id, fatal=False),
  759. re.findall(pattern, webpage))))
  760. # Multiple video article (e.g.
  761. # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
  762. EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+%s(?:\b[^"]+)?' % self._ID_REGEX
  763. entries = []
  764. for match in extract_all(r'new\s+SMP\(({.+?})\)'):
  765. embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
  766. if embed_url and re.match(EMBED_URL, embed_url):
  767. entries.append(embed_url)
  768. entries.extend(re.findall(
  769. r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
  770. if entries:
  771. return self.playlist_result(
  772. [self.url_result(entry, 'BBCCoUk') for entry in entries],
  773. playlist_id, playlist_title, playlist_description)
  774. # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
  775. medias = extract_all(r"data-media-meta='({[^']+})'")
  776. if not medias:
  777. # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
  778. media_asset = self._search_regex(
  779. r'mediaAssetPage\.init\(\s*({.+?}), "/',
  780. webpage, 'media asset', default=None)
  781. if media_asset:
  782. media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
  783. medias = []
  784. for video in media_asset_page.get('videos', {}).values():
  785. medias.extend(video.values())
  786. if not medias:
  787. # Multiple video playlist with single `now playing` entry (e.g.
  788. # http://www.bbc.com/news/video_and_audio/must_see/33767813)
  789. vxp_playlist = self._parse_json(
  790. self._search_regex(
  791. r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
  792. webpage, 'playlist data'),
  793. playlist_id)
  794. playlist_medias = []
  795. for item in vxp_playlist:
  796. media = item.get('media')
  797. if not media:
  798. continue
  799. playlist_medias.append(media)
  800. # Download single video if found media with asset id matching the video id from URL
  801. if item.get('advert', {}).get('assetId') == playlist_id:
  802. medias = [media]
  803. break
  804. # Fallback to the whole playlist
  805. if not medias:
  806. medias = playlist_medias
  807. entries = []
  808. for num, media_meta in enumerate(medias, start=1):
  809. formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
  810. if not formats:
  811. continue
  812. self._sort_formats(formats)
  813. video_id = media_meta.get('externalId')
  814. if not video_id:
  815. video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
  816. title = media_meta.get('caption')
  817. if not title:
  818. title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
  819. duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
  820. images = []
  821. for image in media_meta.get('images', {}).values():
  822. images.extend(image.values())
  823. if 'image' in media_meta:
  824. images.append(media_meta['image'])
  825. thumbnails = [{
  826. 'url': image.get('href'),
  827. 'width': int_or_none(image.get('width')),
  828. 'height': int_or_none(image.get('height')),
  829. } for image in images]
  830. entries.append({
  831. 'id': video_id,
  832. 'title': title,
  833. 'thumbnails': thumbnails,
  834. 'duration': duration,
  835. 'timestamp': timestamp,
  836. 'formats': formats,
  837. 'subtitles': subtitles,
  838. })
  839. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
  840. class BBCCoUkArticleIE(InfoExtractor):
  841. _VALID_URL = 'http://www.bbc.co.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)'
  842. IE_NAME = 'bbc.co.uk:article'
  843. IE_DESC = 'BBC articles'
  844. _TEST = {
  845. 'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer',
  846. 'info_dict': {
  847. 'id': '3jNQLTMrPlYGTBn0WV6M2MS',
  848. 'title': 'Calculating Ada: The Countess of Computing - Not your typical role model: Ada Lovelace the 19th century programmer - BBC Four',
  849. 'description': 'Hannah Fry reveals some of her surprising discoveries about Ada Lovelace during filming.',
  850. },
  851. 'playlist_count': 4,
  852. 'add_ie': ['BBCCoUk'],
  853. }
  854. def _real_extract(self, url):
  855. playlist_id = self._match_id(url)
  856. webpage = self._download_webpage(url, playlist_id)
  857. title = self._og_search_title(webpage)
  858. description = self._og_search_description(webpage).strip()
  859. entries = [self.url_result(programme_url) for programme_url in re.findall(
  860. r'<div[^>]+typeof="Clip"[^>]+resource="([^"]+)"', webpage)]
  861. return self.playlist_result(entries, playlist_id, title, description)