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.

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