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

127 lines
3.2 KiB
TypeScript
Raw Normal View History

2024-05-25 17:26:24 -05:00
import { prisma } from "@/lib/api/db";
import createFolder from "@/lib/api/storage/createFolder";
2024-10-26 12:44:52 -05:00
import { hasPassedLimit } from "../../verifyCapacity";
2024-05-25 17:26:24 -05:00
type WallabagBackup = {
is_archived: number;
is_starred: number;
tags: String[];
is_public: boolean;
id: number;
title: string;
url: string;
content: string;
created_at: Date;
updated_at: Date;
published_by: string[];
starred_at: Date;
annotations: any[];
mimetype: string;
language: string;
reading_time: number;
domain_name: string;
preview_picture: string;
http_status: string;
headers: Record<string, string>;
}[];
export default async function importFromWallabag(
userId: number,
rawData: string
) {
const data: WallabagBackup = JSON.parse(rawData);
const backup = data.filter((e) => e.url);
let totalImports = backup.length;
2024-10-26 12:44:52 -05:00
const hasTooManyLinks = await hasPassedLimit(userId, totalImports);
2024-05-25 17:26:24 -05:00
2024-10-26 12:44:52 -05:00
if (hasTooManyLinks) {
2024-05-25 17:26:24 -05:00
return {
2024-10-26 12:44:52 -05:00
response: `Your subscription have reached the maximum number of links allowed.`,
2024-05-25 17:26:24 -05:00
status: 400,
};
2024-10-26 12:44:52 -05:00
}
2024-05-25 17:26:24 -05:00
await prisma
.$transaction(
async () => {
const newCollection = await prisma.collection.create({
data: {
owner: {
connect: {
id: userId,
},
},
name: "Imports",
2024-10-26 12:44:52 -05:00
createdBy: {
connect: {
id: userId,
},
},
2024-05-25 17:26:24 -05:00
},
});
createFolder({ filePath: `archives/${newCollection.id}` });
for (const link of backup) {
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({
data: {
pinnedBy: link.is_starred
? { connect: { id: userId } }
: undefined,
2024-09-14 15:00:19 -05:00
url: link.url?.trim().slice(0, 254),
name: link.title?.trim().slice(0, 254) || "",
textContent: link.content?.trim() || "",
2024-05-25 17:26:24 -05:00
importDate: link.created_at || null,
collection: {
connect: {
id: newCollection.id,
},
},
2024-10-26 12:44:52 -05:00
createdBy: {
connect: {
id: userId,
},
},
2024-05-25 17:26:24 -05:00
tags:
link.tags && link.tags[0]
? {
2024-07-27 17:41:13 -05:00
connectOrCreate: link.tags.map((tag) => ({
where: {
name_ownerId: {
2024-09-14 15:00:19 -05:00
name: tag?.trim().slice(0, 49),
2024-07-27 17:41:13 -05:00
ownerId: userId,
},
2024-07-27 16:17:38 -05:00
},
2024-07-27 17:41:13 -05:00
create: {
2024-09-14 15:00:19 -05:00
name: tag?.trim().slice(0, 49),
2024-07-27 17:41:13 -05:00
owner: {
connect: {
id: userId,
},
2024-05-25 17:26:24 -05:00
},
},
2024-07-27 17:41:13 -05:00
})),
}
2024-05-25 17:26:24 -05:00
: undefined,
},
});
}
},
{ timeout: 30000 }
)
.catch((err) => console.log(err));
return { response: "Success.", status: 200 };
}