"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.getStorageKey = exports.NewsfeedStorage = void 0; var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _moment = _interopRequireDefault(require("moment")); var _rxjs = require("rxjs"); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ /** * Persistence layer for the newsfeed driver */ class NewsfeedStorage { constructor(storagePrefix) { (0, _defineProperty2.default)(this, "lastFetchStorageKey", void 0); (0, _defineProperty2.default)(this, "readStatusStorageKey", void 0); (0, _defineProperty2.default)(this, "unreadStatus$", void 0); this.lastFetchStorageKey = getStorageKey(storagePrefix, 'lastFetch'); this.readStatusStorageKey = getStorageKey(storagePrefix, 'readStatus'); this.unreadStatus$ = new _rxjs.BehaviorSubject(anyUnread(this.getReadStatus())); } getLastFetchTime() { const lastFetchUtc = localStorage.getItem(this.lastFetchStorageKey); if (!lastFetchUtc) { return undefined; } return (0, _moment.default)(lastFetchUtc, 'x').toDate(); // parse as unix ms timestamp (already is UTC) } setLastFetchTime(date) { localStorage.setItem(this.lastFetchStorageKey, JSON.stringify(date.getTime())); } setFetchedItems(itemHashes) { const currentReadStatus = this.getReadStatus(); const newReadStatus = {}; itemHashes.forEach(hash => { var _currentReadStatus$ha; newReadStatus[hash] = (_currentReadStatus$ha = currentReadStatus[hash]) !== null && _currentReadStatus$ha !== void 0 ? _currentReadStatus$ha : false; }); return this.setReadStatus(newReadStatus); } /** * Marks given items as read, and return the overall unread status. */ markItemsAsRead(itemHashes) { const updatedReadStatus = this.getReadStatus(); itemHashes.forEach(hash => { updatedReadStatus[hash] = true; }); return this.setReadStatus(updatedReadStatus); } isAnyUnread() { return this.unreadStatus$.value; } isAnyUnread$() { return this.unreadStatus$.asObservable(); } getReadStatus() { try { return JSON.parse(localStorage.getItem(this.readStatusStorageKey) || '{}'); } catch (e) { return {}; } } setReadStatus(status) { const hasUnread = anyUnread(status); this.unreadStatus$.next(anyUnread(status)); localStorage.setItem(this.readStatusStorageKey, JSON.stringify(status)); return hasUnread; } } exports.NewsfeedStorage = NewsfeedStorage; const anyUnread = status => Object.values(status).some(read => !read); /** @internal */ const getStorageKey = (prefix, key) => `newsfeed.${prefix}.${key}`; exports.getStorageKey = getStorageKey;