[Storage] Rework everything (#10)

* [storage] rework everything

* [storage] expose createProxy

* [storage] add useProxy hook

* [storage] fix settings.ts

* [Storage] Implement wrapSync, fix UI

* [storage] fix storage

* [plugins] re-add plugin loading

* [storage] fix fix storage

* [storage] make wrapSync more magical

* [storage] save deletes

* [ui] hack around plugin removal... again

* [plugins] make plugin storage work

* [storage] expose api

---------

Co-authored-by: Beef <beefers@riseup.net>
This commit is contained in:
redstonekasi 2023-01-29 22:05:47 +01:00 committed by GitHub
parent 7282d45d39
commit 4c9fe8fcaf
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 201 additions and 87 deletions

35
src/lib/emitter.ts Normal file
View file

@ -0,0 +1,35 @@
import { Emitter, EmitterEvent, EmitterListener, EmitterListenerData, EmitterListeners } from "@types";
export const Events = Object.freeze({
GET: "GET",
SET: "SET",
DEL: "DEL"
});
export default function createEmitter(): Emitter {
return {
listeners: Object.values(Events).reduce<EmitterListeners>((acc, val: string) => ((acc[val] = new Set<EmitterListener>()), acc), {}) as EmitterListeners,
on(event: EmitterEvent, listener: EmitterListener) {
if (!this.listeners[event].has(listener))
this.listeners[event].add(listener);
},
off(event: EmitterEvent, listener: EmitterListener) {
this.listeners[event].delete(listener);
},
once(event: EmitterEvent, listener: EmitterListener) {
const once = (event: EmitterEvent, data: EmitterListenerData) => {
this.off(event, once);
listener(event, data);
}
this.on(event, once);
},
emit(event: EmitterEvent, data: EmitterListenerData) {
for (const listener of this.listeners[event])
listener(event, data);
},
};
}

View file

@ -1,8 +1,8 @@
import { Indexable, PluginManifest, Plugin } from "@types";
import { navigation } from "@metro/common";
import { createStorage, wrapSync } from "@lib/storage";
import logger from "@lib/logger";
import createStorage from "@lib/storage";
import Subpage from "@/ui/settings/components/Subpage";
import Subpage from "@ui/settings/components/Subpage";
type EvaledPlugin = {
onLoad?(): void;
@ -10,19 +10,16 @@ type EvaledPlugin = {
settings: JSX.Element;
};
export const plugins = createStorage<Indexable<Plugin>>("VENDETTA_PLUGINS", async function(parsed) {
for (let p of Object.keys(parsed)) {
const plugin: Plugin = parsed[p];
export const plugins = wrapSync(createStorage<Indexable<Plugin>>("VENDETTA_PLUGINS").then(async function (store) {
for (let p of Object.keys(store)) {
const plugin: Plugin = store[p];
if (parsed[p].update) {
await fetchPlugin(plugin.id);
} else {
plugins[p] = parsed[p];
}
if (parsed[p].enabled && plugins[p]) startPlugin(p);
if (store[p].update) await fetchPlugin(plugin.id);
if (store[p].enabled && plugins[p]) await startPlugin(p);
}
});
return store;
}));
const loadedPlugins: Indexable<EvaledPlugin> = {};
export async function fetchPlugin(id: string) {
@ -58,13 +55,14 @@ export async function fetchPlugin(id: string) {
};
}
export function evalPlugin(plugin: Plugin) {
export async function evalPlugin(plugin: Plugin) {
// TODO: Refactor to not depend on own window object
const vendettaForPlugins = {
...window.vendetta,
plugin: {
manifest: plugin.manifest,
storage: createStorage<Indexable<any>>(plugin.id),
// Wrapping this with wrapSync is NOT an option.
storage: await createStorage<Indexable<any>>(plugin.id),
showSettings: () => showSettings(plugin),
}
};
@ -75,12 +73,12 @@ export function evalPlugin(plugin: Plugin) {
return ret.default || ret;
}
export function startPlugin(id: string) {
export async function startPlugin(id: string) {
const plugin = plugins[id];
if (!plugin) throw new Error("Attempted to start non-existent plugin");
try {
const pluginRet: EvaledPlugin = evalPlugin(plugin);
const pluginRet: EvaledPlugin = await evalPlugin(plugin);
loadedPlugins[id] = pluginRet;
pluginRet.onLoad?.();
plugin.enabled = true;

View file

@ -1,4 +1,4 @@
import createStorage from "@lib/storage";
import { createStorage, wrapSync } from "@lib/storage";
import { Settings } from "@types";
export default createStorage<Settings>("VENDETTA_SETTINGS");
export default wrapSync(createStorage<Settings>("VENDETTA_SETTINGS"));

View file

@ -1,48 +1,101 @@
import { Indexable, MMKVManager } from "@types";
import { Emitter, MMKVManager } from "@types";
import { ReactNative as RN } from "@metro/hoist";
import createEmitter from "./emitter";
// Discord's custom special storage sauce
const MMKVManager = RN.NativeModules.MMKVManager as MMKVManager;
// TODO: React hook?
// TODO: Clean up types, if necessary
export default function createStorage<T>(storeName: string, onRestore?: (parsed: T) => void): T {
const internalStore: Indexable<any> = {};
const emitterSymbol = Symbol("emitter accessor");
const proxyValidator = {
get(target: object, key: string | symbol): any {
const orig = Reflect.get(target, key);
if (typeof orig === "object" && orig !== null) {
return new Proxy(orig, proxyValidator);
} else {
return orig;
}
},
set(target: object, key: string | symbol, value: any) {
Reflect.set(target, key, value);
MMKVManager.setItem(storeName, JSON.stringify(internalStore));
return true;
},
deleteProperty(target: object, key: string | symbol) {
Reflect.deleteProperty(target, key);
MMKVManager.setItem(storeName, JSON.stringify(internalStore));
return true;
export function createProxy(target: any = {}): { proxy: any, emitter: Emitter } {
const emitter = createEmitter();
function createProxy(target: any, path: string[]): any {
return new Proxy(target, {
get(target, prop: string) {
if ((prop as unknown) === emitterSymbol)
return emitter;
const newPath = [...path, prop];
const value: any = target[prop];
if (value !== undefined && value !== null) {
emitter.emit("GET", {
path: newPath,
value,
});
if (typeof value === "object") {
return createProxy(value, newPath);
}
return value;
}
}
MMKVManager.getItem(storeName).then(async function (v) {
if (!v) return;
const parsed: T & Indexable<any> = JSON.parse(v);
return value;
},
if (onRestore && typeof onRestore === "function") {
onRestore(parsed);
} else {
for (let p of Object.keys(parsed)) internalStore[p] = parsed[p];
}
})
set(target, prop: string, value) {
target[prop] = value;
emitter.emit("SET", {
path: [...path, prop],
value
});
// we do not care about success, if this actually does fail we have other problems
return true;
},
return new Proxy(internalStore, proxyValidator) as T;
deleteProperty(target, prop: string) {
const success = delete target[prop];
if (success) emitter.emit("DEL", {
path: [...path, prop],
});
return success;
},
});
}
return {
proxy: createProxy(target, []),
emitter,
}
}
export function useProxy<T>(storage: T): T {
const emitter = (storage as any)[emitterSymbol] as Emitter;
const [, forceUpdate] = React.useReducer((n) => ~n, 0);
React.useEffect(() => {
const listener = () => forceUpdate();
emitter.on("SET", listener);
emitter.on("DEL", listener);
return () => {
emitter.off("SET", listener);
emitter.off("DEL", listener);
}
}, []);
return storage;
}
export async function createStorage<T>(storeName: string): Promise<Awaited<T>> {
const data = JSON.parse(await MMKVManager.getItem(storeName) ?? "{}");
const { proxy, emitter } = createProxy(data);
const handler = () => MMKVManager.setItem(storeName, JSON.stringify(proxy));
emitter.on("SET", handler);
emitter.on("DEL", handler);
return proxy;
}
export function wrapSync<T extends Promise<any>>(store: T): Awaited<T> {
let awaited: any = undefined;
store.then((v) => (awaited = v));
return new Proxy(
{} as Awaited<T>,
Object.fromEntries(Object.getOwnPropertyNames(Reflect)
// @ts-expect-error
.map((k) => [k, (t: T, ...a: any[]) => Reflect[k](awaited ?? t, ...a)])),
);
}