bbc.py 55 KB

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