TeaSpeak-Client/modules/renderer/PersistentLocalStorage.ts

82 lines
2.6 KiB
TypeScript

import * as electron from "electron";
import * as path from "path";
import * as fs from "fs-extra";
const APP_DATA = electron.remote.app.getPath("userData");
const SETTINGS_DIR = path.join(APP_DATA, "settings");
let _local_storage: {[key: string]: any} = {};
let _local_storage_save: {[key: string]: boolean} = {};
export async function initialize() {
await fs.mkdirp(SETTINGS_DIR);
const files = await fs.readdir(SETTINGS_DIR);
for(const file of files) {
const key = decodeURIComponent(file);
console.log("Load settings: %s", key);
try {
const data = await fs.readFile(path.join(SETTINGS_DIR, file));
const decoded = JSON.parse(data.toString() || "{}");
_local_storage[key] = decoded;
} catch(error) {
console.error("Failed to load settings for %s: %o", key, error);
}
}
let _new_storage: Storage = {} as any;
_new_storage.getItem = key => _local_storage[key] || null;
_new_storage.setItem = (key, value) => {
_local_storage[key] = value;
_local_storage_save[key] = true;
save_key(key).catch(error => {
console.warn("Failed to save key: %s => %o", key, error);
});
(_new_storage as any)["length"] = Object.keys(_local_storage).length;
};
_new_storage.clear = () => {
_local_storage = {};
_local_storage_save = {};
try {
fs.emptyDirSync(SETTINGS_DIR);
} catch(error) {
console.warn("Failed to empty settings dir");
}
(_new_storage as any)["length"] = 0;
};
_new_storage.key = index => Object.keys(_local_storage)[index];
_new_storage.removeItem = key => {
delete _local_storage[key];
delete_key(key).catch(error => {
console.warn("Failed to delete key on fs: %s => %o", key, error);
});
(_new_storage as any)["length"] = Object.keys(_local_storage).length;
};
Object.assign(window.localStorage, _new_storage);
}
export async function save_all() {
let promises: Promise<void>[] = [];
for(const key of Object.keys(_local_storage))
promises.push(save_key(key));
await Promise.all(promises);
}
export async function save_key(key: string) {
if(!_local_storage_save[key])
return;
_local_storage_save[key] = false;
await fs.writeJson(path.join(SETTINGS_DIR, encodeURIComponent(key)), _local_storage[key], {spaces: 0});
}
export async function delete_key(key: string) {
delete _local_storage_save[key];
await fs.remove(path.join(SETTINGS_DIR, encodeURIComponent(key)));
}