bbc.py 28 KB

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