el.xwx.moe/lib/api/controllers/migration/importFromLinkwarden.ts

105 lines
2.8 KiB
TypeScript
Raw Normal View History

2023-10-16 17:27:04 -05:00
import { prisma } from "@/lib/api/db";
import { Backup } from "@/types/global";
import createFolder from "@/lib/api/storage/createFolder";
2023-12-19 16:20:09 -06:00
const MAX_LINKS_PER_USER = Number(process.env.MAX_LINKS_PER_USER) || 30000;
export default async function importFromLinkwarden(
userId: number,
rawData: string
) {
2023-10-16 17:27:04 -05:00
const data: Backup = JSON.parse(rawData);
2023-12-19 16:20:09 -06:00
let totalImports = 0;
data.collections.forEach((collection) => {
totalImports += collection.links.length;
});
const numberOfLinksTheUserHas = await prisma.link.count({
where: {
collection: {
ownerId: userId,
},
},
});
if (totalImports + numberOfLinksTheUserHas > MAX_LINKS_PER_USER)
return {
2024-06-28 08:14:09 -05:00
response: `Each collection owner can only have a maximum of ${MAX_LINKS_PER_USER} Links.`,
2023-12-19 16:20:09 -06:00
status: 400,
};
2023-11-07 07:03:35 -06:00
await prisma
.$transaction(
async () => {
// Import collections
for (const e of data.collections) {
e.name = e.name.trim();
2023-10-16 17:27:04 -05:00
2024-02-23 11:11:03 -06:00
const newCollection = await prisma.collection.create({
data: {
owner: {
connect: {
id: userId,
2023-11-07 07:03:35 -06:00
},
},
2024-09-14 15:00:19 -05:00
name: e.name?.trim().slice(0, 254),
description: e.description?.trim().slice(0, 254),
color: e.color?.trim().slice(0, 50),
2023-10-16 17:27:04 -05:00
},
2023-11-07 07:03:35 -06:00
});
2023-10-16 17:27:04 -05:00
2024-02-23 11:11:03 -06:00
createFolder({ filePath: `archives/${newCollection.id}` });
2023-10-16 17:27:04 -05:00
2023-11-07 07:03:35 -06:00
// Import Links
for (const link of e.links) {
2024-09-14 15:00:19 -05:00
if (link.url) {
try {
new URL(link.url.trim());
} catch (err) {
continue;
}
}
2024-05-25 17:26:24 -05:00
await prisma.link.create({
2023-11-07 07:03:35 -06:00
data: {
2024-09-14 15:00:19 -05:00
url: link.url?.trim().slice(0, 254),
name: link.name?.trim().slice(0, 254),
description: link.description?.trim().slice(0, 254),
2023-11-07 07:03:35 -06:00
collection: {
connect: {
2024-02-23 11:11:03 -06:00
id: newCollection.id,
2023-10-16 17:27:04 -05:00
},
},
2023-11-07 07:03:35 -06:00
// Import Tags
tags: {
connectOrCreate: link.tags.map((tag) => ({
where: {
name_ownerId: {
2024-09-14 15:00:19 -05:00
name: tag.name?.slice(0, 49),
2023-11-07 07:03:35 -06:00
ownerId: userId,
},
2023-10-16 17:27:04 -05:00
},
2023-11-07 07:03:35 -06:00
create: {
2024-09-14 15:00:19 -05:00
name: tag.name?.trim().slice(0, 49),
2023-11-07 07:03:35 -06:00
owner: {
connect: {
id: userId,
},
},
},
})),
2023-10-16 17:27:04 -05:00
},
2023-11-07 07:03:35 -06:00
},
});
}
}
},
{ timeout: 30000 }
)
.catch((err) => console.log(err));
2023-10-16 17:27:04 -05:00
return { response: "Success.", status: 200 };
}