2024-04-10 07:13:13 +02:00
|
|
|
import type * as Lysand from "lysand-types";
|
2024-04-13 14:20:12 +02:00
|
|
|
import { db } from "~drizzle/db";
|
2024-04-17 08:36:01 +02:00
|
|
|
import { Instances } from "~drizzle/schema";
|
2023-09-12 22:48:10 +02:00
|
|
|
|
2023-09-28 20:19:21 +02:00
|
|
|
/**
|
|
|
|
|
* Represents an instance in the database.
|
|
|
|
|
*/
|
2023-09-12 22:48:10 +02:00
|
|
|
|
2023-11-11 03:36:06 +01:00
|
|
|
/**
|
|
|
|
|
* Adds an instance to the database if it doesn't already exist.
|
|
|
|
|
* @param url
|
|
|
|
|
* @returns Either the database instance if it already exists, or a newly created instance.
|
|
|
|
|
*/
|
2024-04-11 13:39:07 +02:00
|
|
|
export const addInstanceIfNotExists = async (url: string) => {
|
2024-04-07 07:30:49 +02:00
|
|
|
const origin = new URL(url).origin;
|
2024-04-10 07:13:13 +02:00
|
|
|
const host = new URL(url).host;
|
2024-04-07 07:30:49 +02:00
|
|
|
|
2024-04-25 05:40:27 +02:00
|
|
|
const found = await db.query.Instances.findFirst({
|
2024-04-11 13:39:07 +02:00
|
|
|
where: (instance, { eq }) => eq(instance.baseUrl, host),
|
2024-04-07 07:30:49 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (found) return found;
|
|
|
|
|
|
2024-04-10 08:37:38 +02:00
|
|
|
console.log(`Fetching instance metadata for ${origin}`);
|
|
|
|
|
|
2024-04-07 07:30:49 +02:00
|
|
|
// Fetch the instance configuration
|
2024-04-10 07:13:13 +02:00
|
|
|
const metadata = (await fetch(new URL("/.well-known/lysand", origin)).then(
|
|
|
|
|
(res) => res.json(),
|
|
|
|
|
)) as Lysand.ServerMetadata;
|
2024-04-07 07:30:49 +02:00
|
|
|
|
|
|
|
|
if (metadata.type !== "ServerMetadata") {
|
2024-04-10 07:13:13 +02:00
|
|
|
throw new Error("Invalid instance metadata (wrong type)");
|
2024-04-07 07:30:49 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!(metadata.name && metadata.version)) {
|
2024-04-10 07:13:13 +02:00
|
|
|
throw new Error("Invalid instance metadata (missing name or version)");
|
2024-04-07 07:30:49 +02:00
|
|
|
}
|
|
|
|
|
|
2024-04-11 13:39:07 +02:00
|
|
|
return (
|
|
|
|
|
await db
|
2024-04-17 08:36:01 +02:00
|
|
|
.insert(Instances)
|
2024-04-11 13:39:07 +02:00
|
|
|
.values({
|
|
|
|
|
baseUrl: host,
|
|
|
|
|
name: metadata.name,
|
|
|
|
|
version: metadata.version,
|
|
|
|
|
logo: metadata.logo,
|
|
|
|
|
})
|
|
|
|
|
.returning()
|
|
|
|
|
)[0];
|
2023-11-11 03:36:06 +01:00
|
|
|
};
|