hippofish/packages/backend/src/queue/processors/ExportNotesProcessorService.ts

151 lines
4.1 KiB
TypeScript
Raw Normal View History

/*
* SPDX-FileCopyrightText: syuilo and other misskey contributors
* SPDX-License-Identifier: AGPL-3.0-only
*/
2022-09-17 20:27:08 +02:00
import * as fs from 'node:fs';
import { Inject, Injectable } from '@nestjs/common';
import { MoreThan } from 'typeorm';
2022-09-17 20:27:08 +02:00
import { format as dateFormat } from 'date-fns';
import { DI } from '@/di-symbols.js';
2022-09-20 22:33:11 +02:00
import type { NotesRepository, PollsRepository, UsersRepository } from '@/models/index.js';
2022-09-17 20:27:08 +02:00
import type Logger from '@/logger.js';
import { DriveService } from '@/core/DriveService.js';
import { createTemp } from '@/misc/create-temp.js';
import type { MiPoll } from '@/models/entities/Poll.js';
import type { MiNote } from '@/models/entities/Note.js';
import { bindThis } from '@/decorators.js';
2023-07-16 07:46:41 +02:00
import { DriveFileEntityService } from '@/core/entities/DriveFileEntityService.js';
import { Packed } from '@/misc/json-schema.js';
2022-09-17 20:27:08 +02:00
import { QueueLoggerService } from '../QueueLoggerService.js';
import type * as Bull from 'bullmq';
import type { DbJobDataWithUser } from '../types.js';
2022-09-17 20:27:08 +02:00
@Injectable()
export class ExportNotesProcessorService {
2022-09-18 20:11:50 +02:00
private logger: Logger;
2022-09-17 20:27:08 +02:00
constructor(
@Inject(DI.usersRepository)
private usersRepository: UsersRepository,
@Inject(DI.pollsRepository)
private pollsRepository: PollsRepository,
@Inject(DI.notesRepository)
private notesRepository: NotesRepository,
private driveService: DriveService,
private queueLoggerService: QueueLoggerService,
2023-07-16 07:21:49 +02:00
private driveFileEntityService: DriveFileEntityService,
2022-09-17 20:27:08 +02:00
) {
2022-09-18 20:11:50 +02:00
this.logger = this.queueLoggerService.logger.createSubLogger('export-notes');
2022-09-17 20:27:08 +02:00
}
@bindThis
public async process(job: Bull.Job<DbJobDataWithUser>): Promise<void> {
2022-09-18 20:11:50 +02:00
this.logger.info(`Exporting notes of ${job.data.user.id} ...`);
2022-09-17 20:27:08 +02:00
const user = await this.usersRepository.findOneBy({ id: job.data.user.id });
if (user == null) {
return;
}
// Create temp file
const [path, cleanup] = await createTemp();
2022-09-18 20:11:50 +02:00
this.logger.info(`Temp file is ${path}`);
2022-09-17 20:27:08 +02:00
try {
const stream = fs.createWriteStream(path, { flags: 'a' });
const write = (text: string): Promise<void> => {
return new Promise<void>((res, rej) => {
stream.write(text, err => {
if (err) {
2022-09-18 20:11:50 +02:00
this.logger.error(err);
2022-09-17 20:27:08 +02:00
rej(err);
} else {
res();
}
});
});
};
await write('[');
let exportedNotesCount = 0;
let cursor: MiNote['id'] | null = null;
2022-09-17 20:27:08 +02:00
while (true) {
const notes = await this.notesRepository.find({
where: {
userId: user.id,
...(cursor ? { id: MoreThan(cursor) } : {}),
},
take: 100,
order: {
id: 1,
},
}) as MiNote[];
2022-09-17 20:27:08 +02:00
if (notes.length === 0) {
job.updateProgress(100);
2022-09-17 20:27:08 +02:00
break;
}
cursor = notes.at(-1)?.id ?? null;
2022-09-17 20:27:08 +02:00
for (const note of notes) {
let poll: MiPoll | undefined;
2022-09-17 20:27:08 +02:00
if (note.hasPoll) {
poll = await this.pollsRepository.findOneByOrFail({ noteId: note.id });
}
2023-07-16 07:21:49 +02:00
const files = await this.driveFileEntityService.packManyByIds(note.fileIds);
const content = JSON.stringify(serialize(note, poll, files));
2022-09-17 20:27:08 +02:00
const isFirst = exportedNotesCount === 0;
await write(isFirst ? content : ',\n' + content);
exportedNotesCount++;
}
const total = await this.notesRepository.countBy({
userId: user.id,
});
job.updateProgress(exportedNotesCount / total);
2022-09-17 20:27:08 +02:00
}
await write(']');
stream.end();
2022-09-18 20:11:50 +02:00
this.logger.succ(`Exported to: ${path}`);
2022-09-17 20:27:08 +02:00
const fileName = 'notes-' + dateFormat(new Date(), 'yyyy-MM-dd-HH-mm-ss') + '.json';
const driveFile = await this.driveService.addFile({ user, path, name: fileName, force: true, ext: 'json' });
2022-09-17 20:27:08 +02:00
2022-09-18 20:11:50 +02:00
this.logger.succ(`Exported to: ${driveFile.id}`);
2022-09-17 20:27:08 +02:00
} finally {
cleanup();
}
}
}
function serialize(note: MiNote, poll: MiPoll | null = null, files: Packed<'DriveFile'>[]): Record<string, unknown> {
2022-09-17 20:27:08 +02:00
return {
id: note.id,
text: note.text,
createdAt: note.createdAt,
fileIds: note.fileIds,
2023-07-16 07:21:49 +02:00
files: files,
2022-09-17 20:27:08 +02:00
replyId: note.replyId,
renoteId: note.renoteId,
poll: poll,
cw: note.cw,
visibility: note.visibility,
visibleUserIds: note.visibleUserIds,
localOnly: note.localOnly,
reactionAcceptance: note.reactionAcceptance,
2022-09-17 20:27:08 +02:00
};
}