File size: 6,991 Bytes
e28a7d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
import { Elysia, t } from "elysia";
import { authPlugin } from "$api/authPlugin";
import { ReviewStatus } from "$lib/types/Review";
import { toolFromConfigs } from "$lib/server/tools";
import { collections } from "$lib/server/database";
import { ObjectId, type Filter } from "mongodb";
import type { CommunityToolDB, ToolFront, ToolInputFile } from "$lib/types/Tool";
import { MetricsServer } from "$lib/server/metrics";
import { authCondition } from "$lib/server/auth";
import { SortKey } from "$lib/types/Assistant";
import type { User } from "$lib/types/User";
import { generateQueryTokens, generateSearchTokens } from "$lib/utils/searchTokens";
import { config } from "$lib/server/config";

const NUM_PER_PAGE = 16;

export const toolGroup = new Elysia().use(authPlugin).group("/tools", (app) => {
	return app
		.get("/active", async ({ locals }) => {
			const settings = await collections.settings.findOne(authCondition(locals));

			if (!settings) {
				return [];
			}

			const toolUseDuration = (await MetricsServer.getMetrics().tool.toolUseDuration.get()).values;

			const activeCommunityToolIds = settings.tools ?? [];

			const communityTools = await collections.tools
				.find({ _id: { $in: activeCommunityToolIds.map((el) => new ObjectId(el)) } })
				.toArray()
				.then((tools) =>
					tools.map((tool) => ({
						...tool,
						isHidden: false,
						isOnByDefault: true,
						isLocked: true,
					}))
				);

			const fullTools = [...communityTools, ...toolFromConfigs];

			return fullTools
				.filter((tool) => !tool.isHidden)
				.map(
					(tool) =>
						({
							_id: tool._id.toString(),
							type: tool.type,
							displayName: tool.displayName,
							name: tool.name,
							description: tool.description,
							mimeTypes: (tool.inputs ?? [])
								.filter((input): input is ToolInputFile => input.type === "file")
								.map((input) => (input as ToolInputFile).mimeTypes)
								.flat(),
							isOnByDefault: tool.isOnByDefault ?? true,
							isLocked: tool.isLocked ?? true,
							timeToUseMS:
								toolUseDuration.find(
									(el) => el.labels.tool === tool._id.toString() && el.labels.quantile === 0.9
								)?.value ?? 15_000,
							color: tool.color,
							icon: tool.icon,
						}) satisfies ToolFront
				);
		})
		.get(
			"/search",
			async ({ query, locals, error }) => {
				if (config.COMMUNITY_TOOLS !== "true") {
					error(403, "Community tools are not enabled");
				}

				const username = query.user;
				const search = query.q?.trim() ?? null;

				const pageIndex = query.p ?? 0;
				const sort = query.sort ?? SortKey.TRENDING;
				const createdByCurrentUser = locals.user?.username && locals.user.username === username;
				const activeOnly = query.active ?? false;
				const showUnfeatured = query.showUnfeatured ?? false;

				let user: Pick<User, "_id"> | null = null;
				if (username) {
					user = await collections.users.findOne<Pick<User, "_id">>(
						{ username },
						{ projection: { _id: 1 } }
					);
					if (!user) {
						error(404, `User "${username}" doesn't exist`);
					}
				}

				const settings = await collections.settings.findOne(authCondition(locals));

				if (!settings && activeOnly) {
					error(404, "No user settings found");
				}

				const queryTokens = !!search && generateQueryTokens(search);

				const filter: Filter<CommunityToolDB> = {
					...(!createdByCurrentUser &&
						!activeOnly &&
						!(locals.isAdmin && showUnfeatured) && { review: ReviewStatus.APPROVED }),
					...(user && { createdById: user._id }),
					...(queryTokens && { searchTokens: { $all: queryTokens } }),
					...(activeOnly && {
						_id: {
							$in: (settings?.tools ?? []).map((key) => {
								return new ObjectId(key);
							}),
						},
					}),
				};

				const communityTools = await collections.tools
					.find(filter)
					.skip(NUM_PER_PAGE * pageIndex)
					.sort({
						...(sort === SortKey.TRENDING && { last24HoursUseCount: -1 }),
						useCount: -1,
					})
					.limit(NUM_PER_PAGE)
					.toArray();

				const configTools = toolFromConfigs
					.filter((tool) => !tool?.isHidden)
					.filter((tool) => {
						if (queryTokens) {
							return generateSearchTokens(tool.displayName).some((token) =>
								queryTokens.some((queryToken) => queryToken.test(token))
							);
						}
						return true;
					});

				const tools = [...(pageIndex == 0 && !username ? configTools : []), ...communityTools];

				const numTotalItems =
					(await collections.tools.countDocuments(filter)) + toolFromConfigs.length;

				return {
					tools,
					numTotalItems,
					numItemsPerPage: NUM_PER_PAGE,
					query: search,
					sort,
					showUnfeatured,
				};
			},
			{
				query: t.Object({
					user: t.Optional(t.String()),
					q: t.Optional(t.String()),
					sort: t.Optional(t.Enum(SortKey)),
					p: t.Optional(t.Numeric()),
					showUnfeatured: t.Optional(t.Boolean()),
					active: t.Optional(t.Boolean()),
				}),
			}
		)
		.get("/count", () => {
			// return community tool count
			return collections.tools.countDocuments({ type: "community", review: ReviewStatus.APPROVED });
		})
		.group("/:id", (app) => {
			return app
				.derive(async ({ params, error, locals }) => {
					const tool = await collections.tools.findOne({ _id: new ObjectId(params.id) });

					if (!tool) {
						const tool = toolFromConfigs.find((el) => el._id.toString() === params.id);
						if (!tool) {
							throw error(404, "Tool not found");
						} else {
							return {
								tool: {
									...tool,
									_id: tool._id.toString(),
									call: undefined,
									createdById: null,
									createdByName: null,
									createdByMe: false,
									reported: false,
									review: ReviewStatus.APPROVED,
								},
							};
						}
					} else {
						const reported = await collections.reports.findOne({
							contentId: tool._id,
							object: "tool",
						});

						return {
							tool: {
								...tool,
								_id: tool._id.toString(),
								call: undefined,
								createdById: tool.createdById.toString(),
								createdByMe:
									tool.createdById.toString() === (locals.user?._id ?? locals.sessionId).toString(),
								reported: !!reported,
							},
						};
					}
				})
				.get("", ({ tool }) => {
					return tool;
				})
				.post("/", () => {
					// todo: post new tool
					throw new Error("Not implemented");
				})
				.group("/:toolId", (app) => {
					return app
						.get("/", () => {
							// todo: get tool
							throw new Error("Not implemented");
						})
						.patch("/", () => {
							// todo: patch tool
							throw new Error("Not implemented");
						})
						.delete("/", () => {
							// todo: delete tool
							throw new Error("Not implemented");
						})
						.post("/report", () => {
							// todo: report tool
							throw new Error("Not implemented");
						})
						.patch("/review", () => {
							// todo: review tool
							throw new Error("Not implemented");
						});
				});
		});
});