bbc.py 36 KB

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