bbc.py 67 KB

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