forked from Steem-FOSSbot/steem-fossbot-voter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
1287 lines (1245 loc) · 52.3 KB
/
server.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
lib = require("./lib.js"),
express = require("express"),
expressSession = require('express-session'),
path = require("path"),
bodyParser = require("body-parser"),
cookieParser = require('cookie-parser'),
Cookies = require('cookies'),
fs = require('fs'),
wait = require('wait.for'),
extra = require('./extra.js'),
moment_tz = require('moment-timezone'),
moment = require('moment'),
atob = require('atob'),
btoa = require('btoa');
var cookieSessionKey = "";
var html_algo_emptyList = "<tr><td>None</td><td></td><td>-</td><td>-</td><th><p><a class=\"btn btn-default\" href=\"#\" role=\"button\"><strike>Delete<strike></a></p></th></tr>";
var html_test_emptyList = "<tr><td>None</td><td>-</td>-<td></tr>";
var
html_msgPage1 = "",
html_msgPage2 = "",
html_msgPage3 = "",
html_dashboard1 = "",
html_dashboard2 = "",
html_dashboard3 = "",
html_dashboard4 = "",
html_editAlgo1 = "",
html_editAlgo2 = "",
html_editAlgo3 = "",
html_editAlgo4 = "",
html_testAlgo1 = "",
html_testAlgo2 = "",
html_stats1 = "",
html_stats2 = "",
html_stats3 = "",
html_stats_run1 = "",
html_stats_run2 = "",
html_stats_run3 = "",
html_stats_run4 = "",
html_stats_daily_likes_3 = "",
html_stats_daily_likes_4 = "",
html_edit_config1 = "",
html_edit_config2 = "";
var
json_package = "";
var
html_msg_api_err_body = "API key was not correct.<br/>If you are the owner, please check or re-issue your key.<br/>If you do not have access to this service, please contact the owner.<br/><br/>You might need to supply your API key again in at the <a href=\"/\">Dashboard</a>",
html_msg_run_bot_body = "The processing and votes will take a few" +
" minutes to be cast and registered on Steemit because of the" +
" processing time and Steemit vote cast limiting.<br/>You can check" +
" the stats and logs in a few minutes to see the results.";
var app = express();
app.set('port', process.env.PORT || 5000);
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
// set up cookies and session
app.use(cookieParser());
app.use(expressSession({
secret: process.env.COOKIE_SECRET,
resave: true,
saveUninitialized: true
}));
// Start server
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
lib.initLib(false, function() {
loadFiles();
});
});
module.exports = app;
// Utils
function createMsgPageMessage(title, message) {
return "<h1>"+title+"</h1><p class=\"lead\">"+message+"</p>";
}
function createMsgPageHTML(title, message) {
return html_msgPage1
+ title + " - Voter"
+ html_msgPage2
+ createMsgPageMessage(title, message)
+ html_msgPage3;
}
function handleError(res, reason, message, code) {
console.log("ERROR: " + reason + ", MESSAGE: "+message);
res.status(code || 500).send(createMsgPageHTML("API error", html_msg_api_err_body + "<br/><br/>Details: "+message));
}
function handleErrorJson(res, reason, message, code, payload) {
console.log("JSON ERROR: " + reason + ", MESSAGE: "+message);
var status = code || 500;
if (payload) {
res.json({status:status, error: reason, message: message, payload: payload});
} else {
res.json({status:status, error: reason, message: message});
}
}
function loadFiles() {
loadFileToString("/html/msg-page-1.html", function(str) {
html_msgPage1 = str;
console.log("got /html/msg-page-1.html from file");
});
loadFileToString("/html/msg-page-2.html", function(str) {
html_msgPage2 = str;
console.log("got /html/msg-page-2.html from file");
});
loadFileToString("/html/msg-page-3.html", function(str) {
html_msgPage3 = str;
console.log("got /html/msg-page-3.html from file");
});
loadFileToString("/html/dashboard-part-1.html", function(str) {
html_dashboard1 = str;
console.log("got /html/dashboard-part-1.html from file");
});
loadFileToString("/html/dashboard-part-2.html", function(str) {
html_dashboard2 = str;
console.log("got /html/dashboard-part-2.html from file");
});
loadFileToString("/html/dashboard-part-3.html", function(str) {
html_dashboard3 = str;
console.log("got /html/dashboard-part-3.html from file");
});
loadFileToString("/html/dashboard-part-4.html", function(str) {
html_dashboard4 = str;
console.log("got /html/dashboard-part-4.html from file");
});
loadFileToString("/html/edit-algo-part-1.html", function(str) {
html_editAlgo1 = str;
console.log("got /html/edit-algo-part-1.html from file");
});
loadFileToString("/html/edit-algo-part-2.html", function(str) {
html_editAlgo2 = str;
console.log("got /html/edit-algo-part-2.html from file");
});
loadFileToString("/html/edit-algo-part-3.html", function(str) {
html_editAlgo3 = str;
console.log("got /html/edit-algo-part-3.html from file");
});
loadFileToString("/html/edit-algo-part-4.html", function(str) {
html_editAlgo4 = str;
console.log("got /html/edit-algo-part-4.html from file");
});
loadFileToString("/html/test-algo-part-1.html", function(str) {
html_testAlgo1 = str;
console.log("got /html/test-algo-part-1.html from file");
});
loadFileToString("/html/test-algo-part-2.html", function(str) {
html_testAlgo2 = str;
console.log("got /html/test-algo-part-2.html from file");
});
loadFileToString("/html/stats-1.html", function(str) {
html_stats1 = str;
console.log("got /html/stats-1.html from file");
});
loadFileToString("/html/stats-2.html", function(str) {
html_stats2 = str;
console.log("got /html/stats-2.html from file");
});
loadFileToString("/html/stats-3.html", function(str) {
html_stats3 = str;
console.log("got /html/stats-3.html from file");
});
loadFileToString("/html/stats-run-1.html", function(str) {
html_stats_run1 = str;
console.log("got /html/stats-run-1.html from file");
});
loadFileToString("/html/stats-run-2.html", function(str) {
html_stats_run2 = str;
console.log("got /html/stats-run-2.html from file");
});
loadFileToString("/html/stats-run-3.html", function(str) {
html_stats_run3 = str;
console.log("got /html/stats-run-3.html from file");
});
loadFileToString("/html/stats-run-4.html", function(str) {
html_stats_run4 = str;
console.log("got /html/stats-run-4.html from file");
});
loadFileToString("/html/stats-daily-likes-3.html", function(str) {
html_stats_daily_likes_3 = str;
console.log("got /html/stats-daily-likes-3.html from file");
});
loadFileToString("/html/stats-daily-likes-4.html", function(str) {
html_stats_daily_likes_4 = str;
console.log("got /html/stats-daily-likes-4.html from file");
});
loadFileToString("/html/edit-config-1.html", function(str) {
html_edit_config1 = str;
console.log("got /html/edit-config-1.html from file");
});
loadFileToString("/html/edit-config-2.html", function(str) {
html_edit_config2 = str;
console.log("got /html/edit-config-2.html from file");
});
// JSON
loadFileToString("/package.json", function(str) {
try {
json_package = JSON.parse(str);
} catch(err) {
json_package = {version: "unknown"};
}
console.log("got /package.json from file");
});
}
function loadFileToString(filename, callback) {
fs.readFile(path.join(__dirname, filename), {encoding: 'utf-8'}, function(err,data) {
var str = "";
if (err) {
console.log(err);
} else {
str = data;
}
if (callback) {
callback(str);
}
});
}
function saveStringToFile(filename, str, callback) {
fs.writeFile(path.join(__dirname, filename), str, function(err) {
if (err) {
console.log(err);
callback({message: "cant save file: "+filename});
} else {
console.log("saveStringToFile successfully saved to file: "+filename);
callback();
}
});
}
// public HTTPS interface
/*
* / [root]
*/
app.get("/", function(req, res) {
dashboardExec(req, res);
});
app.post("/", bodyParser.urlencoded({extended: false}), function(req, res) {
if (!req.body.api_key) {
handleError(res, "/stats Unauthorized", "stats: no api key supplied", 401);
return;
} else if (req.body.api_key.localeCompare(process.env.BOT_API_KEY) != 0) {
handleError(res, "/stats Unauthorized", "stats: api key is incorrect", 401);
return;
}
req.session.api_key = req.body.api_key;
var cookies = new Cookies(req, res);
if (cookieSessionKey.length < 1) {
cookieSessionKey = extra.calcMD5("" + (Math.random() * 7919));
}
console.log("created session_key cookie for client: "+cookieSessionKey);
cookies.set("session_key", cookieSessionKey, {overwrite: true, httpOnly: false});
console.log("check cookie for session_key: "+cookies.get("session_key"));
dashboardExec(req, res);
});
function dashboardExec(req, res) {
var html = "";
var html_usercontent = "";
var html_version = "<h3>version "+json_package.version+"</h3>";
if (!req.session.api_key || req.session.api_key.localeCompare(process.env.BOT_API_KEY) != 0) {
html += "<div class=\"jumbotron jumbotron_col\"><p>Enter BOT_API_KEY here and section using the buttons below.</p>" +
"<form class=\"form-add\" action=\"/\" method=\"post\"><input type=\"password\" name=\"api_key\" id=\"input_api_key\" placeholder=\"Key\" required autofocus>" +
"<button class=\"btn btn-primary button_form_spacing\" type=\"submit\" value=\"POST\">Start Session</button>" +
"</form></div>";
} else {
html += "<div class=\"jumbotron jumbotron_col jumbotron_smaller\"><p>Session is valid, dashboard active</p></div>";
if (process.env.STEEM_USER && process.env.STEEM_USER.length > 0) {
html_usercontent = "<a href=\"http://steemit.com/@"+process.env.STEEM_USER+"\" class=\"list-group-item\">"+process.env.STEEM_USER+" on Steemit</a>";
html_usercontent += "<a href=\"http://steemd.com/@"+process.env.STEEM_USER+"\" class=\"list-group-item\">"+process.env.STEEM_USER+" detailed data</a>";
}
}
res.status(200).send(
html_dashboard1
+ html_version
+ html_dashboard2
+ html
+ html_dashboard3
+ html_usercontent
+ html_dashboard4);
}
/*
* /stats
*/
app.get("/stats", function(req, res) {
console.log("_startTime: "+req._startTime);
console.log("req.query.api_key = "+req.query.api_key);
console.log("req.session.api_key = "+req.session.api_key);
if (req.query.api_key) {
req.session.api_key = req.query.api_key;
var cookies = new Cookies(req, res);
if (cookieSessionKey.length < 1) {
cookieSessionKey = extra.calcMD5("" + (Math.random() * 7919));
}
console.log("created session_key cookie for client: "+cookieSessionKey);
cookies.set("session_key", cookieSessionKey, {overwrite: true, httpOnly: false});
console.log("check cookie for session_key: "+cookies.get("session_key"));
} else if (!req.session.api_key) {
handleError(res, "/stats Unauthorized", "stats: session is invalid (no session key), please restart from Dashboard", 401);
return;
} else if (req.session.api_key.localeCompare(process.env.BOT_API_KEY) != 0) {
handleError(res, "/stats Unauthorized", "stats: session is invalid (out of date session key), please restart from Dashboard", 401);
return;
}
console.log("req.session.api_key = "+req.session.api_key);
execStats(req, res);
});
function execStats(req, res) {
lib.getPostsMetadataAllDates(function(err, dates) {
var html = "";
if (err || dates === null || dates.length < 1) {
res.status(200).send(
createMsgPageHTML("No stats available", "It looks like this is a fresh install of Voter. Please generate some stats by using it and then come back here to see the results in detail.")
);
console.log("No keys for /stats");
return;
} else {
var lastDay = -1;
for (var i = (dates.length - 1) ; i >= 0 ; i--) {
var dateTime = moment_tz.tz(Number(dates[i]), lib.getConfigVars().TIME_ZONE);
if (dateTime.date() !== lastDay) {
lastDay = dateTime.date();
// add spacer and then day over list item first
html += "<li></li><li><a href=\"/stats?date_str="+dateTime.format("MM-DD-YYYY")+"\">"+
"Votes for " + dateTime.format("MMM Do YYYY") + "</a></li>";
}
html += "<li><a href=\"/stats?save_date="+dates[i]+"\">" +
" --- --- " + dateTime.format("HH:mm") + "</a></li>";
}
}
if (req.query.date_str) {
lib.getDailyLikedPosts(req.query.date_str, function(err, dailyLikedPostsResults) {
if (err) {
res.status(200).send(
createMsgPageHTML("Stats", "No data for daily liked posts, there may be an internal data inconsistency or corrupt key (err stage 1)"));
} else {
var thisDate = moment(req.query.date_str); // TODO : fix this parsing, soon to be deprecated
var html_header = "";
if (dailyLikedPostsResults === null) {
// #58, no votes cast today, is not system failure, display meaningful message
html_header = "No votes cast on " + (thisDate.format("MMM Do YYYY"));
html_list = html_test_emptyList;
} else {
html_header = "Votes cast on " + (thisDate.format("MMM Do YYYY"));
var postsMetadata = dailyLikedPostsResults.posts;
var html_list = "";
if (postsMetadata.length > 0) {
for (var i = 0 ; i < postsMetadata.length ; i++) {
html_list += "<tr><td><a href=\""+postsMetadata[i].url+"\">"+postsMetadata[i].title+"</a></td><td>"+postsMetadata[i].score+"</td>"
+ "<td>"+(postsMetadata[i].vote ? "YES" : "NO")+"</td></tr>";
}
} else {
html_list = html_test_emptyList;
}
}
res.status(200).send(
html_stats_run1
+ html
+ html_stats_run2
+ html_header
+ html_stats_daily_likes_3
+ html_list
+ html_stats_daily_likes_4);
}
});
} else if (req.query.save_date) {
lib.getPostsMetadataList(req.query.save_date, function(err, postsMetadataList) {
if (err || postsMetadataList === null) {
handleErrorJson(res, "/stats-data-json Server error", "stats-data-json: key "+req.query.save_date+" could not be fetched", 500);
return;
}
var html_list = "";
if (postsMetadataList.length > 0) {
for (var i = 0 ; i < postsMetadataList.length ; i++) {
html_list += "<tr><td><a href=\""+postsMetadataList[i].url+"\">"+postsMetadataList[i].title+"</a></td><td>"+postsMetadataList[i].score+"</td>"
+ "<td>"+(postsMetadataList[i].vote ? "YES" : "NO")+"</td></tr>";
}
} else {
html_list = html_test_emptyList;
}
res.status(200).send(
html_stats_run1
+ html
+ html_stats_run2
+ "Sample of posts processed in bot run at " + (moment_tz.tz(Number(req.query.save_date), lib.getConfigVars().TIME_ZONE).format("MMM Do YYYY HH:mm"))
+ html_stats_run3
+ html_list
+ html_stats_run4);
});
} else {
res.status(200).send(
html_stats1
+ html
+ html_stats2
+ "<p>To see record and proof of voting, visit <a href=\"https://steemd.com/@"+process.env.STEEM_USER
+"\">https://steemd.com/@"+process.env.STEEM_USER+"</a></p>"
+ html_stats3);
}
});
}
/*
* /stats
*/
app.get("/stats-data-json", function(req, res) {
if (!req.query.api_key && !req.query.session_key) {
handleError(res, "/stats-data-json Unauthorized", "stats-data-json: api_key or session_key not supplied", 401);
return;
} else if (req.query.api_key && req.query.api_key.localeCompare(process.env.BOT_API_KEY) != 0) {
handleError(res, "/stats-data-json Unauthorized", "stats-data-json: api_key invalid", 401);
return;
} else if (req.query.session_key && req.query.session_key.localeCompare(cookieSessionKey) != 0) {
handleError(res, "/stats-data-json Unauthorized", "stats-data-json: session_key invalid", 401);
return;
}
if (req.query.save_date) {
lib.getPostsMetadataList(req.query.save_date, function(err, postsMetadataList) {
if (err || postsMetadataList === undefined || postsMetadataList === null) {
handleErrorJson(res, "/stats-data-json Server error", "stats-data-json: key "+req.query.save_date+" could not be fetched", 500);
return;
}
res.json({list: postsMetadataList});
});
return;
} else if (req.query.summary) {
lib.getPostsMetadataSummary(function (summary) {
console.log("Sending summary: "+JSON.stringify(summary));
res.json({summary: summary});
});
} else if (req.query.count_only) {
lib.getPostsMetadataAllDates(function(err, dates) {
if (err || dates === undefined || dates === null) {
handleErrorJson(res, "/stats-data-json Server error", "stats-data-json: no data in store, no keys", 500);
return;
}
console.log(" - /stats-data-json dates: "+JSON.stringify(dates));
res.json({num_keys: dates.length});
});
} else {
handleErrorJson(res, "/stats-data-json Server error", "stats-data-json: no query", 500);
}
});
app.get("/get-config-vars", function(req, res) {
if (!req.query.api_key && !req.query.session_key) {
handleErrorJson(res, "/stats-data-json Unauthorized", "stats-data-json: api_key or session_key not supplied", 401, "1");
return;
} else if (req.query.api_key && req.query.api_key.localeCompare(process.env.BOT_API_KEY) != 0) {
handleErrorJson(res, "/stats-data-json Unauthorized", "stats-data-json: api_key invalid", 401, "2");
return;
} else if (req.query.session_key && req.query.session_key.localeCompare(cookieSessionKey) != 0) {
handleErrorJson(res, "/stats-data-json Unauthorized", "stats-data-json: session_key invalid", 401, "3");
return;
}
var config = lib.getConfigVars();
delete config["_id"];
res.json(config);
});
/*
function recursiveGetPostsMetadata(keys, index, callback, list) {
redisClient.get(keys[index], function(err, result) {
index++;
if (index > keys.length) {
callback(list);
return;
}
if (err || result === null) {
recursiveGetPostsMetadata(keys, index, callback, list);
} else {
list.push(result);
recursiveGetPostsMetadata(keys, index, callback, list);
}
});
}
*/
app.get("/get-algo", function(req, res) {
if (!req.query.api_key && !req.query.session_key) {
handleError(res, "/stats-data-json Unauthorized", "stats-data-json: api_key or session_key not supplied", 401);
return;
} else if (req.query.api_key && req.query.api_key.localeCompare(process.env.BOT_API_KEY) != 0) {
handleError(res, "/stats-data-json Unauthorized", "stats-data-json: api_key invalid", 401);
return;
} else if (req.query.session_key && req.query.session_key.localeCompare(cookieSessionKey) != 0) {
handleError(res, "/stats-data-json Unauthorized", "stats-data-json: session_key invalid", 401);
return;
}
lib.getPersistentObj(lib.DB_ALGORITHM, function(err, algorithm) {
console.log("attempted to get algorithm: "+algorithm);
if (algorithm != null) {
delete algorithm["_id"];
res.json(JSON.stringify(algorithm));
} else if (err || algorithm === undefined || algorithm === null) {
handleErrorJson(res, "/get-algo Server error", "get-algo: no data in store", 500);
}
});
});
app.get("/get-daily-liked-posts", function(req, res) {
if (!req.query.api_key && !req.query.session_key) {
handleError(res, "/get-daily-liked-posts Unauthorized", "get-daily-liked-posts: api_key or session_key not supplied", 401);
return;
} else if (req.query.api_key && req.query.api_key.localeCompare(process.env.BOT_API_KEY) != 0) {
handleError(res, "/get-daily-liked-posts Unauthorized", "get-daily-liked-posts: api_key invalid", 401);
return;
} else if (req.query.session_key && req.query.session_key.localeCompare(cookieSessionKey) != 0) {
handleError(res, "/get-daily-liked-posts Unauthorized", "get-daily-liked-posts: session_key invalid", 401);
return;
}
var query = null;
if (req.query.date_str) {
query = req.query.date_str;
}
lib.getDailyLikedPosts(query, function(err, dailyLikedPostsResults) {
if (err
|| dailyLikedPostsResults === undefined
|| dailyLikedPostsResults === null) {
handleErrorJson(res, "/get-daily-liked-posts Server error", "get-daily-liked-posts: no data in store", 500);
} else {
console.log("got daily_liked_posts");
res.json(dailyLikedPostsResults);
}
});
});
app.get("/get-comment", function(req, res) {
if (!req.query.api_key && !req.query.session_key) {
handleError(res, "/get-comment Unauthorized", "get-comment: api_key or session_key not supplied", 401);
return;
} else if (req.query.api_key && req.query.api_key.localeCompare(process.env.BOT_API_KEY) != 0) {
handleError(res, "/get-comment Unauthorized", "get-comment: api_key invalid", 401);
return;
} else if (req.query.session_key && req.query.session_key.localeCompare(cookieSessionKey) != 0) {
handleError(res, "/get-comment Unauthorized", "get-comment: session_key invalid", 401);
return;
}
lib.getPersistentObj(lib.DB_ALGORITHM, function (err, algorithm) {
console.log("attempted to get algorithm: " + algorithm);
if (algorithm != null && algorithm.comment !== undefined) {
console.log('/get-comment, sending comment: ' + algorithm.comment);
res.json({comment: algorithm.comment});
} else if (err || algorithm === undefined || algorithm === null) {
console.log('/get-comment, no comment or couldnt get algo');
res.json({comment: ''});
}
});
});
/*
* /run-bot endpoint
*
* Starts an iteration of the bot
*
* Example usage:
* /run-bot?api_key=1234
*
* optional json=true
*/
app.get("/run-bot", function(req, res) {
console.log("req.query.api_key = "+req.query.api_key);
console.log("req.session.api_key = "+req.session.api_key);
if (req.query.api_key) {
req.session.api_key = req.query.api_key;
var cookies = new Cookies(req, res);
if (cookieSessionKey.length < 1) {
cookieSessionKey = extra.calcMD5("" + (Math.random() * 7919));
}
console.log("created session_key cookie for client: "+cookieSessionKey);
cookies.set("session_key", cookieSessionKey, {overwrite: true, httpOnly: false});
console.log("check cookie for session_key: "+cookies.get("session_key"));
} else if (!req.session.api_key) {
handleError(res, "/stats Unauthorized", "stats: session is invalid (no session key), please restart from Dashboard", 401);
return;
} else if (req.session.api_key.localeCompare(process.env.BOT_API_KEY) != 0) {
handleError(res, "/stats Unauthorized", "stats: session is invalid (out of date session key), please restart from Dashboard", 401);
return;
}
lib.getPersistentObj(lib.DB_ALGORITHM, function(err, algo) {
if (err || algo === null) {
res.status(200).send(
createMsgPageHTML("Run Bot", "Algorithm is not yet set!<br/>Go to <strong>Edit Algo</strong> from the dashboard to create it."));
return;
}
// #86, fork this process to start bot via bot.js, same as scheduled
// method
var fork = require('child_process').fork;
var child = fork('./bot.js');
res.status(200).send(
createMsgPageHTML("Bot script started.", html_msg_run_bot_body));
});
});
// GET /edit-algo
app.get("/edit-algo", function(req, res) {
console.log("req.query.api_key = "+req.query.api_key);
console.log("req.session.api_key = "+req.session.api_key);
if (req.query.api_key) {
req.session.api_key = req.query.api_key;
var cookies = new Cookies(req, res);
if (cookieSessionKey.length < 1) {
cookieSessionKey = extra.calcMD5("" + (Math.random() * 7919));
}
console.log("created session_key cookie for client: "+cookieSessionKey);
cookies.set("session_key", cookieSessionKey, {overwrite: true, httpOnly: false});
console.log("check cookie for session_key: "+cookies.get("session_key"));
} else if (!req.session.api_key) {
handleError(res, "/stats Unauthorized", "stats: session is invalid (no session key), please restart from Dashboard", 401);
return;
} else if (req.session.api_key.localeCompare(process.env.BOT_API_KEY) != 0) {
handleError(res, "/stats Unauthorized", "stats: session is invalid (out of date session key), please restart from Dashboard", 401);
return;
}
if (req.query.delete) {
lib.deleteWeightMetric(req.query.delete, process.env.BOT_API_KEY, function(result) {
console.log("lib.deleteWeightMetric result: "+JSON.stringify(result));
// show edit-algo as normal
editAlgoExec(res, "<h2 class=\"sub-header\">"+result.message+"</h2>");
});
return;
}
var str = "";
var contents = "";
if (req.query.author_whitelist !== undefined) {
str = "authorWhitelist";
contents = req.query.author_whitelist;
} else if (req.query.author_blacklist !== undefined) {
str = "authorBlacklist";
contents = req.query.author_blacklist;
} else if (req.query.content_category_whitelist !== undefined) {
str = "contentCategoryWhitelist";
contents = req.query.content_category_whitelist;
} else if (req.query.content_category_blacklist !== undefined) {
str = "contentCategoryBlacklist";
contents = req.query.content_category_blacklist;
} else if (req.query.content_word_whitelist !== undefined) {
str = "contentWordWhitelist";
contents = req.query.content_word_whitelist;
} else if (req.query.content_word_blacklist !== undefined) {
str = "contentWordBlacklist";
contents = req.query.content_word_blacklist;
} else if (req.query.domain_whitelist !== undefined) {
str = "domainWhitelist";
contents = req.query.domain_whitelist;
} else if (req.query.domain_blacklist !== undefined) {
str = "domainBlacklist";
contents = req.query.domain_blacklist;
}
if (str.length > 0) {
// update
lib.updateMetricList(str, contents, process.env.BOT_API_KEY, function(result) {
console.log("lib.updateMetricList result: "+JSON.stringify(result));
// show edit-algo as normal
editAlgoExec(res, "<h2 class=\"sub-header\">"+result.message+"</h2>");
});
return;
}
editAlgoExec(res);
});
// POST /edit-algo
app.post("/edit-algo", bodyParser.urlencoded({extended: false}), function(req, res) {
console.log("req.query.api_key = "+req.query.api_key);
console.log("req.session.api_key = "+req.session.api_key);
if (req.query.api_key) {
req.session.api_key = req.query.api_key;
var cookies = new Cookies(req, res);
if (cookieSessionKey.length < 1) {
cookieSessionKey = extra.calcMD5("" + (Math.random() * 7919));
}
console.log("created session_key cookie for client: "+cookieSessionKey);
cookies.set("session_key", cookieSessionKey, {overwrite: true, httpOnly: false});
console.log("check cookie for session_key: "+cookies.get("session_key"));
} else if (!req.session.api_key) {
handleError(res, "/stats Unauthorized", "stats: session is invalid (no session key), please restart from Dashboard", 401);
return;
} else if (req.session.api_key.localeCompare(process.env.BOT_API_KEY) != 0) {
handleError(res, "/stats Unauthorized", "stats: session is invalid (out of date session key), please restart from Dashboard", 401);
return;
}
console.log("/edit-algo POST request");
// get options from post data
console.log(" - req.body: "+JSON.stringify(req.body));
if (req.body.json_algo) {
// is update algorithm query
console.log(" - check algorithm is valid");
try {
var parsed = JSON.parse(req.body.json_algo);
for (var i = 0 ; i < parsed.weights.length ; i++) {
if (!parsed.weights[i].hasOwnProperty("key")
|| !parsed.weights[i].hasOwnProperty("value")) {
throw {message: "Parsed JSON does not have valid weights object at array index "+i};
}
}
if (!parsed.hasOwnProperty("authorWhitelist")) {
throw {message: "Parsed JSON does not have authorWhitelist array"};
}
if (!parsed.hasOwnProperty("authorBlacklist")) {
throw {message: "Parsed JSON does not have authorBlacklist array"};
}
if (!parsed.hasOwnProperty("contentCategoryWhitelist")) {
throw {message: "Parsed JSON does not have contentCategoryWhitelist array"};
}
if (!parsed.hasOwnProperty("contentCategoryBlacklist")) {
throw {message: "Parsed JSON does not have contentCategoryBlacklist array"};
}
if (!parsed.hasOwnProperty("contentWordWhitelist")) {
throw {message: "Parsed JSON does not have contentWordWhitelist array"};
}
if (!parsed.hasOwnProperty("contentWordBlacklist")) {
throw {message: "Parsed JSON does not have contentWordBlacklist array"};
}
if (!parsed.hasOwnProperty("domainWhitelist")) {
throw {message: "Parsed JSON does not have domainWhitelist array"};
}
if (!parsed.hasOwnProperty("domainBlacklist")) {
throw {message: "Parsed JSON does not have domainBlacklist array"};
}
} catch(err) {
handleError(res, "/edit-algo Unimplmented", "edit-algo: supplied JSON failed test: "+err.message, 401);
return;
}
console.log(" - update algorithm");
lib.persistObj(lib.DB_ALGORITHM, JSON.parse(req.body.json_algo), function(err) {
if (err) {
editAlgoExec(res, "<h2 class=\"sub-header\">ERROR SAVING algorithm</h2>");
console.log(" - - ERROR SAVING algorithm");
} else {
editAlgoExec(res, "<h2 class=\"sub-header\">Imported algorithm</h2>");
}
});
return;
}
// create query
var query = {
key: req.body.key,
value: req.body.weight
};
if (req.body.lower) {
query["lower"] = req.body.lower;
}
if (req.body.upper) {
query["upper"] = req.body.upper;
}
// update
lib.updateWeightMetric(query, process.env.BOT_API_KEY, function(result) {
console.log("lib.updateWeightMetric result: "+JSON.stringify(result));
// show edit-algo as normal
editAlgoExec(res, "<h2 class=\"sub-header\">"+result.message+"</h2>");
});
});
app.post("/edit-algo-comment", bodyParser.urlencoded({extended: false}), function(req, res) {
console.log("req.query.api_key = "+req.query.api_key);
console.log("req.session.api_key = "+req.session.api_key);
if (req.query.api_key) {
req.session.api_key = req.query.api_key;
var cookies = new Cookies(req, res);
if (cookieSessionKey.length < 1) {
cookieSessionKey = extra.calcMD5("" + (Math.random() * 7919));
}
console.log("created session_key cookie for client: "+cookieSessionKey);
cookies.set("session_key", cookieSessionKey, {overwrite: true, httpOnly: false});
console.log("check cookie for session_key: "+cookies.get("session_key"));
} else if (!req.session.api_key) {
handleError(res, "/edit-algo-comment Unauthorized", "edit-algo-comment: session is invalid (no session key), please restart from Dashboard", 401);
return;
} else if (req.session.api_key.localeCompare(process.env.BOT_API_KEY) != 0) {
handleError(res, "/edit-algo-comment Unauthorized", "edit-algo-comment: session is invalid (out of date session key), please restart from Dashboard", 401);
return;
}
console.log("/edit-algo-comment POST request");
// get options from post data
console.log(" - req.body: "+JSON.stringify(req.body));
if (req.body.comment_block) {
// is update algorithm query
var comment = req.body.comment_block;
console.log(" - update comment to: " + comment);
lib.getPersistentObj(lib.DB_ALGORITHM, function (err, algorithmResult) {
var algorithm = {};
if (err || algorithmResult === undefined || algorithmResult === null) {
console.log(" - no algorithm in db, USING DEFAULT");
// TODO : remove this default algorithm setting
algorithm = {
weights: [],
authorWhitelist: [],
authorBlacklist: [],
contentCategoryWhitelist: [],
contentCategoryBlacklist: [],
contentWordWhitelist: [],
contentWordBlacklist: [],
domainWhitelist: [],
domainBlacklist: [],
commment: ''
};
} else {
algorithm = algorithmResult;
console.log(" - got algorithm from db: "+JSON.stringify(algorithm));
}
algorithm.comment = comment;
lib.persistObj(lib.DB_ALGORITHM, algorithm, function (err) {
if (err) {
editAlgoExec(res, "<h2 class=\"sub-header\">ERROR SAVING comment</h2>");
console.log(" - - ERROR SAVING algorithm");
} else {
editAlgoExec(res, "<h2 class=\"sub-header\">Updated comment</h2>");
}
});
});
return;
}
// else
editAlgoExec(res, "<h2 class=\"sub-header\">ERROR SAVING comment</h2>");
});
function editAlgoExec(res, message) {
lib.getPersistentObj(lib.DB_ALGORITHM, function(err, algorithmResult) {
var algorithm = {};
if (err || algorithmResult === undefined || algorithmResult === null) {
console.log(" - no algorithm in db, USING DEFAULT");
// TODO : remove this default algorithm setting
algorithm = {
weights: [],
authorWhitelist: [],
authorBlacklist: [],
contentCategoryWhitelist: [],
contentCategoryBlacklist: [],
contentWordWhitelist: [],
contentWordBlacklist: [],
domainWhitelist: [],
domainBlacklist: [],
comment: ''
};
} else {
algorithm = algorithmResult;
console.log(" - got algorithm from db: "+JSON.stringify(algorithm));
}
var html_whiteblacklists = "";
//author_whitelist
html_whiteblacklists += "<div class=\"col-sm-4\"><form class=\"form-list\" action=\"/edit-algo\"><label for=\"inputKey\" class=\"sr-only\"></label>";
html_whiteblacklists += "<textarea name=\"author_whitelist\" cols=\"60\" rows=\"3\">";
for (var i = 0 ; i < algorithm.authorWhitelist.length ; i++) {
html_whiteblacklists += ((i > 0) ? " " : "") + algorithm.authorWhitelist[i];
}
html_whiteblacklists += "</textarea><button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\" value=\"POST\">Update Author whitelist</button></form></div>";
//author_blacklist
html_whiteblacklists += "<div class=\"col-sm-4\"><form class=\"form-list\" action=\"/edit-algo\"><label for=\"inputKey\" class=\"sr-only\"></label>";
html_whiteblacklists += "<textarea name=\"author_blacklist\" cols=\"60\" rows=\"3\">";
for (var i = 0 ; i < algorithm.authorBlacklist.length ; i++) {
html_whiteblacklists += ((i > 0) ? " " : "") + algorithm.authorBlacklist[i];
}
html_whiteblacklists += "</textarea><button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\" value=\"POST\">Update Author blacklist</button></form></div>";
html_whiteblacklists += "</div><div class=\"row\">";
//content_category_whitelist
html_whiteblacklists += "<div class=\"col-sm-4\"><form class=\"form-list\" action=\"/edit-algo\"><label for=\"inputKey\" class=\"sr-only\"></label>";
html_whiteblacklists += "<textarea name=\"content_category_whitelist\" cols=\"60\" rows=\"3\">";
for (var i = 0 ; i < algorithm.contentCategoryWhitelist.length ; i++) {
html_whiteblacklists += ((i > 0) ? " " : "") + algorithm.contentCategoryWhitelist[i];
}
html_whiteblacklists += "</textarea><button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\" value=\"POST\">Update Content Category and Tag whitelist</button></form></div>";
//content_category_blacklist
html_whiteblacklists += "<div class=\"col-sm-4\"><form class=\"form-list\" action=\"/edit-algo\"><label for=\"inputKey\" class=\"sr-only\"></label>";
html_whiteblacklists += "<textarea name=\"content_category_blacklist\" cols=\"60\" rows=\"3\">";
for (var i = 0 ; i < algorithm.contentCategoryBlacklist.length ; i++) {
html_whiteblacklists += ((i > 0) ? " " : "") + algorithm.contentCategoryBlacklist[i];
}
html_whiteblacklists += "</textarea><button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\" value=\"POST\">Update Content Category and Tag blacklist</button></form></div>";
html_whiteblacklists += "</div><div class=\"row\">";
//content_word_whitelist
html_whiteblacklists += "<div class=\"col-sm-4\"><form class=\"form-list\" action=\"/edit-algo\"><label for=\"inputKey\" class=\"sr-only\"></label>";
html_whiteblacklists += "<textarea name=\"content_word_whitelist\" cols=\"60\" rows=\"3\">";
for (var i = 0 ; i < algorithm.contentWordWhitelist.length ; i++) {
html_whiteblacklists += ((i > 0) ? " " : "") + algorithm.contentWordWhitelist[i];
}
html_whiteblacklists += "</textarea><button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\" value=\"POST\">Update Content Word whitelist</button></form></div>";
//content_word_blacklist
html_whiteblacklists += "<div class=\"col-sm-4\"><form class=\"form-list\" action=\"/edit-algo\"><label for=\"inputKey\" class=\"sr-only\"></label>";
html_whiteblacklists += "<textarea name=\"content_word_blacklist\" cols=\"60\" rows=\"3\">";
for (var i = 0 ; i < algorithm.contentWordBlacklist.length ; i++) {
html_whiteblacklists += ((i > 0) ? " " : "") + algorithm.contentWordBlacklist[i];
}
html_whiteblacklists += "</textarea><button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\" value=\"POST\">Update Content Word blacklist</button></form></div>";
html_whiteblacklists += "</div><div class=\"row\">";
//domain_whitelist
html_whiteblacklists += "<div class=\"col-sm-4\"><form class=\"form-list\" action=\"/edit-algo\"><label for=\"inputKey\" class=\"sr-only\"></label>";
html_whiteblacklists += "<textarea name=\"domain_whitelist\" cols=\"60\" rows=\"3\">";
for (var i = 0 ; i < algorithm.domainWhitelist.length ; i++) {
html_whiteblacklists += ((i > 0) ? " " : "") + algorithm.domainWhitelist[i];
}
html_whiteblacklists += "</textarea><button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\" value=\"POST\">Update Domain whitelist</button></form></div>";
//domain_blacklist
html_whiteblacklists += "<div class=\"col-sm-4\"><form class=\"form-list\" action=\"/edit-algo\"><label for=\"inputKey\" class=\"sr-only\"></label>";
html_whiteblacklists += "<textarea name=\"domain_blacklist\" cols=\"60\" rows=\"3\">";
for (var i = 0 ; i < algorithm.domainBlacklist.length ; i++) {
html_whiteblacklists += ((i > 0) ? " " : "") + algorithm.domainBlacklist[i];
}
html_whiteblacklists += "</textarea><button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\" value=\"POST\">Update Domain blacklist</button></form></div>";
console.log(" - algorithm: "+JSON.stringify(algorithm));
var html_list = "";
if (algorithm.weights.length > 0) {
for (var i = 0 ; i < algorithm.weights.length ; i++) {
html_list += "<tr><td><a href=\"javascript:selectKey(\'"+algorithm.weights[i].key+"\', "+algorithm.weights[i].value;
if (algorithm.weights[i].hasOwnProperty("lower")) {
html_list += ", "+algorithm.weights[i].lower;
if (!algorithm.weights[i].hasOwnProperty("upper")) {
html_list += ", 0";
}
}
if (algorithm.weights[i].hasOwnProperty("upper")) {
html_list += ", "+algorithm.weights[i].upper;
}
html_list += ")\">"+algorithm.weights[i].key+"</a></td><td>"+algorithm.weights[i].value+"</td>";
if (algorithm.weights[i].hasOwnProperty("lower")) {
html_list += "<td>"+algorithm.weights[i].lower+"</td>";
} else {
html_list += "<td>-</td>";
}
if (algorithm.weights[i].hasOwnProperty("upper")) {
html_list += "<td>"+algorithm.weights[i].upper+"</td>";
} else {
html_list += "<td>-</td>";
}
// TODO : add href url delete to button
html_list += "<th><p><a class=\"btn btn-default\" role=\"button\" href=\"javascript:deleteMetric(\'"+algorithm.weights[i].key+"\')\">Delete</a></p></th>";
html_list += "</tr>";
}
} else {
html_list = html_algo_emptyList;
}
// send back response
res.status(200).send(
html_editAlgo1
+ (message ? message : "")
+ html_editAlgo2
+ html_list
+ html_editAlgo3
+ html_whiteblacklists
+ html_editAlgo4);
});
}
// GET /edit-algo
app.get("/test-algo", function(req, res) {
console.log("req.query.api_key = "+req.query.api_key);
console.log("req.session.api_key = "+req.session.api_key);
if (req.query.api_key) {
req.session.api_key = req.query.api_key;
var cookies = new Cookies(req, res);
if (cookieSessionKey.length < 1) {
cookieSessionKey = extra.calcMD5("" + (Math.random() * 7919));
}
console.log("created session_key cookie for client: "+cookieSessionKey);
cookies.set("session_key", cookieSessionKey, {overwrite: true, httpOnly: false});
console.log("check cookie for session_key: "+cookies.get("session_key"));
} else if (!req.session.api_key) {
handleError(res, "/stats Unauthorized", "stats: session is invalid (no session key), please restart from Dashboard", 401);
return;
} else if (req.session.api_key.localeCompare(process.env.BOT_API_KEY) != 0) {
handleError(res, "/stats Unauthorized", "stats: session is invalid (out of date session key), please restart from Dashboard", 401);
return;
}
// check for options from query data
if (req.query.limit) {
testAlgoExec(res, {test: true, limit: req.query.limit});
} else {
res.status(200).send(
html_testAlgo1
+ html_test_emptyList
+ html_testAlgo2
);
}
});
// POST /edit-algo
app.post("/test-algo", bodyParser.urlencoded({extended: false}), function(req, res) {
console.log("req.query.api_key = "+req.query.api_key);
console.log("req.session.api_key = "+req.session.api_key);
if (req.query.api_key) {
req.session.api_key = req.query.api_key;
var cookies = new Cookies(req, res);