bbc.py 44 KB

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