bbc.py 52 KB

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