queue/source/utilities/settings.ts

108 lines
2.7 KiB
TypeScript

import browser from 'webextension-polyfill';
import {Queue} from '../types.d';
import {debug} from './log';
const defaultSettings: ISettings = {
latestVersion: '0.0.0',
queue: [],
versionGotUpdated: false,
};
interface ISettings {
latestVersion: string;
queue: Queue.Item[];
versionGotUpdated: boolean;
}
export default class Settings implements ISettings {
public latestVersion: string;
public queue: Queue.Item[];
public versionGotUpdated: boolean;
private constructor(settings: ISettings) {
this.latestVersion = settings.latestVersion;
this.queue = settings.queue;
this.versionGotUpdated = settings.versionGotUpdated;
}
static async get(): Promise<Settings> {
const syncSettings: Record<string, any> = await browser.storage.sync.get();
// Append properties with a name matching 'qi'x to the queue.
const queue: Queue.Item[] = [];
if (syncSettings !== undefined) {
for (const prop in syncSettings) {
if (prop.startsWith('qi')) {
queue.push(syncSettings[prop]);
}
}
}
// Initialize all the non-JSON values, as they are stringified when saved.
for (const item of queue) {
item.added = new Date(item.added);
}
const latestVersion =
(syncSettings.latestVersion as string) ?? defaultSettings.latestVersion;
const versionGotUpdated =
(syncSettings.versionGotUpdated as boolean) ??
defaultSettings.versionGotUpdated;
return new Settings({
latestVersion,
queue,
versionGotUpdated,
});
}
async save(): Promise<void> {
const syncSettings: Record<string, any> = {
latestVersion: this.latestVersion,
versionGotUpdated: this.versionGotUpdated,
};
for (const item of this.queue) {
syncSettings['qi' + item.id.toString()] = item;
}
await browser.storage.sync.set(syncSettings);
}
newItemId(): number {
const highestItem = this.queue.sort((a, b) => b.id - a.id)[0];
return highestItem === undefined ? 1 : highestItem.id + 1;
}
nextItem(): Queue.Item | undefined {
return this.queue.sort((a, b) => a.added.getTime() - b.added.getTime())[0];
}
async removeItem(id: number): Promise<void> {
const index = this.queue.findIndex((item) => item.id === id);
if (index === -1) {
debug(`No Queue.Item with ID ${id} found.`);
return;
}
const removed = this.queue.splice(index, 1);
const history = (
(await browser.storage.local.get({history: []})) as {
history: Queue.Item[];
}
).history;
history.push(removed[0]);
for (const [index, item] of history.entries()) {
item.id = index;
}
await browser.storage.local.set({history});
await browser.storage.sync.remove('qi' + id.toString());
}
}