388 lines
12 kB
1
import { Config, ExtensionLoadSource } from "@moonlight-mod/types";
2
import { ExtensionState, MoonbaseExtension, MoonbaseNatives, RepositoryManifest } from "../types";
3
import { Store } from "@moonlight-mod/wp/discord/packages/flux";
4
import Dispatcher from "@moonlight-mod/wp/discord/Dispatcher";
5
import getNatives from "../native";
6
import { mainRepo } from "@moonlight-mod/types/constants";
7
import { checkExtensionCompat, ExtensionCompat } from "@moonlight-mod/core/extension/loader";
8
import { CustomComponent } from "@moonlight-mod/types/coreExtensions/moonbase";
9
import { getConfigOption, setConfigOption } from "@moonlight-mod/core/util/config";
10
11
const logger = moonlight.getLogger("moonbase");
12
13
let natives: MoonbaseNatives = moonlight.getNatives("moonbase");
14
if (moonlightNode.isBrowser) natives = getNatives();
15
16
class MoonbaseSettingsStore extends Store<any> {
17
private origConfig: Config;
18
private config: Config;
19
private extensionIndex: number;
20
private configComponents: Record<string, Record<string, CustomComponent>> = {};
21
22
modified: boolean;
23
submitting: boolean;
24
installing: boolean;
25
26
newVersion: string | null;
27
shouldShowNotice: boolean;
28
29
extensions: { [id: number]: MoonbaseExtension };
30
updates: {
31
[id: number]: {
32
version: string;
33
download: string;
34
updateManifest: RepositoryManifest;
35
};
36
};
37
38
constructor() {
39
super(Dispatcher);
40
41
this.origConfig = moonlightNode.config;
42
this.config = this.clone(this.origConfig);
43
this.extensionIndex = 0;
44
45
this.modified = false;
46
this.submitting = false;
47
this.installing = false;
48
49
this.newVersion = null;
50
this.shouldShowNotice = false;
51
52
this.extensions = {};
53
this.updates = {};
54
for (const ext of moonlightNode.extensions) {
55
const uniqueId = this.extensionIndex++;
56
this.extensions[uniqueId] = {
57
...ext,
58
uniqueId,
59
state: moonlight.enabledExtensions.has(ext.id) ? ExtensionState.Enabled : ExtensionState.Disabled,
60
compat: checkExtensionCompat(ext.manifest),
61
hasUpdate: false
62
};
63
}
64
65
natives!
66
.fetchRepositories(this.config.repositories)
67
.then((ret) => {
68
for (const [repo, exts] of Object.entries(ret)) {
69
try {
70
for (const ext of exts) {
71
const uniqueId = this.extensionIndex++;
72
const extensionData = {
73
id: ext.id,
74
uniqueId,
75
manifest: ext,
76
source: { type: ExtensionLoadSource.Normal, url: repo },
77
state: ExtensionState.NotDownloaded,
78
compat: ExtensionCompat.Compatible,
79
hasUpdate: false
80
};
81
82
// Don't present incompatible updates
83
if (checkExtensionCompat(ext) !== ExtensionCompat.Compatible) continue;
84
85
const existing = this.getExisting(extensionData);
86
if (existing != null) {
87
// Make sure the download URL is properly updated
88
for (const [id, e] of Object.entries(this.extensions)) {
89
if (e.id === ext.id && e.source.url === repo) {
90
this.extensions[parseInt(id)].manifest = {
91
...e.manifest,
92
download: ext.download
93
};
94
break;
95
}
96
}
97
98
if (this.hasUpdate(extensionData)) {
99
this.updates[existing.uniqueId] = {
100
version: ext.version!,
101
download: ext.download,
102
updateManifest: ext
103
};
104
existing.hasUpdate = true;
105
}
106
107
continue;
108
}
109
110
this.extensions[uniqueId] = extensionData;
111
}
112
} catch (e) {
113
logger.error(`Error processing repository ${repo}`, e);
114
}
115
}
116
117
this.emitChange();
118
})
119
.then(() =>
120
this.getExtensionConfigRaw("moonbase", "updateChecking", true)
121
? natives!.checkForMoonlightUpdate()
122
: new Promise<null>((resolve) => resolve(null))
123
)
124
.then((version) => {
125
this.newVersion = version;
126
this.emitChange();
127
})
128
.then(() => {
129
this.shouldShowNotice = this.newVersion != null || Object.keys(this.updates).length > 0;
130
this.emitChange();
131
});
132
}
133
134
private getExisting(ext: MoonbaseExtension) {
135
return Object.values(this.extensions).find((e) => e.id === ext.id && e.source.url === ext.source.url);
136
}
137
138
private hasUpdate(ext: MoonbaseExtension) {
139
const existing = Object.values(this.extensions).find((e) => e.id === ext.id && e.source.url === ext.source.url);
140
if (existing == null) return false;
141
142
return existing.manifest.version !== ext.manifest.version && existing.state !== ExtensionState.NotDownloaded;
143
}
144
145
// Jank
146
private isModified() {
147
const orig = JSON.stringify(this.origConfig);
148
const curr = JSON.stringify(this.config);
149
return orig !== curr;
150
}
151
152
get busy() {
153
return this.submitting || this.installing;
154
}
155
156
// Required for the settings store contract
157
showNotice() {
158
return this.modified;
159
}
160
161
getExtension(uniqueId: number) {
162
return this.extensions[uniqueId];
163
}
164
165
getExtensionUniqueId(id: string) {
166
return Object.values(this.extensions).find((ext) => ext.id === id)?.uniqueId;
167
}
168
169
getExtensionConflicting(uniqueId: number) {
170
const ext = this.getExtension(uniqueId);
171
if (ext.state !== ExtensionState.NotDownloaded) return false;
172
return Object.values(this.extensions).some(
173
(e) => e.id === ext.id && e.uniqueId !== uniqueId && e.state !== ExtensionState.NotDownloaded
174
);
175
}
176
177
getExtensionName(uniqueId: number) {
178
const ext = this.getExtension(uniqueId);
179
return ext.manifest.meta?.name ?? ext.id;
180
}
181
182
getExtensionUpdate(uniqueId: number) {
183
return this.updates[uniqueId]?.version;
184
}
185
186
getExtensionEnabled(uniqueId: number) {
187
const ext = this.getExtension(uniqueId);
188
if (ext.state === ExtensionState.NotDownloaded) return false;
189
const val = this.config.extensions[ext.id];
190
if (val == null) return false;
191
return typeof val === "boolean" ? val : val.enabled;
192
}
193
194
getExtensionConfig<T>(uniqueId: number, key: string): T | undefined {
195
const ext = this.getExtension(uniqueId);
196
return getConfigOption(ext.id, key, this.config, ext.manifest);
197
}
198
199
getExtensionConfigRaw<T>(id: string, key: string, defaultValue: T | undefined): T | undefined {
200
const cfg = this.config.extensions[id];
201
if (cfg == null || typeof cfg === "boolean") return defaultValue;
202
return cfg.config?.[key] ?? defaultValue;
203
}
204
205
getExtensionConfigName(uniqueId: number, key: string) {
206
const ext = this.getExtension(uniqueId);
207
return ext.manifest.settings?.[key]?.displayName ?? key;
208
}
209
210
getExtensionConfigDescription(uniqueId: number, key: string) {
211
const ext = this.getExtension(uniqueId);
212
return ext.manifest.settings?.[key]?.description;
213
}
214
215
setExtensionConfig(id: string, key: string, value: any) {
216
setConfigOption(this.config, id, key, value);
217
this.modified = this.isModified();
218
this.emitChange();
219
}
220
221
setExtensionEnabled(uniqueId: number, enabled: boolean) {
222
const ext = this.getExtension(uniqueId);
223
let val = this.config.extensions[ext.id];
224
225
if (val == null) {
226
this.config.extensions[ext.id] = { enabled };
227
this.modified = this.isModified();
228
this.emitChange();
229
return;
230
}
231
232
if (typeof val === "boolean") {
233
val = enabled;
234
} else {
235
val.enabled = enabled;
236
}
237
238
this.config.extensions[ext.id] = val;
239
this.modified = this.isModified();
240
this.emitChange();
241
}
242
243
async installExtension(uniqueId: number) {
244
const ext = this.getExtension(uniqueId);
245
if (!("download" in ext.manifest)) {
246
throw new Error("Extension has no download URL");
247
}
248
249
this.installing = true;
250
try {
251
const update = this.updates[uniqueId];
252
const url = update?.download ?? ext.manifest.download;
253
await natives!.installExtension(ext.manifest, url, ext.source.url!);
254
if (ext.state === ExtensionState.NotDownloaded) {
255
this.extensions[uniqueId].state = ExtensionState.Disabled;
256
}
257
258
if (update != null) this.extensions[uniqueId].compat = checkExtensionCompat(update.updateManifest);
259
260
delete this.updates[uniqueId];
261
} catch (e) {
262
logger.error("Error installing extension:", e);
263
}
264
265
this.installing = false;
266
this.emitChange();
267
}
268
269
private getRank(ext: MoonbaseExtension) {
270
if (ext.source.type === ExtensionLoadSource.Developer) return 3;
271
if (ext.source.type === ExtensionLoadSource.Core) return 2;
272
if (ext.source.url === mainRepo) return 1;
273
return 0;
274
}
275
276
async getDependencies(uniqueId: number) {
277
const ext = this.getExtension(uniqueId);
278
279
const missingDeps = [];
280
for (const dep of ext.manifest.dependencies ?? []) {
281
const anyInstalled = Object.values(this.extensions).some(
282
(e) => e.id === dep && e.state !== ExtensionState.NotDownloaded
283
);
284
if (!anyInstalled) missingDeps.push(dep);
285
}
286
287
if (missingDeps.length === 0) return null;
288
289
const deps: Record<string, MoonbaseExtension[]> = {};
290
for (const dep of missingDeps) {
291
const candidates = Object.values(this.extensions).filter((e) => e.id === dep);
292
293
deps[dep] = candidates.sort((a, b) => {
294
const aRank = this.getRank(a);
295
const bRank = this.getRank(b);
296
if (aRank === bRank) {
297
const repoIndex = this.config.repositories.indexOf(a.source.url!);
298
const otherRepoIndex = this.config.repositories.indexOf(b.source.url!);
299
return repoIndex - otherRepoIndex;
300
} else {
301
return bRank - aRank;
302
}
303
});
304
}
305
306
return deps;
307
}
308
309
async deleteExtension(uniqueId: number) {
310
const ext = this.getExtension(uniqueId);
311
if (ext == null) return;
312
313
this.installing = true;
314
try {
315
await natives!.deleteExtension(ext.id);
316
this.extensions[uniqueId].state = ExtensionState.NotDownloaded;
317
} catch (e) {
318
logger.error("Error deleting extension:", e);
319
}
320
321
this.installing = false;
322
this.emitChange();
323
}
324
325
async updateMoonlight() {
326
await natives.updateMoonlight();
327
}
328
329
getConfigOption<K extends keyof Config>(key: K): Config[K] {
330
return this.config[key];
331
}
332
333
setConfigOption<K extends keyof Config>(key: K, value: Config[K]) {
334
this.config[key] = value;
335
this.modified = this.isModified();
336
this.emitChange();
337
}
338
339
tryGetExtensionName(id: string) {
340
const uniqueId = this.getExtensionUniqueId(id);
341
return (uniqueId != null ? this.getExtensionName(uniqueId) : null) ?? id;
342
}
343
344
registerConfigComponent(ext: string, name: string, component: CustomComponent) {
345
if (!(ext in this.configComponents)) this.configComponents[ext] = {};
346
this.configComponents[ext][name] = component;
347
}
348
349
getExtensionConfigComponent(ext: string, name: string) {
350
return this.configComponents[ext]?.[name];
351
}
352
353
writeConfig() {
354
this.submitting = true;
355
356
moonlightNode.writeConfig(this.config);
357
this.origConfig = this.clone(this.config);
358
359
this.submitting = false;
360
this.modified = false;
361
this.emitChange();
362
}
363
364
reset() {
365
this.submitting = false;
366
this.modified = false;
367
this.config = this.clone(this.origConfig);
368
this.emitChange();
369
}
370
371
restartDiscord() {
372
if (moonlightNode.isBrowser) {
373
window.location.reload();
374
} else {
375
// @ts-expect-error TODO: DiscordNative
376
window.DiscordNative.app.relaunch();
377
}
378
}
379
380
// Required because electron likes to make it immutable sometimes.
381
// This sucks.
382
private clone<T>(obj: T): T {
383
return structuredClone(obj);
384
}
385
}
386
387
const settingsStore = new MoonbaseSettingsStore();
388
export { settingsStore as MoonbaseSettingsStore };
389