bbc.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  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 = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}summary').text
  377. def get_programme_id(item):
  378. def get_from_attributes(item):
  379. for p in('identifier', 'group'):
  380. value = item.get(p)
  381. if value and re.match(r'^[pb][\da-z]{7}$', value):
  382. return value
  383. get_from_attributes(item)
  384. mediator = item.find('./{http://bbc.co.uk/2008/emp/playlist}mediator')
  385. if mediator is not None:
  386. return get_from_attributes(mediator)
  387. programme_id = get_programme_id(item)
  388. duration = int_or_none(item.get('duration'))
  389. # TODO: programme_id can be None and media items can be incorporated right inside
  390. # playlist's item (e.g. http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
  391. # as f4m and m3u8
  392. formats, subtitles = self._download_media_selector(programme_id)
  393. return programme_id, title, description, duration, formats, subtitles
  394. def _real_extract(self, url):
  395. group_id = self._match_id(url)
  396. webpage = self._download_webpage(url, group_id, 'Downloading video page')
  397. programme_id = None
  398. tviplayer = self._search_regex(
  399. r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
  400. webpage, 'player', default=None)
  401. if tviplayer:
  402. player = self._parse_json(tviplayer, group_id).get('player', {})
  403. duration = int_or_none(player.get('duration'))
  404. programme_id = player.get('vpid')
  405. if not programme_id:
  406. programme_id = self._search_regex(
  407. r'"vpid"\s*:\s*"([\da-z]{8})"', webpage, 'vpid', fatal=False, default=None)
  408. if programme_id:
  409. formats, subtitles = self._download_media_selector(programme_id)
  410. title = self._og_search_title(webpage)
  411. description = self._search_regex(
  412. r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
  413. webpage, 'description', fatal=False)
  414. else:
  415. programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
  416. self._sort_formats(formats)
  417. return {
  418. 'id': programme_id,
  419. 'title': title,
  420. 'description': description,
  421. 'thumbnail': self._og_search_thumbnail(webpage, default=None),
  422. 'duration': duration,
  423. 'formats': formats,
  424. 'subtitles': subtitles,
  425. }
  426. class BBCIE(BBCCoUkIE):
  427. IE_NAME = 'bbc'
  428. IE_DESC = 'BBC'
  429. _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
  430. _MEDIASELECTOR_URLS = [
  431. # Provides more formats, namely direct mp4 links, but fails on some videos with
  432. # notukerror for non UK (?) users (e.g.
  433. # http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
  434. 'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s',
  435. # Provides fewer formats, but works everywhere for everybody (hopefully)
  436. 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s',
  437. ]
  438. _TESTS = [{
  439. # article with multiple videos embedded with data-media-meta containing
  440. # playlist.sxml, externalId and no direct video links
  441. 'url': 'http://www.bbc.com/news/world-europe-32668511',
  442. 'info_dict': {
  443. 'id': 'world-europe-32668511',
  444. 'title': 'Russia stages massive WW2 parade despite Western boycott',
  445. 'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
  446. },
  447. 'playlist_count': 2,
  448. }, {
  449. # article with multiple videos embedded with data-media-meta (more videos)
  450. 'url': 'http://www.bbc.com/news/business-28299555',
  451. 'info_dict': {
  452. 'id': 'business-28299555',
  453. 'title': 'Farnborough Airshow: Video highlights',
  454. 'description': 'BBC reports and video highlights at the Farnborough Airshow.',
  455. },
  456. 'playlist_count': 9,
  457. 'skip': 'Save time',
  458. }, {
  459. # article with multiple videos embedded with `new SMP()`
  460. 'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
  461. 'info_dict': {
  462. 'id': '3662a707-0af9-3149-963f-47bea720b460',
  463. 'title': 'BBC Blogs - Adam Curtis - BUGGER',
  464. },
  465. 'playlist_count': 18,
  466. }, {
  467. # single video embedded with mediaAssetPage.init()
  468. 'url': 'http://www.bbc.com/news/world-europe-32041533',
  469. 'info_dict': {
  470. 'id': 'p02mprgb',
  471. 'ext': 'mp4',
  472. 'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
  473. 'duration': 47,
  474. 'timestamp': 1427219242,
  475. 'upload_date': '20150324',
  476. },
  477. 'params': {
  478. # rtmp download
  479. 'skip_download': True,
  480. }
  481. }, {
  482. # article with single video embedded with data-media-meta containing
  483. # direct video links (for now these are extracted) and playlist.xml (with
  484. # media items as f4m and m3u8 - currently unsupported)
  485. 'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
  486. 'info_dict': {
  487. 'id': '150615_telabyad_kentin_cogu',
  488. 'ext': 'mp4',
  489. 'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
  490. 'duration': 47,
  491. 'timestamp': 1434397334,
  492. 'upload_date': '20150615',
  493. },
  494. 'params': {
  495. 'skip_download': True,
  496. }
  497. }, {
  498. # single video embedded with mediaAssetPage.init() (regional section)
  499. 'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
  500. 'info_dict': {
  501. 'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
  502. 'ext': 'mp4',
  503. 'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
  504. 'duration': 87,
  505. 'timestamp': 1434713142,
  506. 'upload_date': '20150619',
  507. },
  508. 'params': {
  509. 'skip_download': True,
  510. }
  511. }, {
  512. # single video from video playlist embedded with vxp-playlist-data JSON
  513. 'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
  514. 'info_dict': {
  515. 'id': 'p02w6qjc',
  516. 'ext': 'mp4',
  517. 'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
  518. 'duration': 56,
  519. },
  520. 'params': {
  521. 'skip_download': True,
  522. }
  523. }, {
  524. # single video story with digitalData
  525. 'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
  526. 'info_dict': {
  527. 'id': 'p02q6gc4',
  528. 'ext': 'flv',
  529. 'title': 'Sri Lanka’s spicy secret',
  530. 'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
  531. 'timestamp': 1437674293,
  532. 'upload_date': '20150723',
  533. },
  534. 'params': {
  535. # rtmp download
  536. 'skip_download': True,
  537. }
  538. }, {
  539. # single video story without digitalData
  540. 'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
  541. 'info_dict': {
  542. 'id': 'p018zqqg',
  543. 'ext': 'mp4',
  544. 'title': 'Hyundai Santa Fe Sport: Rock star',
  545. 'description': 'md5:b042a26142c4154a6e472933cf20793d',
  546. 'timestamp': 1368473503,
  547. 'upload_date': '20130513',
  548. },
  549. 'params': {
  550. # rtmp download
  551. 'skip_download': True,
  552. }
  553. }, {
  554. # single video with playlist.sxml URL
  555. 'url': 'http://www.bbc.com/sport/0/football/33653409',
  556. 'info_dict': {
  557. 'id': 'p02xycnp',
  558. 'ext': 'mp4',
  559. 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
  560. 'description': 'md5:398fca0e2e701c609d726e034fa1fc89',
  561. 'duration': 140,
  562. },
  563. 'params': {
  564. # rtmp download
  565. 'skip_download': True,
  566. }
  567. }, {
  568. # article with multiple videos embedded with playlist.sxml
  569. 'url': 'http://www.bbc.com/sport/0/football/34475836',
  570. 'info_dict': {
  571. 'id': '34475836',
  572. 'title': 'What Liverpool can expect from Klopp',
  573. },
  574. 'playlist_count': 3,
  575. }, {
  576. # single video with playlist URL from weather section
  577. 'url': 'http://www.bbc.com/weather/features/33601775',
  578. 'only_matching': True,
  579. }, {
  580. # custom redirection to www.bbc.com
  581. 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
  582. 'only_matching': True,
  583. }]
  584. @classmethod
  585. def suitable(cls, url):
  586. return False if BBCCoUkIE.suitable(url) else super(BBCIE, cls).suitable(url)
  587. def _extract_from_media_meta(self, media_meta, video_id):
  588. # Direct links to media in media metadata (e.g.
  589. # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
  590. # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
  591. source_files = media_meta.get('sourceFiles')
  592. if source_files:
  593. return [{
  594. 'url': f['url'],
  595. 'format_id': format_id,
  596. 'ext': f.get('encoding'),
  597. 'tbr': float_or_none(f.get('bitrate'), 1000),
  598. 'filesize': int_or_none(f.get('filesize')),
  599. } for format_id, f in source_files.items() if f.get('url')], []
  600. programme_id = media_meta.get('externalId')
  601. if programme_id:
  602. return self._download_media_selector(programme_id)
  603. # Process playlist.sxml as legacy playlist
  604. href = media_meta.get('href')
  605. if href:
  606. playlist = self._download_legacy_playlist_url(href)
  607. _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
  608. return formats, subtitles
  609. return [], []
  610. def _real_extract(self, url):
  611. playlist_id = self._match_id(url)
  612. webpage = self._download_webpage(url, playlist_id)
  613. timestamp = parse_iso8601(self._search_regex(
  614. [r'"datePublished":\s*"([^"]+)',
  615. r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
  616. r'itemprop="datePublished"[^>]+datetime="([^"]+)"'],
  617. webpage, 'date', default=None))
  618. # article with multiple videos embedded with playlist.sxml (e.g.
  619. # http://www.bbc.com/sport/0/football/34475836)
  620. playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
  621. if playlists:
  622. entries = []
  623. for playlist in playlists:
  624. programme_id, title, description, duration, formats, subtitles = \
  625. self._process_legacy_playlist_url(playlist, playlist_id)
  626. self._sort_formats(formats)
  627. entries.append({
  628. 'id': programme_id,
  629. 'title': title,
  630. 'description': description,
  631. 'duration': duration,
  632. 'timestamp': timestamp,
  633. 'formats': formats,
  634. 'subtitles': subtitles,
  635. })
  636. playlist_title = self._og_search_title(webpage)
  637. playlist_description = self._og_search_description(webpage)
  638. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
  639. # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
  640. programme_id = self._search_regex(
  641. [r'data-video-player-vpid="([\da-z]{8})"',
  642. r'<param[^>]+name="externalIdentifier"[^>]+value="([\da-z]{8})"'],
  643. webpage, 'vpid', default=None)
  644. duration = None
  645. if not programme_id:
  646. # single video in news article embedded with data-playable (e.g.
  647. # http://www.bbc.com/news/world-us-canada-34473351)
  648. data_playable = self._parse_json(
  649. unescapeHTML(self._search_regex(
  650. r'data-playable="({.+?})"', webpage, 'data playable', default='{}')),
  651. programme_id, fatal=False)
  652. if data_playable:
  653. items = data_playable.get('settings', {}).get('playlistObject', {}).get('items')
  654. if items and isinstance(items, list):
  655. duration = int_or_none(items[0].get('duration'))
  656. programme_id = items[0].get('vpid')
  657. if programme_id:
  658. formats, subtitles = self._download_media_selector(programme_id)
  659. self._sort_formats(formats)
  660. # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
  661. digital_data = self._parse_json(
  662. self._search_regex(
  663. r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
  664. programme_id, fatal=False)
  665. page_info = digital_data.get('page', {}).get('pageInfo', {})
  666. title = page_info.get('pageName') or self._og_search_title(webpage)
  667. description = page_info.get('description') or self._og_search_description(webpage)
  668. timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
  669. return {
  670. 'id': programme_id,
  671. 'title': title,
  672. 'description': description,
  673. 'timestamp': timestamp,
  674. 'duration': duration,
  675. 'formats': formats,
  676. 'subtitles': subtitles,
  677. }
  678. playlist_title = self._html_search_regex(
  679. r'<title>(.*?)(?:\s*-\s*BBC [^ ]+)?</title>', webpage, 'playlist title')
  680. playlist_description = self._og_search_description(webpage, default=None)
  681. def extract_all(pattern):
  682. return list(filter(None, map(
  683. lambda s: self._parse_json(s, playlist_id, fatal=False),
  684. re.findall(pattern, webpage))))
  685. # Multiple video article (e.g.
  686. # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
  687. EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+[\da-z]{8}(?:\b[^"]+)?'
  688. entries = []
  689. for match in extract_all(r'new\s+SMP\(({.+?})\)'):
  690. embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
  691. if embed_url and re.match(EMBED_URL, embed_url):
  692. entries.append(embed_url)
  693. entries.extend(re.findall(
  694. r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
  695. if entries:
  696. return self.playlist_result(
  697. [self.url_result(entry, 'BBCCoUk') for entry in entries],
  698. playlist_id, playlist_title, playlist_description)
  699. # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
  700. medias = extract_all(r"data-media-meta='({[^']+})'")
  701. if not medias:
  702. # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
  703. media_asset = self._search_regex(
  704. r'mediaAssetPage\.init\(\s*({.+?}), "/',
  705. webpage, 'media asset', default=None)
  706. if media_asset:
  707. media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
  708. medias = []
  709. for video in media_asset_page.get('videos', {}).values():
  710. medias.extend(video.values())
  711. if not medias:
  712. # Multiple video playlist with single `now playing` entry (e.g.
  713. # http://www.bbc.com/news/video_and_audio/must_see/33767813)
  714. vxp_playlist = self._parse_json(
  715. self._search_regex(
  716. r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
  717. webpage, 'playlist data'),
  718. playlist_id)
  719. playlist_medias = []
  720. for item in vxp_playlist:
  721. media = item.get('media')
  722. if not media:
  723. continue
  724. playlist_medias.append(media)
  725. # Download single video if found media with asset id matching the video id from URL
  726. if item.get('advert', {}).get('assetId') == playlist_id:
  727. medias = [media]
  728. break
  729. # Fallback to the whole playlist
  730. if not medias:
  731. medias = playlist_medias
  732. entries = []
  733. for num, media_meta in enumerate(medias, start=1):
  734. formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
  735. if not formats:
  736. continue
  737. self._sort_formats(formats)
  738. video_id = media_meta.get('externalId')
  739. if not video_id:
  740. video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
  741. title = media_meta.get('caption')
  742. if not title:
  743. title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
  744. duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
  745. images = []
  746. for image in media_meta.get('images', {}).values():
  747. images.extend(image.values())
  748. if 'image' in media_meta:
  749. images.append(media_meta['image'])
  750. thumbnails = [{
  751. 'url': image.get('href'),
  752. 'width': int_or_none(image.get('width')),
  753. 'height': int_or_none(image.get('height')),
  754. } for image in images]
  755. entries.append({
  756. 'id': video_id,
  757. 'title': title,
  758. 'thumbnails': thumbnails,
  759. 'duration': duration,
  760. 'timestamp': timestamp,
  761. 'formats': formats,
  762. 'subtitles': subtitles,
  763. })
  764. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)