bbc.py 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232
  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. parse_duration,
  14. parse_iso8601,
  15. try_get,
  16. unescapeHTML,
  17. urlencode_postdata,
  18. urljoin,
  19. )
  20. from ..compat import (
  21. compat_etree_fromstring,
  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'[pb][\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. _USP_RE = r'/([^/]+?)\.ism(?:\.hlsv2\.ism)?/[^/]+\.m3u8'
  229. def _login(self):
  230. username, password = self._get_login_info()
  231. if username is None:
  232. return
  233. login_page = self._download_webpage(
  234. self._LOGIN_URL, None, 'Downloading signin page')
  235. login_form = self._hidden_inputs(login_page)
  236. login_form.update({
  237. 'username': username,
  238. 'password': password,
  239. })
  240. post_url = urljoin(self._LOGIN_URL, self._search_regex(
  241. r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
  242. 'post url', default=self._LOGIN_URL, group='url'))
  243. response, urlh = self._download_webpage_handle(
  244. post_url, None, 'Logging in', data=urlencode_postdata(login_form),
  245. headers={'Referer': self._LOGIN_URL})
  246. if self._LOGIN_URL in urlh.geturl():
  247. error = clean_html(get_element_by_class('form-message', response))
  248. if error:
  249. raise ExtractorError(
  250. 'Unable to login: %s' % error, expected=True)
  251. raise ExtractorError('Unable to log in')
  252. def _real_initialize(self):
  253. self._login()
  254. class MediaSelectionError(Exception):
  255. def __init__(self, id):
  256. self.id = id
  257. def _extract_asx_playlist(self, connection, programme_id):
  258. asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
  259. return [ref.get('href') for ref in asx.findall('./Entry/ref')]
  260. def _extract_items(self, playlist):
  261. return playlist.findall('./{%s}item' % self._EMP_PLAYLIST_NS)
  262. def _findall_ns(self, element, xpath):
  263. elements = []
  264. for ns in self._NAMESPACES:
  265. elements.extend(element.findall(xpath % ns))
  266. return elements
  267. def _extract_medias(self, media_selection):
  268. error = media_selection.find('./{%s}error' % self._MEDIASELECTION_NS)
  269. if error is None:
  270. media_selection.find('./{%s}error' % self._EMP_PLAYLIST_NS)
  271. if error is not None:
  272. raise BBCCoUkIE.MediaSelectionError(error.get('id'))
  273. return self._findall_ns(media_selection, './{%s}media')
  274. def _extract_connections(self, media):
  275. return self._findall_ns(media, './{%s}connection')
  276. def _get_subtitles(self, media, programme_id):
  277. subtitles = {}
  278. for connection in self._extract_connections(media):
  279. captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
  280. lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
  281. subtitles[lang] = [
  282. {
  283. 'url': connection.get('href'),
  284. 'ext': 'ttml',
  285. },
  286. ]
  287. return subtitles
  288. def _raise_extractor_error(self, media_selection_error):
  289. raise ExtractorError(
  290. '%s returned error: %s' % (self.IE_NAME, media_selection_error.id),
  291. expected=True)
  292. def _download_media_selector(self, programme_id):
  293. last_exception = None
  294. for mediaselector_url in self._MEDIASELECTOR_URLS:
  295. try:
  296. return self._download_media_selector_url(
  297. mediaselector_url % programme_id, programme_id)
  298. except BBCCoUkIE.MediaSelectionError as e:
  299. if e.id in ('notukerror', 'geolocation', 'selectionunavailable'):
  300. last_exception = e
  301. continue
  302. self._raise_extractor_error(e)
  303. self._raise_extractor_error(last_exception)
  304. def _download_media_selector_url(self, url, programme_id=None):
  305. try:
  306. media_selection = self._download_xml(
  307. url, programme_id, 'Downloading media selection XML')
  308. except ExtractorError as ee:
  309. if isinstance(ee.cause, compat_HTTPError) and ee.cause.code in (403, 404):
  310. media_selection = compat_etree_fromstring(ee.cause.read().decode('utf-8'))
  311. else:
  312. raise
  313. return self._process_media_selector(media_selection, programme_id)
  314. def _process_media_selector(self, media_selection, programme_id):
  315. formats = []
  316. subtitles = None
  317. urls = []
  318. for media in self._extract_medias(media_selection):
  319. kind = media.get('kind')
  320. if kind in ('video', 'audio'):
  321. bitrate = int_or_none(media.get('bitrate'))
  322. encoding = media.get('encoding')
  323. service = media.get('service')
  324. width = int_or_none(media.get('width'))
  325. height = int_or_none(media.get('height'))
  326. file_size = int_or_none(media.get('media_file_size'))
  327. for connection in self._extract_connections(media):
  328. href = connection.get('href')
  329. if href in urls:
  330. continue
  331. if href:
  332. urls.append(href)
  333. conn_kind = connection.get('kind')
  334. protocol = connection.get('protocol')
  335. supplier = connection.get('supplier')
  336. transfer_format = connection.get('transferFormat')
  337. format_id = supplier or conn_kind or protocol
  338. if service:
  339. format_id = '%s_%s' % (service, format_id)
  340. # ASX playlist
  341. if supplier == 'asx':
  342. for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
  343. formats.append({
  344. 'url': ref,
  345. 'format_id': 'ref%s_%s' % (i, format_id),
  346. })
  347. elif transfer_format == 'dash':
  348. formats.extend(self._extract_mpd_formats(
  349. href, programme_id, mpd_id=format_id, fatal=False))
  350. elif transfer_format == 'hls':
  351. formats.extend(self._extract_m3u8_formats(
  352. href, programme_id, ext='mp4', entry_protocol='m3u8_native',
  353. m3u8_id=format_id, fatal=False))
  354. if re.search(self._USP_RE, href):
  355. usp_formats = self._extract_m3u8_formats(
  356. re.sub(self._USP_RE, r'/\1.ism/\1.m3u8', href),
  357. programme_id, ext='mp4', entry_protocol='m3u8_native',
  358. m3u8_id=format_id, fatal=False)
  359. for f in usp_formats:
  360. if f.get('height') and f['height'] > 720:
  361. continue
  362. formats.append(f)
  363. elif transfer_format == 'hds':
  364. formats.extend(self._extract_f4m_formats(
  365. href, programme_id, f4m_id=format_id, fatal=False))
  366. else:
  367. if not service and not supplier and bitrate:
  368. format_id += '-%d' % bitrate
  369. fmt = {
  370. 'format_id': format_id,
  371. 'filesize': file_size,
  372. }
  373. if kind == 'video':
  374. fmt.update({
  375. 'width': width,
  376. 'height': height,
  377. 'tbr': bitrate,
  378. 'vcodec': encoding,
  379. })
  380. else:
  381. fmt.update({
  382. 'abr': bitrate,
  383. 'acodec': encoding,
  384. 'vcodec': 'none',
  385. })
  386. if protocol in ('http', 'https'):
  387. # Direct link
  388. fmt.update({
  389. 'url': href,
  390. })
  391. elif protocol == 'rtmp':
  392. application = connection.get('application', 'ondemand')
  393. auth_string = connection.get('authString')
  394. identifier = connection.get('identifier')
  395. server = connection.get('server')
  396. fmt.update({
  397. 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
  398. 'play_path': identifier,
  399. 'app': '%s?%s' % (application, auth_string),
  400. 'page_url': 'http://www.bbc.co.uk',
  401. 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
  402. 'rtmp_live': False,
  403. 'ext': 'flv',
  404. })
  405. else:
  406. continue
  407. formats.append(fmt)
  408. elif kind == 'captions':
  409. subtitles = self.extract_subtitles(media, programme_id)
  410. return formats, subtitles
  411. def _download_playlist(self, playlist_id):
  412. try:
  413. playlist = self._download_json(
  414. 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
  415. playlist_id, 'Downloading playlist JSON')
  416. version = playlist.get('defaultAvailableVersion')
  417. if version:
  418. smp_config = version['smpConfig']
  419. title = smp_config['title']
  420. description = smp_config['summary']
  421. for item in smp_config['items']:
  422. kind = item['kind']
  423. if kind not in ('programme', 'radioProgramme'):
  424. continue
  425. programme_id = item.get('vpid')
  426. duration = int_or_none(item.get('duration'))
  427. formats, subtitles = self._download_media_selector(programme_id)
  428. return programme_id, title, description, duration, formats, subtitles
  429. except ExtractorError as ee:
  430. if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
  431. raise
  432. # fallback to legacy playlist
  433. return self._process_legacy_playlist(playlist_id)
  434. def _process_legacy_playlist_url(self, url, display_id):
  435. playlist = self._download_legacy_playlist_url(url, display_id)
  436. return self._extract_from_legacy_playlist(playlist, display_id)
  437. def _process_legacy_playlist(self, playlist_id):
  438. return self._process_legacy_playlist_url(
  439. 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
  440. def _download_legacy_playlist_url(self, url, playlist_id=None):
  441. return self._download_xml(
  442. url, playlist_id, 'Downloading legacy playlist XML')
  443. def _extract_from_legacy_playlist(self, playlist, playlist_id):
  444. no_items = playlist.find('./{%s}noItems' % self._EMP_PLAYLIST_NS)
  445. if no_items is not None:
  446. reason = no_items.get('reason')
  447. if reason == 'preAvailability':
  448. msg = 'Episode %s is not yet available' % playlist_id
  449. elif reason == 'postAvailability':
  450. msg = 'Episode %s is no longer available' % playlist_id
  451. elif reason == 'noMedia':
  452. msg = 'Episode %s is not currently available' % playlist_id
  453. else:
  454. msg = 'Episode %s is not available: %s' % (playlist_id, reason)
  455. raise ExtractorError(msg, expected=True)
  456. for item in self._extract_items(playlist):
  457. kind = item.get('kind')
  458. if kind not in ('programme', 'radioProgramme'):
  459. continue
  460. title = playlist.find('./{%s}title' % self._EMP_PLAYLIST_NS).text
  461. description_el = playlist.find('./{%s}summary' % self._EMP_PLAYLIST_NS)
  462. description = description_el.text if description_el is not None else None
  463. def get_programme_id(item):
  464. def get_from_attributes(item):
  465. for p in('identifier', 'group'):
  466. value = item.get(p)
  467. if value and re.match(r'^[pb][\da-z]{7}$', value):
  468. return value
  469. get_from_attributes(item)
  470. mediator = item.find('./{%s}mediator' % self._EMP_PLAYLIST_NS)
  471. if mediator is not None:
  472. return get_from_attributes(mediator)
  473. programme_id = get_programme_id(item)
  474. duration = int_or_none(item.get('duration'))
  475. if programme_id:
  476. formats, subtitles = self._download_media_selector(programme_id)
  477. else:
  478. formats, subtitles = self._process_media_selector(item, playlist_id)
  479. programme_id = playlist_id
  480. return programme_id, title, description, duration, formats, subtitles
  481. def _real_extract(self, url):
  482. group_id = self._match_id(url)
  483. webpage = self._download_webpage(url, group_id, 'Downloading video page')
  484. error = self._search_regex(
  485. r'<div\b[^>]+\bclass=["\']smp__message delta["\'][^>]*>([^<]+)<',
  486. webpage, 'error', default=None)
  487. if error:
  488. raise ExtractorError(error, expected=True)
  489. programme_id = None
  490. duration = None
  491. tviplayer = self._search_regex(
  492. r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
  493. webpage, 'player', default=None)
  494. if tviplayer:
  495. player = self._parse_json(tviplayer, group_id).get('player', {})
  496. duration = int_or_none(player.get('duration'))
  497. programme_id = player.get('vpid')
  498. if not programme_id:
  499. programme_id = self._search_regex(
  500. r'"vpid"\s*:\s*"(%s)"' % self._ID_REGEX, webpage, 'vpid', fatal=False, default=None)
  501. if programme_id:
  502. formats, subtitles = self._download_media_selector(programme_id)
  503. title = self._og_search_title(webpage, default=None) or self._html_search_regex(
  504. (r'<h2[^>]+id="parent-title"[^>]*>(.+?)</h2>',
  505. r'<div[^>]+class="info"[^>]*>\s*<h1>(.+?)</h1>'), webpage, 'title')
  506. description = self._search_regex(
  507. (r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
  508. r'<div[^>]+class="info_+synopsis"[^>]*>([^<]+)</div>'),
  509. webpage, 'description', default=None)
  510. if not description:
  511. description = self._html_search_meta('description', webpage)
  512. else:
  513. programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
  514. self._sort_formats(formats)
  515. return {
  516. 'id': programme_id,
  517. 'title': title,
  518. 'description': description,
  519. 'thumbnail': self._og_search_thumbnail(webpage, default=None),
  520. 'duration': duration,
  521. 'formats': formats,
  522. 'subtitles': subtitles,
  523. }
  524. class BBCIE(BBCCoUkIE):
  525. IE_NAME = 'bbc'
  526. IE_DESC = 'BBC'
  527. _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
  528. _MEDIASELECTOR_URLS = [
  529. # Provides HQ HLS streams but fails with geolocation in some cases when it's
  530. # even not geo restricted at all
  531. 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
  532. # Provides more formats, namely direct mp4 links, but fails on some videos with
  533. # notukerror for non UK (?) users (e.g.
  534. # http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
  535. 'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s',
  536. # Provides fewer formats, but works everywhere for everybody (hopefully)
  537. 'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s',
  538. ]
  539. _TESTS = [{
  540. # article with multiple videos embedded with data-playable containing vpids
  541. 'url': 'http://www.bbc.com/news/world-europe-32668511',
  542. 'info_dict': {
  543. 'id': 'world-europe-32668511',
  544. 'title': 'Russia stages massive WW2 parade despite Western boycott',
  545. 'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
  546. },
  547. 'playlist_count': 2,
  548. }, {
  549. # article with multiple videos embedded with data-playable (more videos)
  550. 'url': 'http://www.bbc.com/news/business-28299555',
  551. 'info_dict': {
  552. 'id': 'business-28299555',
  553. 'title': 'Farnborough Airshow: Video highlights',
  554. 'description': 'BBC reports and video highlights at the Farnborough Airshow.',
  555. },
  556. 'playlist_count': 9,
  557. 'skip': 'Save time',
  558. }, {
  559. # article with multiple videos embedded with `new SMP()`
  560. # broken
  561. 'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
  562. 'info_dict': {
  563. 'id': '3662a707-0af9-3149-963f-47bea720b460',
  564. 'title': 'BUGGER',
  565. },
  566. 'playlist_count': 18,
  567. }, {
  568. # single video embedded with data-playable containing vpid
  569. 'url': 'http://www.bbc.com/news/world-europe-32041533',
  570. 'info_dict': {
  571. 'id': 'p02mprgb',
  572. 'ext': 'mp4',
  573. 'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
  574. 'description': 'md5:2868290467291b37feda7863f7a83f54',
  575. 'duration': 47,
  576. 'timestamp': 1427219242,
  577. 'upload_date': '20150324',
  578. },
  579. 'params': {
  580. # rtmp download
  581. 'skip_download': True,
  582. }
  583. }, {
  584. # article with single video embedded with data-playable containing XML playlist
  585. # with direct video links as progressiveDownloadUrl (for now these are extracted)
  586. # and playlist with f4m and m3u8 as streamingUrl
  587. 'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
  588. 'info_dict': {
  589. 'id': '150615_telabyad_kentin_cogu',
  590. 'ext': 'mp4',
  591. 'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
  592. 'description': 'md5:33a4805a855c9baf7115fcbde57e7025',
  593. 'timestamp': 1434397334,
  594. 'upload_date': '20150615',
  595. },
  596. 'params': {
  597. 'skip_download': True,
  598. }
  599. }, {
  600. # single video embedded with data-playable containing XML playlists (regional section)
  601. 'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
  602. 'info_dict': {
  603. 'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
  604. 'ext': 'mp4',
  605. 'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
  606. 'description': 'md5:1525f17448c4ee262b64b8f0c9ce66c8',
  607. 'timestamp': 1434713142,
  608. 'upload_date': '20150619',
  609. },
  610. 'params': {
  611. 'skip_download': True,
  612. }
  613. }, {
  614. # single video from video playlist embedded with vxp-playlist-data JSON
  615. 'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
  616. 'info_dict': {
  617. 'id': 'p02w6qjc',
  618. 'ext': 'mp4',
  619. 'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
  620. 'duration': 56,
  621. 'description': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
  622. },
  623. 'params': {
  624. 'skip_download': True,
  625. }
  626. }, {
  627. # single video story with digitalData
  628. 'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
  629. 'info_dict': {
  630. 'id': 'p02q6gc4',
  631. 'ext': 'flv',
  632. 'title': 'Sri Lanka’s spicy secret',
  633. 'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
  634. 'timestamp': 1437674293,
  635. 'upload_date': '20150723',
  636. },
  637. 'params': {
  638. # rtmp download
  639. 'skip_download': True,
  640. }
  641. }, {
  642. # single video story without digitalData
  643. 'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
  644. 'info_dict': {
  645. 'id': 'p018zqqg',
  646. 'ext': 'mp4',
  647. 'title': 'Hyundai Santa Fe Sport: Rock star',
  648. 'description': 'md5:b042a26142c4154a6e472933cf20793d',
  649. 'timestamp': 1415867444,
  650. 'upload_date': '20141113',
  651. },
  652. 'params': {
  653. # rtmp download
  654. 'skip_download': True,
  655. }
  656. }, {
  657. # single video embedded with Morph
  658. 'url': 'http://www.bbc.co.uk/sport/live/olympics/36895975',
  659. 'info_dict': {
  660. 'id': 'p041vhd0',
  661. 'ext': 'mp4',
  662. 'title': "Nigeria v Japan - Men's First Round",
  663. 'description': 'Live coverage of the first round from Group B at the Amazonia Arena.',
  664. 'duration': 7980,
  665. 'uploader': 'BBC Sport',
  666. 'uploader_id': 'bbc_sport',
  667. },
  668. 'params': {
  669. # m3u8 download
  670. 'skip_download': True,
  671. },
  672. 'skip': 'Georestricted to UK',
  673. }, {
  674. # single video with playlist.sxml URL in playlist param
  675. 'url': 'http://www.bbc.com/sport/0/football/33653409',
  676. 'info_dict': {
  677. 'id': 'p02xycnp',
  678. 'ext': 'mp4',
  679. 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
  680. 'description': 'BBC Sport\'s David Ornstein has the latest transfer gossip, including rumours of a Manchester United return for Cristiano Ronaldo.',
  681. 'duration': 140,
  682. },
  683. 'params': {
  684. # rtmp download
  685. 'skip_download': True,
  686. }
  687. }, {
  688. # article with multiple videos embedded with playlist.sxml in playlist param
  689. 'url': 'http://www.bbc.com/sport/0/football/34475836',
  690. 'info_dict': {
  691. 'id': '34475836',
  692. 'title': 'Jurgen Klopp: Furious football from a witty and winning coach',
  693. 'description': 'Fast-paced football, wit, wisdom and a ready smile - why Liverpool fans should come to love new boss Jurgen Klopp.',
  694. },
  695. 'playlist_count': 3,
  696. }, {
  697. # school report article with single video
  698. 'url': 'http://www.bbc.co.uk/schoolreport/35744779',
  699. 'info_dict': {
  700. 'id': '35744779',
  701. 'title': 'School which breaks down barriers in Jerusalem',
  702. },
  703. 'playlist_count': 1,
  704. }, {
  705. # single video with playlist URL from weather section
  706. 'url': 'http://www.bbc.com/weather/features/33601775',
  707. 'only_matching': True,
  708. }, {
  709. # custom redirection to www.bbc.com
  710. 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
  711. 'only_matching': True,
  712. }, {
  713. # single video article embedded with data-media-vpid
  714. 'url': 'http://www.bbc.co.uk/sport/rowing/35908187',
  715. 'only_matching': True,
  716. }]
  717. @classmethod
  718. def suitable(cls, url):
  719. EXCLUDE_IE = (BBCCoUkIE, BBCCoUkArticleIE, BBCCoUkIPlayerPlaylistIE, BBCCoUkPlaylistIE)
  720. return (False if any(ie.suitable(url) for ie in EXCLUDE_IE)
  721. else super(BBCIE, cls).suitable(url))
  722. def _extract_from_media_meta(self, media_meta, video_id):
  723. # Direct links to media in media metadata (e.g.
  724. # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
  725. # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
  726. source_files = media_meta.get('sourceFiles')
  727. if source_files:
  728. return [{
  729. 'url': f['url'],
  730. 'format_id': format_id,
  731. 'ext': f.get('encoding'),
  732. 'tbr': float_or_none(f.get('bitrate'), 1000),
  733. 'filesize': int_or_none(f.get('filesize')),
  734. } for format_id, f in source_files.items() if f.get('url')], []
  735. programme_id = media_meta.get('externalId')
  736. if programme_id:
  737. return self._download_media_selector(programme_id)
  738. # Process playlist.sxml as legacy playlist
  739. href = media_meta.get('href')
  740. if href:
  741. playlist = self._download_legacy_playlist_url(href)
  742. _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
  743. return formats, subtitles
  744. return [], []
  745. def _extract_from_playlist_sxml(self, url, playlist_id, timestamp):
  746. programme_id, title, description, duration, formats, subtitles = \
  747. self._process_legacy_playlist_url(url, playlist_id)
  748. self._sort_formats(formats)
  749. return {
  750. 'id': programme_id,
  751. 'title': title,
  752. 'description': description,
  753. 'duration': duration,
  754. 'timestamp': timestamp,
  755. 'formats': formats,
  756. 'subtitles': subtitles,
  757. }
  758. def _real_extract(self, url):
  759. playlist_id = self._match_id(url)
  760. webpage = self._download_webpage(url, playlist_id)
  761. json_ld_info = self._search_json_ld(webpage, playlist_id, default={})
  762. timestamp = json_ld_info.get('timestamp')
  763. playlist_title = json_ld_info.get('title')
  764. if not playlist_title:
  765. playlist_title = self._og_search_title(
  766. webpage, default=None) or self._html_search_regex(
  767. r'<title>(.+?)</title>', webpage, 'playlist title', default=None)
  768. if playlist_title:
  769. playlist_title = re.sub(r'(.+)\s*-\s*BBC.*?$', r'\1', playlist_title).strip()
  770. playlist_description = json_ld_info.get(
  771. 'description') or self._og_search_description(webpage, default=None)
  772. if not timestamp:
  773. timestamp = parse_iso8601(self._search_regex(
  774. [r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
  775. r'itemprop="datePublished"[^>]+datetime="([^"]+)"',
  776. r'"datePublished":\s*"([^"]+)'],
  777. webpage, 'date', default=None))
  778. entries = []
  779. # article with multiple videos embedded with playlist.sxml (e.g.
  780. # http://www.bbc.com/sport/0/football/34475836)
  781. playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
  782. playlists.extend(re.findall(r'data-media-id="([^"]+/playlist\.sxml)"', webpage))
  783. if playlists:
  784. entries = [
  785. self._extract_from_playlist_sxml(playlist_url, playlist_id, timestamp)
  786. for playlist_url in playlists]
  787. # news article with multiple videos embedded with data-playable
  788. data_playables = re.findall(r'data-playable=(["\'])({.+?})\1', webpage)
  789. if data_playables:
  790. for _, data_playable_json in data_playables:
  791. data_playable = self._parse_json(
  792. unescapeHTML(data_playable_json), playlist_id, fatal=False)
  793. if not data_playable:
  794. continue
  795. settings = data_playable.get('settings', {})
  796. if settings:
  797. # data-playable with video vpid in settings.playlistObject.items (e.g.
  798. # http://www.bbc.com/news/world-us-canada-34473351)
  799. playlist_object = settings.get('playlistObject', {})
  800. if playlist_object:
  801. items = playlist_object.get('items')
  802. if items and isinstance(items, list):
  803. title = playlist_object['title']
  804. description = playlist_object.get('summary')
  805. duration = int_or_none(items[0].get('duration'))
  806. programme_id = items[0].get('vpid')
  807. formats, subtitles = self._download_media_selector(programme_id)
  808. self._sort_formats(formats)
  809. entries.append({
  810. 'id': programme_id,
  811. 'title': title,
  812. 'description': description,
  813. 'timestamp': timestamp,
  814. 'duration': duration,
  815. 'formats': formats,
  816. 'subtitles': subtitles,
  817. })
  818. else:
  819. # data-playable without vpid but with a playlist.sxml URLs
  820. # in otherSettings.playlist (e.g.
  821. # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
  822. playlist = data_playable.get('otherSettings', {}).get('playlist', {})
  823. if playlist:
  824. entry = None
  825. for key in ('streaming', 'progressiveDownload'):
  826. playlist_url = playlist.get('%sUrl' % key)
  827. if not playlist_url:
  828. continue
  829. try:
  830. info = self._extract_from_playlist_sxml(
  831. playlist_url, playlist_id, timestamp)
  832. if not entry:
  833. entry = info
  834. else:
  835. entry['title'] = info['title']
  836. entry['formats'].extend(info['formats'])
  837. except Exception as e:
  838. # Some playlist URL may fail with 500, at the same time
  839. # the other one may work fine (e.g.
  840. # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
  841. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 500:
  842. continue
  843. raise
  844. if entry:
  845. self._sort_formats(entry['formats'])
  846. entries.append(entry)
  847. if entries:
  848. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
  849. # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
  850. programme_id = self._search_regex(
  851. [r'data-(?:video-player|media)-vpid="(%s)"' % self._ID_REGEX,
  852. r'<param[^>]+name="externalIdentifier"[^>]+value="(%s)"' % self._ID_REGEX,
  853. r'videoId\s*:\s*["\'](%s)["\']' % self._ID_REGEX],
  854. webpage, 'vpid', default=None)
  855. if programme_id:
  856. formats, subtitles = self._download_media_selector(programme_id)
  857. self._sort_formats(formats)
  858. # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
  859. digital_data = self._parse_json(
  860. self._search_regex(
  861. r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
  862. programme_id, fatal=False)
  863. page_info = digital_data.get('page', {}).get('pageInfo', {})
  864. title = page_info.get('pageName') or self._og_search_title(webpage)
  865. description = page_info.get('description') or self._og_search_description(webpage)
  866. timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
  867. return {
  868. 'id': programme_id,
  869. 'title': title,
  870. 'description': description,
  871. 'timestamp': timestamp,
  872. 'formats': formats,
  873. 'subtitles': subtitles,
  874. }
  875. # Morph based embed (e.g. http://www.bbc.co.uk/sport/live/olympics/36895975)
  876. # There are several setPayload calls may be present but the video
  877. # seems to be always related to the first one
  878. morph_payload = self._parse_json(
  879. self._search_regex(
  880. r'Morph\.setPayload\([^,]+,\s*({.+?})\);',
  881. webpage, 'morph payload', default='{}'),
  882. playlist_id, fatal=False)
  883. if morph_payload:
  884. components = try_get(morph_payload, lambda x: x['body']['components'], list) or []
  885. for component in components:
  886. if not isinstance(component, dict):
  887. continue
  888. lead_media = try_get(component, lambda x: x['props']['leadMedia'], dict)
  889. if not lead_media:
  890. continue
  891. identifiers = lead_media.get('identifiers')
  892. if not identifiers or not isinstance(identifiers, dict):
  893. continue
  894. programme_id = identifiers.get('vpid') or identifiers.get('playablePid')
  895. if not programme_id:
  896. continue
  897. title = lead_media.get('title') or self._og_search_title(webpage)
  898. formats, subtitles = self._download_media_selector(programme_id)
  899. self._sort_formats(formats)
  900. description = lead_media.get('summary')
  901. uploader = lead_media.get('masterBrand')
  902. uploader_id = lead_media.get('mid')
  903. duration = None
  904. duration_d = lead_media.get('duration')
  905. if isinstance(duration_d, dict):
  906. duration = parse_duration(dict_get(
  907. duration_d, ('rawDuration', 'formattedDuration', 'spokenDuration')))
  908. return {
  909. 'id': programme_id,
  910. 'title': title,
  911. 'description': description,
  912. 'duration': duration,
  913. 'uploader': uploader,
  914. 'uploader_id': uploader_id,
  915. 'formats': formats,
  916. 'subtitles': subtitles,
  917. }
  918. def extract_all(pattern):
  919. return list(filter(None, map(
  920. lambda s: self._parse_json(s, playlist_id, fatal=False),
  921. re.findall(pattern, webpage))))
  922. # Multiple video article (e.g.
  923. # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
  924. EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+%s(?:\b[^"]+)?' % self._ID_REGEX
  925. entries = []
  926. for match in extract_all(r'new\s+SMP\(({.+?})\)'):
  927. embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
  928. if embed_url and re.match(EMBED_URL, embed_url):
  929. entries.append(embed_url)
  930. entries.extend(re.findall(
  931. r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
  932. if entries:
  933. return self.playlist_result(
  934. [self.url_result(entry_, 'BBCCoUk') for entry_ in entries],
  935. playlist_id, playlist_title, playlist_description)
  936. # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
  937. medias = extract_all(r"data-media-meta='({[^']+})'")
  938. if not medias:
  939. # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
  940. media_asset = self._search_regex(
  941. r'mediaAssetPage\.init\(\s*({.+?}), "/',
  942. webpage, 'media asset', default=None)
  943. if media_asset:
  944. media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
  945. medias = []
  946. for video in media_asset_page.get('videos', {}).values():
  947. medias.extend(video.values())
  948. if not medias:
  949. # Multiple video playlist with single `now playing` entry (e.g.
  950. # http://www.bbc.com/news/video_and_audio/must_see/33767813)
  951. vxp_playlist = self._parse_json(
  952. self._search_regex(
  953. r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
  954. webpage, 'playlist data'),
  955. playlist_id)
  956. playlist_medias = []
  957. for item in vxp_playlist:
  958. media = item.get('media')
  959. if not media:
  960. continue
  961. playlist_medias.append(media)
  962. # Download single video if found media with asset id matching the video id from URL
  963. if item.get('advert', {}).get('assetId') == playlist_id:
  964. medias = [media]
  965. break
  966. # Fallback to the whole playlist
  967. if not medias:
  968. medias = playlist_medias
  969. entries = []
  970. for num, media_meta in enumerate(medias, start=1):
  971. formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
  972. if not formats:
  973. continue
  974. self._sort_formats(formats)
  975. video_id = media_meta.get('externalId')
  976. if not video_id:
  977. video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
  978. title = media_meta.get('caption')
  979. if not title:
  980. title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
  981. duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
  982. images = []
  983. for image in media_meta.get('images', {}).values():
  984. images.extend(image.values())
  985. if 'image' in media_meta:
  986. images.append(media_meta['image'])
  987. thumbnails = [{
  988. 'url': image.get('href'),
  989. 'width': int_or_none(image.get('width')),
  990. 'height': int_or_none(image.get('height')),
  991. } for image in images]
  992. entries.append({
  993. 'id': video_id,
  994. 'title': title,
  995. 'thumbnails': thumbnails,
  996. 'duration': duration,
  997. 'timestamp': timestamp,
  998. 'formats': formats,
  999. 'subtitles': subtitles,
  1000. })
  1001. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
  1002. class BBCCoUkArticleIE(InfoExtractor):
  1003. _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)'
  1004. IE_NAME = 'bbc.co.uk:article'
  1005. IE_DESC = 'BBC articles'
  1006. _TEST = {
  1007. 'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer',
  1008. 'info_dict': {
  1009. 'id': '3jNQLTMrPlYGTBn0WV6M2MS',
  1010. 'title': 'Calculating Ada: The Countess of Computing - Not your typical role model: Ada Lovelace the 19th century programmer - BBC Four',
  1011. 'description': 'Hannah Fry reveals some of her surprising discoveries about Ada Lovelace during filming.',
  1012. },
  1013. 'playlist_count': 4,
  1014. 'add_ie': ['BBCCoUk'],
  1015. }
  1016. def _real_extract(self, url):
  1017. playlist_id = self._match_id(url)
  1018. webpage = self._download_webpage(url, playlist_id)
  1019. title = self._og_search_title(webpage)
  1020. description = self._og_search_description(webpage).strip()
  1021. entries = [self.url_result(programme_url) for programme_url in re.findall(
  1022. r'<div[^>]+typeof="Clip"[^>]+resource="([^"]+)"', webpage)]
  1023. return self.playlist_result(entries, playlist_id, title, description)
  1024. class BBCCoUkPlaylistBaseIE(InfoExtractor):
  1025. def _entries(self, webpage, url, playlist_id):
  1026. single_page = 'page' in compat_urlparse.parse_qs(
  1027. compat_urlparse.urlparse(url).query)
  1028. for page_num in itertools.count(2):
  1029. for video_id in re.findall(
  1030. self._VIDEO_ID_TEMPLATE % BBCCoUkIE._ID_REGEX, webpage):
  1031. yield self.url_result(
  1032. self._URL_TEMPLATE % video_id, BBCCoUkIE.ie_key())
  1033. if single_page:
  1034. return
  1035. next_page = self._search_regex(
  1036. r'<li[^>]+class=(["\'])pagination_+next\1[^>]*><a[^>]+href=(["\'])(?P<url>(?:(?!\2).)+)\2',
  1037. webpage, 'next page url', default=None, group='url')
  1038. if not next_page:
  1039. break
  1040. webpage = self._download_webpage(
  1041. compat_urlparse.urljoin(url, next_page), playlist_id,
  1042. 'Downloading page %d' % page_num, page_num)
  1043. def _real_extract(self, url):
  1044. playlist_id = self._match_id(url)
  1045. webpage = self._download_webpage(url, playlist_id)
  1046. title, description = self._extract_title_and_description(webpage)
  1047. return self.playlist_result(
  1048. self._entries(webpage, url, playlist_id),
  1049. playlist_id, title, description)
  1050. class BBCCoUkIPlayerPlaylistIE(BBCCoUkPlaylistBaseIE):
  1051. IE_NAME = 'bbc.co.uk:iplayer:playlist'
  1052. _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/iplayer/(?:episodes|group)/(?P<id>%s)' % BBCCoUkIE._ID_REGEX
  1053. _URL_TEMPLATE = 'http://www.bbc.co.uk/iplayer/episode/%s'
  1054. _VIDEO_ID_TEMPLATE = r'data-ip-id=["\'](%s)'
  1055. _TESTS = [{
  1056. 'url': 'http://www.bbc.co.uk/iplayer/episodes/b05rcz9v',
  1057. 'info_dict': {
  1058. 'id': 'b05rcz9v',
  1059. 'title': 'The Disappearance',
  1060. 'description': 'French thriller serial about a missing teenager.',
  1061. },
  1062. 'playlist_mincount': 6,
  1063. 'skip': 'This programme is not currently available on BBC iPlayer',
  1064. }, {
  1065. # Available for over a year unlike 30 days for most other programmes
  1066. 'url': 'http://www.bbc.co.uk/iplayer/group/p02tcc32',
  1067. 'info_dict': {
  1068. 'id': 'p02tcc32',
  1069. 'title': 'Bohemian Icons',
  1070. 'description': 'md5:683e901041b2fe9ba596f2ab04c4dbe7',
  1071. },
  1072. 'playlist_mincount': 10,
  1073. }]
  1074. def _extract_title_and_description(self, webpage):
  1075. title = self._search_regex(r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
  1076. description = self._search_regex(
  1077. r'<p[^>]+class=(["\'])subtitle\1[^>]*>(?P<value>[^<]+)</p>',
  1078. webpage, 'description', fatal=False, group='value')
  1079. return title, description
  1080. class BBCCoUkPlaylistIE(BBCCoUkPlaylistBaseIE):
  1081. IE_NAME = 'bbc.co.uk:playlist'
  1082. _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/(?P<id>%s)/(?:episodes|broadcasts|clips)' % BBCCoUkIE._ID_REGEX
  1083. _URL_TEMPLATE = 'http://www.bbc.co.uk/programmes/%s'
  1084. _VIDEO_ID_TEMPLATE = r'data-pid=["\'](%s)'
  1085. _TESTS = [{
  1086. 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
  1087. 'info_dict': {
  1088. 'id': 'b05rcz9v',
  1089. 'title': 'The Disappearance - Clips - BBC Four',
  1090. 'description': 'French thriller serial about a missing teenager.',
  1091. },
  1092. 'playlist_mincount': 7,
  1093. }, {
  1094. # multipage playlist, explicit page
  1095. 'url': 'http://www.bbc.co.uk/programmes/b00mfl7n/clips?page=1',
  1096. 'info_dict': {
  1097. 'id': 'b00mfl7n',
  1098. 'title': 'Frozen Planet - Clips - BBC One',
  1099. 'description': 'md5:65dcbf591ae628dafe32aa6c4a4a0d8c',
  1100. },
  1101. 'playlist_mincount': 24,
  1102. }, {
  1103. # multipage playlist, all pages
  1104. 'url': 'http://www.bbc.co.uk/programmes/b00mfl7n/clips',
  1105. 'info_dict': {
  1106. 'id': 'b00mfl7n',
  1107. 'title': 'Frozen Planet - Clips - BBC One',
  1108. 'description': 'md5:65dcbf591ae628dafe32aa6c4a4a0d8c',
  1109. },
  1110. 'playlist_mincount': 142,
  1111. }, {
  1112. 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/broadcasts/2016/06',
  1113. 'only_matching': True,
  1114. }, {
  1115. 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
  1116. 'only_matching': True,
  1117. }, {
  1118. 'url': 'http://www.bbc.co.uk/programmes/b055jkys/episodes/player',
  1119. 'only_matching': True,
  1120. }]
  1121. def _extract_title_and_description(self, webpage):
  1122. title = self._og_search_title(webpage, fatal=False)
  1123. description = self._og_search_description(webpage)
  1124. return title, description