bbc.py 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336
  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. 'url': 'http://www.bbc.co.uk/learningenglish/chinese/features/lingohack/ep-181227',
  744. 'info_dict': {
  745. 'id': 'p06w9tws',
  746. 'ext': 'mp4',
  747. 'title': 'md5:2fabf12a726603193a2879a055f72514',
  748. 'description': 'Learn English words and phrases from this story',
  749. },
  750. 'add_ie': [BBCCoUkIE.ie_key()],
  751. }]
  752. @classmethod
  753. def suitable(cls, url):
  754. EXCLUDE_IE = (BBCCoUkIE, BBCCoUkArticleIE, BBCCoUkIPlayerPlaylistIE, BBCCoUkPlaylistIE)
  755. return (False if any(ie.suitable(url) for ie in EXCLUDE_IE)
  756. else super(BBCIE, cls).suitable(url))
  757. def _extract_from_media_meta(self, media_meta, video_id):
  758. # Direct links to media in media metadata (e.g.
  759. # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
  760. # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
  761. source_files = media_meta.get('sourceFiles')
  762. if source_files:
  763. return [{
  764. 'url': f['url'],
  765. 'format_id': format_id,
  766. 'ext': f.get('encoding'),
  767. 'tbr': float_or_none(f.get('bitrate'), 1000),
  768. 'filesize': int_or_none(f.get('filesize')),
  769. } for format_id, f in source_files.items() if f.get('url')], []
  770. programme_id = media_meta.get('externalId')
  771. if programme_id:
  772. return self._download_media_selector(programme_id)
  773. # Process playlist.sxml as legacy playlist
  774. href = media_meta.get('href')
  775. if href:
  776. playlist = self._download_legacy_playlist_url(href)
  777. _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
  778. return formats, subtitles
  779. return [], []
  780. def _extract_from_playlist_sxml(self, url, playlist_id, timestamp):
  781. programme_id, title, description, duration, formats, subtitles = \
  782. self._process_legacy_playlist_url(url, playlist_id)
  783. self._sort_formats(formats)
  784. return {
  785. 'id': programme_id,
  786. 'title': title,
  787. 'description': description,
  788. 'duration': duration,
  789. 'timestamp': timestamp,
  790. 'formats': formats,
  791. 'subtitles': subtitles,
  792. }
  793. def _real_extract(self, url):
  794. playlist_id = self._match_id(url)
  795. webpage = self._download_webpage(url, playlist_id)
  796. json_ld_info = self._search_json_ld(webpage, playlist_id, default={})
  797. timestamp = json_ld_info.get('timestamp')
  798. playlist_title = json_ld_info.get('title')
  799. if not playlist_title:
  800. playlist_title = self._og_search_title(
  801. webpage, default=None) or self._html_search_regex(
  802. r'<title>(.+?)</title>', webpage, 'playlist title', default=None)
  803. if playlist_title:
  804. playlist_title = re.sub(r'(.+)\s*-\s*BBC.*?$', r'\1', playlist_title).strip()
  805. playlist_description = json_ld_info.get(
  806. 'description') or self._og_search_description(webpage, default=None)
  807. if not timestamp:
  808. timestamp = parse_iso8601(self._search_regex(
  809. [r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
  810. r'itemprop="datePublished"[^>]+datetime="([^"]+)"',
  811. r'"datePublished":\s*"([^"]+)'],
  812. webpage, 'date', default=None))
  813. entries = []
  814. # article with multiple videos embedded with playlist.sxml (e.g.
  815. # http://www.bbc.com/sport/0/football/34475836)
  816. playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
  817. playlists.extend(re.findall(r'data-media-id="([^"]+/playlist\.sxml)"', webpage))
  818. if playlists:
  819. entries = [
  820. self._extract_from_playlist_sxml(playlist_url, playlist_id, timestamp)
  821. for playlist_url in playlists]
  822. # news article with multiple videos embedded with data-playable
  823. data_playables = re.findall(r'data-playable=(["\'])({.+?})\1', webpage)
  824. if data_playables:
  825. for _, data_playable_json in data_playables:
  826. data_playable = self._parse_json(
  827. unescapeHTML(data_playable_json), playlist_id, fatal=False)
  828. if not data_playable:
  829. continue
  830. settings = data_playable.get('settings', {})
  831. if settings:
  832. # data-playable with video vpid in settings.playlistObject.items (e.g.
  833. # http://www.bbc.com/news/world-us-canada-34473351)
  834. playlist_object = settings.get('playlistObject', {})
  835. if playlist_object:
  836. items = playlist_object.get('items')
  837. if items and isinstance(items, list):
  838. title = playlist_object['title']
  839. description = playlist_object.get('summary')
  840. duration = int_or_none(items[0].get('duration'))
  841. programme_id = items[0].get('vpid')
  842. formats, subtitles = self._download_media_selector(programme_id)
  843. self._sort_formats(formats)
  844. entries.append({
  845. 'id': programme_id,
  846. 'title': title,
  847. 'description': description,
  848. 'timestamp': timestamp,
  849. 'duration': duration,
  850. 'formats': formats,
  851. 'subtitles': subtitles,
  852. })
  853. else:
  854. # data-playable without vpid but with a playlist.sxml URLs
  855. # in otherSettings.playlist (e.g.
  856. # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
  857. playlist = data_playable.get('otherSettings', {}).get('playlist', {})
  858. if playlist:
  859. entry = None
  860. for key in ('streaming', 'progressiveDownload'):
  861. playlist_url = playlist.get('%sUrl' % key)
  862. if not playlist_url:
  863. continue
  864. try:
  865. info = self._extract_from_playlist_sxml(
  866. playlist_url, playlist_id, timestamp)
  867. if not entry:
  868. entry = info
  869. else:
  870. entry['title'] = info['title']
  871. entry['formats'].extend(info['formats'])
  872. except Exception as e:
  873. # Some playlist URL may fail with 500, at the same time
  874. # the other one may work fine (e.g.
  875. # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
  876. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 500:
  877. continue
  878. raise
  879. if entry:
  880. self._sort_formats(entry['formats'])
  881. entries.append(entry)
  882. if entries:
  883. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
  884. # http://www.bbc.co.uk/learningenglish/chinese/features/lingohack/ep-181227
  885. group_id = self._search_regex(
  886. r'<div[^>]+\bclass=["\']video["\'][^>]+\bdata-pid=["\'](%s)' % self._ID_REGEX,
  887. webpage, 'group id', default=None)
  888. if playlist_id:
  889. return self.url_result(
  890. 'https://www.bbc.co.uk/programmes/%s' % group_id,
  891. ie=BBCCoUkIE.ie_key())
  892. # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
  893. programme_id = self._search_regex(
  894. [r'data-(?:video-player|media)-vpid="(%s)"' % self._ID_REGEX,
  895. r'<param[^>]+name="externalIdentifier"[^>]+value="(%s)"' % self._ID_REGEX,
  896. r'videoId\s*:\s*["\'](%s)["\']' % self._ID_REGEX],
  897. webpage, 'vpid', default=None)
  898. if programme_id:
  899. formats, subtitles = self._download_media_selector(programme_id)
  900. self._sort_formats(formats)
  901. # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
  902. digital_data = self._parse_json(
  903. self._search_regex(
  904. r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
  905. programme_id, fatal=False)
  906. page_info = digital_data.get('page', {}).get('pageInfo', {})
  907. title = page_info.get('pageName') or self._og_search_title(webpage)
  908. description = page_info.get('description') or self._og_search_description(webpage)
  909. timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
  910. return {
  911. 'id': programme_id,
  912. 'title': title,
  913. 'description': description,
  914. 'timestamp': timestamp,
  915. 'formats': formats,
  916. 'subtitles': subtitles,
  917. }
  918. # Morph based embed (e.g. http://www.bbc.co.uk/sport/live/olympics/36895975)
  919. # There are several setPayload calls may be present but the video
  920. # seems to be always related to the first one
  921. morph_payload = self._parse_json(
  922. self._search_regex(
  923. r'Morph\.setPayload\([^,]+,\s*({.+?})\);',
  924. webpage, 'morph payload', default='{}'),
  925. playlist_id, fatal=False)
  926. if morph_payload:
  927. components = try_get(morph_payload, lambda x: x['body']['components'], list) or []
  928. for component in components:
  929. if not isinstance(component, dict):
  930. continue
  931. lead_media = try_get(component, lambda x: x['props']['leadMedia'], dict)
  932. if not lead_media:
  933. continue
  934. identifiers = lead_media.get('identifiers')
  935. if not identifiers or not isinstance(identifiers, dict):
  936. continue
  937. programme_id = identifiers.get('vpid') or identifiers.get('playablePid')
  938. if not programme_id:
  939. continue
  940. title = lead_media.get('title') or self._og_search_title(webpage)
  941. formats, subtitles = self._download_media_selector(programme_id)
  942. self._sort_formats(formats)
  943. description = lead_media.get('summary')
  944. uploader = lead_media.get('masterBrand')
  945. uploader_id = lead_media.get('mid')
  946. duration = None
  947. duration_d = lead_media.get('duration')
  948. if isinstance(duration_d, dict):
  949. duration = parse_duration(dict_get(
  950. duration_d, ('rawDuration', 'formattedDuration', 'spokenDuration')))
  951. return {
  952. 'id': programme_id,
  953. 'title': title,
  954. 'description': description,
  955. 'duration': duration,
  956. 'uploader': uploader,
  957. 'uploader_id': uploader_id,
  958. 'formats': formats,
  959. 'subtitles': subtitles,
  960. }
  961. preload_state = self._parse_json(self._search_regex(
  962. r'window\.__PRELOADED_STATE__\s*=\s*({.+?});', webpage,
  963. 'preload state', default='{}'), playlist_id, fatal=False)
  964. if preload_state:
  965. current_programme = preload_state.get('programmes', {}).get('current') or {}
  966. programme_id = current_programme.get('id')
  967. if current_programme and programme_id and current_programme.get('type') == 'playable_item':
  968. title = current_programme.get('titles', {}).get('tertiary') or playlist_title
  969. formats, subtitles = self._download_media_selector(programme_id)
  970. self._sort_formats(formats)
  971. synopses = current_programme.get('synopses') or {}
  972. network = current_programme.get('network') or {}
  973. duration = int_or_none(
  974. current_programme.get('duration', {}).get('value'))
  975. thumbnail = None
  976. image_url = current_programme.get('image_url')
  977. if image_url:
  978. thumbnail = image_url.replace('{recipe}', '1920x1920')
  979. return {
  980. 'id': programme_id,
  981. 'title': title,
  982. 'description': dict_get(synopses, ('long', 'medium', 'short')),
  983. 'thumbnail': thumbnail,
  984. 'duration': duration,
  985. 'uploader': network.get('short_title'),
  986. 'uploader_id': network.get('id'),
  987. 'formats': formats,
  988. 'subtitles': subtitles,
  989. }
  990. bbc3_config = self._parse_json(
  991. self._search_regex(
  992. r'(?s)bbcthreeConfig\s*=\s*({.+?})\s*;\s*<', webpage,
  993. 'bbcthree config', default='{}'),
  994. playlist_id, transform_source=js_to_json, fatal=False)
  995. if bbc3_config:
  996. bbc3_playlist = try_get(
  997. bbc3_config, lambda x: x['payload']['content']['bbcMedia']['playlist'],
  998. dict)
  999. if bbc3_playlist:
  1000. playlist_title = bbc3_playlist.get('title') or playlist_title
  1001. thumbnail = bbc3_playlist.get('holdingImageURL')
  1002. entries = []
  1003. for bbc3_item in bbc3_playlist['items']:
  1004. programme_id = bbc3_item.get('versionID')
  1005. if not programme_id:
  1006. continue
  1007. formats, subtitles = self._download_media_selector(programme_id)
  1008. self._sort_formats(formats)
  1009. entries.append({
  1010. 'id': programme_id,
  1011. 'title': playlist_title,
  1012. 'thumbnail': thumbnail,
  1013. 'timestamp': timestamp,
  1014. 'formats': formats,
  1015. 'subtitles': subtitles,
  1016. })
  1017. return self.playlist_result(
  1018. entries, playlist_id, playlist_title, playlist_description)
  1019. def extract_all(pattern):
  1020. return list(filter(None, map(
  1021. lambda s: self._parse_json(s, playlist_id, fatal=False),
  1022. re.findall(pattern, webpage))))
  1023. # Multiple video article (e.g.
  1024. # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
  1025. EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+%s(?:\b[^"]+)?' % self._ID_REGEX
  1026. entries = []
  1027. for match in extract_all(r'new\s+SMP\(({.+?})\)'):
  1028. embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
  1029. if embed_url and re.match(EMBED_URL, embed_url):
  1030. entries.append(embed_url)
  1031. entries.extend(re.findall(
  1032. r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
  1033. if entries:
  1034. return self.playlist_result(
  1035. [self.url_result(entry_, 'BBCCoUk') for entry_ in entries],
  1036. playlist_id, playlist_title, playlist_description)
  1037. # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
  1038. medias = extract_all(r"data-media-meta='({[^']+})'")
  1039. if not medias:
  1040. # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
  1041. media_asset = self._search_regex(
  1042. r'mediaAssetPage\.init\(\s*({.+?}), "/',
  1043. webpage, 'media asset', default=None)
  1044. if media_asset:
  1045. media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
  1046. medias = []
  1047. for video in media_asset_page.get('videos', {}).values():
  1048. medias.extend(video.values())
  1049. if not medias:
  1050. # Multiple video playlist with single `now playing` entry (e.g.
  1051. # http://www.bbc.com/news/video_and_audio/must_see/33767813)
  1052. vxp_playlist = self._parse_json(
  1053. self._search_regex(
  1054. r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
  1055. webpage, 'playlist data'),
  1056. playlist_id)
  1057. playlist_medias = []
  1058. for item in vxp_playlist:
  1059. media = item.get('media')
  1060. if not media:
  1061. continue
  1062. playlist_medias.append(media)
  1063. # Download single video if found media with asset id matching the video id from URL
  1064. if item.get('advert', {}).get('assetId') == playlist_id:
  1065. medias = [media]
  1066. break
  1067. # Fallback to the whole playlist
  1068. if not medias:
  1069. medias = playlist_medias
  1070. entries = []
  1071. for num, media_meta in enumerate(medias, start=1):
  1072. formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
  1073. if not formats:
  1074. continue
  1075. self._sort_formats(formats)
  1076. video_id = media_meta.get('externalId')
  1077. if not video_id:
  1078. video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
  1079. title = media_meta.get('caption')
  1080. if not title:
  1081. title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
  1082. duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
  1083. images = []
  1084. for image in media_meta.get('images', {}).values():
  1085. images.extend(image.values())
  1086. if 'image' in media_meta:
  1087. images.append(media_meta['image'])
  1088. thumbnails = [{
  1089. 'url': image.get('href'),
  1090. 'width': int_or_none(image.get('width')),
  1091. 'height': int_or_none(image.get('height')),
  1092. } for image in images]
  1093. entries.append({
  1094. 'id': video_id,
  1095. 'title': title,
  1096. 'thumbnails': thumbnails,
  1097. 'duration': duration,
  1098. 'timestamp': timestamp,
  1099. 'formats': formats,
  1100. 'subtitles': subtitles,
  1101. })
  1102. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
  1103. class BBCCoUkArticleIE(InfoExtractor):
  1104. _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)'
  1105. IE_NAME = 'bbc.co.uk:article'
  1106. IE_DESC = 'BBC articles'
  1107. _TEST = {
  1108. 'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer',
  1109. 'info_dict': {
  1110. 'id': '3jNQLTMrPlYGTBn0WV6M2MS',
  1111. 'title': 'Calculating Ada: The Countess of Computing - Not your typical role model: Ada Lovelace the 19th century programmer - BBC Four',
  1112. 'description': 'Hannah Fry reveals some of her surprising discoveries about Ada Lovelace during filming.',
  1113. },
  1114. 'playlist_count': 4,
  1115. 'add_ie': ['BBCCoUk'],
  1116. }
  1117. def _real_extract(self, url):
  1118. playlist_id = self._match_id(url)
  1119. webpage = self._download_webpage(url, playlist_id)
  1120. title = self._og_search_title(webpage)
  1121. description = self._og_search_description(webpage).strip()
  1122. entries = [self.url_result(programme_url) for programme_url in re.findall(
  1123. r'<div[^>]+typeof="Clip"[^>]+resource="([^"]+)"', webpage)]
  1124. return self.playlist_result(entries, playlist_id, title, description)
  1125. class BBCCoUkPlaylistBaseIE(InfoExtractor):
  1126. def _entries(self, webpage, url, playlist_id):
  1127. single_page = 'page' in compat_urlparse.parse_qs(
  1128. compat_urlparse.urlparse(url).query)
  1129. for page_num in itertools.count(2):
  1130. for video_id in re.findall(
  1131. self._VIDEO_ID_TEMPLATE % BBCCoUkIE._ID_REGEX, webpage):
  1132. yield self.url_result(
  1133. self._URL_TEMPLATE % video_id, BBCCoUkIE.ie_key())
  1134. if single_page:
  1135. return
  1136. next_page = self._search_regex(
  1137. r'<li[^>]+class=(["\'])pagination_+next\1[^>]*><a[^>]+href=(["\'])(?P<url>(?:(?!\2).)+)\2',
  1138. webpage, 'next page url', default=None, group='url')
  1139. if not next_page:
  1140. break
  1141. webpage = self._download_webpage(
  1142. compat_urlparse.urljoin(url, next_page), playlist_id,
  1143. 'Downloading page %d' % page_num, page_num)
  1144. def _real_extract(self, url):
  1145. playlist_id = self._match_id(url)
  1146. webpage = self._download_webpage(url, playlist_id)
  1147. title, description = self._extract_title_and_description(webpage)
  1148. return self.playlist_result(
  1149. self._entries(webpage, url, playlist_id),
  1150. playlist_id, title, description)
  1151. class BBCCoUkIPlayerPlaylistIE(BBCCoUkPlaylistBaseIE):
  1152. IE_NAME = 'bbc.co.uk:iplayer:playlist'
  1153. _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/iplayer/(?:episodes|group)/(?P<id>%s)' % BBCCoUkIE._ID_REGEX
  1154. _URL_TEMPLATE = 'http://www.bbc.co.uk/iplayer/episode/%s'
  1155. _VIDEO_ID_TEMPLATE = r'data-ip-id=["\'](%s)'
  1156. _TESTS = [{
  1157. 'url': 'http://www.bbc.co.uk/iplayer/episodes/b05rcz9v',
  1158. 'info_dict': {
  1159. 'id': 'b05rcz9v',
  1160. 'title': 'The Disappearance',
  1161. 'description': 'French thriller serial about a missing teenager.',
  1162. },
  1163. 'playlist_mincount': 6,
  1164. 'skip': 'This programme is not currently available on BBC iPlayer',
  1165. }, {
  1166. # Available for over a year unlike 30 days for most other programmes
  1167. 'url': 'http://www.bbc.co.uk/iplayer/group/p02tcc32',
  1168. 'info_dict': {
  1169. 'id': 'p02tcc32',
  1170. 'title': 'Bohemian Icons',
  1171. 'description': 'md5:683e901041b2fe9ba596f2ab04c4dbe7',
  1172. },
  1173. 'playlist_mincount': 10,
  1174. }]
  1175. def _extract_title_and_description(self, webpage):
  1176. title = self._search_regex(r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
  1177. description = self._search_regex(
  1178. r'<p[^>]+class=(["\'])subtitle\1[^>]*>(?P<value>[^<]+)</p>',
  1179. webpage, 'description', fatal=False, group='value')
  1180. return title, description
  1181. class BBCCoUkPlaylistIE(BBCCoUkPlaylistBaseIE):
  1182. IE_NAME = 'bbc.co.uk:playlist'
  1183. _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/(?P<id>%s)/(?:episodes|broadcasts|clips)' % BBCCoUkIE._ID_REGEX
  1184. _URL_TEMPLATE = 'http://www.bbc.co.uk/programmes/%s'
  1185. _VIDEO_ID_TEMPLATE = r'data-pid=["\'](%s)'
  1186. _TESTS = [{
  1187. 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
  1188. 'info_dict': {
  1189. 'id': 'b05rcz9v',
  1190. 'title': 'The Disappearance - Clips - BBC Four',
  1191. 'description': 'French thriller serial about a missing teenager.',
  1192. },
  1193. 'playlist_mincount': 7,
  1194. }, {
  1195. # multipage playlist, explicit page
  1196. 'url': 'http://www.bbc.co.uk/programmes/b00mfl7n/clips?page=1',
  1197. 'info_dict': {
  1198. 'id': 'b00mfl7n',
  1199. 'title': 'Frozen Planet - Clips - BBC One',
  1200. 'description': 'md5:65dcbf591ae628dafe32aa6c4a4a0d8c',
  1201. },
  1202. 'playlist_mincount': 24,
  1203. }, {
  1204. # multipage playlist, all pages
  1205. 'url': 'http://www.bbc.co.uk/programmes/b00mfl7n/clips',
  1206. 'info_dict': {
  1207. 'id': 'b00mfl7n',
  1208. 'title': 'Frozen Planet - Clips - BBC One',
  1209. 'description': 'md5:65dcbf591ae628dafe32aa6c4a4a0d8c',
  1210. },
  1211. 'playlist_mincount': 142,
  1212. }, {
  1213. 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/broadcasts/2016/06',
  1214. 'only_matching': True,
  1215. }, {
  1216. 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
  1217. 'only_matching': True,
  1218. }, {
  1219. 'url': 'http://www.bbc.co.uk/programmes/b055jkys/episodes/player',
  1220. 'only_matching': True,
  1221. }]
  1222. def _extract_title_and_description(self, webpage):
  1223. title = self._og_search_title(webpage, fatal=False)
  1224. description = self._og_search_description(webpage)
  1225. return title, description