2021-01-13 23:08:33 +01:00
|
|
|
import {
|
|
|
|
PlatformUtilsService,
|
|
|
|
StorageService,
|
|
|
|
} from 'jslib/abstractions';
|
|
|
|
|
|
|
|
import { SafariApp } from '../browser/safariApp';
|
2018-01-04 16:51:08 +01:00
|
|
|
|
2018-01-09 20:26:20 +01:00
|
|
|
export default class BrowserStorageService implements StorageService {
|
2018-01-12 06:06:53 +01:00
|
|
|
private chromeStorageApi: any;
|
2021-01-13 23:08:33 +01:00
|
|
|
private isSafari: boolean;
|
2018-01-12 06:06:53 +01:00
|
|
|
|
2021-01-13 23:08:33 +01:00
|
|
|
constructor(platformUtilsService: PlatformUtilsService) {
|
|
|
|
this.isSafari = platformUtilsService.isSafari();
|
|
|
|
if (!this.isSafari) {
|
|
|
|
this.chromeStorageApi = chrome.storage.local;
|
|
|
|
}
|
2018-01-04 22:15:06 +01:00
|
|
|
}
|
|
|
|
|
2019-08-13 17:47:29 +02:00
|
|
|
async get<T>(key: string): Promise<T> {
|
2021-01-13 23:08:33 +01:00
|
|
|
if (this.isSafari) {
|
|
|
|
const obj = await SafariApp.sendMessageToApp('storage_get', key);
|
|
|
|
return obj == null ? null : JSON.parse(obj) as T;
|
|
|
|
} else {
|
|
|
|
return new Promise((resolve) => {
|
|
|
|
this.chromeStorageApi.get(key, (obj: any) => {
|
|
|
|
if (obj != null && obj[key] != null) {
|
|
|
|
resolve(obj[key] as T);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
resolve(null);
|
|
|
|
});
|
2018-01-04 16:51:08 +01:00
|
|
|
});
|
2021-01-13 23:08:33 +01:00
|
|
|
}
|
2018-01-04 16:51:08 +01:00
|
|
|
}
|
|
|
|
|
2019-08-13 17:47:29 +02:00
|
|
|
async save(key: string, obj: any): Promise<any> {
|
2021-01-13 23:08:33 +01:00
|
|
|
const keyedObj = { [key]: obj };
|
|
|
|
if (this.isSafari) {
|
|
|
|
await SafariApp.sendMessageToApp('storage_save', JSON.stringify({
|
|
|
|
key: key,
|
|
|
|
obj: JSON.stringify(obj),
|
|
|
|
}));
|
|
|
|
} else {
|
2021-01-13 16:43:18 +01:00
|
|
|
return new Promise((resolve) => {
|
2021-01-13 23:08:33 +01:00
|
|
|
this.chromeStorageApi.set(keyedObj, () => {
|
2021-01-13 16:43:18 +01:00
|
|
|
resolve();
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
2018-01-04 16:51:08 +01:00
|
|
|
}
|
|
|
|
|
2019-08-13 17:47:29 +02:00
|
|
|
async remove(key: string): Promise<any> {
|
2021-01-13 23:08:33 +01:00
|
|
|
if (this.isSafari) {
|
|
|
|
await SafariApp.sendMessageToApp('storage_remove', key);
|
|
|
|
} else {
|
|
|
|
return new Promise((resolve) => {
|
|
|
|
this.chromeStorageApi.remove(key, () => {
|
|
|
|
resolve();
|
|
|
|
});
|
2018-01-04 16:51:08 +01:00
|
|
|
});
|
2021-01-13 23:08:33 +01:00
|
|
|
}
|
2018-01-04 16:51:08 +01:00
|
|
|
}
|
|
|
|
}
|