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

122 lines
3.7 KiB
TypeScript
Raw Normal View History

import { prisma } from "@/lib/api/db";
import createFolder from "@/lib/api/storage/createFolder";
import { JSDOM } from "jsdom";
2023-12-19 16:20:09 -06:00
const MAX_LINKS_PER_USER = Number(process.env.MAX_LINKS_PER_USER) || 30000;
2023-10-16 17:27:04 -05:00
export default async function importFromHTMLFile(
userId: number,
rawData: string
) {
2023-11-07 07:03:35 -06:00
const dom = new JSDOM(rawData);
const document = dom.window.document;
2023-12-19 16:20:09 -06:00
const bookmarks = document.querySelectorAll("A");
const totalImports = bookmarks.length;
const numberOfLinksTheUserHas = await prisma.link.count({
where: {
collection: {
ownerId: userId,
},
},
});
if (totalImports + numberOfLinksTheUserHas > MAX_LINKS_PER_USER)
return {
response: `Error: Each user can only have a maximum of ${MAX_LINKS_PER_USER} Links.`,
status: 400,
};
2023-11-07 07:03:35 -06:00
const folders = document.querySelectorAll("H3");
2023-11-07 07:03:35 -06:00
await prisma
.$transaction(
async () => {
// @ts-ignore
for (const folder of folders) {
const findCollection = await prisma.user.findUnique({
where: {
2023-11-07 07:03:35 -06:00
id: userId,
},
2023-11-07 07:03:35 -06:00
select: {
collections: {
where: {
name: folder.textContent.trim(),
},
},
},
});
2023-11-07 07:03:35 -06:00
const checkIfCollectionExists = findCollection?.collections[0];
2023-11-07 07:03:35 -06:00
let collectionId = findCollection?.collections[0]?.id;
2023-11-07 07:03:35 -06:00
if (!checkIfCollectionExists || !collectionId) {
const newCollection = await prisma.collection.create({
data: {
name: folder.textContent.trim(),
description: "",
color: "#0ea5e9",
isPublic: false,
ownerId: userId,
},
});
2023-11-07 07:03:35 -06:00
createFolder({ filePath: `archives/${newCollection.id}` });
2023-11-07 07:03:35 -06:00
collectionId = newCollection.id;
}
2023-11-07 07:03:35 -06:00
createFolder({ filePath: `archives/${collectionId}` });
2023-11-07 07:03:35 -06:00
const bookmarks = folder.nextElementSibling.querySelectorAll("A");
for (const bookmark of bookmarks) {
await prisma.link.create({
data: {
name: bookmark.textContent.trim(),
url: bookmark.getAttribute("HREF"),
tags: bookmark.getAttribute("TAGS")
? {
connectOrCreate: bookmark
.getAttribute("TAGS")
.split(",")
.map((tag: string) =>
tag
? {
where: {
name_ownerId: {
name: tag.trim(),
ownerId: userId,
},
},
create: {
name: tag.trim(),
owner: {
connect: {
id: userId,
},
},
},
2023-11-07 07:03:35 -06:00
}
: undefined
),
}
: undefined,
description: bookmark.getAttribute("DESCRIPTION")
? bookmark.getAttribute("DESCRIPTION")
: "",
collectionId: collectionId,
createdAt: new Date(),
},
});
}
}
},
{ timeout: 30000 }
)
.catch((err) => console.log(err));
return { response: "Success.", status: 200 };
}