2019-03-12 03:36:29 +01:00
|
|
|
import * as fs from "fs";
|
|
|
|
|
2022-02-22 15:39:11 +01:00
|
|
|
import { ipcMain } from "electron";
|
2019-03-12 03:36:29 +01:00
|
|
|
|
2022-06-27 19:38:12 +02:00
|
|
|
import { AbstractStorageService } from "@bitwarden/common/abstractions/storage.service";
|
2022-06-14 17:10:53 +02:00
|
|
|
import { NodeUtils } from "@bitwarden/common/misc/nodeUtils";
|
2019-03-12 03:36:29 +01:00
|
|
|
|
2022-02-22 15:39:11 +01:00
|
|
|
// eslint-disable-next-line
|
2019-03-12 03:36:29 +01:00
|
|
|
const Store = require("electron-store");
|
|
|
|
|
2022-06-27 19:38:12 +02:00
|
|
|
export class ElectronStorageService implements AbstractStorageService {
|
2019-03-12 03:36:29 +01:00
|
|
|
private store: any;
|
|
|
|
|
2021-06-09 22:53:54 +02:00
|
|
|
constructor(dir: string, defaults = {}) {
|
|
|
|
if (!fs.existsSync(dir)) {
|
|
|
|
NodeUtils.mkdirpSync(dir, "700");
|
|
|
|
}
|
2019-03-12 03:36:29 +01:00
|
|
|
const storeConfig: any = {
|
|
|
|
defaults: defaults,
|
|
|
|
name: "data",
|
2021-12-16 13:36:21 +01:00
|
|
|
};
|
2019-03-12 03:36:29 +01:00
|
|
|
this.store = new Store(storeConfig);
|
2021-12-16 13:36:21 +01:00
|
|
|
|
2021-04-07 19:42:06 +02:00
|
|
|
ipcMain.handle("storageService", (event, options) => {
|
|
|
|
switch (options.action) {
|
2021-12-16 13:36:21 +01:00
|
|
|
case "get":
|
2021-04-07 19:42:06 +02:00
|
|
|
return this.get(options.key);
|
2021-12-16 13:36:21 +01:00
|
|
|
case "has":
|
2021-06-09 22:53:54 +02:00
|
|
|
return this.has(options.key);
|
2021-12-16 13:36:21 +01:00
|
|
|
case "save":
|
2021-04-07 19:42:06 +02:00
|
|
|
return this.save(options.key, options.obj);
|
|
|
|
case "remove":
|
|
|
|
return this.remove(options.key);
|
2021-12-16 13:36:21 +01:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2019-03-12 03:36:29 +01:00
|
|
|
get<T>(key: string): Promise<T> {
|
|
|
|
const val = this.store.get(key) as T;
|
|
|
|
return Promise.resolve(val != null ? val : null);
|
2021-12-16 13:36:21 +01:00
|
|
|
}
|
|
|
|
|
2021-06-09 22:53:54 +02:00
|
|
|
has(key: string): Promise<boolean> {
|
2019-03-12 03:36:29 +01:00
|
|
|
const val = this.store.get(key);
|
|
|
|
return Promise.resolve(val != null);
|
2021-12-16 13:36:21 +01:00
|
|
|
}
|
|
|
|
|
2019-03-12 03:36:29 +01:00
|
|
|
save(key: string, obj: any): Promise<any> {
|
2021-05-19 02:10:20 +02:00
|
|
|
if (obj instanceof Set) {
|
|
|
|
obj = Array.from(obj);
|
2019-03-12 03:36:29 +01:00
|
|
|
}
|
|
|
|
this.store.set(key, obj);
|
|
|
|
return Promise.resolve();
|
2021-12-16 13:36:21 +01:00
|
|
|
}
|
|
|
|
|
2019-03-12 03:36:29 +01:00
|
|
|
remove(key: string): Promise<any> {
|
|
|
|
this.store.delete(key);
|
|
|
|
return Promise.resolve();
|
2021-12-16 13:36:21 +01:00
|
|
|
}
|
2019-03-12 03:36:29 +01:00
|
|
|
}
|