DiscoveryStreamFeed.jsm 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
  6. const {NewTabUtils} = ChromeUtils.import("resource://gre/modules/NewTabUtils.jsm");
  7. const {setTimeout, clearTimeout} = ChromeUtils.import("resource://gre/modules/Timer.jsm");
  8. const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
  9. XPCOMUtils.defineLazyGlobalGetters(this, ["fetch"]);
  10. ChromeUtils.defineModuleGetter(this, "perfService", "resource://activity-stream/common/PerfService.jsm");
  11. const {UserDomainAffinityProvider} = ChromeUtils.import("resource://activity-stream/lib/UserDomainAffinityProvider.jsm");
  12. const {actionTypes: at, actionCreators: ac} = ChromeUtils.import("resource://activity-stream/common/Actions.jsm");
  13. const {PersistentCache} = ChromeUtils.import("resource://activity-stream/lib/PersistentCache.jsm");
  14. const CACHE_KEY = "discovery_stream";
  15. const LAYOUT_UPDATE_TIME = 30 * 60 * 1000; // 30 minutes
  16. const STARTUP_CACHE_EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000; // 1 week
  17. const COMPONENT_FEEDS_UPDATE_TIME = 30 * 60 * 1000; // 30 minutes
  18. const SPOCS_FEEDS_UPDATE_TIME = 30 * 60 * 1000; // 30 minutes
  19. const DEFAULT_RECS_EXPIRE_TIME = 60 * 60 * 1000; // 1 hour
  20. const MIN_DOMAIN_AFFINITIES_UPDATE_TIME = 12 * 60 * 60 * 1000; // 12 hours
  21. const MAX_LIFETIME_CAP = 500; // Guard against misconfiguration on the server
  22. const DEFAULT_MAX_HISTORY_QUERY_RESULTS = 1000;
  23. const FETCH_TIMEOUT = 45 * 1000;
  24. const PREF_CONFIG = "discoverystream.config";
  25. const PREF_ENDPOINTS = "discoverystream.endpoints";
  26. const PREF_SHOW_SPONSORED = "showSponsored";
  27. const PREF_SPOC_IMPRESSIONS = "discoverystream.spoc.impressions";
  28. const PREF_REC_IMPRESSIONS = "discoverystream.rec.impressions";
  29. let defaultLayoutResp;
  30. this.DiscoveryStreamFeed = class DiscoveryStreamFeed {
  31. constructor() {
  32. // Internal state for checking if we've intialized all our data
  33. this.loaded = false;
  34. // Persistent cache for remote endpoint data.
  35. this.cache = new PersistentCache(CACHE_KEY, true);
  36. // Internal in-memory cache for parsing json prefs.
  37. this._prefCache = {};
  38. }
  39. /**
  40. * Send SPOCS Fill telemetry.
  41. * @param {object} filteredItems An object keyed on filter reasons, and the value
  42. * is a list of SPOCS.
  43. * @param {boolean} fullRecalc A boolean indicating if it's a full recalculation.
  44. * Calling `loadSpocs` will be treated as a full recalculation.
  45. * Whereas responding the action "DISCOVERY_STREAM_SPOC_IMPRESSION"
  46. * is not a full recalculation.
  47. */
  48. _sendSpocsFill(filteredItems, fullRecalc) {
  49. const full_recalc = fullRecalc ? 1 : 0;
  50. const spocsFill = [];
  51. for (const [reason, items] of Object.entries(filteredItems)) {
  52. items.forEach(item => {
  53. // Only send SPOCS (i.e. it has a campaign_id)
  54. if (item.campaign_id) {
  55. spocsFill.push({reason, full_recalc, id: item.id, displayed: 0});
  56. }
  57. });
  58. }
  59. if (spocsFill.length) {
  60. this.store.dispatch(ac.DiscoveryStreamSpocsFill({spoc_fills: spocsFill}));
  61. }
  62. }
  63. finalLayoutEndpoint(url, apiKey) {
  64. if (url.includes("$apiKey") && !apiKey) {
  65. throw new Error(`Layout Endpoint - An API key was specified but none configured: ${url}`);
  66. }
  67. return url.replace("$apiKey", apiKey);
  68. }
  69. get config() {
  70. if (this._prefCache.config) {
  71. return this._prefCache.config;
  72. }
  73. try {
  74. this._prefCache.config = JSON.parse(this.store.getState().Prefs.values[PREF_CONFIG]);
  75. const layoutUrl = this._prefCache.config.layout_endpoint;
  76. const apiKeyPref = this._prefCache.config.api_key_pref;
  77. if (layoutUrl && apiKeyPref) {
  78. const apiKey = Services.prefs.getCharPref(apiKeyPref, "");
  79. this._prefCache.config.layout_endpoint = this.finalLayoutEndpoint(layoutUrl, apiKey);
  80. }
  81. } catch (e) {
  82. // istanbul ignore next
  83. this._prefCache.config = {};
  84. // istanbul ignore next
  85. Cu.reportError(`Could not parse preference. Try resetting ${PREF_CONFIG} in about:config. ${e}`);
  86. }
  87. return this._prefCache.config;
  88. }
  89. get showSpocs() {
  90. // Combine user-set sponsored opt-out with Mozilla-set config
  91. return this.store.getState().Prefs.values[PREF_SHOW_SPONSORED] && this.config.show_spocs;
  92. }
  93. get personalized() {
  94. return this.config.personalized;
  95. }
  96. setupPrefs() {
  97. // Send the initial state of the pref on our reducer
  98. this.store.dispatch(ac.BroadcastToContent({type: at.DISCOVERY_STREAM_CONFIG_SETUP, data: this.config}));
  99. }
  100. uninitPrefs() {
  101. // Reset in-memory cache
  102. this._prefCache = {};
  103. }
  104. async fetchFromEndpoint(rawEndpoint) {
  105. if (!rawEndpoint) {
  106. Cu.reportError("Tried to fetch endpoint but none was configured.");
  107. return null;
  108. }
  109. const apiKeyPref = this._prefCache.config.api_key_pref;
  110. const apiKey = Services.prefs.getCharPref(apiKeyPref, "");
  111. // The server somtimes returns this value already replaced, but we try this for two reasons:
  112. // 1. Layout endpoints are not from the server.
  113. // 2. Hardcoded layouts don't have this already done for us.
  114. const endpoint = rawEndpoint.replace("$apiKey", apiKey);
  115. try {
  116. // Make sure the requested endpoint is allowed
  117. const allowed = this.store.getState().Prefs.values[PREF_ENDPOINTS].split(",");
  118. if (!allowed.some(prefix => endpoint.startsWith(prefix))) {
  119. throw new Error(`Not one of allowed prefixes (${allowed})`);
  120. }
  121. const controller = new AbortController();
  122. const {signal} = controller;
  123. const fetchPromise = fetch(endpoint, {credentials: "omit", signal});
  124. // istanbul ignore next
  125. const timeoutId = setTimeout(() => { controller.abort(); }, FETCH_TIMEOUT);
  126. const response = await fetchPromise;
  127. if (!response.ok) {
  128. throw new Error(`Unexpected status (${response.status})`);
  129. }
  130. clearTimeout(timeoutId);
  131. return response.json();
  132. } catch (error) {
  133. Cu.reportError(`Failed to fetch ${endpoint}: ${error.message}`);
  134. }
  135. return null;
  136. }
  137. /**
  138. * Returns true if data in the cache for a particular key has expired or is missing.
  139. * @param {object} cachedData data returned from cache.get()
  140. * @param {string} key a cache key
  141. * @param {string?} url for "feed" only, the URL of the feed.
  142. * @param {boolean} is this check done at initial browser load
  143. */
  144. isExpired({cachedData, key, url, isStartup}) {
  145. const {layout, spocs, feeds} = cachedData;
  146. const updateTimePerComponent = {
  147. "layout": LAYOUT_UPDATE_TIME,
  148. "spocs": SPOCS_FEEDS_UPDATE_TIME,
  149. "feed": COMPONENT_FEEDS_UPDATE_TIME,
  150. };
  151. const EXPIRATION_TIME = isStartup ? STARTUP_CACHE_EXPIRE_TIME : updateTimePerComponent[key];
  152. switch (key) {
  153. case "layout":
  154. // This never needs to expire, as it's not expected to change.
  155. if (this.config.hardcoded_layout) {
  156. return false;
  157. }
  158. return (!layout || !(Date.now() - layout.lastUpdated < EXPIRATION_TIME));
  159. case "spocs":
  160. return (!spocs || !(Date.now() - spocs.lastUpdated < EXPIRATION_TIME));
  161. case "feed":
  162. return (!feeds || !feeds[url] || !(Date.now() - feeds[url].lastUpdated < EXPIRATION_TIME));
  163. default:
  164. // istanbul ignore next
  165. throw new Error(`${key} is not a valid key`);
  166. }
  167. }
  168. async _checkExpirationPerComponent() {
  169. const cachedData = await this.cache.get() || {};
  170. const {feeds} = cachedData;
  171. return {
  172. layout: this.isExpired({cachedData, key: "layout"}),
  173. spocs: this.isExpired({cachedData, key: "spocs"}),
  174. feeds: !feeds || Object.keys(feeds).some(url => this.isExpired({cachedData, key: "feed", url})),
  175. };
  176. }
  177. /**
  178. * Returns true if any data for the cached endpoints has expired or is missing.
  179. */
  180. async checkIfAnyCacheExpired() {
  181. const expirationPerComponent = await this._checkExpirationPerComponent();
  182. return expirationPerComponent.layout ||
  183. expirationPerComponent.spocs ||
  184. expirationPerComponent.feeds;
  185. }
  186. async fetchLayout(isStartup) {
  187. const cachedData = await this.cache.get() || {};
  188. let {layout} = cachedData;
  189. if (this.isExpired({cachedData, key: "layout", isStartup})) {
  190. const start = perfService.absNow();
  191. const layoutResponse = await this.fetchFromEndpoint(this.config.layout_endpoint);
  192. if (layoutResponse && layoutResponse.layout) {
  193. this.layoutRequestTime = Math.round(perfService.absNow() - start);
  194. layout = {
  195. lastUpdated: Date.now(),
  196. spocs: layoutResponse.spocs,
  197. layout: layoutResponse.layout,
  198. status: "success",
  199. };
  200. await this.cache.set("layout", layout);
  201. } else {
  202. Cu.reportError("No response for response.layout prop");
  203. }
  204. }
  205. return layout;
  206. }
  207. async loadLayout(sendUpdate, isStartup) {
  208. let layout = {};
  209. if (!this.config.hardcoded_layout) {
  210. layout = await this.fetchLayout(isStartup);
  211. }
  212. if (!layout || !layout.layout) {
  213. layout = {lastUpdate: Date.now(), ...defaultLayoutResp};
  214. }
  215. sendUpdate({
  216. type: at.DISCOVERY_STREAM_LAYOUT_UPDATE,
  217. data: layout,
  218. });
  219. if (layout.spocs && layout.spocs.url) {
  220. sendUpdate({
  221. type: at.DISCOVERY_STREAM_SPOCS_ENDPOINT,
  222. data: layout.spocs.url,
  223. });
  224. }
  225. }
  226. /**
  227. * buildFeedPromise - Adds the promise result to newFeeds and
  228. * pushes a promise to newsFeedsPromises.
  229. * @param {Object} Has both newFeedsPromises (Array) and newFeeds (Object)
  230. * @param {Boolean} isStartup We have different cache handling for startup.
  231. * @returns {Function} We return a function so we can contain
  232. * the scope for isStartup and the promises object.
  233. * Combines feed results and promises for each component with a feed.
  234. */
  235. buildFeedPromise({newFeedsPromises, newFeeds}, isStartup, sendUpdate) {
  236. return component => {
  237. const {url} = component.feed;
  238. if (!newFeeds[url]) {
  239. // We initially stub this out so we don't fetch dupes,
  240. // we then fill in with the proper object inside the promise.
  241. newFeeds[url] = {};
  242. const feedPromise = this.getComponentFeed(url, isStartup);
  243. feedPromise.then(feed => {
  244. newFeeds[url] = this.filterRecommendations(feed);
  245. sendUpdate({
  246. type: at.DISCOVERY_STREAM_FEED_UPDATE,
  247. data: {
  248. feed: newFeeds[url],
  249. url,
  250. },
  251. });
  252. // We grab affinities off the first feed for the moment.
  253. // Ideally this would be returned from the server on the layout,
  254. // or from another endpoint.
  255. if (!this.affinities) {
  256. const {settings} = feed.data;
  257. this.affinities = {
  258. timeSegments: settings.timeSegments,
  259. parameterSets: settings.domainAffinityParameterSets,
  260. maxHistoryQueryResults: settings.maxHistoryQueryResults || DEFAULT_MAX_HISTORY_QUERY_RESULTS,
  261. version: settings.version,
  262. };
  263. }
  264. }).catch(/* istanbul ignore next */ error => {
  265. Cu.reportError(`Error trying to load component feed ${url}: ${error}`);
  266. });
  267. newFeedsPromises.push(feedPromise);
  268. }
  269. };
  270. }
  271. filterRecommendations(feed) {
  272. if (feed && feed.data && feed.data.recommendations && feed.data.recommendations.length) {
  273. const {data} = this.filterBlocked(feed.data, "recommendations");
  274. return {
  275. ...feed,
  276. data,
  277. };
  278. }
  279. return feed;
  280. }
  281. /**
  282. * reduceFeedComponents - Filters out components with no feeds, and combines
  283. * all feeds on this component with the feeds from other components.
  284. * @param {Boolean} isStartup We have different cache handling for startup.
  285. * @returns {Function} We return a function so we can contain the scope for isStartup.
  286. * Reduces feeds into promises and feed data.
  287. */
  288. reduceFeedComponents(isStartup, sendUpdate) {
  289. return (accumulator, row) => {
  290. row.components
  291. .filter(component => component && component.feed)
  292. .forEach(this.buildFeedPromise(accumulator, isStartup, sendUpdate));
  293. return accumulator;
  294. };
  295. }
  296. /**
  297. * buildFeedPromises - Filters out rows with no components,
  298. * and gets us a promise for each unique feed.
  299. * @param {Object} layout This is the Discovery Stream layout object.
  300. * @param {Boolean} isStartup We have different cache handling for startup.
  301. * @returns {Object} An object with newFeedsPromises (Array) and newFeeds (Object),
  302. * we can Promise.all newFeedsPromises to get completed data in newFeeds.
  303. */
  304. buildFeedPromises(layout, isStartup, sendUpdate) {
  305. const initialData = {
  306. newFeedsPromises: [],
  307. newFeeds: {},
  308. };
  309. return layout
  310. .filter(row => row && row.components)
  311. .reduce(this.reduceFeedComponents(isStartup, sendUpdate), initialData);
  312. }
  313. async loadComponentFeeds(sendUpdate, isStartup) {
  314. const {DiscoveryStream} = this.store.getState();
  315. if (!DiscoveryStream || !DiscoveryStream.layout) {
  316. return;
  317. }
  318. // Reset the flag that indicates whether or not at least one API request
  319. // was issued to fetch the component feed in `getComponentFeed()`.
  320. this.componentFeedFetched = false;
  321. const start = perfService.absNow();
  322. const {newFeedsPromises, newFeeds} = this.buildFeedPromises(DiscoveryStream.layout, isStartup, sendUpdate);
  323. // Each promise has a catch already built in, so no need to catch here.
  324. await Promise.all(newFeedsPromises);
  325. if (this.componentFeedFetched) {
  326. this.cleanUpTopRecImpressionPref(newFeeds);
  327. this.componentFeedRequestTime = Math.round(perfService.absNow() - start);
  328. }
  329. await this.cache.set("feeds", newFeeds);
  330. sendUpdate({
  331. type: at.DISCOVERY_STREAM_FEEDS_UPDATE,
  332. });
  333. }
  334. async loadSpocs(sendUpdate, isStartup) {
  335. const cachedData = await this.cache.get() || {};
  336. let spocs;
  337. if (this.showSpocs) {
  338. spocs = cachedData.spocs;
  339. if (this.isExpired({cachedData, key: "spocs", isStartup})) {
  340. const endpoint = this.store.getState().DiscoveryStream.spocs.spocs_endpoint;
  341. const start = perfService.absNow();
  342. const spocsResponse = await this.fetchFromEndpoint(endpoint);
  343. if (spocsResponse) {
  344. this.spocsRequestTime = Math.round(perfService.absNow() - start);
  345. spocs = {
  346. lastUpdated: Date.now(),
  347. data: spocsResponse,
  348. };
  349. this.cleanUpCampaignImpressionPref(spocs.data);
  350. await this.cache.set("spocs", spocs);
  351. } else {
  352. Cu.reportError("No response for spocs_endpoint prop");
  353. }
  354. }
  355. }
  356. // Use good data if we have it, otherwise nothing.
  357. // We can have no data if spocs set to off.
  358. // We can have no data if request fails and there is no good cache.
  359. // We want to send an update spocs or not, so client can render something.
  360. spocs = spocs && spocs.data ? spocs : {
  361. lastUpdated: Date.now(),
  362. data: {},
  363. };
  364. let {data, filtered: frequencyCapped} = this.frequencyCapSpocs(spocs.data);
  365. let {data: newSpocs, filtered} = this.transform(data);
  366. sendUpdate({
  367. type: at.DISCOVERY_STREAM_SPOCS_UPDATE,
  368. data: {
  369. lastUpdated: spocs.lastUpdated,
  370. spocs: newSpocs,
  371. },
  372. });
  373. this._sendSpocsFill({...filtered, frequency_cap: frequencyCapped}, true);
  374. }
  375. async loadAffinityScoresCache() {
  376. const cachedData = await this.cache.get() || {};
  377. const {affinities} = cachedData;
  378. if (this.personalized && affinities && affinities.scores) {
  379. this.affinityProvider = new UserDomainAffinityProvider(
  380. affinities.timeSegments,
  381. affinities.parameterSets,
  382. affinities.maxHistoryQueryResults,
  383. affinities.version,
  384. affinities.scores);
  385. this.domainAffinitiesLastUpdated = affinities._timestamp;
  386. }
  387. }
  388. updateDomainAffinityScores() {
  389. if (!this.personalized || !this.affinities || !this.affinities.parameterSets ||
  390. Date.now() - this.domainAffinitiesLastUpdated < MIN_DOMAIN_AFFINITIES_UPDATE_TIME) {
  391. return;
  392. }
  393. this.affinityProvider = new UserDomainAffinityProvider(
  394. this.affinities.timeSegments,
  395. this.affinities.parameterSets,
  396. this.affinities.maxHistoryQueryResults,
  397. this.affinities.version,
  398. undefined);
  399. const affinities = this.affinityProvider.getAffinities();
  400. this.domainAffinitiesLastUpdated = Date.now();
  401. affinities._timestamp = this.domainAffinitiesLastUpdated;
  402. this.cache.set("affinities", affinities);
  403. }
  404. observe(subject, topic, data) {
  405. switch (topic) {
  406. case "idle-daily":
  407. this.updateDomainAffinityScores();
  408. break;
  409. }
  410. }
  411. scoreItems(items) {
  412. const filtered = [];
  413. const data = items.map(item => this.scoreItem(item))
  414. // Remove spocs that are scored too low.
  415. .filter(s => {
  416. if (s.score >= s.min_score) {
  417. return true;
  418. }
  419. filtered.push(s);
  420. return false;
  421. })
  422. // Sort by highest scores.
  423. .sort((a, b) => b.score - a.score);
  424. return {data, filtered};
  425. }
  426. scoreItem(item) {
  427. item.score = item.item_score;
  428. item.min_score = item.min_score || 0;
  429. if (item.score !== 0 && !item.score) {
  430. item.score = 1;
  431. }
  432. if (this.personalized && this.affinityProvider) {
  433. const scoreResult = this.affinityProvider.calculateItemRelevanceScore(item);
  434. if (scoreResult === 0 || scoreResult) {
  435. item.score = scoreResult;
  436. }
  437. }
  438. return item;
  439. }
  440. filterBlocked(data, type) {
  441. const filtered = [];
  442. if (data && data[type] && data[type].length) {
  443. const filteredItems = data[type].filter(item => {
  444. const blocked = NewTabUtils.blockedLinks.isBlocked({"url": item.url});
  445. if (blocked) {
  446. filtered.push(item);
  447. }
  448. return !blocked;
  449. });
  450. return {
  451. data: {
  452. ...data,
  453. [type]: filteredItems,
  454. },
  455. filtered,
  456. };
  457. }
  458. return {data, filtered};
  459. }
  460. transform(spocs) {
  461. const {data, filtered: blockedItems} = this.filterBlocked(spocs, "spocs");
  462. if (data && data.spocs && data.spocs.length) {
  463. const spocsPerDomain = this.store.getState().DiscoveryStream.spocs.spocs_per_domain || 1;
  464. const campaignMap = {};
  465. const campaignDuplicates = [];
  466. // This order of operations is intended.
  467. // scoreItems must be first because it creates this.score.
  468. const {data: items, filtered: belowMinScoreItems} = this.scoreItems(data.spocs);
  469. // This removes campaign dupes.
  470. // We do this only after scoring and sorting because that way
  471. // we can keep the first item we see, and end up keeping the highest scored.
  472. const newSpocs = items.filter(s => {
  473. if (!campaignMap[s.campaign_id]) {
  474. campaignMap[s.campaign_id] = 1;
  475. return true;
  476. } else if (campaignMap[s.campaign_id] < spocsPerDomain) {
  477. campaignMap[s.campaign_id]++;
  478. return true;
  479. }
  480. campaignDuplicates.push(s);
  481. return false;
  482. });
  483. return {
  484. data: {...data, spocs: newSpocs},
  485. filtered: {
  486. blocked_by_user: blockedItems,
  487. below_min_score: belowMinScoreItems,
  488. campaign_duplicate: campaignDuplicates,
  489. },
  490. };
  491. }
  492. return {data, filtered: {blocked: blockedItems}};
  493. }
  494. // Filter spocs based on frequency caps
  495. //
  496. // @param {Object} data An object that might have a SPOCS array.
  497. // @returns {Object} An object with a property `data` as the result, and a property
  498. // `filterItems` as the frequency capped items.
  499. frequencyCapSpocs(data) {
  500. if (data && data.spocs && data.spocs.length) {
  501. const {spocs} = data;
  502. const impressions = this.readImpressionsPref(PREF_SPOC_IMPRESSIONS);
  503. const caps = [];
  504. const result = {
  505. ...data,
  506. spocs: spocs.filter(s => {
  507. const isBelow = this.isBelowFrequencyCap(impressions, s);
  508. if (!isBelow) {
  509. caps.push(s);
  510. }
  511. return isBelow;
  512. }),
  513. };
  514. // send caps to redux if any.
  515. if (caps.length) {
  516. this.store.dispatch({type: at.DISCOVERY_STREAM_SPOCS_CAPS, data: caps});
  517. }
  518. return {data: result, filtered: caps};
  519. }
  520. return {data, filtered: []};
  521. }
  522. // Frequency caps are based on campaigns, which may include multiple spocs.
  523. // We currently support two types of frequency caps:
  524. // - lifetime: Indicates how many times spocs from a campaign can be shown in total
  525. // - period: Indicates how many times spocs from a campaign can be shown within a period
  526. //
  527. // So, for example, the feed configuration below defines that for campaign 1 no more
  528. // than 5 spocs can be shown in total, and no more than 2 per hour.
  529. // "campaign_id": 1,
  530. // "caps": {
  531. // "lifetime": 5,
  532. // "campaign": {
  533. // "count": 2,
  534. // "period": 3600
  535. // }
  536. // }
  537. isBelowFrequencyCap(impressions, spoc) {
  538. const campaignImpressions = impressions[spoc.campaign_id];
  539. if (!campaignImpressions) {
  540. return true;
  541. }
  542. const lifetime = spoc.caps && spoc.caps.lifetime;
  543. const lifeTimeCap = Math.min(lifetime || MAX_LIFETIME_CAP, MAX_LIFETIME_CAP);
  544. const lifeTimeCapExceeded = campaignImpressions.length >= lifeTimeCap;
  545. if (lifeTimeCapExceeded) {
  546. return false;
  547. }
  548. const campaignCap = spoc.caps && spoc.caps.campaign;
  549. if (campaignCap) {
  550. const campaignCapExceeded = campaignImpressions
  551. .filter(i => (Date.now() - i) < (campaignCap.period * 1000)).length >= campaignCap.count;
  552. return !campaignCapExceeded;
  553. }
  554. return true;
  555. }
  556. async retryFeed(feed) {
  557. const {url} = feed;
  558. const result = await this.getComponentFeed(url);
  559. const newFeed = this.filterRecommendations(result);
  560. this.store.dispatch(ac.BroadcastToContent({
  561. type: at.DISCOVERY_STREAM_FEED_UPDATE,
  562. data: {
  563. feed: newFeed,
  564. url,
  565. },
  566. }));
  567. }
  568. async getComponentFeed(feedUrl, isStartup) {
  569. const cachedData = await this.cache.get() || {};
  570. const {feeds} = cachedData;
  571. let feed = feeds ? feeds[feedUrl] : null;
  572. if (this.isExpired({cachedData, key: "feed", url: feedUrl, isStartup})) {
  573. const feedResponse = await this.fetchFromEndpoint(feedUrl);
  574. if (feedResponse) {
  575. const {data: scoredItems} = this.scoreItems(feedResponse.recommendations);
  576. const {recsExpireTime} = feedResponse.settings;
  577. const recommendations = this.rotate(scoredItems, recsExpireTime);
  578. this.componentFeedFetched = true;
  579. feed = {
  580. lastUpdated: Date.now(),
  581. data: {
  582. settings: feedResponse.settings,
  583. recommendations,
  584. status: "success",
  585. },
  586. };
  587. } else {
  588. Cu.reportError("No response for feed");
  589. }
  590. }
  591. // If we have no feed at this point, both fetch and cache failed for some reason.
  592. return feed || {
  593. data: {
  594. status: "failed",
  595. },
  596. };
  597. }
  598. /**
  599. * Called at startup to update cached data in the background.
  600. */
  601. async _maybeUpdateCachedData() {
  602. const expirationPerComponent = await this._checkExpirationPerComponent();
  603. // Pass in `store.dispatch` to send the updates only to main
  604. if (expirationPerComponent.layout) {
  605. await this.loadLayout(this.store.dispatch);
  606. }
  607. if (expirationPerComponent.spocs) {
  608. await this.loadSpocs(this.store.dispatch);
  609. }
  610. if (expirationPerComponent.feeds) {
  611. await this.loadComponentFeeds(this.store.dispatch);
  612. }
  613. }
  614. /**
  615. * @typedef {Object} RefreshAllOptions
  616. * @property {boolean} updateOpenTabs - Sends updates to open tabs immediately if true,
  617. * updates in background if false
  618. * @property {boolean} isStartup - When the function is called at browser startup
  619. *
  620. * Refreshes layout, component feeds, and spocs in order if caches have expired.
  621. * @param {RefreshAllOptions} options
  622. */
  623. async refreshAll(options = {}) {
  624. const {updateOpenTabs, isStartup} = options;
  625. const dispatch = updateOpenTabs ?
  626. action => this.store.dispatch(ac.BroadcastToContent(action)) :
  627. this.store.dispatch;
  628. this.loadAffinityScoresCache();
  629. await this.loadLayout(dispatch, isStartup);
  630. await Promise.all([
  631. this.loadSpocs(dispatch, isStartup).catch(error => Cu.reportError(`Error trying to load spocs feed: ${error}`)),
  632. this.loadComponentFeeds(dispatch, isStartup).catch(error => Cu.reportError(`Error trying to load component feeds: ${error}`)),
  633. ]);
  634. if (isStartup) {
  635. await this._maybeUpdateCachedData();
  636. }
  637. }
  638. // We have to rotate stories on the client so that
  639. // active stories are at the front of the list, followed by stories that have expired
  640. // impressions i.e. have been displayed for longer than recsExpireTime.
  641. rotate(recommendations, recsExpireTime) {
  642. const maxImpressionAge = Math.max(recsExpireTime * 1000 || DEFAULT_RECS_EXPIRE_TIME, DEFAULT_RECS_EXPIRE_TIME);
  643. const impressions = this.readImpressionsPref(PREF_REC_IMPRESSIONS);
  644. const expired = [];
  645. const active = [];
  646. for (const item of recommendations) {
  647. if (impressions[item.id] && Date.now() - impressions[item.id] >= maxImpressionAge) {
  648. expired.push(item);
  649. } else {
  650. active.push(item);
  651. }
  652. }
  653. return active.concat(expired);
  654. }
  655. /**
  656. * Reports the cache age in second for Discovery Stream.
  657. */
  658. async reportCacheAge() {
  659. const cachedData = await this.cache.get() || {};
  660. const {layout, spocs, feeds} = cachedData;
  661. let cacheAge = Date.now();
  662. let updated = false;
  663. if (layout && layout.lastUpdated && layout.lastUpdated < cacheAge) {
  664. updated = true;
  665. cacheAge = layout.lastUpdated;
  666. }
  667. if (spocs && spocs.lastUpdated && spocs.lastUpdated < cacheAge) {
  668. updated = true;
  669. cacheAge = spocs.lastUpdated;
  670. }
  671. if (feeds) {
  672. Object.keys(feeds).forEach(url => {
  673. const feed = feeds[url];
  674. if (feed.lastUpdated && feed.lastUpdated < cacheAge) {
  675. updated = true;
  676. cacheAge = feed.lastUpdated;
  677. }
  678. });
  679. }
  680. if (updated) {
  681. this.store.dispatch(ac.PerfEvent({
  682. event: "DS_CACHE_AGE_IN_SEC",
  683. value: Math.round((Date.now() - cacheAge) / 1000),
  684. }));
  685. }
  686. }
  687. /**
  688. * Reports various time durations when the feed is requested from endpoint for
  689. * the first time. This could happen on the browser start-up, or the pref changes
  690. * of discovery stream.
  691. *
  692. * Metrics to be reported:
  693. * - Request time for layout endpoint
  694. * - Request time for feed endpoint
  695. * - Request time for spoc endpoint
  696. * - Total request time for data completeness
  697. */
  698. reportRequestTime() {
  699. if (this.layoutRequestTime) {
  700. this.store.dispatch(ac.PerfEvent({
  701. event: "LAYOUT_REQUEST_TIME",
  702. value: this.layoutRequestTime,
  703. }));
  704. }
  705. if (this.spocsRequestTime) {
  706. this.store.dispatch(ac.PerfEvent({
  707. event: "SPOCS_REQUEST_TIME",
  708. value: this.spocsRequestTime,
  709. }));
  710. }
  711. if (this.componentFeedRequestTime) {
  712. this.store.dispatch(ac.PerfEvent({
  713. event: "COMPONENT_FEED_REQUEST_TIME",
  714. value: this.componentFeedRequestTime,
  715. }));
  716. }
  717. if (this.totalRequestTime) {
  718. this.store.dispatch(ac.PerfEvent({
  719. event: "DS_FEED_TOTAL_REQUEST_TIME",
  720. value: this.totalRequestTime,
  721. }));
  722. }
  723. }
  724. async enable() {
  725. // Note that cache age needs to be reported prior to refreshAll.
  726. await this.reportCacheAge();
  727. const start = perfService.absNow();
  728. await this.refreshAll({updateOpenTabs: true, isStartup: true});
  729. Services.obs.addObserver(this, "idle-daily");
  730. this.loaded = true;
  731. this.totalRequestTime = Math.round(perfService.absNow() - start);
  732. this.reportRequestTime();
  733. }
  734. async reset() {
  735. this.resetImpressionPrefs();
  736. await this.resetCache();
  737. if (this.loaded) {
  738. Services.obs.removeObserver(this, "idle-daily");
  739. }
  740. this.resetState();
  741. }
  742. async resetCache() {
  743. await this.cache.set("layout", {});
  744. await this.cache.set("feeds", {});
  745. await this.cache.set("spocs", {});
  746. await this.cache.set("affinities", {});
  747. }
  748. resetImpressionPrefs() {
  749. this.writeImpressionsPref(PREF_SPOC_IMPRESSIONS, {});
  750. this.writeImpressionsPref(PREF_REC_IMPRESSIONS, {});
  751. }
  752. resetState() {
  753. // Reset reducer
  754. this.store.dispatch(ac.BroadcastToContent({type: at.DISCOVERY_STREAM_LAYOUT_RESET}));
  755. this.loaded = false;
  756. this.layoutRequestTime = undefined;
  757. this.spocsRequestTime = undefined;
  758. this.componentFeedRequestTime = undefined;
  759. this.totalRequestTime = undefined;
  760. }
  761. async onPrefChange() {
  762. // We always want to clear the cache/state if the pref has changed
  763. await this.reset();
  764. if (this.config.enabled) {
  765. // Load data from all endpoints
  766. await this.enable();
  767. }
  768. }
  769. recordCampaignImpression(campaignId) {
  770. let impressions = this.readImpressionsPref(PREF_SPOC_IMPRESSIONS);
  771. const timeStamps = impressions[campaignId] || [];
  772. timeStamps.push(Date.now());
  773. impressions = {...impressions, [campaignId]: timeStamps};
  774. this.writeImpressionsPref(PREF_SPOC_IMPRESSIONS, impressions);
  775. }
  776. recordTopRecImpressions(recId) {
  777. let impressions = this.readImpressionsPref(PREF_REC_IMPRESSIONS);
  778. if (!impressions[recId]) {
  779. impressions = {...impressions, [recId]: Date.now()};
  780. this.writeImpressionsPref(PREF_REC_IMPRESSIONS, impressions);
  781. }
  782. }
  783. cleanUpCampaignImpressionPref(data) {
  784. if (data.spocs && data.spocs.length) {
  785. const campaignIds = data.spocs.map(s => `${s.campaign_id}`);
  786. this.cleanUpImpressionPref(id => !campaignIds.includes(id), PREF_SPOC_IMPRESSIONS);
  787. }
  788. }
  789. // Clean up rec impression pref by removing all stories that are no
  790. // longer part of the response.
  791. cleanUpTopRecImpressionPref(newFeeds) {
  792. // Need to build a single list of stories.
  793. const activeStories = Object.keys(newFeeds).filter(currentValue => newFeeds[currentValue].data).reduce((accumulator, currentValue) => {
  794. const {recommendations} = newFeeds[currentValue].data;
  795. return accumulator.concat(recommendations.map(i => `${i.id}`));
  796. }, []);
  797. this.cleanUpImpressionPref(id => !activeStories.includes(id), PREF_REC_IMPRESSIONS);
  798. }
  799. writeImpressionsPref(pref, impressions) {
  800. this.store.dispatch(ac.SetPref(pref, JSON.stringify(impressions)));
  801. }
  802. readImpressionsPref(pref) {
  803. const prefVal = this.store.getState().Prefs.values[pref];
  804. return prefVal ? JSON.parse(prefVal) : {};
  805. }
  806. cleanUpImpressionPref(isExpired, pref) {
  807. const impressions = this.readImpressionsPref(pref);
  808. let changed = false;
  809. Object
  810. .keys(impressions)
  811. .forEach(id => {
  812. if (isExpired(id)) {
  813. changed = true;
  814. delete impressions[id];
  815. }
  816. });
  817. if (changed) {
  818. this.writeImpressionsPref(pref, impressions);
  819. }
  820. }
  821. async onAction(action) {
  822. switch (action.type) {
  823. case at.INIT:
  824. // During the initialization of Firefox:
  825. // 1. Set-up listeners and initialize the redux state for config;
  826. this.setupPrefs();
  827. // 2. If config.enabled is true, start loading data.
  828. if (this.config.enabled) {
  829. await this.enable();
  830. }
  831. break;
  832. case at.SYSTEM_TICK:
  833. // Only refresh if we loaded once in .enable()
  834. if (this.config.enabled && this.loaded && await this.checkIfAnyCacheExpired()) {
  835. await this.refreshAll({updateOpenTabs: false});
  836. }
  837. break;
  838. case at.DISCOVERY_STREAM_CONFIG_SET_VALUE:
  839. // Use the original string pref to then set a value instead of
  840. // this.config which has some modifications
  841. this.store.dispatch(ac.SetPref(PREF_CONFIG, JSON.stringify({
  842. ...JSON.parse(this.store.getState().Prefs.values[PREF_CONFIG]),
  843. [action.data.name]: action.data.value,
  844. })));
  845. break;
  846. case at.DISCOVERY_STREAM_RETRY_FEED:
  847. this.retryFeed(action.data.feed);
  848. break;
  849. case at.DISCOVERY_STREAM_CONFIG_CHANGE:
  850. // When the config pref changes, load or unload data as needed.
  851. await this.onPrefChange();
  852. break;
  853. case at.DISCOVERY_STREAM_IMPRESSION_STATS:
  854. if (action.data.tiles && action.data.tiles[0] && action.data.tiles[0].id) {
  855. this.recordTopRecImpressions(action.data.tiles[0].id);
  856. }
  857. break;
  858. case at.DISCOVERY_STREAM_SPOC_IMPRESSION:
  859. if (this.showSpocs) {
  860. this.recordCampaignImpression(action.data.campaignId);
  861. // Apply frequency capping to SPOCs in the redux store, only update the
  862. // store if the SPOCs are changed.
  863. const {spocs} = this.store.getState().DiscoveryStream;
  864. const {data: newSpocs, filtered} = this.frequencyCapSpocs(spocs.data);
  865. if (filtered.length) {
  866. this.store.dispatch(ac.AlsoToPreloaded({
  867. type: at.DISCOVERY_STREAM_SPOCS_UPDATE,
  868. data: {
  869. lastUpdated: spocs.lastUpdated,
  870. spocs: newSpocs,
  871. },
  872. }));
  873. this._sendSpocsFill({frequency_cap: filtered}, false);
  874. }
  875. }
  876. break;
  877. case at.PLACES_LINK_BLOCKED:
  878. if (this.showSpocs) {
  879. const {spocs} = this.store.getState().DiscoveryStream;
  880. const spocsList = spocs.data.spocs || [];
  881. const filtered = spocsList.filter(s => s.url === action.data.url);
  882. if (filtered.length) {
  883. this._sendSpocsFill({blocked_by_user: filtered}, false);
  884. }
  885. }
  886. this.store.dispatch(ac.BroadcastToContent({
  887. type: at.DISCOVERY_STREAM_LINK_BLOCKED,
  888. data: action.data,
  889. }));
  890. break;
  891. case at.UNINIT:
  892. // When this feed is shutting down:
  893. this.uninitPrefs();
  894. break;
  895. case at.PREF_CHANGED:
  896. switch (action.data.name) {
  897. case PREF_CONFIG:
  898. // Clear the cached config and broadcast the newly computed value
  899. this._prefCache.config = null;
  900. this.store.dispatch(ac.BroadcastToContent({
  901. type: at.DISCOVERY_STREAM_CONFIG_CHANGE,
  902. data: this.config,
  903. }));
  904. break;
  905. // Check if spocs was disabled. Remove them if they were.
  906. case PREF_SHOW_SPONSORED:
  907. await this.loadSpocs(update => this.store.dispatch(ac.BroadcastToContent(update)));
  908. break;
  909. }
  910. break;
  911. }
  912. }
  913. };
  914. defaultLayoutResp = {
  915. "spocs": {
  916. "url": "https://getpocket.cdn.mozilla.net/v3/firefox/unique-spocs?consumer_key=$apiKey",
  917. "spocs_per_domain": 1,
  918. },
  919. "layout": [
  920. {
  921. "width": 12,
  922. "components": [
  923. {
  924. "type": "TopSites",
  925. "header": {
  926. "title": "Top Sites",
  927. },
  928. "properties": {},
  929. },
  930. ],
  931. },
  932. {
  933. "width": 12,
  934. "components": [
  935. {
  936. "type": "Message",
  937. "header": {
  938. "title": "Recommended by Pocket",
  939. "subtitle": "",
  940. "link_text": "How it works",
  941. "link_url": "https://getpocket.com/firefox/new_tab_learn_more",
  942. "icon": "resource://activity-stream/data/content/assets/glyph-pocket-16.svg",
  943. },
  944. "properties": {},
  945. "styles": {
  946. ".ds-message": "margin-bottom: -20px",
  947. },
  948. },
  949. ],
  950. },
  951. {
  952. "width": 12,
  953. "components": [
  954. {
  955. "type": "CardGrid",
  956. "properties": {
  957. "items": 3,
  958. },
  959. "header": {
  960. "title": "",
  961. },
  962. "feed": {
  963. "embed_reference": null,
  964. "url": "https://getpocket.cdn.mozilla.net/v3/firefox/global-recs?version=3&consumer_key=$apiKey&locale_lang=en-US",
  965. },
  966. "spocs": {
  967. "probability": 1,
  968. "positions": [
  969. {
  970. "index": 2,
  971. },
  972. ],
  973. },
  974. },
  975. ],
  976. },
  977. {
  978. "width": 12,
  979. "components": [
  980. {
  981. "type": "CardGrid",
  982. "header": {
  983. "title": "Health & Fitness 💪",
  984. },
  985. "feed": {
  986. "embed_reference": null,
  987. "url": "https://getpocket.cdn.mozilla.net/v3/firefox/global-recs?topic_id=4&end_time_offset=172800&version=3&consumer_key=$apiKey&locale_lang=en-US&feed_variant=OptimalCuratedLinksForLocaleFeed&model_id=external_time_live",
  988. },
  989. "properties": {
  990. "items": 4,
  991. "has_numbers": false,
  992. "has_images": true,
  993. },
  994. "styles": {
  995. ".ds-header": "margin-top: 4px;",
  996. },
  997. "spocs": {
  998. "probability": 1,
  999. "positions": [
  1000. {
  1001. "index": 2,
  1002. },
  1003. ],
  1004. },
  1005. },
  1006. ],
  1007. },
  1008. {
  1009. "width": 12,
  1010. "components": [
  1011. {
  1012. "type": "CardGrid",
  1013. "header": {
  1014. "title": "Tech 💻",
  1015. },
  1016. "feed": {
  1017. "embed_reference": null,
  1018. "url": "https://getpocket.cdn.mozilla.net/v3/firefox/global-recs?topic_id=5&end_time_offset=172800&version=3&consumer_key=$apiKey&locale_lang=en-US&feed_variant=OptimalCuratedLinksForLocaleFeed&model_id=external_time_live",
  1019. },
  1020. "properties": {
  1021. "items": 4,
  1022. "has_numbers": false,
  1023. "has_images": true,
  1024. },
  1025. "styles": {
  1026. ".ds-header": "margin-top: 4px;",
  1027. },
  1028. },
  1029. ],
  1030. },
  1031. {
  1032. "width": 12,
  1033. "components": [
  1034. {
  1035. "type": "CardGrid",
  1036. "header": {
  1037. "title": "Entertainment 🍿",
  1038. },
  1039. "feed": {
  1040. "embed_reference": null,
  1041. "url": "https://getpocket.cdn.mozilla.net/v3/firefox/global-recs?topic_id=8&end_time_offset=172800&version=3&consumer_key=$apiKey&locale_lang=en-US&feed_variant=OptimalCuratedLinksForLocaleFeed&model_id=external_time_live",
  1042. },
  1043. "properties": {
  1044. "items": 4,
  1045. "has_numbers": false,
  1046. "has_images": true,
  1047. },
  1048. "styles": {
  1049. ".ds-header": "margin-top: 4px;",
  1050. },
  1051. "spocs": {
  1052. "probability": 1,
  1053. "positions": [
  1054. {
  1055. "index": 3,
  1056. },
  1057. ],
  1058. },
  1059. },
  1060. ],
  1061. },
  1062. {
  1063. "width": 12,
  1064. "components": [
  1065. {
  1066. "type": "CardGrid",
  1067. "header": {
  1068. "title": "Personal Finance 💰",
  1069. },
  1070. "feed": {
  1071. "embed_reference": null,
  1072. "url": "https://getpocket.cdn.mozilla.net/v3/firefox/global-recs?topic_id=2&end_time_offset=172800&version=3&consumer_key=$apiKey&locale_lang=en-US&feed_variant=OptimalCuratedLinksForLocaleFeed&model_id=external_time_live",
  1073. },
  1074. "styles": {
  1075. ".ds-header": "margin-top: 4px;",
  1076. },
  1077. "properties": {
  1078. "items": 4,
  1079. "has_numbers": false,
  1080. "has_images": true,
  1081. },
  1082. },
  1083. ],
  1084. },
  1085. {
  1086. "width": 12,
  1087. "components": [
  1088. {
  1089. "type": "CardGrid",
  1090. "header": {
  1091. "title": "Business 💼",
  1092. },
  1093. "feed": {
  1094. "embed_reference": null,
  1095. "url": "https://getpocket.cdn.mozilla.net/v3/firefox/global-recs?topic_id=1&end_time_offset=172800&version=3&consumer_key=$apiKey&locale_lang=en-US&feed_variant=OptimalCuratedLinksForLocaleFeed&model_id=external_time_live",
  1096. },
  1097. "properties": {
  1098. "items": 4,
  1099. "has_numbers": false,
  1100. "has_images": true,
  1101. },
  1102. "styles": {
  1103. ".ds-header": "margin-top: 4px;",
  1104. },
  1105. },
  1106. ],
  1107. },
  1108. {
  1109. "width": 12,
  1110. "components": [
  1111. {
  1112. "type": "CardGrid",
  1113. "header": {
  1114. "title": "Science 🔬",
  1115. },
  1116. "feed": {
  1117. "embed_reference": null,
  1118. "url": "https://getpocket.cdn.mozilla.net/v3/firefox/global-recs?topic_id=7&end_time_offset=172800&version=3&consumer_key=$apiKey&locale_lang=en-US&feed_variant=OptimalCuratedLinksForLocaleFeed&model_id=external_time_live",
  1119. },
  1120. "properties": {
  1121. "items": 4,
  1122. "has_numbers": false,
  1123. "has_images": true,
  1124. },
  1125. "styles": {
  1126. ".ds-header": "margin-top: 4px;",
  1127. },
  1128. "spocs": {
  1129. "probability": 1,
  1130. "positions": [
  1131. {
  1132. "index": 3,
  1133. },
  1134. ],
  1135. },
  1136. },
  1137. ],
  1138. },
  1139. ],
  1140. };
  1141. const EXPORTED_SYMBOLS = ["DiscoveryStreamFeed"];