-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcorpus.js
More file actions
498 lines (472 loc) · 18.1 KB
/
corpus.js
File metadata and controls
498 lines (472 loc) · 18.1 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
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
const { couchKeys } = require('config');
const debug = require('debug')('lib:corpus');
const url = require('url');
const { Corpus } = require('fielddb/api/corpus/Corpus');
const { CorpusMask } = require('fielddb/api/corpus/CorpusMask');
const { DataList } = require('fielddb/api/data_list/DataList');
const { Team } = require('fielddb/api/user/Team');
const { UserMask } = require('fielddb/api/user/UserMask');
const uuid = require('uuid');
const nano = require('nano');
/* variable for permissions */
const commenter = 'commenter';
const collaborator = 'reader';
const contributor = 'writer';
const admin = 'admin';
// Only create users on the same server.
const parsed = url.parse('http://localhost:5984');
const couchConnectUrl = `${parsed.protocol}//${couchKeys.username}:${couchKeys.password}@${parsed.host}`;
debug('Using corpus url: ', couchConnectUrl);
function addRoleToUserInfo({
connection,
userPermission: userPermissionOriginal,
req = {
body: {},
id: '',
},
}) {
const userPermission = {
...userPermissionOriginal,
};
debug(`${new Date()} In addRoleToUser ${JSON.stringify(userPermission)} to ${userPermission.username} on ${connection.dbname}`);
const db = nano({
headers: {
'x-request-id': req.id,
},
url: couchConnectUrl,
}).use('_users');
const userid = `org.couchdb.user:${userPermission.username}`;
return db.get(userid)
.then((body) => {
const userold = body;
debug(`userold ${userPermission.username}`, userold);
const userRoles = {};
userold.roles.forEach((dbRole) => {
const dbname = dbRole.substring(0, dbRole.lastIndexOf('_'));
const role = dbRole.substring(dbRole.lastIndexOf('_') + 1);
userRoles[dbname] = userRoles[dbname] || {};
userRoles[dbname][role] = true;
});
userPermission.before = Object.keys(userRoles[connection.dbname] || {});
debug(' userRoles parsed', userRoles);
debug(`${new Date()} These are the users's roles before adding/removing roles.${JSON.stringify(userold.roles)}`);
if (userPermission.add && userPermission.add.length) {
userPermission.add.forEach((dbRole) => {
const dbname = dbRole.substring(0, dbRole.lastIndexOf('_'));
const role = dbRole.substring(dbRole.lastIndexOf('_') + 1);
userRoles[dbname] = userRoles[dbname] || {};
userRoles[dbname][role] = true;
});
}
if (userPermission.remove && userPermission.remove.length) {
userPermission.remove.forEach((dbRole) => {
const dbname = dbRole.substring(0, dbRole.lastIndexOf('_'));
const role = dbRole.substring(dbRole.lastIndexOf('_') + 1);
if (role === 'all') {
delete userRoles[connection.dbname];
return;
}
if (!userRoles[dbname]) {
return;
}
delete userRoles[dbname][role];
});
}
userPermission.after = Object.keys(userRoles[connection.dbname] || {});
userold.roles = Object.keys(userRoles).reduce((accumulator, dbname) => {
const roles = Object.keys(userRoles[dbname]).map((role) => `${dbname ? `${dbname}_` : ''}${role}`);
debug('roles for this db', dbname, roles);
return accumulator.concat(roles);
},
[]).sort();
debug(`${new Date()} These are the users's roles on ${connection.dbname} after adding/removing roles.${JSON.stringify(userold.roles)}`);
return db.insert(userold)
.then(() => (userPermission));
})
.then((userPermissionResult) => {
debug(`${new Date()} User roles updated.`, userPermissionResult);
return { userPermissionResult };
})
.catch((err) => {
debug({ err, userPermission }, `${new Date()} failed to change ${userPermission.username} user's roles due to couchdb error`);
throw err;
});
}
// Add docs to new database
function createPlaceholderDocsForCorpus({
req = {
body: {},
id: '',
},
user: userOriginal,
corpusObject,
}) {
const user = {
...userOriginal,
};
// Create connection and activityConnection based on server
let { appbrand } = req.body;
if (!appbrand && req.body.username) {
if (req.body.username.indexOf('test') > -1) {
appbrand = 'beta';
} else if (req.body.username.indexOf('anonymouskartulispeechrecognition') === 0) {
appbrand = 'kartulispeechrecognition';
} else if (req.body.username.search(/anonymous[0-9]/) === 0) {
appbrand = 'georgiantogether';
} else if (req.body.username.search(/anonymouswordcloud/) === 0) {
appbrand = 'wordcloud';
} else {
appbrand = 'lingsync';
}
}
debug('createPlaceholderDocsForCorpus appbrand', appbrand);
const corpusDetails = new Corpus(Corpus.prototype.defaults);
corpusDetails.merge('self', new Corpus(corpusObject), 'overwrite');
corpusDetails.connection.corpusid = corpusDetails.id;
corpusDetails.dateCreated = Date.now();
// TODO this has to be come asynchonous if this design is a central server who can register users on other servers
// const connection = new Connection(req.body.connection
// || req.body.couchConnection) || Connection.defaultConnection(appbrand);
if (!corpusDetails.connection.dbname || corpusDetails.connection.dbname === `${req.body.username}-firstcorpus`) {
corpusDetails.connection.dbname = `${req.body.username}-firstcorpus`;
if (appbrand === 'phophlo') {
corpusDetails.connection.dbname = `${req.body.username}-phophlo`;
}
if (appbrand === 'kartulispeechrecognition') {
corpusDetails.connection.dbname = `${req.body.username}-kartuli`;
}
if (appbrand === 'georgiantogether') {
corpusDetails.connection.dbname = `${req.body.username}-kartuli`;
}
// corpusDetails.connection.dbname = corpusDetails.connection.dbname;
/* Set gravatar using the user's registered email, or username if none */
/* Prepare a private corpus doc for the user's first corpus */
}
corpusDetails.dbname = corpusDetails.connection.dbname;
if (!corpusDetails.title) {
corpusDetails.title = 'Practice Corpus';
if (appbrand === 'phophlo') {
corpusDetails.title = 'Phophlo';
}
if (appbrand === 'georgiantogether') {
corpusDetails.title = 'Geogian';
}
if (appbrand === 'kartulispeechrecognition') {
corpusDetails.title = 'Kartuli Speech Recognition';
}
corpusDetails.connection.title = corpusDetails.title;
if (appbrand === 'phophlo') {
corpusDetails.description = 'This is your Phophlo database, here you can see your imported class lists and participants results. You can share your database with others by adding them to your team as readers, writers, commenters or admins on your database.';
}
if (appbrand === 'georgiantogether') {
corpusDetails.description = 'This is your Georgian database, here you can see the lessons you made for your self. You can share your database with others by adding them to your team as readers, writers, commenters or admins on your database.';
}
if (appbrand === 'kartulispeechrecognition') {
corpusDetails.description = 'This is your personal database, here you can see the sentences you made for your own speech recognition system trained to your voice and vocabulary. You can share your database with others by adding them to your team as readers, writers, commenters or admins on your database.';
}
}
const corpusMaskDetails = new CorpusMask({
connection: corpusDetails.connection,
corpusid: corpusDetails.id,
dateCreated: Date.now(),
dbname: corpusDetails.dbname,
description: corpusDetails.description,
gravatar: corpusDetails.gravatar,
});
corpusDetails.corpusMask = corpusMaskDetails;
const datalistDetails = new DataList({
title: 'Default Datalist - Empty',
description: 'The app comes with a default datalist which is empty. Once you have data in your corpus, you can create a datalist using search. Imported data will also show up as a datalist. Datalists are lists of data which can be used to create handouts, export to LaTeX, or share with collaborators.',
dbname: corpusDetails.dbname,
dateCreated: Date.now(),
});
const sessionDetails = corpusDetails.newSession({
goal: 'Practice collecting linguistic utterances or words',
dbname: corpusDetails.dbname,
dateCreated: Date.now(),
});
const team = new Team({
affiliation: 'No public information available',
dateCreated: Date.now(),
description: 'No public information available',
gravatar: user.gravatar,
researchInterest: 'No public information available',
username: user.username,
});
corpusDetails.team = team;
corpusMaskDetails.team = team;
/* Prepare mostRecentIds so apps can load a most recent dashboard if applicable */
user.mostRecentIds = {
connection: corpusDetails.connection.toJSON(),
};
const usersPublicSelfForThisCorpus = new UserMask({
_id: user.username,
gravatar: user.gravatar,
username: user.username,
appbrand,
collection: 'users',
firstname: '',
lastname: '',
email: '',
researchInterest: 'No public information available',
affiliation: 'No public information available',
description: 'No public information available',
dateCreated: Date.now(),
});
usersPublicSelfForThisCorpus.corpora = [corpusMaskDetails.connection.toJSON()];
user.userMask = usersPublicSelfForThisCorpus;
const activityConnection = corpusDetails.connection.toJSON();
activityConnection.dbname = `${req.body.username}-activity_feed`;
const docsNeededForAProperFieldDBDatabase = [
team.toJSON(),
usersPublicSelfForThisCorpus.toJSON(),
corpusMaskDetails.toJSON(),
corpusDetails.toJSON(),
datalistDetails.toJSON(),
sessionDetails.toJSON(),
];
return docsNeededForAProperFieldDBDatabase;
}
/*
* This function creates a new db/corpus using parameters in the dbConnection
* object, which user it is for, as well as callbacks for success or error. It
* also builds out the default security settings (ie access control lists, roles
* and role based permissions for the user's corpus implemented as security
* settings on the created couchdb
*
* The corpus is composed of the dbname, prefixed with the user's username
*/
function createNewCorpus({
_id,
connection,
dbname,
id,
req = {
id: '',
log: {
// eslint-disable-next-line no-console
warn: console.warn,
},
},
title,
user,
} = {}) {
debug('createNewCorpus', connection);
const corpusObject = {
dbname,
connection,
id,
_id,
title,
};
if (corpusObject.dbname) {
corpusObject.connection.dbname = corpusObject.dbname;
} else {
corpusObject.dbname = corpusObject.connection.dbname;
}
// eslint-disable-next-line no-underscore-dangle
if (!corpusObject.id && !corpusObject._id) {
corpusObject.id = uuid.v4();
}
debug(`${new Date()} Creating new database ${corpusObject.dbname}`);
const securityParamsforNewDB = {
admins: {
names: [],
roles: ['fielddbadmin', `${corpusObject.dbname}_${admin}`],
},
members: {
names: [],
roles: [
`${corpusObject.dbname}_${collaborator}`,
`${corpusObject.dbname}_${contributor}`,
`${corpusObject.dbname}_${commenter}`, // TODO this used to be missing on the first corpus
],
},
};
const docsNeededForAProperFieldDBCorpus = createPlaceholderDocsForCorpus({ corpusObject, user, req });
const server = nano({
headers: {
'x-request-id': req.id || '',
},
url: couchConnectUrl,
});
const newDatabase = nano({
headers: {
'x-request-id': req.id || '',
},
url: couchConnectUrl,
}).use(corpusObject.dbname);
return server.db.create(corpusObject.dbname)
.then((response) => {
debug(`Created db ${corpusObject.dbname}`, response);
/**
* Upon success of db creation, set up the collaborator, contributor
* and admin roles for this corpus
*/
return addRoleToUserInfo({
connection: corpusObject.connection,
userPermission: {
username: user.username,
add: [
`${corpusObject.connection.dbname}_${admin}`,
`${corpusObject.connection.dbname}_${contributor}`,
`${corpusObject.connection.dbname}_${collaborator}`,
`${corpusObject.connection.dbname}_${commenter}`,
],
},
req,
})
.then((roleResult) => {
debug('roleResult', roleResult);
return newDatabase.insert(securityParamsforNewDB, '_security');
})
.catch((couchDBError) => {
debug(`${new Date()} Did not add user security roles.`, couchDBError);
})
.then((couchResponse) => {
debug(`${new Date()} Added user security roles to new db.`, couchResponse);
let sourceDB = 'new_corpus';
if (user.whichUserGroup && user.whichUserGroup === 'betatesters') {
sourceDB = 'new_testing_corpus';
}
debug('usig sourceDB', sourceDB);
return server.db.replicate(sourceDB, corpusObject.dbname);
})
.catch((couchDBError) => {
debug(`${new Date()} Corpus replication failed.`, couchDBError);
})
// Replicate template databases to new database
.then((couchResponse) => {
debug(`${new Date()} Corpus successfully replicated.`, couchResponse);
return server.db.replicate('new_lexicon', corpusObject.dbname);
})
.catch((couchDBError) => {
debug(`${new Date()} Lexicon replication failed.`, couchDBError);
})
.then((couchResponse) => {
debug(`${new Date()} Lexicon successfully replicated.`, couchResponse);
// server.db.replicate('new_export', corpusObject.dbname, function(err, couchResponse) {
// if (!err) {
// debug(new Date() + " Export successfully replicated.", couchResponse);
// } else {
// debug(new Date() + " Export replication failed.");
// }
// });
return newDatabase.bulk({
docs: docsNeededForAProperFieldDBCorpus,
});
})
.catch((couchDBError) => {
req.log.warn(couchDBError, `${new Date()} There was an couchDBErroror in creating the docs for the user's new corpus:`);
// undoCorpusCreation(user, corpusDetails.corpusObject.connection, docsNeededForAProperFieldDBCorpus);
})
.then((couchResponse) => {
debug(`${new Date()} Created starter docs for ${corpusObject.dbname}`, couchResponse);
// Replicate activity feed template to new activity feed database
return server.db.replicate('new_corpus_activity_feed', `${corpusObject.dbname}-activity_feed`, {
create_target: true,
});
})
.catch((couchDBError) => {
debug(`${new Date()} Corpus activity feed replication failed.`, couchDBError);
})
.then((couchActivityFeedResponse) => {
debug(`${new Date()} Corpus activity feed successfully replicated.`, couchActivityFeedResponse);
// Set up security on new corpus activity feed
const activityDb = nano({
headers: {
'x-request-id': req.id,
},
url: couchConnectUrl,
}).use(`${corpusObject.dbname}-activity_feed`);
return activityDb.insert(securityParamsforNewDB, '_security');
})
.catch((couchDBError) => {
debug(`${new Date()} Did not add user security roles to new activity feed.`, couchDBError);
})
.then((couchResponse) => {
debug(`${new Date()} Added user security roles to new activity feed.`, couchResponse);
return {
corpusDetails: docsNeededForAProperFieldDBCorpus[2],
info: {},
};
});
})
// TODO Add corpus created activity to activity feeds
.catch((errOriginal) => {
const err = {
...errOriginal,
};
debug('createNewCorpus', err);
// Clean the error of couchdb leaks
delete err.request;
delete err.headers;
err.status = err.status || err.statusCode || 500;
if (err.status === 412) {
err.status = 302;
err.corpusexisted = true;
err.userFriendlyErrors = [
`Your corpus ${corpusObject.dbname} already exists, no need to create it.`,
];
} else {
err.userFriendlyErrors = ['The server was unable to complete this request. Please report this.'];
}
throw err;
});
}
/*
* Ensures the requesting user to make the permissions
* modificaitons, can be used for any corpus operations which require admin privildages.
*/
function isRequestingUserAnAdminOnCorpus({
connection,
req = {
body: {},
id: '',
},
username,
}) {
if (!connection) {
const err = new Error('Client didn\'t define the database connection.');
err.status = 412;
err.userFriendlyErrors = ['This app has made an invalid request. Please notify its developer. missing: serverCode or connection'];
return Promise.reject(err);
}
/*
* Check to see if the user is an admin on the corpus
*/
const nanoforpermissions = nano({
headers: {
'x-request-id': req.id || '',
},
url: couchConnectUrl,
});
const usersdb = nanoforpermissions.db.use('_users');
return usersdb.get(`org.couchdb.user:${username}`)
.then((result) => {
const userIsAdminOnTeam = result.roles.includes(`${connection.dbname}_admin`);
if (userIsAdminOnTeam) {
return { ok: true };
}
debug('isRequestingUserAnAdminOnCorpus userroles', username, connection.dbname, userIsAdminOnTeam, result.roles);
const err = new Error(`User ${username} found but didnt have permission on ${connection.dbname}`);
err.status = 401;
err.userFriendlyErrors = ["You don't have permission to perform this action."];
throw err;
})
.catch((errOriginal) => {
const err = {
message: errOriginal.message,
status: errOriginal.status || errOriginal.statusCode,
userFriendlyErrors: ['There was a problem deciding if you have permission to do this.'],
...errOriginal,
};
throw err;
});
}
module.exports = {
createPlaceholderDocsForCorpus,
createNewCorpus,
addRoleToUserInfo,
isRequestingUserAnAdminOnCorpus,
};