-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpopulate.js
More file actions
394 lines (373 loc) · 18.7 KB
/
populate.js
File metadata and controls
394 lines (373 loc) · 18.7 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
const color_start = '\x1b[33m%s\x1b[0m'; // yellow
const color_success = '\x1b[32m%s\x1b[0m'; // green
const color_error = '\x1b[31m%s\x1b[0m'; // red
console.log(color_start, 'Started populate.js script...');
const async = require('async');
const Actor = require('./models/Actor.js');
const Script = require('./models/Script.js');
const Notification = require('./models/Notification.js');
const _ = require('lodash');
const dotenv = require('dotenv');
const mongoose = require('mongoose');
const CSVToJSON = require("csvtojson");
//Input Files
const actor_inputFile = './input/actors.csv';
const posts_inputFile = './input/posts.csv';
const replies_inputFile = './input/replies.csv';
const notifications_inputFile = './input/notifications (read, like).csv';
const notifications_replies_inputFile = './input/notifications (reply).csv';
// Variables to be used later.
var actors_list;
var posts_list;
var comment_list;
var notification_list;
var notification_reply_list;
dotenv.config({ path: '.env' });
mongoose.connect(process.env.MONGODB_URI || process.env.MONGOLAB_URI, { useNewUrlParser: true });
var db = mongoose.connection;
mongoose.connection.on('error', (err) => {
console.error(err);
console.log(color_error, '%s MongoDB connection error. Please make sure MongoDB is running.');
process.exit(1);
});
/*
This is a huge function of chained promises, done to achieve serial completion of asynchronous actions.
There's probably a better way to do this, but this worked.
*/
async function doPopulate() {
/****
Dropping collections
****/
let promise = new Promise((resolve, reject) => { //Drop the actors collection
console.log(color_start, "Dropping actors...");
db.collections['actors'].drop(function(err) {
console.log(color_success, 'Actors collection dropped');
resolve("done");
});
}).then(function(result) { //Drop the scripts collection
return new Promise((resolve, reject) => {
console.log(color_start, "Dropping scripts...");
db.collections['scripts'].drop(function(err) {
console.log(color_success, 'Scripts collection dropped');
resolve("done");
});
});
}).then(function(result) { //Drop the notifications collection
return new Promise((resolve, reject) => {
console.log(color_start, "Dropping notifications...");
db.collections['notifications'].drop(function(err) {
console.log(color_success, 'Notifications collection dropped');
resolve("done");
});
});
/***
Converting CSV files to JSON
***/
}).then(function(result) { //Convert the actors csv file to json, store in actors_list
return new Promise((resolve, reject) => {
console.log(color_start, "Reading actors list...");
CSVToJSON().fromFile(actor_inputFile).then(function(json_array) {
actors_list = json_array;
console.log(color_success, "Finished getting the actors_list");
resolve("done");
});
});
}).then(function(result) { //Convert the posts csv file to json, store in posts_list
return new Promise((resolve, reject) => {
console.log(color_start, "Reading posts list...");
CSVToJSON().fromFile(posts_inputFile).then(function(json_array) {
posts_list = json_array;
console.log(color_success, "Finished getting the posts list");
resolve("done");
});
});
}).then(function(result) { //Convert the comments csv file to json, store in comment_list
return new Promise((resolve, reject) => {
console.log(color_start, "Reading comment list...");
CSVToJSON().fromFile(replies_inputFile).then(function(json_array) {
comment_list = json_array;
console.log(color_success, "Finished getting the comment list");
resolve("done");
});
});
}).then(function(result) { //Convert the comments csv file to json, store in comment_list\
return new Promise((resolve, reject) => {
console.log(color_start, "Reading notification list...");
CSVToJSON().fromFile(notifications_inputFile).then(function(json_array) {
notification_list = json_array;
console.log(color_success, "Finished getting the notification list");
resolve("done");
});
});
}).then(function(result) { //Convert the notification reply csv file to json, store in comment_list\
return new Promise((resolve, reject) => {
console.log(color_start, "Reading notification reply list...");
CSVToJSON().fromFile(notifications_replies_inputFile).then(function(json_array) {
notification_reply_list = json_array;
console.log(color_success, "Finished getting the notification reply list");
resolve("done");
});
});
/*************************
Create all the Actors in the simulation
Must be done before creating any other instances
*************************/
}).then(function(result) {
console.log(color_start, "Starting to populate actors collection...");
return new Promise((resolve, reject) => {
async.each(actors_list, async function(actor_raw, callback) {
const actordetail = {
username: actor_raw.username,
profile: {
name: actor_raw.name,
gender: actor_raw.gender,
age: actor_raw.age,
location: actor_raw.location,
bio: actor_raw.bio,
picture: actor_raw.picture
},
class: actor_raw.class
};
const actor = new Actor(actordetail);
try {
await actor.save();
} catch (err) {
console.log(color_error, "ERROR: Something went wrong with saving actor in database");
next(err);
}
},
function(err) {
if (err) {
console.log(color_error, "ERROR: Something went wrong with saving actors in database");
callback(err);
}
// Return response
console.log(color_success, "All actors added to database!")
resolve('Promise is resolved successfully.');
return 'Loaded Actors';
}
);
});
/*************************
Create each post and upload it to the DB
Actors must be in DB first to add them correctly to the post
*************************/
}).then(function(result) {
console.log(color_start, "Starting to populate posts collection...");
return new Promise((resolve, reject) => {
async.each(posts_list, async function(new_post, callback) {
const act = await Actor.findOne({ username: new_post.actor }).exec();
if (act) {
const postdetail = {
postID: new_post.id,
body: new_post.body,
picture: new_post.picture,
likes: getLikes(),
actor: act,
time: timeStringToNum(new_post.time) || null,
class: new_post.class
}
const script = new Script(postdetail);
try {
await script.save();
} catch (err) {
console.log(color_error, "ERROR: Something went wrong with saving post in database");
next(err);
}
} else { //Else no actor found
console.log(color_error, "ERROR: Actor not found in database");
callback();
};
},
function(err) {
if (err) {
console.log(color_error, "ERROR: Something went wrong with saving posts in database");
callback(err);
}
// Return response
console.log(color_success, "All posts added to database!")
resolve('Promise is resolved successfully.');
return 'Loaded Posts';
}
);
});
/*************************
Creates inline comments for each post
Looks up actors and posts to insert the correct comment
Does this in series to insure comments are put in the correct order
Takes a while to run because of this.
*************************/
})
.then(function(result) {
console.log(color_start, "Starting to populate post replies...");
return new Promise((resolve, reject) => {
async.eachSeries(comment_list, async function(new_reply, callback) {
const act = await Actor.findOne({ username: new_reply.actor }).exec();
if (act) {
const pr = await Script.findOne({ postID: new_reply.postID }).exec();
if (pr) {
const comment_detail = {
commentID: new_reply.id,
body: new_reply.body,
likes: getLikesComment(),
actor: act,
time: timeStringToNum(new_reply.time),
class: new_reply.class
};
pr.comments.push(comment_detail);
pr.comments.sort(function(a, b) { return a.time - b.time; });
try {
await pr.save();
} catch (err) {
console.log(color_error, "ERROR: Something went wrong with saving reply in database");
next(err);
}
} else { //Else no post found
console.log(color_error, "ERROR: Post not found in database");
callback();
}
} else { //Else no actor found
console.log(color_error, "ERROR: Actor not found in database");
callback();
}
},
function(err) {
if (err) {
console.log(color_error, "ERROR: Something went wrong with saving replies in database");
callback(err);
}
// Return response
console.log(color_success, "All replies added to database!");
//mongoose.connection.close();
resolve('Promise is resolved successfully.');
return 'Loaded Replies';
}
);
});
/*************************
Creates each notification(replies) and uploads it to the DB
Actors must be in DB first to add them correctly to the post
*************************/
})
.then(function(result) {
console.log(color_start, "Starting to populate notifications (replies) collection...");
return new Promise((resolve, reject) => {
async.each(notification_reply_list, async function(new_notify, callback) {
const act = await Actor.findOne({ username: new_notify.actor }).exec();
if (act) {
const notifydetail = {
actor: act,
notificationType: 'reply',
time: timeStringToNum(new_notify.time),
userPostID: new_notify.userPostID,
replyBody: new_notify.body,
class: new_notify.class
};
const notify = new Notification(notifydetail);
try {
await notify.save();
} catch (err) {
console.log(color_error, "ERROR: Something went wrong with saving notification(reply) in database");
console.log(err);
next(err);
}
} else { //Else no actor found
console.log(color_error, "ERROR: Actor not found in database");
callback();
}
},
function(err) {
if (err) {
console.log(color_error, "ERROR: Something went wrong with saving notifications(replies) in database");
}
// Return response
console.log(color_success, "All notifications(replies) added to database!")
resolve('Promise is resolved successfully.');
return 'Loaded Notifications';
}
);
});
/*************************
Creates each notification(likes, reads) and uploads it to the DB
Actors must be in DB first to add them correctly to the post
*************************/
}).then(function(result) {
console.log(color_start, "Starting to populate notifications (likes, reads) collection...");
return new Promise((resolve, reject) => {
async.each(notification_list, async function(new_notify, callback) {
const act = await Actor.findOne({ username: new_notify.actor }).exec();
if (act) {
const notifydetail = {
actor: act,
notificationType: new_notify.type,
time: timeStringToNum(new_notify.time),
class: new_notify.class
};
if (new_notify.userPostID >= 0 && new_notify.userPostID) {
notifydetail.userPostID = new_notify.userPostID;
} else if (new_notify.userReplyID >= 0 && new_notify.userReplyID) {
notifydetail.userReplyID = new_notify.userReplyID;
} else if (new_notify.actorReply >= 0 && new_notify.actorReply) {
notifydetail.actorReply = new_notify.actorReply;
}
const notify = new Notification(notifydetail);
try {
await notify.save();
} catch (err) {
console.log(color_error, "ERROR: Something went wrong with saving notification(like, read) in database");
next(err);
}
} else { //Else no actor found
console.log(color_error, "ERROR: Actor not found in database");
callback();
}
},
function(err) {
if (err) {
console.log(color_error, "ERROR: Something went wrong with saving notifications in database");
callback(err);
}
// Return response
console.log(color_success, "All notifications added to database!")
mongoose.connection.close();
resolve('Promise is resolved successfully.');
return 'Loaded Notifications';
}
);
});
})
}
//capitalize a string
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
//Transforms a time like -12:32 (minus 12 hours and 32 minutes) into a time in milliseconds
//Positive numbers indicate future posts (after they joined), Negative numbers indicate past posts (before they joined)
//Format: (+/-)HH:MM
function timeStringToNum(v) {
var timeParts = v.split(":");
if (timeParts[0] == "-0")
// -0:XX
return -1 * parseInt(((timeParts[0] * (60000 * 60)) + (timeParts[1] * 60000)), 10);
else if (timeParts[0].startsWith('-'))
//-X:XX
return parseInt(((timeParts[0] * (60000 * 60)) + (-1 * (timeParts[1] * 60000))), 10);
else
return parseInt(((timeParts[0] * (60000 * 60)) + (timeParts[1] * 60000)), 10);
};
//Create a random number (for the number of likes) with a weighted distrubution
//This is for posts
function getLikes() {
var notRandomNumbers = [1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 6];
var idx = Math.floor(Math.random() * notRandomNumbers.length);
return notRandomNumbers[idx];
}
//Create a radom number (for likes) with a weighted distrubution
//This is for comments
function getLikesComment() {
var notRandomNumbers = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4];
var idx = Math.floor(Math.random() * notRandomNumbers.length);
return notRandomNumbers[idx];
}
//Call the function with the long chain of promises
doPopulate();