You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1359 lines
58 KiB

8 years ago
10 years ago
8 years ago
9 years ago
8 years ago
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import itertools
  4. import re
  5. from .common import InfoExtractor
  6. from ..utils import (
  7. clean_html,
  8. dict_get,
  9. ExtractorError,
  10. float_or_none,
  11. get_element_by_class,
  12. int_or_none,
  13. js_to_json,
  14. parse_duration,
  15. parse_iso8601,
  16. try_get,
  17. unescapeHTML,
  18. url_or_none,
  19. urlencode_postdata,
  20. urljoin,
  21. )
  22. from ..compat import (
  23. compat_etree_Element,
  24. compat_HTTPError,
  25. compat_urlparse,
  26. )
  27. class BBCCoUkIE(InfoExtractor):
  28. IE_NAME = 'bbc.co.uk'
  29. IE_DESC = 'BBC iPlayer'
  30. _ID_REGEX = r'(?:[pbm][\da-z]{7}|w[\da-z]{7,14})'
  31. _VALID_URL = r'''(?x)
  32. https?://
  33. (?:www\.)?bbc\.co\.uk/
  34. (?:
  35. programmes/(?!articles/)|
  36. iplayer(?:/[^/]+)?/(?:episode/|playlist/)|
  37. music/(?:clips|audiovideo/popular)[/#]|
  38. radio/player/|
  39. sounds/play/|
  40. events/[^/]+/play/[^/]+/
  41. )
  42. (?P<id>%s)(?!/(?:episodes|broadcasts|clips))
  43. ''' % _ID_REGEX
  44. _LOGIN_URL = 'https://account.bbc.com/signin'
  45. _NETRC_MACHINE = 'bbc'
  46. _MEDIASELECTOR_URLS = [
  47. # Provides HQ HLS streams with even better quality that pc mediaset but fails
  48. # with geolocation in some cases when it's even not geo restricted at all (e.g.
  49. # http://www.bbc.co.uk/programmes/b06bp7lf). Also may fail with selectionunavailable.
  50. 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
  51. 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s',
  52. ]
  53. _MEDIASELECTION_NS = 'http://bbc.co.uk/2008/mp/mediaselection'
  54. _EMP_PLAYLIST_NS = 'http://bbc.co.uk/2008/emp/playlist'
  55. _NAMESPACES = (
  56. _MEDIASELECTION_NS,
  57. _EMP_PLAYLIST_NS,
  58. )
  59. _TESTS = [
  60. {
  61. 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
  62. 'info_dict': {
  63. 'id': 'b039d07m',
  64. 'ext': 'flv',
  65. 'title': 'Kaleidoscope, Leonard Cohen',
  66. 'description': 'The Canadian poet and songwriter reflects on his musical career.',
  67. },
  68. 'params': {
  69. # rtmp download
  70. 'skip_download': True,
  71. }
  72. },
  73. {
  74. 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
  75. 'info_dict': {
  76. 'id': 'b00yng1d',
  77. 'ext': 'flv',
  78. 'title': 'The Man in Black: Series 3: The Printed Name',
  79. 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
  80. 'duration': 1800,
  81. },
  82. 'params': {
  83. # rtmp download
  84. 'skip_download': True,
  85. },
  86. 'skip': 'Episode is no longer available on BBC iPlayer Radio',
  87. },
  88. {
  89. 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
  90. 'info_dict': {
  91. 'id': 'b00yng1d',
  92. 'ext': 'flv',
  93. 'title': 'The Voice UK: Series 3: Blind Auditions 5',
  94. '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.',
  95. 'duration': 5100,
  96. },
  97. 'params': {
  98. # rtmp download
  99. 'skip_download': True,
  100. },
  101. 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
  102. },
  103. {
  104. 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
  105. 'info_dict': {
  106. 'id': 'b03k3pb7',
  107. 'ext': 'flv',
  108. 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
  109. 'description': '2. Invasion',
  110. 'duration': 3600,
  111. },
  112. 'params': {
  113. # rtmp download
  114. 'skip_download': True,
  115. },
  116. 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
  117. }, {
  118. 'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
  119. 'info_dict': {
  120. 'id': 'b04v209v',
  121. 'ext': 'flv',
  122. 'title': 'Pete Tong, The Essential New Tune Special',
  123. 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
  124. 'duration': 10800,
  125. },
  126. 'params': {
  127. # rtmp download
  128. 'skip_download': True,
  129. },
  130. 'skip': 'Episode is no longer available on BBC iPlayer Radio',
  131. }, {
  132. 'url': 'http://www.bbc.co.uk/music/clips/p022h44b',
  133. 'note': 'Audio',
  134. 'info_dict': {
  135. 'id': 'p022h44j',
  136. 'ext': 'flv',
  137. 'title': 'BBC Proms Music Guides, Rachmaninov: Symphonic Dances',
  138. 'description': "In this Proms Music Guide, Andrew McGregor looks at Rachmaninov's Symphonic Dances.",
  139. 'duration': 227,
  140. },
  141. 'params': {
  142. # rtmp download
  143. 'skip_download': True,
  144. }
  145. }, {
  146. 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
  147. 'note': 'Video',
  148. 'info_dict': {
  149. 'id': 'p025c103',
  150. 'ext': 'flv',
  151. 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
  152. 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
  153. 'duration': 226,
  154. },
  155. 'params': {
  156. # rtmp download
  157. 'skip_download': True,
  158. }
  159. }, {
  160. 'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
  161. 'info_dict': {
  162. 'id': 'p02n76xf',
  163. 'ext': 'flv',
  164. 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
  165. 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
  166. 'duration': 3540,
  167. },
  168. 'params': {
  169. # rtmp download
  170. 'skip_download': True,
  171. },
  172. 'skip': 'geolocation',
  173. }, {
  174. 'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
  175. 'info_dict': {
  176. 'id': 'b05zmgw1',
  177. 'ext': 'flv',
  178. '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.',
  179. 'title': 'Royal Academy Summer Exhibition',
  180. 'duration': 3540,
  181. },
  182. 'params': {
  183. # rtmp download
  184. 'skip_download': True,
  185. },
  186. 'skip': 'geolocation',
  187. }, {
  188. # iptv-all mediaset fails with geolocation however there is no geo restriction
  189. # for this programme at all
  190. 'url': 'http://www.bbc.co.uk/programmes/b06rkn85',
  191. 'info_dict': {
  192. 'id': 'b06rkms3',
  193. 'ext': 'flv',
  194. 'title': "Best of the Mini-Mixes 2015: Part 3, Annie Mac's Friday Night - BBC Radio 1",
  195. 'description': "Annie has part three in the Best of the Mini-Mixes 2015, plus the year's Most Played!",
  196. },
  197. 'params': {
  198. # rtmp download
  199. 'skip_download': True,
  200. },
  201. 'skip': 'Now it\'s really geo-restricted',
  202. }, {
  203. # compact player (https://github.com/ytdl-org/youtube-dl/issues/8147)
  204. 'url': 'http://www.bbc.co.uk/programmes/p028bfkf/player',
  205. 'info_dict': {
  206. 'id': 'p028bfkj',
  207. 'ext': 'flv',
  208. 'title': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
  209. 'description': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
  210. },
  211. 'params': {
  212. # rtmp download
  213. 'skip_download': True,
  214. },
  215. }, {
  216. 'url': 'https://www.bbc.co.uk/sounds/play/m0007jzb',
  217. 'note': 'Audio',
  218. 'info_dict': {
  219. 'id': 'm0007jz9',
  220. 'ext': 'mp4',
  221. 'title': 'BBC Proms, 2019, Prom 34: West–Eastern Divan Orchestra',
  222. 'description': "Live BBC Proms. West–Eastern Divan Orchestra with Daniel Barenboim and Martha Argerich.",
  223. 'duration': 9840,
  224. },
  225. 'params': {
  226. # rtmp download
  227. 'skip_download': True,
  228. }
  229. }, {
  230. 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
  231. 'only_matching': True,
  232. }, {
  233. 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
  234. 'only_matching': True,
  235. }, {
  236. 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
  237. 'only_matching': True,
  238. }, {
  239. 'url': 'http://www.bbc.co.uk/radio/player/p03cchwf',
  240. 'only_matching': True,
  241. }, {
  242. 'url': 'https://www.bbc.co.uk/music/audiovideo/popular#p055bc55',
  243. 'only_matching': True,
  244. }, {
  245. 'url': 'http://www.bbc.co.uk/programmes/w3csv1y9',
  246. 'only_matching': True,
  247. }, {
  248. 'url': 'https://www.bbc.co.uk/programmes/m00005xn',
  249. 'only_matching': True,
  250. }, {
  251. 'url': 'https://www.bbc.co.uk/programmes/w172w4dww1jqt5s',
  252. 'only_matching': True,
  253. }]
  254. _USP_RE = r'/([^/]+?)\.ism(?:\.hlsv2\.ism)?/[^/]+\.m3u8'
  255. def _login(self):
  256. username, password = self._get_login_info()
  257. if username is None:
  258. return
  259. login_page = self._download_webpage(
  260. self._LOGIN_URL, None, 'Downloading signin page')
  261. login_form = self._hidden_inputs(login_page)
  262. login_form.update({
  263. 'username': username,
  264. 'password': password,
  265. })
  266. post_url = urljoin(self._LOGIN_URL, self._search_regex(
  267. r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
  268. 'post url', default=self._LOGIN_URL, group='url'))
  269. response, urlh = self._download_webpage_handle(
  270. post_url, None, 'Logging in', data=urlencode_postdata(login_form),
  271. headers={'Referer': self._LOGIN_URL})
  272. if self._LOGIN_URL in urlh.geturl():
  273. error = clean_html(get_element_by_class('form-message', response))
  274. if error:
  275. raise ExtractorError(
  276. 'Unable to login: %s' % error, expected=True)
  277. raise ExtractorError('Unable to log in')
  278. def _real_initialize(self):
  279. self._login()
  280. class MediaSelectionError(Exception):
  281. def __init__(self, id):
  282. self.id = id
  283. def _extract_asx_playlist(self, connection, programme_id):
  284. asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
  285. return [ref.get('href') for ref in asx.findall('./Entry/ref')]
  286. def _extract_items(self, playlist):
  287. return playlist.findall('./{%s}item' % self._EMP_PLAYLIST_NS)
  288. def _findall_ns(self, element, xpath):
  289. elements = []
  290. for ns in self._NAMESPACES:
  291. elements.extend(element.findall(xpath % ns))
  292. return elements
  293. def _extract_medias(self, media_selection):
  294. error = media_selection.find('./{%s}error' % self._MEDIASELECTION_NS)
  295. if error is None:
  296. media_selection.find('./{%s}error' % self._EMP_PLAYLIST_NS)
  297. if error is not None:
  298. raise BBCCoUkIE.MediaSelectionError(error.get('id'))
  299. return self._findall_ns(media_selection, './{%s}media')
  300. def _extract_connections(self, media):
  301. return self._findall_ns(media, './{%s}connection')
  302. def _get_subtitles(self, media, programme_id):
  303. subtitles = {}
  304. for connection in self._extract_connections(media):
  305. cc_url = url_or_none(connection.get('href'))
  306. if not cc_url:
  307. continue
  308. captions = self._download_xml(
  309. cc_url, programme_id, 'Downloading captions', fatal=False)
  310. if not isinstance(captions, compat_etree_Element):
  311. continue
  312. lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
  313. subtitles[lang] = [
  314. {
  315. 'url': connection.get('href'),
  316. 'ext': 'ttml',
  317. },
  318. ]
  319. return subtitles
  320. def _raise_extractor_error(self, media_selection_error):
  321. raise ExtractorError(
  322. '%s returned error: %s' % (self.IE_NAME, media_selection_error.id),
  323. expected=True)
  324. def _download_media_selector(self, programme_id):
  325. last_exception = None
  326. for mediaselector_url in self._MEDIASELECTOR_URLS:
  327. try:
  328. return self._download_media_selector_url(
  329. mediaselector_url % programme_id, programme_id)
  330. except BBCCoUkIE.MediaSelectionError as e:
  331. if e.id in ('notukerror', 'geolocation', 'selectionunavailable'):
  332. last_exception = e
  333. continue
  334. self._raise_extractor_error(e)
  335. self._raise_extractor_error(last_exception)
  336. def _download_media_selector_url(self, url, programme_id=None):
  337. media_selection = self._download_xml(
  338. url, programme_id, 'Downloading media selection XML',
  339. expected_status=(403, 404))
  340. return self._process_media_selector(media_selection, programme_id)
  341. def _process_media_selector(self, media_selection, programme_id):
  342. formats = []
  343. subtitles = None
  344. urls = []
  345. for media in self._extract_medias(media_selection):
  346. kind = media.get('kind')
  347. if kind in ('video', 'audio'):
  348. bitrate = int_or_none(media.get('bitrate'))
  349. encoding = media.get('encoding')
  350. service = media.get('service')
  351. width = int_or_none(media.get('width'))
  352. height = int_or_none(media.get('height'))
  353. file_size = int_or_none(media.get('media_file_size'))
  354. for connection in self._extract_connections(media):
  355. href = connection.get('href')
  356. if href in urls:
  357. continue
  358. if href:
  359. urls.append(href)
  360. conn_kind = connection.get('kind')
  361. protocol = connection.get('protocol')
  362. supplier = connection.get('supplier')
  363. transfer_format = connection.get('transferFormat')
  364. format_id = supplier or conn_kind or protocol
  365. if service:
  366. format_id = '%s_%s' % (service, format_id)
  367. # ASX playlist
  368. if supplier == 'asx':
  369. for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
  370. formats.append({
  371. 'url': ref,
  372. 'format_id': 'ref%s_%s' % (i, format_id),
  373. })
  374. elif transfer_format == 'dash':
  375. formats.extend(self._extract_mpd_formats(
  376. href, programme_id, mpd_id=format_id, fatal=False))
  377. elif transfer_format == 'hls':
  378. formats.extend(self._extract_m3u8_formats(
  379. href, programme_id, ext='mp4', entry_protocol='m3u8_native',
  380. m3u8_id=format_id, fatal=False))
  381. if re.search(self._USP_RE, href):
  382. usp_formats = self._extract_m3u8_formats(
  383. re.sub(self._USP_RE, r'/\1.ism/\1.m3u8', href),
  384. programme_id, ext='mp4', entry_protocol='m3u8_native',
  385. m3u8_id=format_id, fatal=False)
  386. for f in usp_formats:
  387. if f.get('height') and f['height'] > 720:
  388. continue
  389. formats.append(f)
  390. elif transfer_format == 'hds':
  391. formats.extend(self._extract_f4m_formats(
  392. href, programme_id, f4m_id=format_id, fatal=False))
  393. else:
  394. if not service and not supplier and bitrate:
  395. format_id += '-%d' % bitrate
  396. fmt = {
  397. 'format_id': format_id,
  398. 'filesize': file_size,
  399. }
  400. if kind == 'video':
  401. fmt.update({
  402. 'width': width,
  403. 'height': height,
  404. 'tbr': bitrate,
  405. 'vcodec': encoding,
  406. })
  407. else:
  408. fmt.update({
  409. 'abr': bitrate,
  410. 'acodec': encoding,
  411. 'vcodec': 'none',
  412. })
  413. if protocol in ('http', 'https'):
  414. # Direct link
  415. fmt.update({
  416. 'url': href,
  417. })
  418. elif protocol == 'rtmp':
  419. application = connection.get('application', 'ondemand')
  420. auth_string = connection.get('authString')
  421. identifier = connection.get('identifier')
  422. server = connection.get('server')
  423. fmt.update({
  424. 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
  425. 'play_path': identifier,
  426. 'app': '%s?%s' % (application, auth_string),
  427. 'page_url': 'http://www.bbc.co.uk',
  428. 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
  429. 'rtmp_live': False,
  430. 'ext': 'flv',
  431. })
  432. else:
  433. continue
  434. formats.append(fmt)
  435. elif kind == 'captions':
  436. subtitles = self.extract_subtitles(media, programme_id)
  437. return formats, subtitles
  438. def _download_playlist(self, playlist_id):
  439. try:
  440. playlist = self._download_json(
  441. 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
  442. playlist_id, 'Downloading playlist JSON')
  443. version = playlist.get('defaultAvailableVersion')
  444. if version:
  445. smp_config = version['smpConfig']
  446. title = smp_config['title']
  447. description = smp_config['summary']
  448. for item in smp_config['items']:
  449. kind = item['kind']
  450. if kind not in ('programme', 'radioProgramme'):
  451. continue
  452. programme_id = item.get('vpid')
  453. duration = int_or_none(item.get('duration'))
  454. formats, subtitles = self._download_media_selector(programme_id)
  455. return programme_id, title, description, duration, formats, subtitles
  456. except ExtractorError as ee:
  457. if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
  458. raise
  459. # fallback to legacy playlist
  460. return self._process_legacy_playlist(playlist_id)
  461. def _process_legacy_playlist_url(self, url, display_id):
  462. playlist = self._download_legacy_playlist_url(url, display_id)
  463. return self._extract_from_legacy_playlist(playlist, display_id)
  464. def _process_legacy_playlist(self, playlist_id):
  465. return self._process_legacy_playlist_url(
  466. 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
  467. def _download_legacy_playlist_url(self, url, playlist_id=None):
  468. return self._download_xml(
  469. url, playlist_id, 'Downloading legacy playlist XML')
  470. def _extract_from_legacy_playlist(self, playlist, playlist_id):
  471. no_items = playlist.find('./{%s}noItems' % self._EMP_PLAYLIST_NS)
  472. if no_items is not None:
  473. reason = no_items.get('reason')
  474. if reason == 'preAvailability':
  475. msg = 'Episode %s is not yet available' % playlist_id
  476. elif reason == 'postAvailability':
  477. msg = 'Episode %s is no longer available' % playlist_id
  478. elif reason == 'noMedia':
  479. msg = 'Episode %s is not currently available' % playlist_id
  480. else:
  481. msg = 'Episode %s is not available: %s' % (playlist_id, reason)
  482. raise ExtractorError(msg, expected=True)
  483. for item in self._extract_items(playlist):
  484. kind = item.get('kind')
  485. if kind not in ('programme', 'radioProgramme'):
  486. continue
  487. title = playlist.find('./{%s}title' % self._EMP_PLAYLIST_NS).text
  488. description_el = playlist.find('./{%s}summary' % self._EMP_PLAYLIST_NS)
  489. description = description_el.text if description_el is not None else None
  490. def get_programme_id(item):
  491. def get_from_attributes(item):
  492. for p in('identifier', 'group'):
  493. value = item.get(p)
  494. if value and re.match(r'^[pb][\da-z]{7}$', value):
  495. return value
  496. get_from_attributes(item)
  497. mediator = item.find('./{%s}mediator' % self._EMP_PLAYLIST_NS)
  498. if mediator is not None:
  499. return get_from_attributes(mediator)
  500. programme_id = get_programme_id(item)
  501. duration = int_or_none(item.get('duration'))
  502. if programme_id:
  503. formats, subtitles = self._download_media_selector(programme_id)
  504. else:
  505. formats, subtitles = self._process_media_selector(item, playlist_id)
  506. programme_id = playlist_id
  507. return programme_id, title, description, duration, formats, subtitles
  508. def _real_extract(self, url):
  509. group_id = self._match_id(url)
  510. webpage = self._download_webpage(url, group_id, 'Downloading video page')
  511. error = self._search_regex(
  512. r'<div\b[^>]+\bclass=["\']smp__message delta["\'][^>]*>([^<]+)<',
  513. webpage, 'error', default=None)
  514. if error:
  515. raise ExtractorError(error, expected=True)
  516. programme_id = None
  517. duration = None
  518. tviplayer = self._search_regex(
  519. r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
  520. webpage, 'player', default=None)
  521. if tviplayer:
  522. player = self._parse_json(tviplayer, group_id).get('player', {})
  523. duration = int_or_none(player.get('duration'))
  524. programme_id = player.get('vpid')
  525. if not programme_id:
  526. programme_id = self._search_regex(
  527. r'"vpid"\s*:\s*"(%s)"' % self._ID_REGEX, webpage, 'vpid', fatal=False, default=None)
  528. if programme_id:
  529. formats, subtitles = self._download_media_selector(programme_id)
  530. title = self._og_search_title(webpage, default=None) or self._html_search_regex(
  531. (r'<h2[^>]+id="parent-title"[^>]*>(.+?)</h2>',
  532. r'<div[^>]+class="info"[^>]*>\s*<h1>(.+?)</h1>'), webpage, 'title')
  533. description = self._search_regex(
  534. (r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
  535. r'<div[^>]+class="info_+synopsis"[^>]*>([^<]+)</div>'),
  536. webpage, 'description', default=None)
  537. if not description:
  538. description = self._html_search_meta('description', webpage)
  539. else:
  540. programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
  541. self._sort_formats(formats)
  542. return {
  543. 'id': programme_id,
  544. 'title': title,
  545. 'description': description,
  546. 'thumbnail': self._og_search_thumbnail(webpage, default=None),
  547. 'duration': duration,
  548. 'formats': formats,
  549. 'subtitles': subtitles,
  550. }
  551. class BBCIE(BBCCoUkIE):
  552. IE_NAME = 'bbc'
  553. IE_DESC = 'BBC'
  554. _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
  555. _MEDIASELECTOR_URLS = [
  556. # Provides HQ HLS streams but fails with geolocation in some cases when it's
  557. # even not geo restricted at all
  558. 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
  559. # Provides more formats, namely direct mp4 links, but fails on some videos with
  560. # notukerror for non UK (?) users (e.g.
  561. # http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
  562. 'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s',
  563. # Provides fewer formats, but works everywhere for everybody (hopefully)
  564. 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s',
  565. ]
  566. _TESTS = [{
  567. # article with multiple videos embedded with data-playable containing vpids
  568. 'url': 'http://www.bbc.com/news/world-europe-32668511',
  569. 'info_dict': {
  570. 'id': 'world-europe-32668511',
  571. 'title': 'Russia stages massive WW2 parade',
  572. 'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
  573. },
  574. 'playlist_count': 2,
  575. }, {
  576. # article with multiple videos embedded with data-playable (more videos)
  577. 'url': 'http://www.bbc.com/news/business-28299555',
  578. 'info_dict': {
  579. 'id': 'business-28299555',
  580. 'title': 'Farnborough Airshow: Video highlights',
  581. 'description': 'BBC reports and video highlights at the Farnborough Airshow.',
  582. },
  583. 'playlist_count': 9,
  584. 'skip': 'Save time',
  585. }, {
  586. # article with multiple videos embedded with `new SMP()`
  587. # broken
  588. 'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
  589. 'info_dict': {
  590. 'id': '3662a707-0af9-3149-963f-47bea720b460',
  591. 'title': 'BUGGER',
  592. },
  593. 'playlist_count': 18,
  594. }, {
  595. # single video embedded with data-playable containing vpid
  596. 'url': 'http://www.bbc.com/news/world-europe-32041533',
  597. 'info_dict': {
  598. 'id': 'p02mprgb',
  599. 'ext': 'mp4',
  600. 'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
  601. 'description': 'md5:2868290467291b37feda7863f7a83f54',
  602. 'duration': 47,
  603. 'timestamp': 1427219242,
  604. 'upload_date': '20150324',
  605. },
  606. 'params': {
  607. # rtmp download
  608. 'skip_download': True,
  609. }
  610. }, {
  611. # article with single video embedded with data-playable containing XML playlist
  612. # with direct video links as progressiveDownloadUrl (for now these are extracted)
  613. # and playlist with f4m and m3u8 as streamingUrl
  614. 'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
  615. 'info_dict': {
  616. 'id': '150615_telabyad_kentin_cogu',
  617. 'ext': 'mp4',
  618. 'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
  619. 'description': 'md5:33a4805a855c9baf7115fcbde57e7025',
  620. 'timestamp': 1434397334,
  621. 'upload_date': '20150615',
  622. },
  623. 'params': {
  624. 'skip_download': True,
  625. }
  626. }, {
  627. # single video embedded with data-playable containing XML playlists (regional section)
  628. 'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
  629. 'info_dict': {
  630. 'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
  631. 'ext': 'mp4',
  632. 'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
  633. 'description': 'md5:1525f17448c4ee262b64b8f0c9ce66c8',
  634. 'timestamp': 1434713142,
  635. 'upload_date': '20150619',
  636. },
  637. 'params': {
  638. 'skip_download': True,
  639. }
  640. }, {
  641. # single video from video playlist embedded with vxp-playlist-data JSON
  642. 'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
  643. 'info_dict': {
  644. 'id': 'p02w6qjc',
  645. 'ext': 'mp4',
  646. 'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
  647. 'duration': 56,
  648. 'description': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
  649. },
  650. 'params': {
  651. 'skip_download': True,
  652. }
  653. }, {
  654. # single video story with digitalData
  655. 'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
  656. 'info_dict': {
  657. 'id': 'p02q6gc4',
  658. 'ext': 'flv',
  659. 'title': 'Sri Lanka’s spicy secret',
  660. 'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
  661. 'timestamp': 1437674293,
  662. 'upload_date': '20150723',
  663. },
  664. 'params': {
  665. # rtmp download
  666. 'skip_download': True,
  667. }
  668. }, {
  669. # single video story without digitalData
  670. 'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
  671. 'info_dict': {
  672. 'id': 'p018zqqg',
  673. 'ext': 'mp4',
  674. 'title': 'Hyundai Santa Fe Sport: Rock star',
  675. 'description': 'md5:b042a26142c4154a6e472933cf20793d',
  676. 'timestamp': 1415867444,
  677. 'upload_date': '20141113',
  678. },
  679. 'params': {
  680. # rtmp download
  681. 'skip_download': True,
  682. }
  683. }, {
  684. # single video embedded with Morph
  685. 'url': 'http://www.bbc.co.uk/sport/live/olympics/36895975',
  686. 'info_dict': {
  687. 'id': 'p041vhd0',
  688. 'ext': 'mp4',
  689. 'title': "Nigeria v Japan - Men's First Round",
  690. 'description': 'Live coverage of the first round from Group B at the Amazonia Arena.',
  691. 'duration': 7980,
  692. 'uploader': 'BBC Sport',
  693. 'uploader_id': 'bbc_sport',
  694. },
  695. 'params': {
  696. # m3u8 download
  697. 'skip_download': True,
  698. },
  699. 'skip': 'Georestricted to UK',
  700. }, {
  701. # single video with playlist.sxml URL in playlist param
  702. 'url': 'http://www.bbc.com/sport/0/football/33653409',
  703. 'info_dict': {
  704. 'id': 'p02xycnp',
  705. 'ext': 'mp4',
  706. 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
  707. 'description': 'BBC Sport\'s David Ornstein has the latest transfer gossip, including rumours of a Manchester United return for Cristiano Ronaldo.',
  708. 'duration': 140,
  709. },
  710. 'params': {
  711. # rtmp download
  712. 'skip_download': True,
  713. }
  714. }, {
  715. # article with multiple videos embedded with playlist.sxml in playlist param
  716. 'url': 'http://www.bbc.com/sport/0/football/34475836',
  717. 'info_dict': {
  718. 'id': '34475836',
  719. 'title': 'Jurgen Klopp: Furious football from a witty and winning coach',
  720. 'description': 'Fast-paced football, wit, wisdom and a ready smile - why Liverpool fans should come to love new boss Jurgen Klopp.',
  721. },
  722. 'playlist_count': 3,
  723. }, {
  724. # school report article with single video
  725. 'url': 'http://www.bbc.co.uk/schoolreport/35744779',
  726. 'info_dict': {
  727. 'id': '35744779',
  728. 'title': 'School which breaks down barriers in Jerusalem',
  729. },
  730. 'playlist_count': 1,
  731. }, {
  732. # single video with playlist URL from weather section
  733. 'url': 'http://www.bbc.com/weather/features/33601775',
  734. 'only_matching': True,
  735. }, {
  736. # custom redirection to www.bbc.com
  737. 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
  738. 'only_matching': True,
  739. }, {
  740. # single video article embedded with data-media-vpid
  741. 'url': 'http://www.bbc.co.uk/sport/rowing/35908187',
  742. 'only_matching': True,
  743. }, {
  744. 'url': 'https://www.bbc.co.uk/bbcthree/clip/73d0bbd0-abc3-4cea-b3c0-cdae21905eb1',
  745. 'info_dict': {
  746. 'id': 'p06556y7',
  747. 'ext': 'mp4',
  748. 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
  749. 'description': 'md5:4b7dfd063d5a789a1512e99662be3ddd',
  750. },
  751. 'params': {
  752. 'skip_download': True,
  753. }
  754. }, {
  755. # window.__PRELOADED_STATE__
  756. 'url': 'https://www.bbc.co.uk/radio/play/b0b9z4yl',
  757. 'info_dict': {
  758. 'id': 'b0b9z4vz',
  759. 'ext': 'mp4',
  760. 'title': 'Prom 6: An American in Paris and Turangalila',
  761. 'description': 'md5:51cf7d6f5c8553f197e58203bc78dff8',
  762. 'uploader': 'Radio 3',
  763. 'uploader_id': 'bbc_radio_three',
  764. },
  765. }, {
  766. 'url': 'http://www.bbc.co.uk/learningenglish/chinese/features/lingohack/ep-181227',
  767. 'info_dict': {
  768. 'id': 'p06w9tws',
  769. 'ext': 'mp4',
  770. 'title': 'md5:2fabf12a726603193a2879a055f72514',
  771. 'description': 'Learn English words and phrases from this story',
  772. },
  773. 'add_ie': [BBCCoUkIE.ie_key()],
  774. }]
  775. @classmethod
  776. def suitable(cls, url):
  777. EXCLUDE_IE = (BBCCoUkIE, BBCCoUkArticleIE, BBCCoUkIPlayerPlaylistIE, BBCCoUkPlaylistIE)
  778. return (False if any(ie.suitable(url) for ie in EXCLUDE_IE)
  779. else super(BBCIE, cls).suitable(url))
  780. def _extract_from_media_meta(self, media_meta, video_id):
  781. # Direct links to media in media metadata (e.g.
  782. # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
  783. # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
  784. source_files = media_meta.get('sourceFiles')
  785. if source_files:
  786. return [{
  787. 'url': f['url'],
  788. 'format_id': format_id,
  789. 'ext': f.get('encoding'),
  790. 'tbr': float_or_none(f.get('bitrate'), 1000),
  791. 'filesize': int_or_none(f.get('filesize')),
  792. } for format_id, f in source_files.items() if f.get('url')], []
  793. programme_id = media_meta.get('externalId')
  794. if programme_id:
  795. return self._download_media_selector(programme_id)
  796. # Process playlist.sxml as legacy playlist
  797. href = media_meta.get('href')
  798. if href:
  799. playlist = self._download_legacy_playlist_url(href)
  800. _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
  801. return formats, subtitles
  802. return [], []
  803. def _extract_from_playlist_sxml(self, url, playlist_id, timestamp):
  804. programme_id, title, description, duration, formats, subtitles = \
  805. self._process_legacy_playlist_url(url, playlist_id)
  806. self._sort_formats(formats)
  807. return {
  808. 'id': programme_id,
  809. 'title': title,
  810. 'description': description,
  811. 'duration': duration,
  812. 'timestamp': timestamp,
  813. 'formats': formats,
  814. 'subtitles': subtitles,
  815. }
  816. def _real_extract(self, url):
  817. playlist_id = self._match_id(url)
  818. webpage = self._download_webpage(url, playlist_id)
  819. json_ld_info = self._search_json_ld(webpage, playlist_id, default={})
  820. timestamp = json_ld_info.get('timestamp')
  821. playlist_title = json_ld_info.get('title')
  822. if not playlist_title:
  823. playlist_title = self._og_search_title(
  824. webpage, default=None) or self._html_search_regex(
  825. r'<title>(.+?)</title>', webpage, 'playlist title', default=None)
  826. if playlist_title:
  827. playlist_title = re.sub(r'(.+)\s*-\s*BBC.*?$', r'\1', playlist_title).strip()
  828. playlist_description = json_ld_info.get(
  829. 'description') or self._og_search_description(webpage, default=None)
  830. if not timestamp:
  831. timestamp = parse_iso8601(self._search_regex(
  832. [r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
  833. r'itemprop="datePublished"[^>]+datetime="([^"]+)"',
  834. r'"datePublished":\s*"([^"]+)'],
  835. webpage, 'date', default=None))
  836. entries = []
  837. # article with multiple videos embedded with playlist.sxml (e.g.
  838. # http://www.bbc.com/sport/0/football/34475836)
  839. playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
  840. playlists.extend(re.findall(r'data-media-id="([^"]+/playlist\.sxml)"', webpage))
  841. if playlists:
  842. entries = [
  843. self._extract_from_playlist_sxml(playlist_url, playlist_id, timestamp)
  844. for playlist_url in playlists]
  845. # news article with multiple videos embedded with data-playable
  846. data_playables = re.findall(r'data-playable=(["\'])({.+?})\1', webpage)
  847. if data_playables:
  848. for _, data_playable_json in data_playables:
  849. data_playable = self._parse_json(
  850. unescapeHTML(data_playable_json), playlist_id, fatal=False)
  851. if not data_playable:
  852. continue
  853. settings = data_playable.get('settings', {})
  854. if settings:
  855. # data-playable with video vpid in settings.playlistObject.items (e.g.
  856. # http://www.bbc.com/news/world-us-canada-34473351)
  857. playlist_object = settings.get('playlistObject', {})
  858. if playlist_object:
  859. items = playlist_object.get('items')
  860. if items and isinstance(items, list):
  861. title = playlist_object['title']
  862. description = playlist_object.get('summary')
  863. duration = int_or_none(items[0].get('duration'))
  864. programme_id = items[0].get('vpid')
  865. formats, subtitles = self._download_media_selector(programme_id)
  866. self._sort_formats(formats)
  867. entries.append({
  868. 'id': programme_id,
  869. 'title': title,
  870. 'description': description,
  871. 'timestamp': timestamp,
  872. 'duration': duration,
  873. 'formats': formats,
  874. 'subtitles': subtitles,
  875. })
  876. else:
  877. # data-playable without vpid but with a playlist.sxml URLs
  878. # in otherSettings.playlist (e.g.
  879. # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
  880. playlist = data_playable.get('otherSettings', {}).get('playlist', {})
  881. if playlist:
  882. entry = None
  883. for key in ('streaming', 'progressiveDownload'):
  884. playlist_url = playlist.get('%sUrl' % key)
  885. if not playlist_url:
  886. continue
  887. try:
  888. info = self._extract_from_playlist_sxml(
  889. playlist_url, playlist_id, timestamp)
  890. if not entry:
  891. entry = info
  892. else:
  893. entry['title'] = info['title']
  894. entry['formats'].extend(info['formats'])
  895. except Exception as e:
  896. # Some playlist URL may fail with 500, at the same time
  897. # the other one may work fine (e.g.
  898. # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
  899. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 500:
  900. continue
  901. raise
  902. if entry:
  903. self._sort_formats(entry['formats'])
  904. entries.append(entry)
  905. if entries:
  906. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
  907. # http://www.bbc.co.uk/learningenglish/chinese/features/lingohack/ep-181227
  908. group_id = self._search_regex(
  909. r'<div[^>]+\bclass=["\']video["\'][^>]+\bdata-pid=["\'](%s)' % self._ID_REGEX,
  910. webpage, 'group id', default=None)
  911. if playlist_id:
  912. return self.url_result(
  913. 'https://www.bbc.co.uk/programmes/%s' % group_id,
  914. ie=BBCCoUkIE.ie_key())
  915. # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
  916. programme_id = self._search_regex(
  917. [r'data-(?:video-player|media)-vpid="(%s)"' % self._ID_REGEX,
  918. r'<param[^>]+name="externalIdentifier"[^>]+value="(%s)"' % self._ID_REGEX,
  919. r'videoId\s*:\s*["\'](%s)["\']' % self._ID_REGEX],
  920. webpage, 'vpid', default=None)
  921. if programme_id:
  922. formats, subtitles = self._download_media_selector(programme_id)
  923. self._sort_formats(formats)
  924. # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
  925. digital_data = self._parse_json(
  926. self._search_regex(
  927. r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
  928. programme_id, fatal=False)
  929. page_info = digital_data.get('page', {}).get('pageInfo', {})
  930. title = page_info.get('pageName') or self._og_search_title(webpage)
  931. description = page_info.get('description') or self._og_search_description(webpage)
  932. timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
  933. return {
  934. 'id': programme_id,
  935. 'title': title,
  936. 'description': description,
  937. 'timestamp': timestamp,
  938. 'formats': formats,
  939. 'subtitles': subtitles,
  940. }
  941. # Morph based embed (e.g. http://www.bbc.co.uk/sport/live/olympics/36895975)
  942. # There are several setPayload calls may be present but the video
  943. # seems to be always related to the first one
  944. morph_payload = self._parse_json(
  945. self._search_regex(
  946. r'Morph\.setPayload\([^,]+,\s*({.+?})\);',
  947. webpage, 'morph payload', default='{}'),
  948. playlist_id, fatal=False)
  949. if morph_payload:
  950. components = try_get(morph_payload, lambda x: x['body']['components'], list) or []
  951. for component in components:
  952. if not isinstance(component, dict):
  953. continue
  954. lead_media = try_get(component, lambda x: x['props']['leadMedia'], dict)
  955. if not lead_media:
  956. continue
  957. identifiers = lead_media.get('identifiers')
  958. if not identifiers or not isinstance(identifiers, dict):
  959. continue
  960. programme_id = identifiers.get('vpid') or identifiers.get('playablePid')
  961. if not programme_id:
  962. continue
  963. title = lead_media.get('title') or self._og_search_title(webpage)
  964. formats, subtitles = self._download_media_selector(programme_id)
  965. self._sort_formats(formats)
  966. description = lead_media.get('summary')
  967. uploader = lead_media.get('masterBrand')
  968. uploader_id = lead_media.get('mid')
  969. duration = None
  970. duration_d = lead_media.get('duration')
  971. if isinstance(duration_d, dict):
  972. duration = parse_duration(dict_get(
  973. duration_d, ('rawDuration', 'formattedDuration', 'spokenDuration')))
  974. return {
  975. 'id': programme_id,
  976. 'title': title,
  977. 'description': description,
  978. 'duration': duration,
  979. 'uploader': uploader,
  980. 'uploader_id': uploader_id,
  981. 'formats': formats,
  982. 'subtitles': subtitles,
  983. }
  984. preload_state = self._parse_json(self._search_regex(
  985. r'window\.__PRELOADED_STATE__\s*=\s*({.+?});', webpage,
  986. 'preload state', default='{}'), playlist_id, fatal=False)
  987. if preload_state:
  988. current_programme = preload_state.get('programmes', {}).get('current') or {}
  989. programme_id = current_programme.get('id')
  990. if current_programme and programme_id and current_programme.get('type') == 'playable_item':
  991. title = current_programme.get('titles', {}).get('tertiary') or playlist_title
  992. formats, subtitles = self._download_media_selector(programme_id)
  993. self._sort_formats(formats)
  994. synopses = current_programme.get('synopses') or {}
  995. network = current_programme.get('network') or {}
  996. duration = int_or_none(
  997. current_programme.get('duration', {}).get('value'))
  998. thumbnail = None
  999. image_url = current_programme.get('image_url')
  1000. if image_url:
  1001. thumbnail = image_url.replace('{recipe}', '1920x1920')
  1002. return {
  1003. 'id': programme_id,
  1004. 'title': title,
  1005. 'description': dict_get(synopses, ('long', 'medium', 'short')),
  1006. 'thumbnail': thumbnail,
  1007. 'duration': duration,
  1008. 'uploader': network.get('short_title'),
  1009. 'uploader_id': network.get('id'),
  1010. 'formats': formats,
  1011. 'subtitles': subtitles,
  1012. }
  1013. bbc3_config = self._parse_json(
  1014. self._search_regex(
  1015. r'(?s)bbcthreeConfig\s*=\s*({.+?})\s*;\s*<', webpage,
  1016. 'bbcthree config', default='{}'),
  1017. playlist_id, transform_source=js_to_json, fatal=False)
  1018. if bbc3_config:
  1019. bbc3_playlist = try_get(
  1020. bbc3_config, lambda x: x['payload']['content']['bbcMedia']['playlist'],
  1021. dict)
  1022. if bbc3_playlist:
  1023. playlist_title = bbc3_playlist.get('title') or playlist_title
  1024. thumbnail = bbc3_playlist.get('holdingImageURL')
  1025. entries = []
  1026. for bbc3_item in bbc3_playlist['items']:
  1027. programme_id = bbc3_item.get('versionID')
  1028. if not programme_id:
  1029. continue
  1030. formats, subtitles = self._download_media_selector(programme_id)
  1031. self._sort_formats(formats)
  1032. entries.append({
  1033. 'id': programme_id,
  1034. 'title': playlist_title,
  1035. 'thumbnail': thumbnail,
  1036. 'timestamp': timestamp,
  1037. 'formats': formats,
  1038. 'subtitles': subtitles,
  1039. })
  1040. return self.playlist_result(
  1041. entries, playlist_id, playlist_title, playlist_description)
  1042. def extract_all(pattern):
  1043. return list(filter(None, map(
  1044. lambda s: self._parse_json(s, playlist_id, fatal=False),
  1045. re.findall(pattern, webpage))))
  1046. # Multiple video article (e.g.
  1047. # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
  1048. EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+%s(?:\b[^"]+)?' % self._ID_REGEX
  1049. entries = []
  1050. for match in extract_all(r'new\s+SMP\(({.+?})\)'):
  1051. embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
  1052. if embed_url and re.match(EMBED_URL, embed_url):
  1053. entries.append(embed_url)
  1054. entries.extend(re.findall(
  1055. r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
  1056. if entries:
  1057. return self.playlist_result(
  1058. [self.url_result(entry_, 'BBCCoUk') for entry_ in entries],
  1059. playlist_id, playlist_title, playlist_description)
  1060. # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
  1061. medias = extract_all(r"data-media-meta='({[^']+})'")
  1062. if not medias:
  1063. # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
  1064. media_asset = self._search_regex(
  1065. r'mediaAssetPage\.init\(\s*({.+?}), "/',
  1066. webpage, 'media asset', default=None)
  1067. if media_asset:
  1068. media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
  1069. medias = []
  1070. for video in media_asset_page.get('videos', {}).values():
  1071. medias.extend(video.values())
  1072. if not medias:
  1073. # Multiple video playlist with single `now playing` entry (e.g.
  1074. # http://www.bbc.com/news/video_and_audio/must_see/33767813)
  1075. vxp_playlist = self._parse_json(
  1076. self._search_regex(
  1077. r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
  1078. webpage, 'playlist data'),
  1079. playlist_id)
  1080. playlist_medias = []
  1081. for item in vxp_playlist:
  1082. media = item.get('media')
  1083. if not media:
  1084. continue
  1085. playlist_medias.append(media)
  1086. # Download single video if found media with asset id matching the video id from URL
  1087. if item.get('advert', {}).get('assetId') == playlist_id:
  1088. medias = [media]
  1089. break
  1090. # Fallback to the whole playlist
  1091. if not medias:
  1092. medias = playlist_medias
  1093. entries = []
  1094. for num, media_meta in enumerate(medias, start=1):
  1095. formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
  1096. if not formats:
  1097. continue
  1098. self._sort_formats(formats)
  1099. video_id = media_meta.get('externalId')
  1100. if not video_id:
  1101. video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
  1102. title = media_meta.get('caption')
  1103. if not title:
  1104. title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
  1105. duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
  1106. images = []
  1107. for image in media_meta.get('images', {}).values():
  1108. images.extend(image.values())
  1109. if 'image' in media_meta:
  1110. images.append(media_meta['image'])
  1111. thumbnails = [{
  1112. 'url': image.get('href'),
  1113. 'width': int_or_none(image.get('width')),
  1114. 'height': int_or_none(image.get('height')),
  1115. } for image in images]
  1116. entries.append({
  1117. 'id': video_id,
  1118. 'title': title,
  1119. 'thumbnails': thumbnails,
  1120. 'duration': duration,
  1121. 'timestamp': timestamp,
  1122. 'formats': formats,
  1123. 'subtitles': subtitles,
  1124. })
  1125. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
  1126. class BBCCoUkArticleIE(InfoExtractor):
  1127. _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)'
  1128. IE_NAME = 'bbc.co.uk:article'
  1129. IE_DESC = 'BBC articles'
  1130. _TEST = {
  1131. 'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer',
  1132. 'info_dict': {
  1133. 'id': '3jNQLTMrPlYGTBn0WV6M2MS',
  1134. 'title': 'Calculating Ada: The Countess of Computing - Not your typical role model: Ada Lovelace the 19th century programmer - BBC Four',
  1135. 'description': 'Hannah Fry reveals some of her surprising discoveries about Ada Lovelace during filming.',
  1136. },
  1137. 'playlist_count': 4,
  1138. 'add_ie': ['BBCCoUk'],
  1139. }
  1140. def _real_extract(self, url):
  1141. playlist_id = self._match_id(url)
  1142. webpage = self._download_webpage(url, playlist_id)
  1143. title = self._og_search_title(webpage)
  1144. description = self._og_search_description(webpage).strip()
  1145. entries = [self.url_result(programme_url) for programme_url in re.findall(
  1146. r'<div[^>]+typeof="Clip"[^>]+resource="([^"]+)"', webpage)]
  1147. return self.playlist_result(entries, playlist_id, title, description)
  1148. class BBCCoUkPlaylistBaseIE(InfoExtractor):
  1149. def _entries(self, webpage, url, playlist_id):
  1150. single_page = 'page' in compat_urlparse.parse_qs(
  1151. compat_urlparse.urlparse(url).query)
  1152. for page_num in itertools.count(2):
  1153. for video_id in re.findall(
  1154. self._VIDEO_ID_TEMPLATE % BBCCoUkIE._ID_REGEX, webpage):
  1155. yield self.url_result(
  1156. self._URL_TEMPLATE % video_id, BBCCoUkIE.ie_key())
  1157. if single_page:
  1158. return
  1159. next_page = self._search_regex(
  1160. r'<li[^>]+class=(["\'])pagination_+next\1[^>]*><a[^>]+href=(["\'])(?P<url>(?:(?!\2).)+)\2',
  1161. webpage, 'next page url', default=None, group='url')
  1162. if not next_page:
  1163. break
  1164. webpage = self._download_webpage(
  1165. compat_urlparse.urljoin(url, next_page), playlist_id,
  1166. 'Downloading page %d' % page_num, page_num)
  1167. def _real_extract(self, url):
  1168. playlist_id = self._match_id(url)
  1169. webpage = self._download_webpage(url, playlist_id)
  1170. title, description = self._extract_title_and_description(webpage)
  1171. return self.playlist_result(
  1172. self._entries(webpage, url, playlist_id),
  1173. playlist_id, title, description)
  1174. class BBCCoUkIPlayerPlaylistIE(BBCCoUkPlaylistBaseIE):
  1175. IE_NAME = 'bbc.co.uk:iplayer:playlist'
  1176. _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/iplayer/(?:episodes|group)/(?P<id>%s)' % BBCCoUkIE._ID_REGEX
  1177. _URL_TEMPLATE = 'http://www.bbc.co.uk/iplayer/episode/%s'
  1178. _VIDEO_ID_TEMPLATE = r'data-ip-id=["\'](%s)'
  1179. _TESTS = [{
  1180. 'url': 'http://www.bbc.co.uk/iplayer/episodes/b05rcz9v',
  1181. 'info_dict': {
  1182. 'id': 'b05rcz9v',
  1183. 'title': 'The Disappearance',
  1184. 'description': 'French thriller serial about a missing teenager.',
  1185. },
  1186. 'playlist_mincount': 6,
  1187. 'skip': 'This programme is not currently available on BBC iPlayer',
  1188. }, {
  1189. # Available for over a year unlike 30 days for most other programmes
  1190. 'url': 'http://www.bbc.co.uk/iplayer/group/p02tcc32',
  1191. 'info_dict': {
  1192. 'id': 'p02tcc32',
  1193. 'title': 'Bohemian Icons',
  1194. 'description': 'md5:683e901041b2fe9ba596f2ab04c4dbe7',
  1195. },
  1196. 'playlist_mincount': 10,
  1197. }]
  1198. def _extract_title_and_description(self, webpage):
  1199. title = self._search_regex(r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
  1200. description = self._search_regex(
  1201. r'<p[^>]+class=(["\'])subtitle\1[^>]*>(?P<value>[^<]+)</p>',
  1202. webpage, 'description', fatal=False, group='value')
  1203. return title, description
  1204. class BBCCoUkPlaylistIE(BBCCoUkPlaylistBaseIE):
  1205. IE_NAME = 'bbc.co.uk:playlist'
  1206. _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/(?P<id>%s)/(?:episodes|broadcasts|clips)' % BBCCoUkIE._ID_REGEX
  1207. _URL_TEMPLATE = 'http://www.bbc.co.uk/programmes/%s'
  1208. _VIDEO_ID_TEMPLATE = r'data-pid=["\'](%s)'
  1209. _TESTS = [{
  1210. 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
  1211. 'info_dict': {
  1212. 'id': 'b05rcz9v',
  1213. 'title': 'The Disappearance - Clips - BBC Four',
  1214. 'description': 'French thriller serial about a missing teenager.',
  1215. },
  1216. 'playlist_mincount': 7,
  1217. }, {
  1218. # multipage playlist, explicit page
  1219. 'url': 'http://www.bbc.co.uk/programmes/b00mfl7n/clips?page=1',
  1220. 'info_dict': {
  1221. 'id': 'b00mfl7n',
  1222. 'title': 'Frozen Planet - Clips - BBC One',
  1223. 'description': 'md5:65dcbf591ae628dafe32aa6c4a4a0d8c',
  1224. },
  1225. 'playlist_mincount': 24,
  1226. }, {
  1227. # multipage playlist, all pages
  1228. 'url': 'http://www.bbc.co.uk/programmes/b00mfl7n/clips',
  1229. 'info_dict': {
  1230. 'id': 'b00mfl7n',
  1231. 'title': 'Frozen Planet - Clips - BBC One',
  1232. 'description': 'md5:65dcbf591ae628dafe32aa6c4a4a0d8c',
  1233. },
  1234. 'playlist_mincount': 142,
  1235. }, {
  1236. 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/broadcasts/2016/06',
  1237. 'only_matching': True,
  1238. }, {
  1239. 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
  1240. 'only_matching': True,
  1241. }, {
  1242. 'url': 'http://www.bbc.co.uk/programmes/b055jkys/episodes/player',
  1243. 'only_matching': True,
  1244. }]
  1245. def _extract_title_and_description(self, webpage):
  1246. title = self._og_search_title(webpage, fatal=False)
  1247. description = self._og_search_description(webpage)
  1248. return title, description