bbc.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. import xml.etree.ElementTree
  5. from .common import InfoExtractor
  6. from ..utils import (
  7. ExtractorError,
  8. float_or_none,
  9. int_or_none,
  10. parse_duration,
  11. parse_iso8601,
  12. )
  13. from ..compat import compat_HTTPError
  14. class BBCCoUkIE(InfoExtractor):
  15. IE_NAME = 'bbc.co.uk'
  16. IE_DESC = 'BBC iPlayer'
  17. _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:(?:(?:programmes|iplayer(?:/[^/]+)?/(?:episode|playlist))/)|music/clips[/#])(?P<id>[\da-z]{8})'
  18. _MEDIASELECTOR_URLS = [
  19. # Provides HQ HLS streams with even better quality that pc mediaset but fails
  20. # with geolocation in some cases when it's even not geo restricted at all (e.g.
  21. # http://www.bbc.co.uk/programmes/b06bp7lf)
  22. 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
  23. 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s',
  24. ]
  25. _TESTS = [
  26. {
  27. 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
  28. 'info_dict': {
  29. 'id': 'b039d07m',
  30. 'ext': 'flv',
  31. 'title': 'Kaleidoscope, Leonard Cohen',
  32. 'description': 'The Canadian poet and songwriter reflects on his musical career.',
  33. 'duration': 1740,
  34. },
  35. 'params': {
  36. # rtmp download
  37. 'skip_download': True,
  38. }
  39. },
  40. {
  41. 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
  42. 'info_dict': {
  43. 'id': 'b00yng1d',
  44. 'ext': 'flv',
  45. 'title': 'The Man in Black: Series 3: The Printed Name',
  46. 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
  47. 'duration': 1800,
  48. },
  49. 'params': {
  50. # rtmp download
  51. 'skip_download': True,
  52. },
  53. 'skip': 'Episode is no longer available on BBC iPlayer Radio',
  54. },
  55. {
  56. 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
  57. 'info_dict': {
  58. 'id': 'b00yng1d',
  59. 'ext': 'flv',
  60. 'title': 'The Voice UK: Series 3: Blind Auditions 5',
  61. '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.",
  62. 'duration': 5100,
  63. },
  64. 'params': {
  65. # rtmp download
  66. 'skip_download': True,
  67. },
  68. 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
  69. },
  70. {
  71. 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
  72. 'info_dict': {
  73. 'id': 'b03k3pb7',
  74. 'ext': 'flv',
  75. 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
  76. 'description': '2. Invasion',
  77. 'duration': 3600,
  78. },
  79. 'params': {
  80. # rtmp download
  81. 'skip_download': True,
  82. },
  83. 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
  84. }, {
  85. 'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
  86. 'info_dict': {
  87. 'id': 'b04v209v',
  88. 'ext': 'flv',
  89. 'title': 'Pete Tong, The Essential New Tune Special',
  90. 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
  91. 'duration': 10800,
  92. },
  93. 'params': {
  94. # rtmp download
  95. 'skip_download': True,
  96. }
  97. }, {
  98. 'url': 'http://www.bbc.co.uk/music/clips/p02frcc3',
  99. 'note': 'Audio',
  100. 'info_dict': {
  101. 'id': 'p02frcch',
  102. 'ext': 'flv',
  103. 'title': 'Pete Tong, Past, Present and Future Special, Madeon - After Hours mix',
  104. 'description': 'French house superstar Madeon takes us out of the club and onto the after party.',
  105. 'duration': 3507,
  106. },
  107. 'params': {
  108. # rtmp download
  109. 'skip_download': True,
  110. }
  111. }, {
  112. 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
  113. 'note': 'Video',
  114. 'info_dict': {
  115. 'id': 'p025c103',
  116. 'ext': 'flv',
  117. 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
  118. 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
  119. 'duration': 226,
  120. },
  121. 'params': {
  122. # rtmp download
  123. 'skip_download': True,
  124. }
  125. }, {
  126. 'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
  127. 'info_dict': {
  128. 'id': 'p02n76xf',
  129. 'ext': 'flv',
  130. 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
  131. 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
  132. 'duration': 3540,
  133. },
  134. 'params': {
  135. # rtmp download
  136. 'skip_download': True,
  137. },
  138. 'skip': 'geolocation',
  139. }, {
  140. 'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
  141. 'info_dict': {
  142. 'id': 'b05zmgw1',
  143. 'ext': 'flv',
  144. '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.',
  145. 'title': 'Royal Academy Summer Exhibition',
  146. 'duration': 3540,
  147. },
  148. 'params': {
  149. # rtmp download
  150. 'skip_download': True,
  151. },
  152. 'skip': 'geolocation',
  153. }, {
  154. 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
  155. 'only_matching': True,
  156. }, {
  157. 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
  158. 'only_matching': True,
  159. }, {
  160. 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
  161. 'only_matching': True,
  162. }
  163. ]
  164. class MediaSelectionError(Exception):
  165. def __init__(self, id):
  166. self.id = id
  167. def _extract_asx_playlist(self, connection, programme_id):
  168. asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
  169. return [ref.get('href') for ref in asx.findall('./Entry/ref')]
  170. def _extract_connection(self, connection, programme_id):
  171. formats = []
  172. protocol = connection.get('protocol')
  173. supplier = connection.get('supplier')
  174. if protocol == 'http':
  175. href = connection.get('href')
  176. transfer_format = connection.get('transferFormat')
  177. # ASX playlist
  178. if supplier == 'asx':
  179. for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
  180. formats.append({
  181. 'url': ref,
  182. 'format_id': 'ref%s_%s' % (i, supplier),
  183. })
  184. # Skip DASH until supported
  185. elif transfer_format == 'dash':
  186. pass
  187. elif transfer_format == 'hls':
  188. m3u8_formats = self._extract_m3u8_formats(
  189. href, programme_id, ext='mp4', entry_protocol='m3u8_native',
  190. m3u8_id=supplier, fatal=False)
  191. if m3u8_formats:
  192. formats.extend(m3u8_formats)
  193. # Direct link
  194. else:
  195. formats.append({
  196. 'url': href,
  197. 'format_id': supplier,
  198. })
  199. elif protocol == 'rtmp':
  200. application = connection.get('application', 'ondemand')
  201. auth_string = connection.get('authString')
  202. identifier = connection.get('identifier')
  203. server = connection.get('server')
  204. formats.append({
  205. 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
  206. 'play_path': identifier,
  207. 'app': '%s?%s' % (application, auth_string),
  208. 'page_url': 'http://www.bbc.co.uk',
  209. 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
  210. 'rtmp_live': False,
  211. 'ext': 'flv',
  212. 'format_id': supplier,
  213. })
  214. return formats
  215. def _extract_items(self, playlist):
  216. return playlist.findall('./{http://bbc.co.uk/2008/emp/playlist}item')
  217. def _extract_medias(self, media_selection):
  218. error = media_selection.find('./{http://bbc.co.uk/2008/mp/mediaselection}error')
  219. if error is not None:
  220. raise BBCCoUkIE.MediaSelectionError(error.get('id'))
  221. return media_selection.findall('./{http://bbc.co.uk/2008/mp/mediaselection}media')
  222. def _extract_connections(self, media):
  223. return media.findall('./{http://bbc.co.uk/2008/mp/mediaselection}connection')
  224. def _extract_video(self, media, programme_id):
  225. formats = []
  226. vbr = int_or_none(media.get('bitrate'))
  227. vcodec = media.get('encoding')
  228. service = media.get('service')
  229. width = int_or_none(media.get('width'))
  230. height = int_or_none(media.get('height'))
  231. file_size = int_or_none(media.get('media_file_size'))
  232. for connection in self._extract_connections(media):
  233. conn_formats = self._extract_connection(connection, programme_id)
  234. for format in conn_formats:
  235. format.update({
  236. 'format_id': '%s_%s' % (service, format['format_id']),
  237. 'width': width,
  238. 'height': height,
  239. 'vbr': vbr,
  240. 'vcodec': vcodec,
  241. 'filesize': file_size,
  242. })
  243. formats.extend(conn_formats)
  244. return formats
  245. def _extract_audio(self, media, programme_id):
  246. formats = []
  247. abr = int_or_none(media.get('bitrate'))
  248. acodec = media.get('encoding')
  249. service = media.get('service')
  250. for connection in self._extract_connections(media):
  251. conn_formats = self._extract_connection(connection, programme_id)
  252. for format in conn_formats:
  253. format.update({
  254. 'format_id': '%s_%s' % (service, format['format_id']),
  255. 'abr': abr,
  256. 'acodec': acodec,
  257. })
  258. formats.extend(conn_formats)
  259. return formats
  260. def _get_subtitles(self, media, programme_id):
  261. subtitles = {}
  262. for connection in self._extract_connections(media):
  263. captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
  264. lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
  265. subtitles[lang] = [
  266. {
  267. 'url': connection.get('href'),
  268. 'ext': 'ttml',
  269. },
  270. ]
  271. return subtitles
  272. def _raise_extractor_error(self, media_selection_error):
  273. raise ExtractorError(
  274. '%s returned error: %s' % (self.IE_NAME, media_selection_error.id),
  275. expected=True)
  276. def _download_media_selector(self, programme_id):
  277. last_exception = None
  278. for mediaselector_url in self._MEDIASELECTOR_URLS:
  279. try:
  280. return self._download_media_selector_url(
  281. mediaselector_url % programme_id, programme_id)
  282. except BBCCoUkIE.MediaSelectionError as e:
  283. if e.id in ('notukerror', 'geolocation'):
  284. last_exception = e
  285. continue
  286. self._raise_extractor_error(e)
  287. self._raise_extractor_error(last_exception)
  288. def _download_media_selector_url(self, url, programme_id=None):
  289. try:
  290. media_selection = self._download_xml(
  291. url, programme_id, 'Downloading media selection XML')
  292. except ExtractorError as ee:
  293. if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
  294. media_selection = xml.etree.ElementTree.fromstring(ee.cause.read().decode('utf-8'))
  295. else:
  296. raise
  297. return self._process_media_selector(media_selection, programme_id)
  298. def _process_media_selector(self, media_selection, programme_id):
  299. formats = []
  300. subtitles = None
  301. for media in self._extract_medias(media_selection):
  302. kind = media.get('kind')
  303. if kind == 'audio':
  304. formats.extend(self._extract_audio(media, programme_id))
  305. elif kind == 'video':
  306. formats.extend(self._extract_video(media, programme_id))
  307. elif kind == 'captions':
  308. subtitles = self.extract_subtitles(media, programme_id)
  309. return formats, subtitles
  310. def _download_playlist(self, playlist_id):
  311. try:
  312. playlist = self._download_json(
  313. 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
  314. playlist_id, 'Downloading playlist JSON')
  315. version = playlist.get('defaultAvailableVersion')
  316. if version:
  317. smp_config = version['smpConfig']
  318. title = smp_config['title']
  319. description = smp_config['summary']
  320. for item in smp_config['items']:
  321. kind = item['kind']
  322. if kind != 'programme' and kind != 'radioProgramme':
  323. continue
  324. programme_id = item.get('vpid')
  325. duration = int_or_none(item.get('duration'))
  326. formats, subtitles = self._download_media_selector(programme_id)
  327. return programme_id, title, description, duration, formats, subtitles
  328. except ExtractorError as ee:
  329. if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
  330. raise
  331. # fallback to legacy playlist
  332. return self._process_legacy_playlist(playlist_id)
  333. def _process_legacy_playlist_url(self, url, display_id):
  334. playlist = self._download_legacy_playlist_url(url, display_id)
  335. return self._extract_from_legacy_playlist(playlist, display_id)
  336. def _process_legacy_playlist(self, playlist_id):
  337. return self._process_legacy_playlist_url(
  338. 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
  339. def _download_legacy_playlist_url(self, url, playlist_id=None):
  340. return self._download_xml(
  341. url, playlist_id, 'Downloading legacy playlist XML')
  342. def _extract_from_legacy_playlist(self, playlist, playlist_id):
  343. no_items = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}noItems')
  344. if no_items is not None:
  345. reason = no_items.get('reason')
  346. if reason == 'preAvailability':
  347. msg = 'Episode %s is not yet available' % playlist_id
  348. elif reason == 'postAvailability':
  349. msg = 'Episode %s is no longer available' % playlist_id
  350. elif reason == 'noMedia':
  351. msg = 'Episode %s is not currently available' % playlist_id
  352. else:
  353. msg = 'Episode %s is not available: %s' % (playlist_id, reason)
  354. raise ExtractorError(msg, expected=True)
  355. for item in self._extract_items(playlist):
  356. kind = item.get('kind')
  357. if kind != 'programme' and kind != 'radioProgramme':
  358. continue
  359. title = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}title').text
  360. description = playlist.find('./{http://bbc.co.uk/2008/emp/playlist}summary').text
  361. def get_programme_id(item):
  362. def get_from_attributes(item):
  363. for p in('identifier', 'group'):
  364. value = item.get(p)
  365. if value and re.match(r'^[pb][\da-z]{7}$', value):
  366. return value
  367. get_from_attributes(item)
  368. mediator = item.find('./{http://bbc.co.uk/2008/emp/playlist}mediator')
  369. if mediator is not None:
  370. return get_from_attributes(mediator)
  371. programme_id = get_programme_id(item)
  372. duration = int_or_none(item.get('duration'))
  373. # TODO: programme_id can be None and media items can be incorporated right inside
  374. # playlist's item (e.g. http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
  375. # as f4m and m3u8
  376. formats, subtitles = self._download_media_selector(programme_id)
  377. return programme_id, title, description, duration, formats, subtitles
  378. def _real_extract(self, url):
  379. group_id = self._match_id(url)
  380. webpage = self._download_webpage(url, group_id, 'Downloading video page')
  381. programme_id = None
  382. tviplayer = self._search_regex(
  383. r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
  384. webpage, 'player', default=None)
  385. if tviplayer:
  386. player = self._parse_json(tviplayer, group_id).get('player', {})
  387. duration = int_or_none(player.get('duration'))
  388. programme_id = player.get('vpid')
  389. if not programme_id:
  390. programme_id = self._search_regex(
  391. r'"vpid"\s*:\s*"([\da-z]{8})"', webpage, 'vpid', fatal=False, default=None)
  392. if programme_id:
  393. formats, subtitles = self._download_media_selector(programme_id)
  394. title = self._og_search_title(webpage)
  395. description = self._search_regex(
  396. r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
  397. webpage, 'description', fatal=False)
  398. else:
  399. programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
  400. self._sort_formats(formats)
  401. return {
  402. 'id': programme_id,
  403. 'title': title,
  404. 'description': description,
  405. 'thumbnail': self._og_search_thumbnail(webpage, default=None),
  406. 'duration': duration,
  407. 'formats': formats,
  408. 'subtitles': subtitles,
  409. }
  410. class BBCIE(BBCCoUkIE):
  411. IE_NAME = 'bbc'
  412. IE_DESC = 'BBC'
  413. _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
  414. _MEDIASELECTOR_URLS = [
  415. # Provides more formats, namely direct mp4 links, but fails on some videos with
  416. # notukerror for non UK (?) users (e.g.
  417. # http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
  418. 'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s',
  419. # Provides fewer formats, but works everywhere for everybody (hopefully)
  420. 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s',
  421. ]
  422. _TESTS = [{
  423. # article with multiple videos embedded with data-media-meta containing
  424. # playlist.sxml, externalId and no direct video links
  425. 'url': 'http://www.bbc.com/news/world-europe-32668511',
  426. 'info_dict': {
  427. 'id': 'world-europe-32668511',
  428. 'title': 'Russia stages massive WW2 parade despite Western boycott',
  429. 'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
  430. },
  431. 'playlist_count': 2,
  432. }, {
  433. # article with multiple videos embedded with data-media-meta (more videos)
  434. 'url': 'http://www.bbc.com/news/business-28299555',
  435. 'info_dict': {
  436. 'id': 'business-28299555',
  437. 'title': 'Farnborough Airshow: Video highlights',
  438. 'description': 'BBC reports and video highlights at the Farnborough Airshow.',
  439. },
  440. 'playlist_count': 9,
  441. 'skip': 'Save time',
  442. }, {
  443. # article with multiple videos embedded with `new SMP()`
  444. 'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
  445. 'info_dict': {
  446. 'id': '3662a707-0af9-3149-963f-47bea720b460',
  447. 'title': 'BBC Blogs - Adam Curtis - BUGGER',
  448. },
  449. 'playlist_count': 18,
  450. }, {
  451. # single video embedded with mediaAssetPage.init()
  452. 'url': 'http://www.bbc.com/news/world-europe-32041533',
  453. 'info_dict': {
  454. 'id': 'p02mprgb',
  455. 'ext': 'mp4',
  456. 'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
  457. 'duration': 47,
  458. 'timestamp': 1427219242,
  459. 'upload_date': '20150324',
  460. },
  461. 'params': {
  462. # rtmp download
  463. 'skip_download': True,
  464. }
  465. }, {
  466. # article with single video embedded with data-media-meta containing
  467. # direct video links (for now these are extracted) and playlist.xml (with
  468. # media items as f4m and m3u8 - currently unsupported)
  469. 'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
  470. 'info_dict': {
  471. 'id': '150615_telabyad_kentin_cogu',
  472. 'ext': 'mp4',
  473. 'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
  474. 'duration': 47,
  475. 'timestamp': 1434397334,
  476. 'upload_date': '20150615',
  477. },
  478. 'params': {
  479. 'skip_download': True,
  480. }
  481. }, {
  482. # single video embedded with mediaAssetPage.init() (regional section)
  483. 'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
  484. 'info_dict': {
  485. 'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
  486. 'ext': 'mp4',
  487. 'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
  488. 'duration': 87,
  489. 'timestamp': 1434713142,
  490. 'upload_date': '20150619',
  491. },
  492. 'params': {
  493. 'skip_download': True,
  494. }
  495. }, {
  496. # single video from video playlist embedded with vxp-playlist-data JSON
  497. 'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
  498. 'info_dict': {
  499. 'id': 'p02w6qjc',
  500. 'ext': 'mp4',
  501. 'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
  502. 'duration': 56,
  503. },
  504. 'params': {
  505. 'skip_download': True,
  506. }
  507. }, {
  508. # single video story with digitalData
  509. 'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
  510. 'info_dict': {
  511. 'id': 'p02q6gc4',
  512. 'ext': 'flv',
  513. 'title': 'Sri Lanka’s spicy secret',
  514. 'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
  515. 'timestamp': 1437674293,
  516. 'upload_date': '20150723',
  517. },
  518. 'params': {
  519. # rtmp download
  520. 'skip_download': True,
  521. }
  522. }, {
  523. # single video story without digitalData
  524. 'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
  525. 'info_dict': {
  526. 'id': 'p018zqqg',
  527. 'ext': 'mp4',
  528. 'title': 'Hyundai Santa Fe Sport: Rock star',
  529. 'description': 'md5:b042a26142c4154a6e472933cf20793d',
  530. 'timestamp': 1368473503,
  531. 'upload_date': '20130513',
  532. },
  533. 'params': {
  534. # rtmp download
  535. 'skip_download': True,
  536. }
  537. }, {
  538. # single video with playlist.sxml URL
  539. 'url': 'http://www.bbc.com/sport/0/football/33653409',
  540. 'info_dict': {
  541. 'id': 'p02xycnp',
  542. 'ext': 'mp4',
  543. 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
  544. 'description': 'md5:398fca0e2e701c609d726e034fa1fc89',
  545. 'duration': 140,
  546. },
  547. 'params': {
  548. # rtmp download
  549. 'skip_download': True,
  550. }
  551. }, {
  552. # single video with playlist URL from weather section
  553. 'url': 'http://www.bbc.com/weather/features/33601775',
  554. 'only_matching': True,
  555. }, {
  556. # custom redirection to www.bbc.com
  557. 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
  558. 'only_matching': True,
  559. }]
  560. @classmethod
  561. def suitable(cls, url):
  562. return False if BBCCoUkIE.suitable(url) else super(BBCIE, cls).suitable(url)
  563. def _extract_from_media_meta(self, media_meta, video_id):
  564. # Direct links to media in media metadata (e.g.
  565. # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
  566. # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
  567. source_files = media_meta.get('sourceFiles')
  568. if source_files:
  569. return [{
  570. 'url': f['url'],
  571. 'format_id': format_id,
  572. 'ext': f.get('encoding'),
  573. 'tbr': float_or_none(f.get('bitrate'), 1000),
  574. 'filesize': int_or_none(f.get('filesize')),
  575. } for format_id, f in source_files.items() if f.get('url')], []
  576. programme_id = media_meta.get('externalId')
  577. if programme_id:
  578. return self._download_media_selector(programme_id)
  579. # Process playlist.sxml as legacy playlist
  580. href = media_meta.get('href')
  581. if href:
  582. playlist = self._download_legacy_playlist_url(href)
  583. _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
  584. return formats, subtitles
  585. return [], []
  586. def _real_extract(self, url):
  587. playlist_id = self._match_id(url)
  588. webpage = self._download_webpage(url, playlist_id)
  589. timestamp = parse_iso8601(self._search_regex(
  590. [r'"datePublished":\s*"([^"]+)',
  591. r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
  592. r'itemprop="datePublished"[^>]+datetime="([^"]+)"'],
  593. webpage, 'date', default=None))
  594. # single video with playlist.sxml URL (e.g. http://www.bbc.com/sport/0/football/3365340ng)
  595. playlist = self._search_regex(
  596. r'<param[^>]+name="playlist"[^>]+value="([^"]+)"',
  597. webpage, 'playlist', default=None)
  598. if playlist:
  599. programme_id, title, description, duration, formats, subtitles = \
  600. self._process_legacy_playlist_url(playlist, playlist_id)
  601. self._sort_formats(formats)
  602. return {
  603. 'id': programme_id,
  604. 'title': title,
  605. 'description': description,
  606. 'duration': duration,
  607. 'timestamp': timestamp,
  608. 'formats': formats,
  609. 'subtitles': subtitles,
  610. }
  611. # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
  612. programme_id = self._search_regex(
  613. [r'data-video-player-vpid="([\da-z]{8})"',
  614. r'<param[^>]+name="externalIdentifier"[^>]+value="([\da-z]{8})"'],
  615. webpage, 'vpid', default=None)
  616. if programme_id:
  617. formats, subtitles = self._download_media_selector(programme_id)
  618. self._sort_formats(formats)
  619. # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
  620. digital_data = self._parse_json(
  621. self._search_regex(
  622. r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
  623. programme_id, fatal=False)
  624. page_info = digital_data.get('page', {}).get('pageInfo', {})
  625. title = page_info.get('pageName') or self._og_search_title(webpage)
  626. description = page_info.get('description') or self._og_search_description(webpage)
  627. timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
  628. return {
  629. 'id': programme_id,
  630. 'title': title,
  631. 'description': description,
  632. 'timestamp': timestamp,
  633. 'formats': formats,
  634. 'subtitles': subtitles,
  635. }
  636. playlist_title = self._html_search_regex(
  637. r'<title>(.*?)(?:\s*-\s*BBC [^ ]+)?</title>', webpage, 'playlist title')
  638. playlist_description = self._og_search_description(webpage, default=None)
  639. def extract_all(pattern):
  640. return list(filter(None, map(
  641. lambda s: self._parse_json(s, playlist_id, fatal=False),
  642. re.findall(pattern, webpage))))
  643. # Multiple video article (e.g.
  644. # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
  645. EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+[\da-z]{8}(?:\b[^"]+)?'
  646. entries = []
  647. for match in extract_all(r'new\s+SMP\(({.+?})\)'):
  648. embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
  649. if embed_url and re.match(EMBED_URL, embed_url):
  650. entries.append(embed_url)
  651. entries.extend(re.findall(
  652. r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
  653. if entries:
  654. return self.playlist_result(
  655. [self.url_result(entry, 'BBCCoUk') for entry in entries],
  656. playlist_id, playlist_title, playlist_description)
  657. # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
  658. medias = extract_all(r"data-media-meta='({[^']+})'")
  659. if not medias:
  660. # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
  661. media_asset = self._search_regex(
  662. r'mediaAssetPage\.init\(\s*({.+?}), "/',
  663. webpage, 'media asset', default=None)
  664. if media_asset:
  665. media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
  666. medias = []
  667. for video in media_asset_page.get('videos', {}).values():
  668. medias.extend(video.values())
  669. if not medias:
  670. # Multiple video playlist with single `now playing` entry (e.g.
  671. # http://www.bbc.com/news/video_and_audio/must_see/33767813)
  672. vxp_playlist = self._parse_json(
  673. self._search_regex(
  674. r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
  675. webpage, 'playlist data'),
  676. playlist_id)
  677. playlist_medias = []
  678. for item in vxp_playlist:
  679. media = item.get('media')
  680. if not media:
  681. continue
  682. playlist_medias.append(media)
  683. # Download single video if found media with asset id matching the video id from URL
  684. if item.get('advert', {}).get('assetId') == playlist_id:
  685. medias = [media]
  686. break
  687. # Fallback to the whole playlist
  688. if not medias:
  689. medias = playlist_medias
  690. entries = []
  691. for num, media_meta in enumerate(medias, start=1):
  692. formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
  693. if not formats:
  694. continue
  695. self._sort_formats(formats)
  696. video_id = media_meta.get('externalId')
  697. if not video_id:
  698. video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
  699. title = media_meta.get('caption')
  700. if not title:
  701. title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
  702. duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
  703. images = []
  704. for image in media_meta.get('images', {}).values():
  705. images.extend(image.values())
  706. if 'image' in media_meta:
  707. images.append(media_meta['image'])
  708. thumbnails = [{
  709. 'url': image.get('href'),
  710. 'width': int_or_none(image.get('width')),
  711. 'height': int_or_none(image.get('height')),
  712. } for image in images]
  713. entries.append({
  714. 'id': video_id,
  715. 'title': title,
  716. 'thumbnails': thumbnails,
  717. 'duration': duration,
  718. 'timestamp': timestamp,
  719. 'formats': formats,
  720. 'subtitles': subtitles,
  721. })
  722. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)