You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
session-desktop/ts/session/sending/PendingMessageCache.ts

145 lines
4.1 KiB
TypeScript

5 years ago
import * as Data from '../../../js/modules/data';
import { RawMessage } from '../types/RawMessage';
import { ContentMessage } from '../messages/outgoing';
5 years ago
import * as MessageUtils from '../utils';
import { PubKey } from '../types';
5 years ago
// This is an abstraction for storing pending messages.
// Ideally we want to store pending messages in the database so that
// on next launch we can re-send the pending messages, but we don't want
// to constantly fetch pending messages from the database.
// Thus we have an intermediary cache which will store pending messagesin
// memory and sync its state with the database on modification (add or remove).
export class PendingMessageCache {
5 years ago
private cache: Array<RawMessage>;
constructor() {
5 years ago
// Load pending messages from the database
// You should await init() on making a new PendingMessageCache
// if you'd like to have instant access to the cache
5 years ago
this.cache = [];
void this.init();
5 years ago
}
5 years ago
public get(): Array<RawMessage> {
// Get all pending from cache, sorted with oldest first
return this.cache.sort((a, b) => a.timestamp - b.timestamp);
}
5 years ago
public async add(
device: PubKey,
message: ContentMessage
): Promise<RawMessage> {
5 years ago
const rawMessage = MessageUtils.toRawMessage(device, message);
// Does it exist in cache already?
5 years ago
if (this.find(rawMessage)) {
5 years ago
return rawMessage;
}
this.cache.push(rawMessage);
await this.syncCacheWithDB();
return rawMessage;
}
5 years ago
public async remove(
message: RawMessage
): Promise<Array<RawMessage> | undefined> {
5 years ago
// Should only be called after message is processed
// Return if message doesn't exist in cache
if (!this.find(message)) {
return;
}
// Remove item from cache and sync with database
const updatedCache = this.cache.filter(
m => m.identifier !== message.identifier
);
this.cache = updatedCache;
await this.syncCacheWithDB();
return updatedCache;
}
5 years ago
public find(message: RawMessage): RawMessage | undefined {
// Find a message in the cache
return this.cache.find(
m => m.device === message.device && m.timestamp === message.timestamp
);
}
5 years ago
public getForDevice(device: PubKey): Array<RawMessage> {
5 years ago
const pending = this.cache.filter(m => m.device === device.key);
return pending.sort((a, b) => a.timestamp - b.timestamp);
}
5 years ago
public async clear() {
// Clears the cache and syncs to DB
this.cache = [];
await this.syncCacheWithDB();
}
5 years ago
public getDevices(): Array<PubKey> {
// Gets all unique devices with pending messages
5 years ago
const pubkeyStrings = [...new Set(this.cache.map(m => m.device))];
5 years ago
5 years ago
const pubkeys: Array<PubKey> = [];
pubkeyStrings.forEach(pubkey => {
if (PubKey.validate(pubkey)) {
pubkeys.push(new PubKey(pubkey));
}
});
return pubkeys;
5 years ago
}
public async init() {
const messages = await this.getFromStorage();
this.cache = messages;
}
5 years ago
private async getFromStorage(): Promise<Array<RawMessage>> {
5 years ago
// tslint:disable-next-line: no-backbone-get-set-outside-model
const data = await Data.getItemById('pendingMessages');
if (!data || !data.value) {
return [];
}
5 years ago
const barePending = JSON.parse(String(data.value));
5 years ago
// tslint:disable-next-line: no-unnecessary-local-variable
const pending = barePending.map((message: any) => {
const { identifier, timestamp, device, ttl, encryption } = message;
// Recreate buffers
const rawBuffer = message.plainTextBuffer;
const bufferValues: Array<number> = Object.values(rawBuffer);
const plainTextBuffer = Uint8Array.from(bufferValues);
return {
identifier,
plainTextBuffer,
timestamp,
device,
ttl,
encryption,
} as RawMessage;
});
5 years ago
return pending as Array<RawMessage>;
5 years ago
}
5 years ago
private async syncCacheWithDB() {
5 years ago
// Only call when adding / removing from cache.
const encodedPendingMessages = JSON.stringify(this.cache) || '';
5 years ago
await Data.createOrUpdateItem({
id: 'pendingMessages',
value: encodedPendingMessages,
});
5 years ago
}
5 years ago
}