78 lines
2.7 KiB
TypeScript
78 lines
2.7 KiB
TypeScript
import { AddInstanceDialog } from "./add_an_instance.mjs";
|
|
import { initializeInstanceDetailsDialog } from "./confirm_instance_details.mjs";
|
|
import { Dialog } from "./dialog.mjs";
|
|
import storageManager, { Instance } from "./storage_manager.mjs";
|
|
|
|
export class AddInstanceFlow {
|
|
addDialog: AddInstanceDialog;
|
|
spinnerDialog: Dialog;
|
|
detailsDialog: HTMLDialogElement;
|
|
|
|
constructor(
|
|
addDialog: AddInstanceDialog | HTMLDialogElement,
|
|
spinnerDialog: HTMLDialogElement,
|
|
detailsDialog: HTMLDialogElement,
|
|
) {
|
|
if (addDialog instanceof AddInstanceDialog)
|
|
this.addDialog = addDialog;
|
|
else
|
|
this.addDialog = new AddInstanceDialog(addDialog, true);
|
|
this.spinnerDialog = new Dialog(spinnerDialog);
|
|
this.detailsDialog = detailsDialog;
|
|
}
|
|
|
|
async start() {
|
|
const instanceDetailsDialogCallback = (
|
|
name: string,
|
|
host: string,
|
|
hostSecure: boolean,
|
|
software: string,
|
|
icon: string | null
|
|
) => {
|
|
const instance: Instance = {
|
|
name,
|
|
origin: `http${hostSecure ? "s" : ""}://${host}`,
|
|
software,
|
|
iconURL: icon ?? undefined
|
|
};
|
|
storageManager.storage.instances.push(instance);
|
|
storageManager.save();
|
|
console.log("Successfully added new instance:", instance);
|
|
};
|
|
|
|
const {
|
|
showInstanceDetailsDialog,
|
|
hideInstanceDetailsDialog,
|
|
populateInstanceDetailsDialog
|
|
} = initializeInstanceDetailsDialog(this.detailsDialog, instanceDetailsDialogCallback);
|
|
|
|
const {
|
|
autoQueryMetadata,
|
|
host,
|
|
secure,
|
|
} = await this.addDialog.prompt();
|
|
|
|
try {
|
|
if (!autoQueryMetadata) throw null; // Skip to catch block
|
|
|
|
this.spinnerDialog.open();
|
|
|
|
const { name, software, iconURL } =
|
|
await fetch(`/api/instance_info/${secure}/${encodeURIComponent(host)}`)
|
|
.then(r => r.json());
|
|
if (
|
|
typeof name !== "string"
|
|
|| typeof software !== "string"
|
|
|| !(typeof iconURL === "string" || iconURL === null) // I guess TS is too stupid to understand this?
|
|
)
|
|
throw new Error("Invalid API response");
|
|
|
|
populateInstanceDetailsDialog(name, host, secure, software, iconURL as string | null);
|
|
} catch {
|
|
populateInstanceDetailsDialog(host, host, secure, "", null);
|
|
} finally {
|
|
this.spinnerDialog.close();
|
|
showInstanceDetailsDialog();
|
|
}
|
|
}
|
|
}
|