You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1134 lines
49 KiB

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