File size: 6,027 Bytes
7d7a53f
 
7a0420c
7d7a53f
 
 
ecff593
 
 
e8b57dd
7d7a53f
 
 
 
 
64c473c
7d7a53f
 
 
 
 
 
 
 
7a0420c
7d7a53f
64c473c
7d7a53f
 
ecff593
 
 
 
 
 
 
 
 
4cbbe64
 
 
 
e8b57dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4331e77
e8b57dd
 
 
 
 
 
 
 
 
 
ecff593
 
 
 
 
 
 
 
 
e8b57dd
ecff593
 
e8b57dd
ecff593
 
 
 
 
 
 
 
8c94898
 
 
 
 
 
ecff593
 
 
 
 
8c94898
 
e8b57dd
ecff593
 
e8b57dd
ecff593
 
e8b57dd
ecff593
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8b57dd
ecff593
 
e8b57dd
 
ecff593
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8b57dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecff593
 
 
 
 
 
 
 
7d7a53f
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import { Elysia } from "elysia";
import { authPlugin } from "../../authPlugin";
import { loginEnabled } from "$lib/server/auth";
import { collections } from "$lib/server/database";
import { authCondition } from "$lib/server/auth";
import { config } from "$lib/server/config";
import yazl from "yazl";
import { downloadFile } from "$lib/server/files/downloadFile";
import mimeTypes from "mime-types";
import { logger } from "$lib/server/logger";

export interface FeatureFlags {
	enableAssistants: boolean;
	loginEnabled: boolean;
	isAdmin: boolean;
	transcriptionEnabled: boolean;
}

export const misc = new Elysia()
	.use(authPlugin)
	.get("/public-config", async () => config.getPublicConfig())
	.get("/feature-flags", async ({ locals }) => {
		return {
			enableAssistants: config.ENABLE_ASSISTANTS === "true",
			loginEnabled, // login feature is on when OID is configured
			isAdmin: locals.isAdmin,
			transcriptionEnabled: !!config.get("TRANSCRIPTION_MODEL"),
		} satisfies FeatureFlags;
	})
	.get("/export", async ({ locals }) => {
		if (!locals.user) {
			throw new Error("Not logged in");
		}

		if (!locals.isAdmin) {
			throw new Error("Not admin");
		}

		if (config.ENABLE_DATA_EXPORT !== "true") {
			throw new Error("Data export is not enabled");
		}

		const nExports = await collections.messageEvents.countDocuments({
			userId: locals.user._id,
			type: "export",
			expiresAt: { $gt: new Date() },
		});

		if (nExports >= 1) {
			throw new Error(
				"You have already exported your data recently. Please wait 1 hour before exporting again."
			);
		}

		const stats: {
			nConversations: number;
			nMessages: number;
			nFiles: number;
			nAssistants: number;
			nAvatars: number;
		} = {
			nConversations: 0,
			nMessages: 0,
			nFiles: 0,
			nAssistants: 0,
			nAvatars: 0,
		};

		const zipfile = new yazl.ZipFile();

		const promises = [
			collections.conversations
				.find({ ...authCondition(locals) })
				.toArray()
				.then(async (conversations) => {
					const formattedConversations = await Promise.all(
						conversations.map(async (conversation) => {
							stats.nConversations++;
							const hashes: string[] = [];
							conversation.messages.forEach(async (message) => {
								stats.nMessages++;
								if (message.files) {
									message.files.forEach((file) => {
										hashes.push(file.value);
									});
								}
							});
							const files = await Promise.all(
								hashes.map(async (hash) => {
									try {
										const fileData = await downloadFile(hash, conversation._id);
										return fileData;
									} catch {
										return null;
									}
								})
							);

							const filenames: string[] = [];
							files.forEach((file) => {
								if (!file) return;

								const extension = mimeTypes.extension(file.mime) || null;
								const convId = conversation._id.toString();
								const fileId = file.name.split("-")[1].slice(0, 8);
								const fileName = `file-${convId}-${fileId}` + (extension ? `.${extension}` : "");
								filenames.push(fileName);
								zipfile.addBuffer(Buffer.from(file.value, "base64"), fileName);
								stats.nFiles++;
							});

							return {
								...conversation,
								messages: conversation.messages.map((message) => {
									return {
										...message,
										files: filenames,
										updates: undefined,
									};
								}),
							};
						})
					);

					zipfile.addBuffer(
						Buffer.from(JSON.stringify(formattedConversations, null, 2)),
						"conversations.json"
					);
				}),
			collections.assistants
				.find({ createdById: locals.user._id })
				.toArray()
				.then(async (assistants) => {
					const formattedAssistants = await Promise.all(
						assistants.map(async (assistant) => {
							if (assistant.avatar) {
								const fileId = collections.bucket.find({ filename: assistant._id.toString() });

								const content = await fileId.next().then(async (file) => {
									if (!file?._id) return;

									const fileStream = collections.bucket.openDownloadStream(file?._id);

									const fileBuffer = await new Promise<Buffer>((resolve, reject) => {
										const chunks: Uint8Array[] = [];
										fileStream.on("data", (chunk) => chunks.push(chunk));
										fileStream.on("error", reject);
										fileStream.on("end", () => resolve(Buffer.concat(chunks)));
									});

									return fileBuffer;
								});

								if (!content) return;

								zipfile.addBuffer(content, `avatar-${assistant._id.toString()}.jpg`);
								stats.nAvatars++;
							}

							stats.nAssistants++;

							return {
								_id: assistant._id.toString(),
								name: assistant.name,
								createdById: assistant.createdById.toString(),
								createdByName: assistant.createdByName,
								avatar: `avatar-${assistant._id.toString()}.jpg`,
								modelId: assistant.modelId,
								preprompt: assistant.preprompt,
								description: assistant.description,
								dynamicPrompt: assistant.dynamicPrompt,
								exampleInputs: assistant.exampleInputs,
								generateSettings: assistant.generateSettings,
								createdAt: assistant.createdAt.toISOString(),
								updatedAt: assistant.updatedAt.toISOString(),
							};
						})
					);

					zipfile.addBuffer(
						Buffer.from(JSON.stringify(formattedAssistants, null, 2)),
						"assistants.json"
					);
				}),
		];

		Promise.all(promises).then(async () => {
			logger.info(
				{
					userId: locals.user?._id,
					...stats,
				},
				"Exported user data"
			);
			zipfile.end();
			if (locals.user?._id) {
				await collections.messageEvents.insertOne({
					userId: locals.user?._id,
					type: "export",
					createdAt: new Date(),
					expiresAt: new Date(Date.now() + 1000 * 60 * 60), // 1 hour
				});
			}
		});

		// @ts-expect-error - zipfile.outputStream is not typed correctly
		return new Response(zipfile.outputStream, {
			headers: {
				"Content-Type": "application/zip",
				"Content-Disposition": 'attachment; filename="export.zip"',
			},
		});
	});