bbc.py 46 KB

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