bbc.py 37 KB

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