bbc.py 56 KB

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