This repository has been archived by the owner on May 10, 2023. It is now read-only.
/
sentences-meta.js
293 lines (246 loc) · 8.07 KB
/
sentences-meta.js
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import { getAllLanguages } from '../../languages';
import { BUCKET_NAME } from '../../db.js';
import { parseBatchResults } from '../api-result-parser';
import { authedCreateReadAndWrite, authedReadAndWrite } from '../permissions';
import hash from '../../hash';
const NAME = 'Sentences_Meta';
const PREFIX = NAME + '_';
const USER_PREFIX = PREFIX + 'UserVote_';
const VALID = true;
const INVALID = false;
// Two out of three votes need to be say the sentence is valid
// for it to be approved.
const APPROVAL_MIN_VALID_VOTES = 2;
const APPROVAL_MIN_TOTAL_VOTES = 3;
export default class SentencesMeta {
constructor(kintoServer, username) {
this.server = kintoServer;
this.username = username;
}
getCollectionName(code) {
return PREFIX + code;
}
getUserKey(username) {
return USER_PREFIX + username;
}
getPreparedRecord({ sentence, reviewed, source }) {
const preparedRecord = {
id: hash(sentence),
sentence,
source,
valid: [],
invalid: [],
username: this.username,
};
if (reviewed) {
preparedRecord.valid = [this.username];
preparedRecord[`${USER_PREFIX}${this.username}`] = true;
}
return preparedRecord;
}
async createAllCollections(bucket) {
const languages = getAllLanguages();
const results = await bucket.batch(b => {
for (let i = 0; i < languages.length; i++) {
const code = languages[i].code;
const name = this.getCollectionName(code);
b.createCollection(name, authedCreateReadAndWrite());
}
});
const { successes, errors } = parseBatchResults(results);
if (errors.length > 0) {
throw new Error('Failed: create meta collections' + errors.join(','));
}
if (successes.length !== languages.length) {
throw new Error('Failed: missing meta collections');
}
}
async getLanguages(bucket) {
const result = await this.getLanguageTables(bucket);
return result.map(c => c.replace(PREFIX, ''));
}
async getLanguageTableNames(bucket) {
const result = await bucket.listCollections({
filters: {
like_id: PREFIX,
},
});
return result.data.map(c => c.id);
}
async getCollection(language) {
return this.server.bucket(BUCKET_NAME)
.collection(this.getCollectionName(language));
}
async getAll(language) {
const collection = await this.getCollection(language);
const result = await collection.listRecords();
return result.data;
}
async getLanguageAndSentenceCounts(bucket) {
const languages = await this.getLanguageTableNames(bucket);
const responses = await this.server.batch((batch) => {
for (const cid of languages) {
batch.collection(cid).getTotalRecords();
}
}, { bucket: "App" });
return responses.reduce((info, response) => {
let numberOfSentences = 0;
try {
numberOfSentences = parseInt(response.headers['Total-Records'], 10);
} catch (err) { /* ignore */ }
info.sentences = info.sentences + numberOfSentences;
if (numberOfSentences > 0) {
info.languages = info.languages + 1;
}
return info;
}, { languages: 0, sentences: 0 });
}
async getNotVoted(language) {
const filters = {};
// filter current user from votes.
filters['has_' + this.getUserKey(this.username)] = false;
filters['has_approved'] = false;
const collection = await this.getCollection(language);
const result = await collection.listRecords({ filters });
return result.data;
}
async getValidatedSentences(language) {
const filters = {};
filters.approved = true;
const collection = await this.getCollection(language);
const result = await collection.listRecords({ filters });
return result.data;
}
prepareForSubmission(sentences) {
const allUnreviewedSentences = sentences.unreviewed.map((sentence) => {
return { sentence, reviewed: false };
});
const allValidatedSentences = sentences.validated.map((sentence) => {
return { sentence, reviewed: true };
});
return allUnreviewedSentences.concat(allValidatedSentences);
}
async submitSentences(language, sentences, source = '') {
const allSentences = this.prepareForSubmission(sentences);
const collection = await this.getCollection(language);
const results = await collection.batch(batch => {
for (let i = 0; i < allSentences.length; i++) {
const record = this.getPreparedRecord({
sentence: allSentences[i].sentence,
reviewed: allSentences[i].reviewed,
source,
});
batch.createRecord(record, {
...authedReadAndWrite(),
safe: true,
});
}
});
const { successes, errors } = parseBatchResults(results);
return {
sentences: successes,
errors,
};
}
async getMyVotes(language) {
const collection = await this.getCollection(language);
const filters = {};
filters['has_' + this.getUserKey(this.username)] = true;
const result = await collection.listRecords({ filters });
return result.data;
}
getVoteRecords(isValid, sentences, existing) {
return sentences.map(sentence => {
let record = existing[sentence.id] ?
existing[sentence.id] : this.getPreparedRecord({
sentence: sentence.sentence,
reviewed: false,
});
if (isValid) {
record.valid.push(this.username);
record[this.getUserKey(this.username)] = VALID;
} else {
record.invalid.push(this.username);
record[this.getUserKey(this.username)] = INVALID;
}
const isApproved = this.checkIfApproved(record);
if (typeof isApproved === 'undefined') {
// We don't have any approval yet (not enough votes)
// therefore we leave the record as is
return record;
}
record.approved = isApproved;
return record;
});
}
checkIfApproved(record) {
const validVotes = record.valid.length;
const invalidVotes = record.invalid.length;
const totalVotes = validVotes + invalidVotes;
if (totalVotes < APPROVAL_MIN_TOTAL_VOTES) {
return;
}
return validVotes >= APPROVAL_MIN_VALID_VOTES;
}
async vote(language, validated, invalidated) {
const list = [...validated, ...invalidated].map(sentence => sentence.id);
const collection = await this.getCollection(language);
const result = await collection.listRecords({
filters: {
in_id: list
},
});
const records = result.data;
const existing = records.reduce((accum, record) => {
accum[record.id] = record;
return accum;
}, {});
const results = await collection.batch(c => {
let updateRecords = [
...this.getVoteRecords(true, validated, existing),
...this.getVoteRecords(false, invalidated, existing),
];
updateRecords.forEach(record => {
c.updateRecord(record, {
safe: true,
last_modified: record.last_modified,
});
});
});
let votes = [];
let errors = [];
results.forEach(result => {
if (result.status === 200 || result === 201) {
votes.push(result.body.data);
} else {
console.error('vote error', result.status, result.body);
errors.push(result);
}
});
return {
votes,
errors,
};
}
async count(language) {
let collection = await this.getCollection(language);
return collection.getTotalRecords();
}
async getAlreadyExistingSubset(language, sentences) {
const idList = sentences.map(s => hash(s));
const result = await this.getAll(language);
const existingIDs = result.map((existingSentence) => existingSentence.id);
const existingSubmittedSentencesIDs = idList.filter((id) => existingIDs.includes(id));
return result.filter((existingSentence) => existingSubmittedSentencesIDs.includes(existingSentence.id));
}
async getMySentences(language) {
const collection = await this.getCollection(language);
const result = await collection.listRecords({
filters: {
username: this.username,
},
});
return result.data;
}
}
SentencesMeta.NAME = NAME;