bbc.py 59 KB

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