forked from monkeytypegame/monkeytype
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnew-quotes.ts
More file actions
231 lines (209 loc) · 6.07 KB
/
new-quotes.ts
File metadata and controls
231 lines (209 loc) · 6.07 KB
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
import { SimpleGit, simpleGit } from "simple-git";
import { Collection, ObjectId } from "mongodb";
import path from "path";
import { existsSync, writeFileSync } from "fs";
import { readFile } from "node:fs/promises";
import * as db from "../init/db";
import MonkeyError from "../utils/error";
import { compareTwoStrings } from "string-similarity";
import { ApproveQuote, Quote } from "@monkeytype/contracts/schemas/quotes";
import { WithObjectId } from "../utils/misc";
import { parseWithSchema as parseJsonWithSchema } from "@monkeytype/util/json";
import { z } from "zod";
const JsonQuoteSchema = z.object({
text: z.string(),
britishText: z.string().optional(),
source: z.string(),
length: z.number(),
id: z.number(),
});
const QuoteDataSchema = z.object({
language: z.string(),
quotes: z.array(JsonQuoteSchema),
groups: z.array(z.tuple([z.number(), z.number()])),
});
const PATH_TO_REPO = "../../../../monkeytype-new-quotes";
let git: SimpleGit | undefined;
try {
git = simpleGit(path.join(__dirname, PATH_TO_REPO));
} catch (e) {
console.error(`Failed to initialize git: ${e}`);
git = undefined;
}
type AddQuoteReturn = {
languageError?: number;
duplicateId?: number;
similarityScore?: number;
};
export type DBNewQuote = WithObjectId<Quote>;
// Export for use in tests
export const getNewQuoteCollection = (): Collection<DBNewQuote> =>
db.collection<DBNewQuote>("new-quotes");
export async function add(
text: string,
source: string,
language: string,
uid: string
): Promise<AddQuoteReturn | undefined> {
if (git === undefined) throw new MonkeyError(500, "Git not available.");
const quote = {
_id: new ObjectId(),
text: text,
source: source,
language: language.toLowerCase(),
submittedBy: uid,
timestamp: Date.now(),
approved: false,
};
if (!/^\w+$/.test(language)) {
throw new MonkeyError(500, `Invalid language name`, language);
}
const count = await getNewQuoteCollection().countDocuments({
language: language,
});
if (count >= 100) {
throw new MonkeyError(
409,
"There are already 100 quotes in the queue for this language."
);
}
//check for duplicate first
const fileDir = path.join(
__dirname,
`${PATH_TO_REPO}/frontend/static/quotes/${language}.json`
);
let duplicateId = -1;
let similarityScore = -1;
if (existsSync(fileDir)) {
const quoteFile = await readFile(fileDir);
const quoteFileJSON = parseJsonWithSchema(
quoteFile.toString(),
QuoteDataSchema
);
quoteFileJSON.quotes.every((old) => {
if (compareTwoStrings(old.text, quote.text) > 0.9) {
duplicateId = old.id;
similarityScore = compareTwoStrings(old.text, quote.text);
return false;
}
return true;
});
} else {
return { languageError: 1 };
}
if (duplicateId !== -1) {
return { duplicateId, similarityScore };
}
await db.collection("new-quotes").insertOne(quote);
return undefined;
}
export async function get(language: string): Promise<DBNewQuote[]> {
if (git === undefined) throw new MonkeyError(500, "Git not available.");
const where: {
approved: boolean;
language?: string;
} = {
approved: false,
};
if (!/^\w+$/.test(language)) {
throw new MonkeyError(500, `Invalid language name`, language);
}
if (language !== "all") {
where.language = language;
}
return await getNewQuoteCollection()
.find(where)
.sort({ timestamp: 1 })
.limit(10)
.toArray();
}
type ApproveReturn = {
quote: ApproveQuote;
message: string;
};
export async function approve(
quoteId: string,
editQuote: string | undefined,
editSource: string | undefined,
name: string
): Promise<ApproveReturn> {
if (git === undefined) throw new MonkeyError(500, "Git not available.");
//check mod status
const targetQuote = await getNewQuoteCollection().findOne({
_id: new ObjectId(quoteId),
});
if (!targetQuote) {
throw new MonkeyError(
404,
"Quote not found. It might have already been reviewed. Please refresh the list."
);
}
const language = targetQuote.language;
const quote: ApproveQuote = {
text: editQuote ?? targetQuote.text,
source: editSource ?? targetQuote.source,
length: targetQuote.text.length,
approvedBy: name,
id: -1,
};
let message = "";
if (!/^\w+$/.test(language)) {
throw new MonkeyError(500, `Invalid language name`, language);
}
const fileDir = path.join(
__dirname,
`${PATH_TO_REPO}/frontend/static/quotes/${language}.json`
);
await git.pull("upstream", "master");
if (existsSync(fileDir)) {
const quoteFile = await readFile(fileDir);
const quoteObject = parseJsonWithSchema(
quoteFile.toString(),
QuoteDataSchema
);
quoteObject.quotes.every((old) => {
if (compareTwoStrings(old.text, quote.text) > 0.8) {
throw new MonkeyError(409, "Duplicate quote");
}
});
let maxid = 0;
quoteObject.quotes.map(function (q) {
if (q.id > maxid) {
maxid = q.id;
}
});
quote.id = maxid + 1;
if (quote.id === -1) {
throw new MonkeyError(500, "Failed to get max id");
}
quoteObject.quotes.push(quote);
writeFileSync(fileDir, JSON.stringify(quoteObject, null, 2));
message = `Added quote to ${language}.json.`;
} else {
//file doesnt exist, create it
quote.id = 1;
writeFileSync(
fileDir,
JSON.stringify({
language: language,
groups: [
[0, 100],
[101, 300],
[301, 600],
[601, 9999],
],
quotes: [quote],
})
);
message = `Created file ${language}.json and added quote.`;
}
await git.add([`frontend/static/quotes/${language}.json`]);
await git.commit(`Added quote to ${language}.json`);
await git.push("origin", "master");
await getNewQuoteCollection().deleteOne({ _id: new ObjectId(quoteId) });
return { quote, message };
}
export async function refuse(quoteId: string): Promise<void> {
if (git === undefined) throw new MonkeyError(500, "Git not available.");
await getNewQuoteCollection().deleteOne({ _id: new ObjectId(quoteId) });
}