summaryrefslogtreecommitdiff
path: root/packages/backend/src/queue/processors/ExportNotesProcessorService.ts
blob: 7d49a8dab286087004d1c9d14040b7a84d67200b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
/*
 * SPDX-FileCopyrightText: syuilo and misskey-project
 * SPDX-License-Identifier: AGPL-3.0-only
 */

import { ReadableStream, TextEncoderStream } from 'node:stream/web';
import { Inject, Injectable } from '@nestjs/common';
import { MoreThan } from 'typeorm';
import { format as dateFormat } from 'date-fns';
import { DI } from '@/di-symbols.js';
import type { NotesRepository, PollsRepository, UsersRepository } from '@/models/_.js';
import type Logger from '@/logger.js';
import { DriveService } from '@/core/DriveService.js';
import { createTemp } from '@/misc/create-temp.js';
import type { MiPoll } from '@/models/Poll.js';
import type { MiNote } from '@/models/Note.js';
import { bindThis } from '@/decorators.js';
import { DriveFileEntityService } from '@/core/entities/DriveFileEntityService.js';
import { Packed } from '@/misc/json-schema.js';
import { IdService } from '@/core/IdService.js';
import { NotificationService } from '@/core/NotificationService.js';
import { JsonArrayStream } from '@/misc/JsonArrayStream.js';
import { FileWriterStream } from '@/misc/FileWriterStream.js';
import { QueueLoggerService } from '../QueueLoggerService.js';
import type * as Bull from 'bullmq';
import type { DbJobDataWithUser } from '../types.js';

class NoteStream extends ReadableStream<Record<string, unknown>> {
	constructor(
		job: Bull.Job,
		notesRepository: NotesRepository,
		pollsRepository: PollsRepository,
		driveFileEntityService: DriveFileEntityService,
		idService: IdService,
		userId: string,
	) {
		let exportedNotesCount = 0;
		let cursor: MiNote['id'] | null = null;

		const serialize = (
			note: MiNote,
			poll: MiPoll | null,
			files: Packed<'DriveFile'>[],
		): Record<string, unknown> => {
			return {
				id: note.id,
				text: note.text,
				createdAt: idService.parse(note.id).date.toISOString(),
				fileIds: note.fileIds,
				files: files,
				replyId: note.replyId,
				renoteId: note.renoteId,
				poll: poll,
				cw: note.cw,
				visibility: note.visibility,
				visibleUserIds: note.visibleUserIds,
				localOnly: note.localOnly,
				reactionAcceptance: note.reactionAcceptance,
			};
		};

		super({
			async pull(controller): Promise<void> {
				const notes = await notesRepository.find({
					where: {
						userId,
						...(cursor !== null ? { id: MoreThan(cursor) } : {}),
					},
					take: 100, // 100件ずつ取得
					order: { id: 1 },
				});

				if (notes.length === 0) {
					job.updateProgress(100);
					controller.close();
				}

				cursor = notes.at(-1)?.id ?? null;

				for (const note of notes) {
					const poll = note.hasPoll
						? await pollsRepository.findOneByOrFail({ noteId: note.id }) // N+1
						: null;
					const files = await driveFileEntityService.packManyByIds(note.fileIds); // N+1
					const content = serialize(note, poll, files);

					controller.enqueue(content);
					exportedNotesCount++;
				}

				const total = await notesRepository.countBy({ userId });
				job.updateProgress(exportedNotesCount / total);
			},
		});
	}
}

@Injectable()
export class ExportNotesProcessorService {
	private logger: Logger;

	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,
		private driveFileEntityService: DriveFileEntityService,
		private idService: IdService,
		private notificationService: NotificationService,
	) {
		this.logger = this.queueLoggerService.logger.createSubLogger('export-notes');
	}

	@bindThis
	public async process(job: Bull.Job<DbJobDataWithUser>): Promise<void> {
		const user = await this.usersRepository.findOneBy({ id: job.data.user.id });
		if (user == null) {
			this.logger.debug(`Skip: user ${job.data.user.id} does not exist`);
			return;
		}

		this.logger.info(`Exporting notes of ${job.data.user.id} ...`);

		// Create temp file
		const [path, cleanup] = await createTemp();

		this.logger.debug(`Temp file is ${path}`);

		try {
			// メモリが足りなくならないようにストリームで処理する
			await new NoteStream(
				job,
				this.notesRepository,
				this.pollsRepository,
				this.driveFileEntityService,
				this.idService,
				user.id,
			)
				.pipeThrough(new JsonArrayStream())
				.pipeThrough(new TextEncoderStream())
				.pipeTo(new FileWriterStream(path));

			this.logger.debug(`Exported to: ${path}`);

			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' });

			this.logger.debug(`Exported to: ${driveFile.id}`);

			this.notificationService.createNotification(user.id, 'exportCompleted', {
				exportedEntity: 'note',
				fileId: driveFile.id,
			});
		} finally {
			cleanup();
		}
	}
}