forked from social-media-testdrive/truman_testdrive
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpopulate.js
364 lines (324 loc) · 13.6 KB
/
populate.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
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
#! /usr/bin/env node
console.log('Started data loading script !!');
var async = require('async')
var Actor = require('./models/Actor.js');
var User = require('./models/User.js');
var Script = require('./models/Script.js');
var Notification = require('./models/Notification.js');
const _ = require('lodash');
const dotenv = require('dotenv');
var mongoose = require('mongoose');
var fs = require('fs')
const CSVToJSON = require("csvtojson");
//input files
/********
TODO:
Use CSV files instead of json files
use a CSV file reader and use that as input
********/
var actors_list //= require('./input/actors.json');
var posts_list //= require('./input/posts.json');
var comment_list //= require('./input/comments.json');
async function readData() {
try {
//synchronously read all csv files and convert them to JSON
await console.log("Start reading data from .csv files")
actors_list = await CSVToJSON().fromFile('./input/bots.csv');
posts_list = await CSVToJSON().fromFile('./input/allposts.csv');
comment_list = await CSVToJSON().fromFile('./input/allreplies.csv');
//synchronously write all converted JSON output to .json files incase for future use
// fs.writeFileSync("./input/bots.json", JSON.stringify(actors_list));
// fs.writeFileSync("./input/allposts.json", JSON.stringify(posts_list));
// fs.writeFileSync("./input/allreplies.json", JSON.stringify(comment_list));
await console.log("Converted data to json")
} catch (err) {
console.log('Error occurred in reading data from csv files', err);
}
}
dotenv.config({ path: '.env' });
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
//var connection = mongo.connect('mongodb://127.0.0.1/test');
mongoose.connect(process.env.PRO_MONGODB_URI, { useNewUrlParser: true });
var db = mongoose.connection;
mongoose.connection.on('error', (err) => {
console.error(err);
console.log('%s MongoDB connection error. Please make sure MongoDB is running.');
process.exit(1);
});
/*
drop existing collections before loading
to make sure we dont overwrite the data
in case we run the script twice or more
*/
function dropCollections() {
db.collections['actors'].drop(function (err) {
console.log('actors collection dropped');
});
db.collections['scripts'].drop(function (err) {
console.log('scripts collection dropped');
});
// db.collections['users'].drop(function (err) {
// console.log('users collection dropped');
// });
}
//capitalize a string
String.prototype.capitalize = function () {
return this.charAt(0).toUpperCase() + this.slice(1);
}
//usuful when adding comments to ensure they are always in the correct order
//(based on the time of the comments)
function insert_order(element, array) {
array.push(element);
array.sort(function (a, b) {
return a.time - b.time;
});
return array;
}
//Transforms a time like -12:32 (minus 12 minutes and 32 seconds)
//into a time in milliseconds
function timeStringToNum(v) {
var timeParts = v.split(":");
if (timeParts[0] == "-0")
return -1 * parseInt(((timeParts[0] * (60000 * 60)) + (timeParts[1] * 60000)), 10);
else if (timeParts[0].startsWith('-'))
return parseInt(((timeParts[0] * (60000 * 60)) + (-1 * (timeParts[1] * 60000))), 10);
else if (timeParts.length == 3)
return parseInt(((timeParts[0] * (60000 * 60)) + (timeParts[1] * 60000) + (timeParts[2] * 1000)), 10);
else
return parseInt(((timeParts[0] * (60000 * 60)) + (timeParts[1] * 60000)), 10);
};
//create a radom number (for 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];
}
function randomIntFromInterval(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
//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];
}
//Create a random number between two values (like when a post needs a number of times it has been read)
function getReads(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
/*************************
createActorInstances:
Creates all the Actors in the simulation
Must be done first!
*************************/
function createActorInstances() {
async.each(actors_list, function (actor_raw, callback) {
actordetail = {};
actordetail.profile = {};
actordetail.profile.name = actor_raw.name
actordetail.profile.location = actor_raw.location;
actordetail.profile.picture = actor_raw.picture;
actordetail.profile.bio = actor_raw.bio;
actordetail.profile.age = actor_raw.age;
//actordetail.class = actor_raw.class;
actordetail.username = actor_raw.username;
var actor = new Actor(actordetail);
actor.save(function (err) {
if (err) {
console.log("Something went wrong!!!");
return -1;
}
console.log('New Actor: ' + actor.username);
callback();
});
},
function (err) {
//return response
console.log("All DONE WITH ACTORS!!!")
return 'Loaded Actors'
}
);
}
/*************************
createPostInstances:
Creates each post and uploads it to the DB
Actors must be in DB first to add them correctly to the post
*************************/
function createPostInstances() {
async.each(posts_list, function (new_post, callback) {
Actor.findOne({ username: new_post.actor }, (err, act) => {
if (err) { console.log("createPostInstances error"); console.log(err); return; }
// console.log("start post for: "+new_post.id);
if (act) {
// console.log('Looking up Actor username is : ' + act.username);
var postdetail = new Object();
postdetail.module = new_post.module;
postdetail.type = new_post.type;
postdetail.body = new_post.body;
postdetail.info_text = new_post.info_text;
postdetail.likes = new_post.likes || getLikes();
//only for likes posts
postdetail.post_id = new_post.id;
postdetail.class = new_post.type;
postdetail.picture = new_post.picture;
postdetail.lowread = getReads(6, 20);
postdetail.highread = getReads(145, 203);
postdetail.actor = act;
postdetail.time = timeStringToNum(new_post.time);
console.log('Looking up Actor: ' + act.username);
//console.log(mongoose.Types.ObjectId.isValid(postdetail.actor.$oid));
//console.log(postdetail);
var script = new Script(postdetail);
script.save(function (err) {
if (err) {
console.log("Something went wrong in Saving POST!!!");
// console.log(err);
callback(err);
}
// console.log('Saved New Post: ' + script.id);
callback();
});
}//if ACT
else {
//Else no ACTOR Found
console.log("No Actor Found!!!");
callback();
}
// console.log("BOTTOM OF SAVE");
});
},
function (err) {
if (err) {
console.log("END IS WRONG!!!");
// console.log(err);
callback(err);
}
//return response
console.log("All DONE WITH POSTS!!!")
return 'Loaded Posts'
//mongoose.connection.close();
}
);
}
/*************************
createPostRepliesInstances:
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, in correct order
Takes a while because of this
*************************/
function createPostRepliesInstances() {
async.eachSeries(comment_list, function (new_replies, callback) {
// console.log("start REPLY for: "+new_replies.id);
Actor.findOne({ username: new_replies.actor }, (err, act) => {
if (act) {
Script.findOne({ post_id: new_replies.reply }, function (err, pr) {
if (pr) {
// console.log('Looking up Actor ID is : ' + act._id);
// console.log('Looking up OP POST ID is : ' + pr._id);
var comment_detail = new Object();
//postdetail.actor = {};
comment_detail.body = new_replies.body
comment_detail.commentID = new_replies.id;
//comment_detail.class = new_replies.class;
comment_detail.module = new_replies.module;
comment_detail.likes = getLikesComment();
comment_detail.time = timeStringToNum(new_replies.time);
/*1 hr is 3600000
console.log('Time is of POST is: ' + pr.time);
let comment_time = pr.time + randomIntFromInterval(300000,3600000)
console.log('New Comment time is: ' + comment_time);
comment_detail.time = comment_time;
console.log('NEW NON BULLY Time is : ' + comment_detail.time);
console.log('NEW Time is : ' + comment_detail.time);*/
// console.log('Adding in Actor: ' + act.username);
comment_detail.actor = act;
//pr.comments = insert_order(comment_detail, pr.comments);
//console.log('Comment'+comment_detail.commentID+' on Post '+pr.post_id+' Length before: ' + pr.comments.length);
pr.comments.push(comment_detail);
pr.comments.sort(function (a, b) { return a.time - b.time; });
//console.log('Comment'+comment_detail.commentID+' on Post '+pr.post_id+' Length After: ' + pr.comments.length);
//var script = new Script(postdetail);
pr.save(function (err) {
if (err) {
console.log("@@@@@@@@@@@@@@@@Something went wrong in Saving COMMENT!!!");
console.log("Error IN: " + new_replies.id);
// console.log('Looking up Actor: ' + act.username);
// console.log('Looking up OP POST ID: ' + pr._id);
// console.log('Time is : ' + new_replies.time);
// console.log('NEW Time is : ' + comment_detail.time);
// console.log(err);
callback(err);
}
console.log('Added new Comment to Post: ' + pr.id);
callback();
});
}// if PR
else {
//Else no ACTOR Found
console.log("############Error IN: " + new_replies.id);
console.log("No POST Found!!!");
callback();
}
});//Script.findOne
}//if ACT
else {
//Else no ACTOR Found
console.log("****************Error IN: " + new_replies.id);
console.log("No Actor Found!!!");
callback();
}
// console.log("BoTTom REPLY for: "+new_replies.id);
// console.log("BOTTOM OF SAVE");
});
},
function (err) {
if (err) {
console.log("END IS WRONG!!!");
console.log(err);
callback(err);
}
//return response
console.log("All DONE WITH REPLIES/Comments!!!")
mongoose.connection.close();
return 'Loaded Post Replies/Comments'
}
);
}
/*
promisify function will convert a function call to promise
which will eventually resolve when function completes its execution,
additionally it will wait for 2 seconds before starting.
*/
function promisify(inputFunction) {
return new Promise(resolve => {
setTimeout(() => {
resolve(inputFunction());
}, 2000);
});
}
/*
TODO: Async function that runs
all these functions in serial, in this order
Once all done, stop the program (Be sure to close the mongoose connection)
*/
async function loadDatabase() {
try {
await readData(); //read data from csv files and convert it to json for loading
await promisify(dropCollections); //drop existing collecions before loading data
await promisify(createActorInstances);
await promisify(createPostInstances);
await promisify(createPostRepliesInstances);
} catch (err) {
console.log('Error occurred in Loading', err);
}
}
// createActorInstances()
// createPostInstances()
// createPostRepliesInstances()
loadDatabase()