bbc.py 37 KB

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