hippofish/packages/backend/src/queue/processors/db/delete-account.ts

103 lines
2.2 KiB
TypeScript
Raw Normal View History

2023-01-13 05:40:33 +01:00
import type Bull from "bull";
import { queueLogger } from "../../logger.js";
import { DriveFiles, Notes, UserProfiles, Users } from "@/models/index.js";
import type { DbUserDeleteJobData } from "@/queue/types.js";
import type { Note } from "@/models/entities/note.js";
import type { DriveFile } from "@/models/entities/drive-file.js";
import { MoreThan } from "typeorm";
import { deleteFileSync } from "@/services/drive/delete-file.js";
import { sendEmail } from "@/services/send-email.js";
const logger = queueLogger.createSubLogger("delete-account");
export async function deleteAccount(
job: Bull.Job<DbUserDeleteJobData>,
): Promise<string | void> {
logger.info(`Deleting account of ${job.data.user.id} ...`);
const user = await Users.findOneBy({ id: job.data.user.id });
if (user == null) {
return;
}
2023-01-13 05:40:33 +01:00
{
// Delete notes
let cursor: Note["id"] | null = null;
while (true) {
2023-01-13 05:40:33 +01:00
const notes = (await Notes.find({
where: {
userId: user.id,
2021-12-09 15:58:30 +01:00
...(cursor ? { id: MoreThan(cursor) } : {}),
},
take: 100,
order: {
2021-12-09 15:58:30 +01:00
id: 1,
},
2023-01-13 05:40:33 +01:00
})) as Note[];
if (notes.length === 0) {
break;
}
cursor = notes[notes.length - 1].id;
2023-01-13 05:40:33 +01:00
await Notes.delete(notes.map((note) => note.id));
}
2023-01-13 05:40:33 +01:00
logger.succ("All of notes deleted");
}
2023-01-13 05:40:33 +01:00
{
// Delete files
let cursor: DriveFile["id"] | null = null;
while (true) {
2023-01-13 05:40:33 +01:00
const files = (await DriveFiles.find({
where: {
userId: user.id,
2021-12-09 15:58:30 +01:00
...(cursor ? { id: MoreThan(cursor) } : {}),
},
take: 10,
order: {
2021-12-09 15:58:30 +01:00
id: 1,
},
2023-01-13 05:40:33 +01:00
})) as DriveFile[];
if (files.length === 0) {
break;
}
cursor = files[files.length - 1].id;
for (const file of files) {
await deleteFileSync(file);
}
}
2023-01-13 05:40:33 +01:00
logger.succ("All of files deleted");
}
2023-01-13 05:40:33 +01:00
{
// Send email notification
const profile = await UserProfiles.findOneByOrFail({ userId: user.id });
if (profile.email && profile.emailVerified) {
2023-01-13 05:40:33 +01:00
sendEmail(
profile.email,
"Account deleted",
"Your account has been deleted.",
"Your account has been deleted.",
);
}
}
// soft指定されている場合は物理削除しない
if (job.data.soft) {
// nop
} else {
await Users.delete(job.data.user.id);
}
2023-01-13 05:40:33 +01:00
return "Account deleted";
}