forked from uriahsanders/Sasasame
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sasame.js
5659 lines (5541 loc) · 204 KB
/
sasame.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
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const express = require('express');
const fileUpload = require('express-fileupload');
const querystring = require('querystring');
const bcrypt = require('bcrypt');
const mongoose = require('mongoose');
const bodyParser = require("body-parser");
const helmet = require('helmet');
const cors = require("cors");
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
require('dotenv').config();
const PORT = process.env.PORT || 3000;
var http = require('http');
const https = require('https');
var compression = require('compression');
const { promisify } = require('util');
const request = promisify(require('request'));
const browser = require('browser-detect');
var ffmpeg = require('fluent-ffmpeg');
const axios = require("axios"); //you can use any http client
// const tf = require("@tensorflow/tfjs-node");
// const nsfw = require("nsfwjs");
var fs = require('fs');
const fsp = require('fs').promises;
//for daemons access to help code
function DAEMONLIBS(passage, USERID){
return `
var THIS = `+JSON.stringify(passage)+`;
var USERID = "`+(USERID)+`";
// async function INTERACT(content){
// const result = await $.ajax({
// type: 'post',
// url: '`+process.env.DOMAIN+`/interact',
// data: {
// _id: _id
// }});
// return result;
// }
async function GETDAEMON(daemon, param){
var passage = await GETPASSAGE(daemon);
var code = passage.code;
var parameter = await GETPASSAGE(param);
//add Param Line
code = "const PARAM = " + JSON.stringify(parameter) + ';' + code;
//then eval code
return code;
}
async function GETPASSAGE(_id){
//run ajax
const result = await $.ajax({
type: 'get',
url: '`+process.env.DOMAIN+`/get_passage',
data: {
_id: _id
}});
return result;
}
`;
}
// Models
const User = require('./models/User');
const Passage = require('./models/Passage');
const Interaction = require('./models/Interaction');
const Category = require('./models/Category');
const Subcat = require('./models/Subcat');
const Subforum = require('./models/Subforum');
const Visitor = require('./models/Visitor');
const Follower = require('./models/Follower');
const Notification = require('./models/Notification');
const Star = require('./models/Star');
// Controllers
const passageController = require('./controllers/passageController');
// Routes
// const passageRoutes = require('./routes/passage');
var fs = require('fs');
var path = require('path');
const { exec } = require('child_process');
const { v4 } = require('uuid');
const FormData = require('form-data');
const writeFile = promisify(fs.writeFile);
const readdir = promisify(fs.readdir);
//pagination for home and profile
const DOCS_PER_PAGE = 10; // Documents per Page Limit (Pagination)
// Database Connection Setup
mongoose.connect(process.env.MONGODB_CONNECTION_URL, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
}).then(() => {
console.log('Connected to MongoDB');
}).catch((err) => {
console.error('MongoDB connection error:', err);
// Implement proper cleanup
process.exit(1);
});
var app = express();
var server = http.Server(app);
//socket io
const io = require('socket.io')(server);
const BKP = require('mongodb-snapshot');
async function mongoSnap(path, restore = false) {
console.log("TEST");
const mongo_connector = new BKP.MongoDBDuplexConnector({
connection: { uri: process.env.MONGODB_CONNECTION_URL, dbname: 'sasame' }
});
const localfile_connector = new BKP.LocalFileSystemDuplexConnector({
connection: { path: path }
});
const transferer = restore ?
new BKP.MongoTransferer({ source: localfile_connector, targets: [mongo_connector] }) :
new BKP.MongoTransferer({ source: mongo_connector, targets: [localfile_connector] }) ;
for await (const { total, write } of transferer) { }
}
// const io = require("socket.io")(server, {
// cors: {
// origin: "https://example.com",
// methods: ["GET", "POST"],
// allowedHeaders: ["my-custom-header"],
// credentials: true
// }
// });
app.use(express.urlencoded({ extended: false, limit: '1gb' }));
app.use(compression());
app.use(cors());
app.use(helmet());
app.use(fileUpload());
const labelOptions = [
"Project",
'Idea',
'Database',
"Social",
"Question",
"Comment",
"Task",
"Forum"
];
// make sure recordings folder exists
const recordingFolder = './dist/recordings/';
if (!fs.existsSync(recordingFolder)) {
fs.mkdirSync(recordingFolder);
}
// Setup Frontend Templating Engine - ejs
const ejs = require('ejs');
// app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.json({
verify: function (req, res, buf) {
var url = req.originalUrl;
if (url.startsWith('/stripe')) {
req.rawBody = buf.toString();
}
}
}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
const MongoStore = require('connect-mongo');
// User Session Setup Logic
// const session = require('express-session')({
// secret: "ls",
// resave: true,
// saveUninitialized: true,
// store: MongoStore.create({ mongoUrl: process.env.MONGODB_CONNECTION_URL })
// });
const session = require('express-session')({
secret: "ls",
resave: false,
saveUninitialized: false,
store: MongoStore.create({
mongoUrl: process.env.MONGODB_CONNECTION_URL,
ttl: 24 * 60 * 60, // 1 day TTL
autoRemove: 'native',
touchAfter: 24 * 3600 // Only update sessions every 24 hours
}),
cookie: {
maxAge: 24 * 60 * 60 * 1000 // 1 day
}
});
var sharedsession = require("express-socket.io-session");
const cookieParser = require('cookie-parser');
const nodemailer = require('nodemailer');
const scripts = {};
scripts.isPassageUser = function(user, passage){
if(typeof user == 'undefined'){
return false;
}
var ret;
if(user._id.toString() == passage.author._id.toString()){
return true;
}
var i = 0;
for(const u of passage.users){
if(u._id.toString() == user._id.toString()){
return true;
}
}
return false;
};
scripts.getCategoryTopicsNum = function (cat) {
var num = 0;
for(var c of cat.passages){
if(c.forumType != 'subforum'){
++num;
}
}
return num;
};
scripts.getNumPosts = function (cat){
var num = 0;
for(var c of cat.passages){
if(c.forumType != 'subforum'){
// ++num;
num += c.passages.length;
}
}
return num;
};
//for categories
scripts.lastPost = function(cat){
if(cat.passages && cat.passages.length > 0){
var passage = cat.passages.at(-1);
return 'by ' + passage.author.name + '<br>' + passage.date.toLocaleDateString();
}
else{
return 'No Posts Yet.'
}
};
scripts.getNumViews = async function(id){
var views = await Visitor.countDocuments({visited:id});
// if(views == '' || !views){
// return 0;
// }
return views;
}
scripts.getMaxToGiveOut = async function(){
let users = await User.find({stripeOnboardingComplete: true});
const maxAmountPerUser = 100; //ofc they can get more than this; this is just number for if they all had equal portion
var maxToGiveOut = maxAmountPerUser * users.length * 100;
var usd = parseInt(await totalUSD());
if(maxToGiveOut > usd){
usd = usd;
}
else if(maxToGiveOut < usd){
usd = maxToGiveOut;
}
return usd;
}
scripts.getBest = async function(passage){
return await getPassage(await Passage.findOne({parent: passage._id}, null, {sort: {stars: -1}}).populate('author users'));
};
scripts.getPassage = async function(passage){
return await getPassage(await Passage.findOne({parent: passage._id}, null, {sort: {stars: -1}}).populate('author users'));
};
app.use(cookieParser());
app.use(session);
io.use(sharedsession(session, {
autoSave: true
}));
// app.use('/protected/:pID', async function(req, res, next){
// if(!req.session.user){
// return res.redirect('/');
// }
// else{
// var passage = await Passage.findOne({filename:req.params.pID});
// if(passage != null)
// if(passage.author._id.toString() != req.session.user._id.toString() && !scripts.isPassageUser(req.session.user, passage)){
// return res.redirect('/');
// }
// }
// next();
// });
app.use(express.static('./dist'));
app.set('view engine', 'ejs');
app.set('views', './views');
function getUploadFolder(passage){
return passage.personal ? 'protected' : 'uploads';
}
app.use(async function(req, res, next) {
//shortcuts for ejs
res.locals.getUploadFolder = getUploadFolder;
res.locals.user = req.session.user;
res.locals.daemonLibs = DAEMONLIBS;
res.locals.DOMAIN = process.env.DOMAIN;
res.locals.LOCAL = process.env.LOCAL;
if(!req.session.CESCONNECT){
req.session.CESCONNECT = false;
}
res.locals.CESCONNECT = req.session.CESCONNECT;
res.locals.fromOtro = req.query.fromOtro || false;
//daemoncheck
if(['notifications', 'feed', 'posts', 'comments', 'subforums', 'profile', '', 'passage', 'messages', 'leaderboard', 'donate', 'filestream', 'loginform', 'personal', 'admin', 'forum', 'projects', 'tasks', 'recover', 'recoverpassword'].includes(req.url.split('/')[1])){
let daemons = [];
if(req.session.user){
let user = await User.findOne({_id: req.session.user._id}).populate('daemons');
regenerateSession(req);
daemons = user.daemons;
}
let defaults = await Passage.find({default_daemon: true}).populate('author users sourceList');
if(defaults.length > 0)
daemons = daemons.concat(defaults);
for(var i = 0; i < daemons.length; ++i){
daemons[i] = await getPassage(daemons[i]);
}
res.locals.DAEMONS = daemons;
}
next();
});
// UNDER CONSTRUCTION PAGE
// app.all('*', async (req, res) => {
// res.render('construction');
// });
//Serving Files
app.get('/jquery.min.js', function(req, res) {
res.sendFile(__dirname + '/node_modules/jquery/dist/jquery.min.js');
});
app.get('/jquery-ui.min.js', function(req, res) {
res.sendFile(__dirname + '/node_modules/jquery-ui-dist/jquery-ui.min.js');
});
app.get('/jquery-ui.css', function(req, res) {
res.sendFile(__dirname + '/node_modules/jquery-ui-dist/jquery-ui.css');
});
app.get('/jquery.modal.min.js', function(req, res) {
res.sendFile(__dirname + '/node_modules/jquery-modal/jquery.modal.min.js');
});
app.get('/jquery.modal.js', function(req, res) {
res.sendFile(__dirname + '/node_modules/jquery-modal/jquery.modal.js');
});
app.get('/jquery.modal.min.css', function(req, res) {
res.sendFile(__dirname + '/node_modules/jquery-modal/jquery.modal.min.css');
});
app.get('/data.json', function(req, res) {
res.sendFile(__dirname + '/data.json');
});
app.get('/ionicons.esm.js', function(req, res) {
res.sendFile(__dirname + '/node_modules/ionicons/dist/ionicons/ionicons.esm.js');
});
app.get('/ionicons.js', function(req, res) {
res.sendFile(__dirname + '/node_modules/ionicons/dist/ionicons/ionicons.js');
});
app.get('/p-9c97a69a.js', function(req, res) {
res.sendFile(__dirname + '/node_modules/ionicons/dist/ionicons/p-9c97a69a.js');
});
app.get('/p-c1aa32dd.entry.js', function(req, res) {
res.sendFile(__dirname + '/node_modules/ionicons/dist/ionicons/p-c1aa32dd.entry.js');
});
app.get('/p-85f22907.js', function(req, res) {
res.sendFile(__dirname + '/node_modules/ionicons/dist/ionicons/p-85f22907.js');
});
app.get('/quill.snow.css', function(req, res) {
res.sendFile(__dirname + '/node_modules/quill/dist/quill.snow.css');
});
app.get('/quill.min.js', function(req, res) {
res.sendFile(__dirname + '/node_modules/quill/dist/quill.min.js');
});
app.get('/highlight.css', function(req, res) {
res.sendFile(__dirname + '/node_modules/highlight.js/styles/a11y-light.css');
});
app.get('/highlight.js', function(req, res) {
res.sendFile(__dirname + '/node_modules/highlight.js/lib/index.js');
});
app.get('/caret-down.svg', function(req, res) {
res.send(__dirname + '/node_modules/ionicons/dist/svg/caret-down.svg');
});
//CRON
var cron = require('node-cron');
const { exit } = require('process');
const { response } = require('express');
const e = require('express');
const Message = require('./models/Message');
const { copyPassage } = require('./controllers/passageController');
const Bookmark = require('./models/Bookmark');
// const { getMode } = require('ionicons/dist/types/stencil-public-runtime');
//run monthly cron
cron.schedule('0 12 1 * *', async () => {
await rewardUsers();
console.log('Monthly Cron ran at 12pm.');
});
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth();
months += d2.getMonth();
return months <= 0 ? 0 : months;
}
//Get total star count and pay out users
async function rewardUsers(){
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
var usd = await scripts.getMaxToGiveOut();
for(const user of users){
//appropriate percentage based on stars
//users get same allotment as they have percentage of stars
let userUSD = parseInt((await percentStars(user.starsGiven)) * usd);
try{
const transfer = await stripe.transfers.create({
amount: userUSD,
currency: "usd",
destination: user.stripeAccountId,
});
}
catch(err){
console.log(err);
}
}
console.log("Users paid");
}
//get percentage of total stars
async function percentStars(user_stars){
let final = user_stars / (await totalStars());
return final;
}
//get percentage of total usd
async function percentUSD(donationUSD){
var amount = await totalUSD();
if(amount == 0){
return 1;
}
let final = donationUSD / (amount);
return final;
}
async function totalUSD(){
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const balance = await stripe.balance.retrieve();
var usd = 0;
for(const i of balance.available){
if(i.currency == 'usd'){
usd = i.amount;
break;
}
}
return usd;
}
async function totalStars(){
let users = await User.find({stripeOnboardingComplete: true});
if(users == false){
return 0;
}
var stars = 0;
for(const user of users){
stars += user.starsGiven;
}
return stars;
}
//function from string-similarity-js
//since i was having import issues
var stringSimilarity = function (str1, str2, substringLength, caseSensitive) {
if (substringLength === void 0) { substringLength = 2; }
if (caseSensitive === void 0) { caseSensitive = false; }
if (!caseSensitive) {
str1 = str1.toLowerCase();
str2 = str2.toLowerCase();
}
if (str1.length < substringLength || str2.length < substringLength)
return 0;
var map = new Map();
for (var i = 0; i < str1.length - (substringLength - 1); i++) {
var substr1 = str1.substr(i, substringLength);
map.set(substr1, map.has(substr1) ? map.get(substr1) + 1 : 1);
}
var match = 0;
for (var j = 0; j < str2.length - (substringLength - 1); j++) {
var substr2 = str2.substr(j, substringLength);
var count = map.has(substr2) ? map.get(substr2) : 0;
if (count > 0) {
map.set(substr2, count - 1);
match++;
}
}
return (match * 2) / (str1.length + str2.length - ((substringLength - 1) * 2));
};
function passageSimilarity(passage, source){
if(passage.lang == source.lang){
if(passage.lang == 'rich'){
return stringSimilarity(passage.content, source.content);
}
else if(passage.lang == 'mixed'){
return stringSimilarity(passage.html + passage.css + passage.javascript, source.html + source.css + source.javascript);
}
else{
return stringSimilarity(passage.code, source.code);
}
}
}
async function getLastSource(passage){
var source = await Passage.findOne({_id:passage.sourceList.at(-1)});
return source;
}
async function starPassage(req, amount, passageID, userID, deplete=true){
let user = await User.findOne({_id: userID});
//infinite stars on a local sasame
if(user.stars < amount && process.env.REMOTE == 'true'){
return "Not enough stars.";
}
if(deplete){
user.stars -= amount;
}
let passage = await Passage.findOne({_id: passageID}).populate('author sourceList');
var lastSource = await getLastSource(passage);
var bonus = 0;
//calculate bonus
for(const source of passage.sourceList){
if(passage.author._id.toString() != source.author._id.toString()){
var similarity = passageSimilarity(passage, source);
bonus += similarity > 0.1 ? similarity : 0;
}
}
// if(lastSource != null){
// bonus = passageSimilarity(passage, lastSource);
// }else{
// bonus = 0;
// }
// if(lastSource && lastSource.author._id.toString() == req.session.user._id.toString()){
// bonus = 0;
// }
//add stars to passage and sources
passage.stars += amount + bonus;
//star all sub passages (content is displayed in parent)
if(passage.bubbling && passage.passages && !passage.public){
for(const p of passage.passages){
//also star sources for each sub passage
passage.sourceList = [...passage.sourceList, ...p.sourceList];
await starPassage(req, amount, p._id, userID, false);
}
}
await starMessages(passage._id, amount);
//you have to star someone elses passage to get stars
if(passage.author._id.toString() != req.session.user._id.toString()){
user.starsGiven += amount;
if(passage.collaborators.length > 0){
passage.author.stars += (amount + bonus)/(passage.collaborators.length + 1);
}
else{
passage.author.stars += amount + bonus;
}
//give stars to collaborators if applicable
//split stars with collaborators
if(passage.collaborators.length > 0){
for(const collaborator in passage.collaborators){
if(collaborator == passage.author.email){
//we already starred the author
continue;
}
let collaber = await User.findOne({email:collaborator});
if(collaber != null){
collaber.stars += (amount + bonus)/(passage.collaborators.length + 1);
await collaber.save();
}
}
}
await passage.author.save();
}
await user.save();
await passage.save();
//star each source
var i = 0;
var authors = [];
//add sources for best,bestof,and mirror
if(passage.showBestOf){
var best = await Passage.findOne({parent: passage._id}, null, {sort: {stars: -1}});
if(best != null){
passage.sourceList.push(best);
}
}
else{
try{
var mirror = await Passage.findOne({_id:passage.mirror._id}).populate('parent author users sourceList subforums');
if(mirror != null)
passage.sourceList.push(mirror);
}
catch(e){
}
try{
var bestOf = await Passage.findOne({parent:passage.bestOf._id}).sort('-stars').populate('parent author users sourceList subforums');
if(bestOf != null)
passage.sourceList.push(bestOf);
}
catch(e){
}
}
//recursively star ssources
await starSources(passage, passage, [], amount, req);
return await fillUsedInListSingle(passage);
}
async function starSources(passage, top, authors=[], amount, req){
var i = 0;
var bonus;
for(const source of passage.sourceList){
await starMessages(source._id, amount);
let sourceAuthor = await User.findOne({_id: source.author._id});
//you won't get extra stars for citing your own work
//also star once per author
if(sourceAuthor._id.toString() != req.session.user._id.toString()
&& sourceAuthor._id.toString() != passage.author._id.toString()
/*&& !authors.includes(sourceAuthor._id)*/){
bonus = passageSimilarity(top, source);
source.stars += amount + bonus;
if(!authors.includes(sourceAuthor._id)){
sourceAuthor.stars += amount + bonus;
await sourceAuthor.save();
}
authors.push(sourceAuthor._id);
await source.save();
}
await starSources(source, passage, authors);
++i;
}
}
async function starMessages(passage, stars=1){
//keep message stars aligned with passage
var messages = await Message.find({passage: passage});
for(const message of messages){
message.stars += stars;
await message.save();
}
}
async function notifyUser(userId, content, type="General"){
let notification = await Notification.create({
user: userId,
content: content,
type: type
});
}
//basically messages
async function sharePassage(from, _id, username){
var user = await User.findOne({
username: username
});
var passage = await Passage.findOne({
_id: _id
});
if(user != null){
var message = await Message.create({
from: from,
to: user._id,
passage: _id,
title: passage.title
});
return 'Message Sent';
}
return 'User not Found.';
}
app.post('/share_passage', async(req, res) => {
res.send(await sharePassage(req.session.user._id, req.body.passageId, req.body.username));
});
app.get('/messages', async(req, res) => {
//paginate messages
//...TODO
//serve messages
//sort them by stars
var messages = await Message.find({
to: req.session.user._id,
passage: {
$ne: null
}
}).populate('passage').sort({stars:-1, _id:-1}).limit(DOCS_PER_PAGE);
messages = messages.filter(function(x){
return x.passage != null;
});
var passages = [];
for(const message of messages){
var p = await Passage.findOne({
_id: message.passage._id
}).populate('author users sourcelist');
passages.push(p);
}
for(var i = 0; i < passages.length; ++i){
passages[i] = await getPassage(passage);
}
let bookmarks = [];
// if(req.session.user){
// bookmarks = await User.find({_id: req.session.user._id}).populate('bookmarks').passages;
// }
if(req.session.user){
bookmarks = getBookmarks(req.session.user);
}
passages = await fillUsedInList(passages);
res.render('messages', {
passages: passages,
subPassages: false,
passageTitle: false,
scripts: scripts,
passage: {id:'root', author: {
_id: 'root',
username: 'Sasame'
}},
bookmarks: bookmarks,
});
});
//get highest rank passage with title
async function bestOf(title){
return await Passage.find({title:title, personal: false}).sort('-stars').limit(1)[0];
}
//get best passage in best module for passage
//hard to tell the difference from the above function
//still thinking about it...
//but this is better (more useful), I think...
async function bestOfPassage(title){
var parent = await Passage.find({title:title, public: true, personal: false}).sort('-stars').limit(1)[0];
if(parent != null){
var sub = await Passage.find({parent: parent._id, personal: false}).sort('-stars').limit(1);
return sub;
}
return 'No public passage "' + title + '"';
}
app.get('/bestOf/:title', async(req, res) => {
res.send(await bestOfPassage(req.params.title));
});
//ROUTES
app.get('/personal/:user_id', async (req, res) => {
if(!req.session.user || req.session.user._id != req.params.user_id){
return res.redirect('/');
}
else{
var passages = await Passage.find({
//author: req.params.user_id,
personal: true,
users: {
$in: [req.params.user_id]
}
}).populate('author users sourcelist parent versions').limit(DOCS_PER_PAGE);
for(var i = 0; i < passages.length; ++i){
passages[i] = await getPassage(passage);
}
let bookmarks = [];
// if(req.session.user){
// bookmarks = await User.find({_id: req.session.user._id}).populate('bookmarks').passages;
// }
if(req.session.user){
bookmarks = getBookmarks(req.session.user);
}
passages = await fillUsedInList(passages);
const ISMOBILE = browser(req.headers['user-agent']).mobile;
return res.render("stream", {
subPassages: false,
passageTitle: false,
scripts: scripts,
passages: passages,
page: 'personal',
passage: {id:'root', author: {
_id: 'root',
username: 'Sasame'
}},
bookmarks: bookmarks,
ISMOBILE: ISMOBILE,
whichPage: 'personal'
});
}
});
//GET (or show view)
app.get("/profile/:username?/:_id?/", async (req, res) => {
let bookmarks = [];
let profile;
if(typeof req.params.username == 'undefined' || !req.params._id){
if(!req.session.user){
return res.redirect('/');
}
profile = req.session.user;
}
else{
profile = await User.findOne({_id: req.params._id});
}
if(profile == null){
return res.redirect('/');
}
let find = {
//author: profile,
users: {
$in: [profile]
},
deleted: false,
personal: false
};
//if it's their profile show personal passages
// if(req.session.user && profile._id.toString() == req.session.user._id.toString()){
// find.$or = [{personal: true}, {personal: false}];
// }
let passages = await Passage.find(find).populate('author users sourceList').sort({stars: -1, _id: -1}).limit(DOCS_PER_PAGE);
for(var i = 0; i < passages.length; ++i){
passages[i] = await getPassage(passages[i]);
}
// if(req.session.user){
// bookmarks = await User.find({_id: req.session.user._id}).populate('passages').passages;
// }
if(req.session.user){
bookmarks = getBookmarks(req.session.user);
}
var usd = 0;
usd = parseInt((await percentStars(profile.starsGiven)) * (await scripts.getMaxToGiveOut()));
if(isNaN(usd)){
usd = 0;
}
passages = await fillUsedInList(passages);
var following;
if(req.session.user){
var follower = await Follower.findOne({
user: req.session.user._id,
following: profile._id
});
}
else{
var follower = null;
}
if(follower == null){
var followings = await Follower.find({});
console.log(followings);
console.log("Not Following");
following = false;
}
else{
following = true;
}
res.render("profile", {usd: (usd/100), subPassages: false, passages: passages, scripts: scripts, profile: profile,
bookmarks: bookmarks,
whichPage: 'profile',
thread: false,
following: following,
passage: {id:'root', author: {
_id: 'root',
username: 'Sasame'
}}
});
});
app.post('/follow', async (req, res) => {
var isFollowing = await Follower.findOne({
user: req.session.user,
following: req.body.who
});
if(isFollowing == null){
var following = await Follower.create({
user: req.session.user,
following: req.body.who
});
return res.send("Followed.");
}
else{
await Follower.deleteOne({
user: req.session.user,
following: req.body.who
});
}
return res.send("Unfollowed");
});
app.get('/notifications', async (req, res) => {
const ISMOBILE = browser(req.headers['user-agent']).mobile;
if(!req.session.user){
return res.redirect('/');
}
var notifications = await Notification.find({
for: req.session.user
}).sort({_id: -1}).limit(20);
if(req.session.user){
var bookmarks = getBookmarks(req.session.user);
}
return res.render('notifications', {
subPassages: false,
passageTitle: false,
scripts: scripts,
passages: [],
passage: {id:'root', author: {
_id: 'root',
username: 'Sasame'
}},
bookmarks: bookmarks,
ISMOBILE: ISMOBILE,
page: 'more',
whichPage: 'notifications',
notifications: notifications
});
});
app.get('/loginform', function(req, res){
res.render('login_register', {scripts: scripts});
});
app.post('/get_username_number', async function(req, res){
let name = req.body.name;
let number = await User.countDocuments({name:name.trim()}) + 1;
res.send(number + '');
});
//HOME/INDEX
app.get('/rex_login', async (req, res) => {
res.render('rex_login');
});
async function getFullPassage(_id){
//get fully populated passage as JSON
var passage = await Passage.findOne({_id: _id});
}
async function alternate(passageID, iteration, prevs){
console.log(iteration);
var passage = await Passage.findOne({_id: passageID});
var find = {
title: passage.title,
_id: {
$ne: passage._id
}
};
var numDocuments = await Passage.countDocuments(find);
if(iteration >= numDocuments){
return false;
}
var test = await Passage.find(find);
var alternate = await Passage.find(find).sort('-stars').populate('author users sourceList').skip(parseInt(iteration)).limit(1);
alternate = alternate[0];
return alternate;
}
app.get('/alternate', async(req, res) => {
//UPDATE TODO
//Okay, so, we need to get the _id of the parent passage
//then splice/replace in the alternate passage
//and then return the whole deal :)
//\UPDATE TODO
var parent = await Passage.findOne({_id: req.query.parentID});
var passage = await alternate(req.query.passageID, req.query.iteration, req.query.altPrevs);
if(!passage){
return res.send("restart");
}
console.log('?' + passage.content);
//return sub false rendered view of parent
//...
//I know and sorry this is a lot of duplicated code from passage view route
//but TODO will see if we can put all this into a function
var subPassages = await Passage.find({parent: parent._id, personal: false}).populate('author users sourceList');
//reorder sub passages to match order of passage.passages
var reordered = Array(subPassages.length).fill(0);
for(var i = 0; i < parent.passages.length; ++i){
for(var j = 0; j < subPassages.length; ++j){
if(subPassages[j]._id.toString() == parent.passages[i]._id.toString()){
reordered[i] = subPassages[j];
}
}
}
//idk why but sometimes in production there were extra 0s...
//need to test more and bugfix algorithm above
reordered = reordered.filter(x => x !== 0); //just get rid of extra 0s
if(parent.passages.length < 1){
reordered = subPassages;
}
parent.passages = reordered;
// if(parent._id.toString() == req.query.passageID){
// parent = passage[0];
// }
// else{
// parent.passages.forEach(function(p, i){
// if(i == req.query.position){
// parent.passages[i] = passage;
// }
// });
var i = 0;
for(const p of parent.passages){
if(i == req.query.position){
parent.passages[i] = passage;
}
++i;
}
// }
// if(typeof parent.passages != 'undefined' && parent.passages[0] != null){
// for(const p of parent.passages){
// parent.passages[p] = bubbleUpAll(p);
// }
// }
parent = await getPassage(parent);
if(parent.displayHTML.length > 0 || parent.displayCSS.length > 0 || parent.displayJavascript.length > 0){
parent.showIframe = true;
}
if(passage){
return res.render('passage', {
subPassages: parent.passages,
passage: parent,
sub: false,
altIteration: '_' + req.query.iteration
});
}
else{
return res.send('restart');
}
});
app.post('/save_alternate', async(req, res) => {
var original = await Passage.findOne({_id: req.body.passageID});
var passage = await passageController.copyPassage(original, [req.session.user], null, async function(){