bbc.py 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import functools
  4. import itertools
  5. import json
  6. import re
  7. from .common import InfoExtractor
  8. from ..compat import (
  9. compat_etree_Element,
  10. compat_HTTPError,
  11. compat_parse_qs,
  12. compat_str,
  13. compat_urllib_parse_urlparse,
  14. compat_urlparse,
  15. )
  16. from ..utils import (
  17. ExtractorError,
  18. OnDemandPagedList,
  19. clean_html,
  20. dict_get,
  21. float_or_none,
  22. get_element_by_class,
  23. int_or_none,
  24. js_to_json,
  25. parse_duration,
  26. parse_iso8601,
  27. strip_or_none,
  28. try_get,
  29. unescapeHTML,
  30. unified_timestamp,
  31. url_or_none,
  32. urlencode_postdata,
  33. urljoin,
  34. )
  35. class BBCCoUkIE(InfoExtractor):
  36. IE_NAME = 'bbc.co.uk'
  37. IE_DESC = 'BBC iPlayer'
  38. _ID_REGEX = r'(?:[pbm][\da-z]{7}|w[\da-z]{7,14})'
  39. _VALID_URL = r'''(?x)
  40. https?://
  41. (?:www\.)?bbc\.co\.uk/
  42. (?:
  43. programmes/(?!articles/)|
  44. iplayer(?:/[^/]+)?/(?:episode/|playlist/)|
  45. music/(?:clips|audiovideo/popular)[/#]|
  46. radio/player/|
  47. sounds/play/|
  48. events/[^/]+/play/[^/]+/
  49. )
  50. (?P<id>%s)(?!/(?:episodes|broadcasts|clips))
  51. ''' % _ID_REGEX
  52. _LOGIN_URL = 'https://account.bbc.com/signin'
  53. _NETRC_MACHINE = 'bbc'
  54. _MEDIA_SELECTOR_URL_TEMPL = 'https://open.live.bbc.co.uk/mediaselector/6/select/version/2.0/mediaset/%s/vpid/%s'
  55. _MEDIA_SETS = [
  56. # Provides HQ HLS streams with even better quality that pc mediaset but fails
  57. # with geolocation in some cases when it's even not geo restricted at all (e.g.
  58. # http://www.bbc.co.uk/programmes/b06bp7lf). Also may fail with selectionunavailable.
  59. 'iptv-all',
  60. 'pc',
  61. ]
  62. _EMP_PLAYLIST_NS = 'http://bbc.co.uk/2008/emp/playlist'
  63. _TESTS = [
  64. {
  65. 'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
  66. 'info_dict': {
  67. 'id': 'b039d07m',
  68. 'ext': 'flv',
  69. 'title': 'Kaleidoscope, Leonard Cohen',
  70. 'description': 'The Canadian poet and songwriter reflects on his musical career.',
  71. },
  72. 'params': {
  73. # rtmp download
  74. 'skip_download': True,
  75. }
  76. },
  77. {
  78. 'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
  79. 'info_dict': {
  80. 'id': 'b00yng1d',
  81. 'ext': 'flv',
  82. 'title': 'The Man in Black: Series 3: The Printed Name',
  83. 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
  84. 'duration': 1800,
  85. },
  86. 'params': {
  87. # rtmp download
  88. 'skip_download': True,
  89. },
  90. 'skip': 'Episode is no longer available on BBC iPlayer Radio',
  91. },
  92. {
  93. 'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
  94. 'info_dict': {
  95. 'id': 'b00yng1d',
  96. 'ext': 'flv',
  97. 'title': 'The Voice UK: Series 3: Blind Auditions 5',
  98. '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.',
  99. 'duration': 5100,
  100. },
  101. 'params': {
  102. # rtmp download
  103. 'skip_download': True,
  104. },
  105. 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
  106. },
  107. {
  108. 'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
  109. 'info_dict': {
  110. 'id': 'b03k3pb7',
  111. 'ext': 'flv',
  112. 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
  113. 'description': '2. Invasion',
  114. 'duration': 3600,
  115. },
  116. 'params': {
  117. # rtmp download
  118. 'skip_download': True,
  119. },
  120. 'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
  121. }, {
  122. 'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
  123. 'info_dict': {
  124. 'id': 'b04v209v',
  125. 'ext': 'flv',
  126. 'title': 'Pete Tong, The Essential New Tune Special',
  127. 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
  128. 'duration': 10800,
  129. },
  130. 'params': {
  131. # rtmp download
  132. 'skip_download': True,
  133. },
  134. 'skip': 'Episode is no longer available on BBC iPlayer Radio',
  135. }, {
  136. 'url': 'http://www.bbc.co.uk/music/clips/p022h44b',
  137. 'note': 'Audio',
  138. 'info_dict': {
  139. 'id': 'p022h44j',
  140. 'ext': 'flv',
  141. 'title': 'BBC Proms Music Guides, Rachmaninov: Symphonic Dances',
  142. 'description': "In this Proms Music Guide, Andrew McGregor looks at Rachmaninov's Symphonic Dances.",
  143. 'duration': 227,
  144. },
  145. 'params': {
  146. # rtmp download
  147. 'skip_download': True,
  148. }
  149. }, {
  150. 'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
  151. 'note': 'Video',
  152. 'info_dict': {
  153. 'id': 'p025c103',
  154. 'ext': 'flv',
  155. 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
  156. 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
  157. 'duration': 226,
  158. },
  159. 'params': {
  160. # rtmp download
  161. 'skip_download': True,
  162. }
  163. }, {
  164. 'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
  165. 'info_dict': {
  166. 'id': 'p02n76xf',
  167. 'ext': 'flv',
  168. 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
  169. 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
  170. 'duration': 3540,
  171. },
  172. 'params': {
  173. # rtmp download
  174. 'skip_download': True,
  175. },
  176. 'skip': 'geolocation',
  177. }, {
  178. 'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
  179. 'info_dict': {
  180. 'id': 'b05zmgw1',
  181. 'ext': 'flv',
  182. '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.',
  183. 'title': 'Royal Academy Summer Exhibition',
  184. 'duration': 3540,
  185. },
  186. 'params': {
  187. # rtmp download
  188. 'skip_download': True,
  189. },
  190. 'skip': 'geolocation',
  191. }, {
  192. # iptv-all mediaset fails with geolocation however there is no geo restriction
  193. # for this programme at all
  194. 'url': 'http://www.bbc.co.uk/programmes/b06rkn85',
  195. 'info_dict': {
  196. 'id': 'b06rkms3',
  197. 'ext': 'flv',
  198. 'title': "Best of the Mini-Mixes 2015: Part 3, Annie Mac's Friday Night - BBC Radio 1",
  199. 'description': "Annie has part three in the Best of the Mini-Mixes 2015, plus the year's Most Played!",
  200. },
  201. 'params': {
  202. # rtmp download
  203. 'skip_download': True,
  204. },
  205. 'skip': 'Now it\'s really geo-restricted',
  206. }, {
  207. # compact player (https://github.com/ytdl-org/youtube-dl/issues/8147)
  208. 'url': 'http://www.bbc.co.uk/programmes/p028bfkf/player',
  209. 'info_dict': {
  210. 'id': 'p028bfkj',
  211. 'ext': 'flv',
  212. 'title': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
  213. 'description': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
  214. },
  215. 'params': {
  216. # rtmp download
  217. 'skip_download': True,
  218. },
  219. }, {
  220. 'url': 'https://www.bbc.co.uk/sounds/play/m0007jzb',
  221. 'note': 'Audio',
  222. 'info_dict': {
  223. 'id': 'm0007jz9',
  224. 'ext': 'mp4',
  225. 'title': 'BBC Proms, 2019, Prom 34: West–Eastern Divan Orchestra',
  226. 'description': "Live BBC Proms. West–Eastern Divan Orchestra with Daniel Barenboim and Martha Argerich.",
  227. 'duration': 9840,
  228. },
  229. 'params': {
  230. # rtmp download
  231. 'skip_download': True,
  232. }
  233. }, {
  234. 'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
  235. 'only_matching': True,
  236. }, {
  237. 'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
  238. 'only_matching': True,
  239. }, {
  240. 'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
  241. 'only_matching': True,
  242. }, {
  243. 'url': 'http://www.bbc.co.uk/radio/player/p03cchwf',
  244. 'only_matching': True,
  245. }, {
  246. 'url': 'https://www.bbc.co.uk/music/audiovideo/popular#p055bc55',
  247. 'only_matching': True,
  248. }, {
  249. 'url': 'http://www.bbc.co.uk/programmes/w3csv1y9',
  250. 'only_matching': True,
  251. }, {
  252. 'url': 'https://www.bbc.co.uk/programmes/m00005xn',
  253. 'only_matching': True,
  254. }, {
  255. 'url': 'https://www.bbc.co.uk/programmes/w172w4dww1jqt5s',
  256. 'only_matching': True,
  257. }]
  258. def _login(self):
  259. username, password = self._get_login_info()
  260. if username is None:
  261. return
  262. login_page = self._download_webpage(
  263. self._LOGIN_URL, None, 'Downloading signin page')
  264. login_form = self._hidden_inputs(login_page)
  265. login_form.update({
  266. 'username': username,
  267. 'password': password,
  268. })
  269. post_url = urljoin(self._LOGIN_URL, self._search_regex(
  270. r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
  271. 'post url', default=self._LOGIN_URL, group='url'))
  272. response, urlh = self._download_webpage_handle(
  273. post_url, None, 'Logging in', data=urlencode_postdata(login_form),
  274. headers={'Referer': self._LOGIN_URL})
  275. if self._LOGIN_URL in urlh.geturl():
  276. error = clean_html(get_element_by_class('form-message', response))
  277. if error:
  278. raise ExtractorError(
  279. 'Unable to login: %s' % error, expected=True)
  280. raise ExtractorError('Unable to log in')
  281. def _real_initialize(self):
  282. self._login()
  283. class MediaSelectionError(Exception):
  284. def __init__(self, id):
  285. self.id = id
  286. def _extract_asx_playlist(self, connection, programme_id):
  287. asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
  288. return [ref.get('href') for ref in asx.findall('./Entry/ref')]
  289. def _extract_items(self, playlist):
  290. return playlist.findall('./{%s}item' % self._EMP_PLAYLIST_NS)
  291. def _extract_medias(self, media_selection):
  292. error = media_selection.get('result')
  293. if error:
  294. raise BBCCoUkIE.MediaSelectionError(error)
  295. return media_selection.get('media') or []
  296. def _extract_connections(self, media):
  297. return media.get('connection') or []
  298. def _get_subtitles(self, media, programme_id):
  299. subtitles = {}
  300. for connection in self._extract_connections(media):
  301. cc_url = url_or_none(connection.get('href'))
  302. if not cc_url:
  303. continue
  304. captions = self._download_xml(
  305. cc_url, programme_id, 'Downloading captions', fatal=False)
  306. if not isinstance(captions, compat_etree_Element):
  307. continue
  308. subtitles['en'] = [
  309. {
  310. 'url': connection.get('href'),
  311. 'ext': 'ttml',
  312. },
  313. ]
  314. break
  315. return subtitles
  316. def _raise_extractor_error(self, media_selection_error):
  317. raise ExtractorError(
  318. '%s returned error: %s' % (self.IE_NAME, media_selection_error.id),
  319. expected=True)
  320. def _download_media_selector(self, programme_id):
  321. last_exception = None
  322. for media_set in self._MEDIA_SETS:
  323. try:
  324. return self._download_media_selector_url(
  325. self._MEDIA_SELECTOR_URL_TEMPL % (media_set, programme_id), programme_id)
  326. except BBCCoUkIE.MediaSelectionError as e:
  327. if e.id in ('notukerror', 'geolocation', 'selectionunavailable'):
  328. last_exception = e
  329. continue
  330. self._raise_extractor_error(e)
  331. self._raise_extractor_error(last_exception)
  332. def _download_media_selector_url(self, url, programme_id=None):
  333. media_selection = self._download_json(
  334. url, programme_id, 'Downloading media selection JSON',
  335. expected_status=(403, 404))
  336. return self._process_media_selector(media_selection, programme_id)
  337. def _process_media_selector(self, media_selection, programme_id):
  338. formats = []
  339. subtitles = None
  340. urls = []
  341. for media in self._extract_medias(media_selection):
  342. kind = media.get('kind')
  343. if kind in ('video', 'audio'):
  344. bitrate = int_or_none(media.get('bitrate'))
  345. encoding = media.get('encoding')
  346. width = int_or_none(media.get('width'))
  347. height = int_or_none(media.get('height'))
  348. file_size = int_or_none(media.get('media_file_size'))
  349. for connection in self._extract_connections(media):
  350. href = connection.get('href')
  351. if href in urls:
  352. continue
  353. if href:
  354. urls.append(href)
  355. conn_kind = connection.get('kind')
  356. protocol = connection.get('protocol')
  357. supplier = connection.get('supplier')
  358. transfer_format = connection.get('transferFormat')
  359. format_id = supplier or conn_kind or protocol
  360. # ASX playlist
  361. if supplier == 'asx':
  362. for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
  363. formats.append({
  364. 'url': ref,
  365. 'format_id': 'ref%s_%s' % (i, format_id),
  366. })
  367. elif transfer_format == 'dash':
  368. formats.extend(self._extract_mpd_formats(
  369. href, programme_id, mpd_id=format_id, fatal=False))
  370. elif transfer_format == 'hls':
  371. formats.extend(self._extract_m3u8_formats(
  372. href, programme_id, ext='mp4', entry_protocol='m3u8_native',
  373. m3u8_id=format_id, fatal=False))
  374. elif transfer_format == 'hds':
  375. formats.extend(self._extract_f4m_formats(
  376. href, programme_id, f4m_id=format_id, fatal=False))
  377. else:
  378. if not supplier and bitrate:
  379. format_id += '-%d' % bitrate
  380. fmt = {
  381. 'format_id': format_id,
  382. 'filesize': file_size,
  383. }
  384. if kind == 'video':
  385. fmt.update({
  386. 'width': width,
  387. 'height': height,
  388. 'tbr': bitrate,
  389. 'vcodec': encoding,
  390. })
  391. else:
  392. fmt.update({
  393. 'abr': bitrate,
  394. 'acodec': encoding,
  395. 'vcodec': 'none',
  396. })
  397. if protocol in ('http', 'https'):
  398. # Direct link
  399. fmt.update({
  400. 'url': href,
  401. })
  402. elif protocol == 'rtmp':
  403. application = connection.get('application', 'ondemand')
  404. auth_string = connection.get('authString')
  405. identifier = connection.get('identifier')
  406. server = connection.get('server')
  407. fmt.update({
  408. 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
  409. 'play_path': identifier,
  410. 'app': '%s?%s' % (application, auth_string),
  411. 'page_url': 'http://www.bbc.co.uk',
  412. 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
  413. 'rtmp_live': False,
  414. 'ext': 'flv',
  415. })
  416. else:
  417. continue
  418. formats.append(fmt)
  419. elif kind == 'captions':
  420. subtitles = self.extract_subtitles(media, programme_id)
  421. return formats, subtitles
  422. def _download_playlist(self, playlist_id):
  423. try:
  424. playlist = self._download_json(
  425. 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
  426. playlist_id, 'Downloading playlist JSON')
  427. version = playlist.get('defaultAvailableVersion')
  428. if version:
  429. smp_config = version['smpConfig']
  430. title = smp_config['title']
  431. description = smp_config['summary']
  432. for item in smp_config['items']:
  433. kind = item['kind']
  434. if kind not in ('programme', 'radioProgramme'):
  435. continue
  436. programme_id = item.get('vpid')
  437. duration = int_or_none(item.get('duration'))
  438. formats, subtitles = self._download_media_selector(programme_id)
  439. return programme_id, title, description, duration, formats, subtitles
  440. except ExtractorError as ee:
  441. if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
  442. raise
  443. # fallback to legacy playlist
  444. return self._process_legacy_playlist(playlist_id)
  445. def _process_legacy_playlist_url(self, url, display_id):
  446. playlist = self._download_legacy_playlist_url(url, display_id)
  447. return self._extract_from_legacy_playlist(playlist, display_id)
  448. def _process_legacy_playlist(self, playlist_id):
  449. return self._process_legacy_playlist_url(
  450. 'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
  451. def _download_legacy_playlist_url(self, url, playlist_id=None):
  452. return self._download_xml(
  453. url, playlist_id, 'Downloading legacy playlist XML')
  454. def _extract_from_legacy_playlist(self, playlist, playlist_id):
  455. no_items = playlist.find('./{%s}noItems' % self._EMP_PLAYLIST_NS)
  456. if no_items is not None:
  457. reason = no_items.get('reason')
  458. if reason == 'preAvailability':
  459. msg = 'Episode %s is not yet available' % playlist_id
  460. elif reason == 'postAvailability':
  461. msg = 'Episode %s is no longer available' % playlist_id
  462. elif reason == 'noMedia':
  463. msg = 'Episode %s is not currently available' % playlist_id
  464. else:
  465. msg = 'Episode %s is not available: %s' % (playlist_id, reason)
  466. raise ExtractorError(msg, expected=True)
  467. for item in self._extract_items(playlist):
  468. kind = item.get('kind')
  469. if kind not in ('programme', 'radioProgramme'):
  470. continue
  471. title = playlist.find('./{%s}title' % self._EMP_PLAYLIST_NS).text
  472. description_el = playlist.find('./{%s}summary' % self._EMP_PLAYLIST_NS)
  473. description = description_el.text if description_el is not None else None
  474. def get_programme_id(item):
  475. def get_from_attributes(item):
  476. for p in ('identifier', 'group'):
  477. value = item.get(p)
  478. if value and re.match(r'^[pb][\da-z]{7}$', value):
  479. return value
  480. get_from_attributes(item)
  481. mediator = item.find('./{%s}mediator' % self._EMP_PLAYLIST_NS)
  482. if mediator is not None:
  483. return get_from_attributes(mediator)
  484. programme_id = get_programme_id(item)
  485. duration = int_or_none(item.get('duration'))
  486. if programme_id:
  487. formats, subtitles = self._download_media_selector(programme_id)
  488. else:
  489. formats, subtitles = self._process_media_selector(item, playlist_id)
  490. programme_id = playlist_id
  491. return programme_id, title, description, duration, formats, subtitles
  492. def _real_extract(self, url):
  493. group_id = self._match_id(url)
  494. webpage = self._download_webpage(url, group_id, 'Downloading video page')
  495. error = self._search_regex(
  496. r'<div\b[^>]+\bclass=["\'](?:smp|playout)__message delta["\'][^>]*>\s*([^<]+?)\s*<',
  497. webpage, 'error', default=None)
  498. if error:
  499. raise ExtractorError(error, expected=True)
  500. programme_id = None
  501. duration = None
  502. tviplayer = self._search_regex(
  503. r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
  504. webpage, 'player', default=None)
  505. if tviplayer:
  506. player = self._parse_json(tviplayer, group_id).get('player', {})
  507. duration = int_or_none(player.get('duration'))
  508. programme_id = player.get('vpid')
  509. if not programme_id:
  510. programme_id = self._search_regex(
  511. r'"vpid"\s*:\s*"(%s)"' % self._ID_REGEX, webpage, 'vpid', fatal=False, default=None)
  512. if programme_id:
  513. formats, subtitles = self._download_media_selector(programme_id)
  514. title = self._og_search_title(webpage, default=None) or self._html_search_regex(
  515. (r'<h2[^>]+id="parent-title"[^>]*>(.+?)</h2>',
  516. r'<div[^>]+class="info"[^>]*>\s*<h1>(.+?)</h1>'), webpage, 'title')
  517. description = self._search_regex(
  518. (r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
  519. r'<div[^>]+class="info_+synopsis"[^>]*>([^<]+)</div>'),
  520. webpage, 'description', default=None)
  521. if not description:
  522. description = self._html_search_meta('description', webpage)
  523. else:
  524. programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
  525. self._sort_formats(formats)
  526. return {
  527. 'id': programme_id,
  528. 'title': title,
  529. 'description': description,
  530. 'thumbnail': self._og_search_thumbnail(webpage, default=None),
  531. 'duration': duration,
  532. 'formats': formats,
  533. 'subtitles': subtitles,
  534. }
  535. class BBCIE(BBCCoUkIE):
  536. IE_NAME = 'bbc'
  537. IE_DESC = 'BBC'
  538. _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
  539. _MEDIA_SETS = [
  540. 'mobile-tablet-main',
  541. 'pc',
  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',
  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. # also, video with window.__INITIAL_DATA__
  715. 'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
  716. 'info_dict': {
  717. 'id': 'p02xzws1',
  718. 'ext': 'mp4',
  719. 'title': "Pluto may have 'nitrogen glaciers'",
  720. 'description': 'md5:6a95b593f528d7a5f2605221bc56912f',
  721. 'thumbnail': r're:https?://.+/.+\.jpg',
  722. 'timestamp': 1437785037,
  723. 'upload_date': '20150725',
  724. },
  725. }, {
  726. # single video article embedded with data-media-vpid
  727. 'url': 'http://www.bbc.co.uk/sport/rowing/35908187',
  728. 'only_matching': True,
  729. }, {
  730. 'url': 'https://www.bbc.co.uk/bbcthree/clip/73d0bbd0-abc3-4cea-b3c0-cdae21905eb1',
  731. 'info_dict': {
  732. 'id': 'p06556y7',
  733. 'ext': 'mp4',
  734. 'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
  735. 'description': 'md5:4b7dfd063d5a789a1512e99662be3ddd',
  736. },
  737. 'params': {
  738. 'skip_download': True,
  739. }
  740. }, {
  741. # window.__PRELOADED_STATE__
  742. 'url': 'https://www.bbc.co.uk/radio/play/b0b9z4yl',
  743. 'info_dict': {
  744. 'id': 'b0b9z4vz',
  745. 'ext': 'mp4',
  746. 'title': 'Prom 6: An American in Paris and Turangalila',
  747. 'description': 'md5:51cf7d6f5c8553f197e58203bc78dff8',
  748. 'uploader': 'Radio 3',
  749. 'uploader_id': 'bbc_radio_three',
  750. },
  751. }, {
  752. 'url': 'http://www.bbc.co.uk/learningenglish/chinese/features/lingohack/ep-181227',
  753. 'info_dict': {
  754. 'id': 'p06w9tws',
  755. 'ext': 'mp4',
  756. 'title': 'md5:2fabf12a726603193a2879a055f72514',
  757. 'description': 'Learn English words and phrases from this story',
  758. },
  759. 'add_ie': [BBCCoUkIE.ie_key()],
  760. }, {
  761. # BBC Reel
  762. 'url': 'https://www.bbc.com/reel/video/p07c6sb6/how-positive-thinking-is-harming-your-happiness',
  763. 'info_dict': {
  764. 'id': 'p07c6sb9',
  765. 'ext': 'mp4',
  766. 'title': 'How positive thinking is harming your happiness',
  767. 'alt_title': 'The downsides of positive thinking',
  768. 'description': 'md5:fad74b31da60d83b8265954ee42d85b4',
  769. 'duration': 235,
  770. 'thumbnail': r're:https?://.+/p07c9dsr.jpg',
  771. 'upload_date': '20190604',
  772. 'categories': ['Psychology'],
  773. },
  774. }]
  775. @classmethod
  776. def suitable(cls, url):
  777. EXCLUDE_IE = (BBCCoUkIE, BBCCoUkArticleIE, BBCCoUkIPlayerEpisodesIE, BBCCoUkIPlayerGroupIE, BBCCoUkPlaylistIE)
  778. return (False if any(ie.suitable(url) for ie in EXCLUDE_IE)
  779. else super(BBCIE, cls).suitable(url))
  780. def _extract_from_media_meta(self, media_meta, video_id):
  781. # Direct links to media in media metadata (e.g.
  782. # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
  783. # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
  784. source_files = media_meta.get('sourceFiles')
  785. if source_files:
  786. return [{
  787. 'url': f['url'],
  788. 'format_id': format_id,
  789. 'ext': f.get('encoding'),
  790. 'tbr': float_or_none(f.get('bitrate'), 1000),
  791. 'filesize': int_or_none(f.get('filesize')),
  792. } for format_id, f in source_files.items() if f.get('url')], []
  793. programme_id = media_meta.get('externalId')
  794. if programme_id:
  795. return self._download_media_selector(programme_id)
  796. # Process playlist.sxml as legacy playlist
  797. href = media_meta.get('href')
  798. if href:
  799. playlist = self._download_legacy_playlist_url(href)
  800. _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
  801. return formats, subtitles
  802. return [], []
  803. def _extract_from_playlist_sxml(self, url, playlist_id, timestamp):
  804. programme_id, title, description, duration, formats, subtitles = \
  805. self._process_legacy_playlist_url(url, playlist_id)
  806. self._sort_formats(formats)
  807. return {
  808. 'id': programme_id,
  809. 'title': title,
  810. 'description': description,
  811. 'duration': duration,
  812. 'timestamp': timestamp,
  813. 'formats': formats,
  814. 'subtitles': subtitles,
  815. }
  816. def _real_extract(self, url):
  817. playlist_id = self._match_id(url)
  818. webpage = self._download_webpage(url, playlist_id)
  819. json_ld_info = self._search_json_ld(webpage, playlist_id, default={})
  820. timestamp = json_ld_info.get('timestamp')
  821. playlist_title = json_ld_info.get('title')
  822. if not playlist_title:
  823. playlist_title = self._og_search_title(
  824. webpage, default=None) or self._html_search_regex(
  825. r'<title>(.+?)</title>', webpage, 'playlist title', default=None)
  826. if playlist_title:
  827. playlist_title = re.sub(r'(.+)\s*-\s*BBC.*?$', r'\1', playlist_title).strip()
  828. playlist_description = json_ld_info.get(
  829. 'description') or self._og_search_description(webpage, default=None)
  830. if not timestamp:
  831. timestamp = parse_iso8601(self._search_regex(
  832. [r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
  833. r'itemprop="datePublished"[^>]+datetime="([^"]+)"',
  834. r'"datePublished":\s*"([^"]+)'],
  835. webpage, 'date', default=None))
  836. entries = []
  837. # article with multiple videos embedded with playlist.sxml (e.g.
  838. # http://www.bbc.com/sport/0/football/34475836)
  839. playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
  840. playlists.extend(re.findall(r'data-media-id="([^"]+/playlist\.sxml)"', webpage))
  841. if playlists:
  842. entries = [
  843. self._extract_from_playlist_sxml(playlist_url, playlist_id, timestamp)
  844. for playlist_url in playlists]
  845. # news article with multiple videos embedded with data-playable
  846. data_playables = re.findall(r'data-playable=(["\'])({.+?})\1', webpage)
  847. if data_playables:
  848. for _, data_playable_json in data_playables:
  849. data_playable = self._parse_json(
  850. unescapeHTML(data_playable_json), playlist_id, fatal=False)
  851. if not data_playable:
  852. continue
  853. settings = data_playable.get('settings', {})
  854. if settings:
  855. # data-playable with video vpid in settings.playlistObject.items (e.g.
  856. # http://www.bbc.com/news/world-us-canada-34473351)
  857. playlist_object = settings.get('playlistObject', {})
  858. if playlist_object:
  859. items = playlist_object.get('items')
  860. if items and isinstance(items, list):
  861. title = playlist_object['title']
  862. description = playlist_object.get('summary')
  863. duration = int_or_none(items[0].get('duration'))
  864. programme_id = items[0].get('vpid')
  865. formats, subtitles = self._download_media_selector(programme_id)
  866. self._sort_formats(formats)
  867. entries.append({
  868. 'id': programme_id,
  869. 'title': title,
  870. 'description': description,
  871. 'timestamp': timestamp,
  872. 'duration': duration,
  873. 'formats': formats,
  874. 'subtitles': subtitles,
  875. })
  876. else:
  877. # data-playable without vpid but with a playlist.sxml URLs
  878. # in otherSettings.playlist (e.g.
  879. # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
  880. playlist = data_playable.get('otherSettings', {}).get('playlist', {})
  881. if playlist:
  882. entry = None
  883. for key in ('streaming', 'progressiveDownload'):
  884. playlist_url = playlist.get('%sUrl' % key)
  885. if not playlist_url:
  886. continue
  887. try:
  888. info = self._extract_from_playlist_sxml(
  889. playlist_url, playlist_id, timestamp)
  890. if not entry:
  891. entry = info
  892. else:
  893. entry['title'] = info['title']
  894. entry['formats'].extend(info['formats'])
  895. except ExtractorError as e:
  896. # Some playlist URL may fail with 500, at the same time
  897. # the other one may work fine (e.g.
  898. # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
  899. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 500:
  900. continue
  901. raise
  902. if entry:
  903. self._sort_formats(entry['formats'])
  904. entries.append(entry)
  905. if entries:
  906. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
  907. # http://www.bbc.co.uk/learningenglish/chinese/features/lingohack/ep-181227
  908. group_id = self._search_regex(
  909. r'<div[^>]+\bclass=["\']video["\'][^>]+\bdata-pid=["\'](%s)' % self._ID_REGEX,
  910. webpage, 'group id', default=None)
  911. if group_id:
  912. return self.url_result(
  913. 'https://www.bbc.co.uk/programmes/%s' % group_id,
  914. ie=BBCCoUkIE.ie_key())
  915. # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
  916. programme_id = self._search_regex(
  917. [r'data-(?:video-player|media)-vpid="(%s)"' % self._ID_REGEX,
  918. r'<param[^>]+name="externalIdentifier"[^>]+value="(%s)"' % self._ID_REGEX,
  919. r'videoId\s*:\s*["\'](%s)["\']' % self._ID_REGEX],
  920. webpage, 'vpid', default=None)
  921. if programme_id:
  922. formats, subtitles = self._download_media_selector(programme_id)
  923. self._sort_formats(formats)
  924. # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
  925. digital_data = self._parse_json(
  926. self._search_regex(
  927. r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
  928. programme_id, fatal=False)
  929. page_info = digital_data.get('page', {}).get('pageInfo', {})
  930. title = page_info.get('pageName') or self._og_search_title(webpage)
  931. description = page_info.get('description') or self._og_search_description(webpage)
  932. timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
  933. return {
  934. 'id': programme_id,
  935. 'title': title,
  936. 'description': description,
  937. 'timestamp': timestamp,
  938. 'formats': formats,
  939. 'subtitles': subtitles,
  940. }
  941. # bbc reel (e.g. https://www.bbc.com/reel/video/p07c6sb6/how-positive-thinking-is-harming-your-happiness)
  942. initial_data = self._parse_json(self._html_search_regex(
  943. r'<script[^>]+id=(["\'])initial-data\1[^>]+data-json=(["\'])(?P<json>(?:(?!\2).)+)',
  944. webpage, 'initial data', default='{}', group='json'), playlist_id, fatal=False)
  945. if initial_data:
  946. init_data = try_get(
  947. initial_data, lambda x: x['initData']['items'][0], dict) or {}
  948. smp_data = init_data.get('smpData') or {}
  949. clip_data = try_get(smp_data, lambda x: x['items'][0], dict) or {}
  950. version_id = clip_data.get('versionID')
  951. if version_id:
  952. title = smp_data['title']
  953. formats, subtitles = self._download_media_selector(version_id)
  954. self._sort_formats(formats)
  955. image_url = smp_data.get('holdingImageURL')
  956. display_date = init_data.get('displayDate')
  957. topic_title = init_data.get('topicTitle')
  958. return {
  959. 'id': version_id,
  960. 'title': title,
  961. 'formats': formats,
  962. 'alt_title': init_data.get('shortTitle'),
  963. 'thumbnail': image_url.replace('$recipe', 'raw') if image_url else None,
  964. 'description': smp_data.get('summary') or init_data.get('shortSummary'),
  965. 'upload_date': display_date.replace('-', '') if display_date else None,
  966. 'subtitles': subtitles,
  967. 'duration': int_or_none(clip_data.get('duration')),
  968. 'categories': [topic_title] if topic_title else None,
  969. }
  970. # Morph based embed (e.g. http://www.bbc.co.uk/sport/live/olympics/36895975)
  971. # There are several setPayload calls may be present but the video
  972. # seems to be always related to the first one
  973. morph_payload = self._parse_json(
  974. self._search_regex(
  975. r'Morph\.setPayload\([^,]+,\s*({.+?})\);',
  976. webpage, 'morph payload', default='{}'),
  977. playlist_id, fatal=False)
  978. if morph_payload:
  979. components = try_get(morph_payload, lambda x: x['body']['components'], list) or []
  980. for component in components:
  981. if not isinstance(component, dict):
  982. continue
  983. lead_media = try_get(component, lambda x: x['props']['leadMedia'], dict)
  984. if not lead_media:
  985. continue
  986. identifiers = lead_media.get('identifiers')
  987. if not identifiers or not isinstance(identifiers, dict):
  988. continue
  989. programme_id = identifiers.get('vpid') or identifiers.get('playablePid')
  990. if not programme_id:
  991. continue
  992. title = lead_media.get('title') or self._og_search_title(webpage)
  993. formats, subtitles = self._download_media_selector(programme_id)
  994. self._sort_formats(formats)
  995. description = lead_media.get('summary')
  996. uploader = lead_media.get('masterBrand')
  997. uploader_id = lead_media.get('mid')
  998. duration = None
  999. duration_d = lead_media.get('duration')
  1000. if isinstance(duration_d, dict):
  1001. duration = parse_duration(dict_get(
  1002. duration_d, ('rawDuration', 'formattedDuration', 'spokenDuration')))
  1003. return {
  1004. 'id': programme_id,
  1005. 'title': title,
  1006. 'description': description,
  1007. 'duration': duration,
  1008. 'uploader': uploader,
  1009. 'uploader_id': uploader_id,
  1010. 'formats': formats,
  1011. 'subtitles': subtitles,
  1012. }
  1013. preload_state = self._parse_json(self._search_regex(
  1014. r'window\.__PRELOADED_STATE__\s*=\s*({.+?});', webpage,
  1015. 'preload state', default='{}'), playlist_id, fatal=False)
  1016. if preload_state:
  1017. current_programme = preload_state.get('programmes', {}).get('current') or {}
  1018. programme_id = current_programme.get('id')
  1019. if current_programme and programme_id and current_programme.get('type') == 'playable_item':
  1020. title = current_programme.get('titles', {}).get('tertiary') or playlist_title
  1021. formats, subtitles = self._download_media_selector(programme_id)
  1022. self._sort_formats(formats)
  1023. synopses = current_programme.get('synopses') or {}
  1024. network = current_programme.get('network') or {}
  1025. duration = int_or_none(
  1026. current_programme.get('duration', {}).get('value'))
  1027. thumbnail = None
  1028. image_url = current_programme.get('image_url')
  1029. if image_url:
  1030. thumbnail = image_url.replace('{recipe}', 'raw')
  1031. return {
  1032. 'id': programme_id,
  1033. 'title': title,
  1034. 'description': dict_get(synopses, ('long', 'medium', 'short')),
  1035. 'thumbnail': thumbnail,
  1036. 'duration': duration,
  1037. 'uploader': network.get('short_title'),
  1038. 'uploader_id': network.get('id'),
  1039. 'formats': formats,
  1040. 'subtitles': subtitles,
  1041. }
  1042. bbc3_config = self._parse_json(
  1043. self._search_regex(
  1044. r'(?s)bbcthreeConfig\s*=\s*({.+?})\s*;\s*<', webpage,
  1045. 'bbcthree config', default='{}'),
  1046. playlist_id, transform_source=js_to_json, fatal=False) or {}
  1047. payload = bbc3_config.get('payload') or {}
  1048. if payload:
  1049. clip = payload.get('currentClip') or {}
  1050. clip_vpid = clip.get('vpid')
  1051. clip_title = clip.get('title')
  1052. if clip_vpid and clip_title:
  1053. formats, subtitles = self._download_media_selector(clip_vpid)
  1054. self._sort_formats(formats)
  1055. return {
  1056. 'id': clip_vpid,
  1057. 'title': clip_title,
  1058. 'thumbnail': dict_get(clip, ('poster', 'imageUrl')),
  1059. 'description': clip.get('description'),
  1060. 'duration': parse_duration(clip.get('duration')),
  1061. 'formats': formats,
  1062. 'subtitles': subtitles,
  1063. }
  1064. bbc3_playlist = try_get(
  1065. payload, lambda x: x['content']['bbcMedia']['playlist'],
  1066. dict)
  1067. if bbc3_playlist:
  1068. playlist_title = bbc3_playlist.get('title') or playlist_title
  1069. thumbnail = bbc3_playlist.get('holdingImageURL')
  1070. entries = []
  1071. for bbc3_item in bbc3_playlist['items']:
  1072. programme_id = bbc3_item.get('versionID')
  1073. if not programme_id:
  1074. continue
  1075. formats, subtitles = self._download_media_selector(programme_id)
  1076. self._sort_formats(formats)
  1077. entries.append({
  1078. 'id': programme_id,
  1079. 'title': playlist_title,
  1080. 'thumbnail': thumbnail,
  1081. 'timestamp': timestamp,
  1082. 'formats': formats,
  1083. 'subtitles': subtitles,
  1084. })
  1085. return self.playlist_result(
  1086. entries, playlist_id, playlist_title, playlist_description)
  1087. initial_data = self._parse_json(self._search_regex(
  1088. r'window\.__INITIAL_DATA__\s*=\s*({.+?});', webpage,
  1089. 'preload state', default='{}'), playlist_id, fatal=False)
  1090. if initial_data:
  1091. def parse_media(media):
  1092. if not media:
  1093. return
  1094. for item in (try_get(media, lambda x: x['media']['items'], list) or []):
  1095. item_id = item.get('id')
  1096. item_title = item.get('title')
  1097. if not (item_id and item_title):
  1098. continue
  1099. formats, subtitles = self._download_media_selector(item_id)
  1100. self._sort_formats(formats)
  1101. item_desc = None
  1102. blocks = try_get(media, lambda x: x['summary']['blocks'], list)
  1103. if blocks:
  1104. summary = []
  1105. for block in blocks:
  1106. text = try_get(block, lambda x: x['model']['text'], compat_str)
  1107. if text:
  1108. summary.append(text)
  1109. if summary:
  1110. item_desc = '\n\n'.join(summary)
  1111. item_time = None
  1112. for meta in try_get(media, lambda x: x['metadata']['items'], list) or []:
  1113. if try_get(meta, lambda x: x['label']) == 'Published':
  1114. item_time = unified_timestamp(meta.get('timestamp'))
  1115. break
  1116. entries.append({
  1117. 'id': item_id,
  1118. 'title': item_title,
  1119. 'thumbnail': item.get('holdingImageUrl'),
  1120. 'formats': formats,
  1121. 'subtitles': subtitles,
  1122. 'timestamp': item_time,
  1123. 'description': strip_or_none(item_desc),
  1124. })
  1125. for resp in (initial_data.get('data') or {}).values():
  1126. name = resp.get('name')
  1127. if name == 'media-experience':
  1128. parse_media(try_get(resp, lambda x: x['data']['initialItem']['mediaItem'], dict))
  1129. elif name == 'article':
  1130. for block in (try_get(resp, lambda x: x['data']['blocks'], list) or []):
  1131. if block.get('type') != 'media':
  1132. continue
  1133. parse_media(block.get('model'))
  1134. return self.playlist_result(
  1135. entries, playlist_id, playlist_title, playlist_description)
  1136. def extract_all(pattern):
  1137. return list(filter(None, map(
  1138. lambda s: self._parse_json(s, playlist_id, fatal=False),
  1139. re.findall(pattern, webpage))))
  1140. # Multiple video article (e.g.
  1141. # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
  1142. EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+%s(?:\b[^"]+)?' % self._ID_REGEX
  1143. entries = []
  1144. for match in extract_all(r'new\s+SMP\(({.+?})\)'):
  1145. embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
  1146. if embed_url and re.match(EMBED_URL, embed_url):
  1147. entries.append(embed_url)
  1148. entries.extend(re.findall(
  1149. r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
  1150. if entries:
  1151. return self.playlist_result(
  1152. [self.url_result(entry_, 'BBCCoUk') for entry_ in entries],
  1153. playlist_id, playlist_title, playlist_description)
  1154. # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
  1155. medias = extract_all(r"data-media-meta='({[^']+})'")
  1156. if not medias:
  1157. # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
  1158. media_asset = self._search_regex(
  1159. r'mediaAssetPage\.init\(\s*({.+?}), "/',
  1160. webpage, 'media asset', default=None)
  1161. if media_asset:
  1162. media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
  1163. medias = []
  1164. for video in media_asset_page.get('videos', {}).values():
  1165. medias.extend(video.values())
  1166. if not medias:
  1167. # Multiple video playlist with single `now playing` entry (e.g.
  1168. # http://www.bbc.com/news/video_and_audio/must_see/33767813)
  1169. vxp_playlist = self._parse_json(
  1170. self._search_regex(
  1171. r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
  1172. webpage, 'playlist data'),
  1173. playlist_id)
  1174. playlist_medias = []
  1175. for item in vxp_playlist:
  1176. media = item.get('media')
  1177. if not media:
  1178. continue
  1179. playlist_medias.append(media)
  1180. # Download single video if found media with asset id matching the video id from URL
  1181. if item.get('advert', {}).get('assetId') == playlist_id:
  1182. medias = [media]
  1183. break
  1184. # Fallback to the whole playlist
  1185. if not medias:
  1186. medias = playlist_medias
  1187. entries = []
  1188. for num, media_meta in enumerate(medias, start=1):
  1189. formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
  1190. if not formats:
  1191. continue
  1192. self._sort_formats(formats)
  1193. video_id = media_meta.get('externalId')
  1194. if not video_id:
  1195. video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
  1196. title = media_meta.get('caption')
  1197. if not title:
  1198. title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
  1199. duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
  1200. images = []
  1201. for image in media_meta.get('images', {}).values():
  1202. images.extend(image.values())
  1203. if 'image' in media_meta:
  1204. images.append(media_meta['image'])
  1205. thumbnails = [{
  1206. 'url': image.get('href'),
  1207. 'width': int_or_none(image.get('width')),
  1208. 'height': int_or_none(image.get('height')),
  1209. } for image in images]
  1210. entries.append({
  1211. 'id': video_id,
  1212. 'title': title,
  1213. 'thumbnails': thumbnails,
  1214. 'duration': duration,
  1215. 'timestamp': timestamp,
  1216. 'formats': formats,
  1217. 'subtitles': subtitles,
  1218. })
  1219. return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
  1220. class BBCCoUkArticleIE(InfoExtractor):
  1221. _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)'
  1222. IE_NAME = 'bbc.co.uk:article'
  1223. IE_DESC = 'BBC articles'
  1224. _TEST = {
  1225. 'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer',
  1226. 'info_dict': {
  1227. 'id': '3jNQLTMrPlYGTBn0WV6M2MS',
  1228. 'title': 'Calculating Ada: The Countess of Computing - Not your typical role model: Ada Lovelace the 19th century programmer - BBC Four',
  1229. 'description': 'Hannah Fry reveals some of her surprising discoveries about Ada Lovelace during filming.',
  1230. },
  1231. 'playlist_count': 4,
  1232. 'add_ie': ['BBCCoUk'],
  1233. }
  1234. def _real_extract(self, url):
  1235. playlist_id = self._match_id(url)
  1236. webpage = self._download_webpage(url, playlist_id)
  1237. title = self._og_search_title(webpage)
  1238. description = self._og_search_description(webpage).strip()
  1239. entries = [self.url_result(programme_url) for programme_url in re.findall(
  1240. r'<div[^>]+typeof="Clip"[^>]+resource="([^"]+)"', webpage)]
  1241. return self.playlist_result(entries, playlist_id, title, description)
  1242. class BBCCoUkPlaylistBaseIE(InfoExtractor):
  1243. def _entries(self, webpage, url, playlist_id):
  1244. single_page = 'page' in compat_urlparse.parse_qs(
  1245. compat_urlparse.urlparse(url).query)
  1246. for page_num in itertools.count(2):
  1247. for video_id in re.findall(
  1248. self._VIDEO_ID_TEMPLATE % BBCCoUkIE._ID_REGEX, webpage):
  1249. yield self.url_result(
  1250. self._URL_TEMPLATE % video_id, BBCCoUkIE.ie_key())
  1251. if single_page:
  1252. return
  1253. next_page = self._search_regex(
  1254. r'<li[^>]+class=(["\'])pagination_+next\1[^>]*><a[^>]+href=(["\'])(?P<url>(?:(?!\2).)+)\2',
  1255. webpage, 'next page url', default=None, group='url')
  1256. if not next_page:
  1257. break
  1258. webpage = self._download_webpage(
  1259. compat_urlparse.urljoin(url, next_page), playlist_id,
  1260. 'Downloading page %d' % page_num, page_num)
  1261. def _real_extract(self, url):
  1262. playlist_id = self._match_id(url)
  1263. webpage = self._download_webpage(url, playlist_id)
  1264. title, description = self._extract_title_and_description(webpage)
  1265. return self.playlist_result(
  1266. self._entries(webpage, url, playlist_id),
  1267. playlist_id, title, description)
  1268. class BBCCoUkIPlayerPlaylistBaseIE(InfoExtractor):
  1269. _VALID_URL_TMPL = r'https?://(?:www\.)?bbc\.co\.uk/iplayer/%%s/(?P<id>%s)' % BBCCoUkIE._ID_REGEX
  1270. @staticmethod
  1271. def _get_default(episode, key, default_key='default'):
  1272. return try_get(episode, lambda x: x[key][default_key])
  1273. def _get_description(self, data):
  1274. synopsis = data.get(self._DESCRIPTION_KEY) or {}
  1275. return dict_get(synopsis, ('large', 'medium', 'small'))
  1276. def _fetch_page(self, programme_id, per_page, series_id, page):
  1277. elements = self._get_elements(self._call_api(
  1278. programme_id, per_page, page + 1, series_id))
  1279. for element in elements:
  1280. episode = self._get_episode(element)
  1281. episode_id = episode.get('id')
  1282. if not episode_id:
  1283. continue
  1284. thumbnail = None
  1285. image = self._get_episode_image(episode)
  1286. if image:
  1287. thumbnail = image.replace('{recipe}', 'raw')
  1288. category = self._get_default(episode, 'labels', 'category')
  1289. yield {
  1290. '_type': 'url',
  1291. 'id': episode_id,
  1292. 'title': self._get_episode_field(episode, 'subtitle'),
  1293. 'url': 'https://www.bbc.co.uk/iplayer/episode/' + episode_id,
  1294. 'thumbnail': thumbnail,
  1295. 'description': self._get_description(episode),
  1296. 'categories': [category] if category else None,
  1297. 'series': self._get_episode_field(episode, 'title'),
  1298. 'ie_key': BBCCoUkIE.ie_key(),
  1299. }
  1300. def _real_extract(self, url):
  1301. pid = self._match_id(url)
  1302. qs = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
  1303. series_id = qs.get('seriesId', [None])[0]
  1304. page = qs.get('page', [None])[0]
  1305. per_page = 36 if page else self._PAGE_SIZE
  1306. fetch_page = functools.partial(self._fetch_page, pid, per_page, series_id)
  1307. entries = fetch_page(int(page) - 1) if page else OnDemandPagedList(fetch_page, self._PAGE_SIZE)
  1308. playlist_data = self._get_playlist_data(self._call_api(pid, 1))
  1309. return self.playlist_result(
  1310. entries, pid, self._get_playlist_title(playlist_data),
  1311. self._get_description(playlist_data))
  1312. class BBCCoUkIPlayerEpisodesIE(BBCCoUkIPlayerPlaylistBaseIE):
  1313. IE_NAME = 'bbc.co.uk:iplayer:episodes'
  1314. _VALID_URL = BBCCoUkIPlayerPlaylistBaseIE._VALID_URL_TMPL % 'episodes'
  1315. _TESTS = [{
  1316. 'url': 'http://www.bbc.co.uk/iplayer/episodes/b05rcz9v',
  1317. 'info_dict': {
  1318. 'id': 'b05rcz9v',
  1319. 'title': 'The Disappearance',
  1320. 'description': 'md5:58eb101aee3116bad4da05f91179c0cb',
  1321. },
  1322. 'playlist_mincount': 8,
  1323. }, {
  1324. # all seasons
  1325. 'url': 'https://www.bbc.co.uk/iplayer/episodes/b094m5t9/doctor-foster',
  1326. 'info_dict': {
  1327. 'id': 'b094m5t9',
  1328. 'title': 'Doctor Foster',
  1329. 'description': 'md5:5aa9195fad900e8e14b52acd765a9fd6',
  1330. },
  1331. 'playlist_mincount': 10,
  1332. }, {
  1333. # explicit season
  1334. 'url': 'https://www.bbc.co.uk/iplayer/episodes/b094m5t9/doctor-foster?seriesId=b094m6nv',
  1335. 'info_dict': {
  1336. 'id': 'b094m5t9',
  1337. 'title': 'Doctor Foster',
  1338. 'description': 'md5:5aa9195fad900e8e14b52acd765a9fd6',
  1339. },
  1340. 'playlist_mincount': 5,
  1341. }, {
  1342. # all pages
  1343. 'url': 'https://www.bbc.co.uk/iplayer/episodes/m0004c4v/beechgrove',
  1344. 'info_dict': {
  1345. 'id': 'm0004c4v',
  1346. 'title': 'Beechgrove',
  1347. 'description': 'Gardening show that celebrates Scottish horticulture and growing conditions.',
  1348. },
  1349. 'playlist_mincount': 37,
  1350. }, {
  1351. # explicit page
  1352. 'url': 'https://www.bbc.co.uk/iplayer/episodes/m0004c4v/beechgrove?page=2',
  1353. 'info_dict': {
  1354. 'id': 'm0004c4v',
  1355. 'title': 'Beechgrove',
  1356. 'description': 'Gardening show that celebrates Scottish horticulture and growing conditions.',
  1357. },
  1358. 'playlist_mincount': 1,
  1359. }]
  1360. _PAGE_SIZE = 100
  1361. _DESCRIPTION_KEY = 'synopsis'
  1362. def _get_episode_image(self, episode):
  1363. return self._get_default(episode, 'image')
  1364. def _get_episode_field(self, episode, field):
  1365. return self._get_default(episode, field)
  1366. @staticmethod
  1367. def _get_elements(data):
  1368. return data['entities']['results']
  1369. @staticmethod
  1370. def _get_episode(element):
  1371. return element.get('episode') or {}
  1372. def _call_api(self, pid, per_page, page=1, series_id=None):
  1373. variables = {
  1374. 'id': pid,
  1375. 'page': page,
  1376. 'perPage': per_page,
  1377. }
  1378. if series_id:
  1379. variables['sliceId'] = series_id
  1380. return self._download_json(
  1381. 'https://graph.ibl.api.bbc.co.uk/', pid, headers={
  1382. 'Content-Type': 'application/json'
  1383. }, data=json.dumps({
  1384. 'id': '5692d93d5aac8d796a0305e895e61551',
  1385. 'variables': variables,
  1386. }).encode('utf-8'))['data']['programme']
  1387. @staticmethod
  1388. def _get_playlist_data(data):
  1389. return data
  1390. def _get_playlist_title(self, data):
  1391. return self._get_default(data, 'title')
  1392. class BBCCoUkIPlayerGroupIE(BBCCoUkIPlayerPlaylistBaseIE):
  1393. IE_NAME = 'bbc.co.uk:iplayer:group'
  1394. _VALID_URL = BBCCoUkIPlayerPlaylistBaseIE._VALID_URL_TMPL % 'group'
  1395. _TESTS = [{
  1396. # Available for over a year unlike 30 days for most other programmes
  1397. 'url': 'http://www.bbc.co.uk/iplayer/group/p02tcc32',
  1398. 'info_dict': {
  1399. 'id': 'p02tcc32',
  1400. 'title': 'Bohemian Icons',
  1401. 'description': 'md5:683e901041b2fe9ba596f2ab04c4dbe7',
  1402. },
  1403. 'playlist_mincount': 10,
  1404. }, {
  1405. # all pages
  1406. 'url': 'https://www.bbc.co.uk/iplayer/group/p081d7j7',
  1407. 'info_dict': {
  1408. 'id': 'p081d7j7',
  1409. 'title': 'Music in Scotland',
  1410. 'description': 'Perfomances in Scotland and programmes featuring Scottish acts.',
  1411. },
  1412. 'playlist_mincount': 47,
  1413. }, {
  1414. # explicit page
  1415. 'url': 'https://www.bbc.co.uk/iplayer/group/p081d7j7?page=2',
  1416. 'info_dict': {
  1417. 'id': 'p081d7j7',
  1418. 'title': 'Music in Scotland',
  1419. 'description': 'Perfomances in Scotland and programmes featuring Scottish acts.',
  1420. },
  1421. 'playlist_mincount': 11,
  1422. }]
  1423. _PAGE_SIZE = 200
  1424. _DESCRIPTION_KEY = 'synopses'
  1425. def _get_episode_image(self, episode):
  1426. return self._get_default(episode, 'images', 'standard')
  1427. def _get_episode_field(self, episode, field):
  1428. return episode.get(field)
  1429. @staticmethod
  1430. def _get_elements(data):
  1431. return data['elements']
  1432. @staticmethod
  1433. def _get_episode(element):
  1434. return element
  1435. def _call_api(self, pid, per_page, page=1, series_id=None):
  1436. return self._download_json(
  1437. 'http://ibl.api.bbc.co.uk/ibl/v1/groups/%s/episodes' % pid,
  1438. pid, query={
  1439. 'page': page,
  1440. 'per_page': per_page,
  1441. })['group_episodes']
  1442. @staticmethod
  1443. def _get_playlist_data(data):
  1444. return data['group']
  1445. def _get_playlist_title(self, data):
  1446. return data.get('title')
  1447. class BBCCoUkPlaylistIE(BBCCoUkPlaylistBaseIE):
  1448. IE_NAME = 'bbc.co.uk:playlist'
  1449. _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/(?P<id>%s)/(?:episodes|broadcasts|clips)' % BBCCoUkIE._ID_REGEX
  1450. _URL_TEMPLATE = 'http://www.bbc.co.uk/programmes/%s'
  1451. _VIDEO_ID_TEMPLATE = r'data-pid=["\'](%s)'
  1452. _TESTS = [{
  1453. 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
  1454. 'info_dict': {
  1455. 'id': 'b05rcz9v',
  1456. 'title': 'The Disappearance - Clips - BBC Four',
  1457. 'description': 'French thriller serial about a missing teenager.',
  1458. },
  1459. 'playlist_mincount': 7,
  1460. }, {
  1461. # multipage playlist, explicit page
  1462. 'url': 'http://www.bbc.co.uk/programmes/b00mfl7n/clips?page=1',
  1463. 'info_dict': {
  1464. 'id': 'b00mfl7n',
  1465. 'title': 'Frozen Planet - Clips - BBC One',
  1466. 'description': 'md5:65dcbf591ae628dafe32aa6c4a4a0d8c',
  1467. },
  1468. 'playlist_mincount': 24,
  1469. }, {
  1470. # multipage playlist, all pages
  1471. 'url': 'http://www.bbc.co.uk/programmes/b00mfl7n/clips',
  1472. 'info_dict': {
  1473. 'id': 'b00mfl7n',
  1474. 'title': 'Frozen Planet - Clips - BBC One',
  1475. 'description': 'md5:65dcbf591ae628dafe32aa6c4a4a0d8c',
  1476. },
  1477. 'playlist_mincount': 142,
  1478. }, {
  1479. 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/broadcasts/2016/06',
  1480. 'only_matching': True,
  1481. }, {
  1482. 'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
  1483. 'only_matching': True,
  1484. }, {
  1485. 'url': 'http://www.bbc.co.uk/programmes/b055jkys/episodes/player',
  1486. 'only_matching': True,
  1487. }]
  1488. def _extract_title_and_description(self, webpage):
  1489. title = self._og_search_title(webpage, fatal=False)
  1490. description = self._og_search_description(webpage)
  1491. return title, description