bbc.py 54 KB

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