· 6 years ago · Dec 11, 2019, 12:24 AM
1const express = require('express');
2const fileUpload = require('express-fileupload');
3const bodyParser = require('body-parser');
4const mysql = require('mysql');
5const path = require('path');
6
7const app = express();
8
9const scrape = require('scrape-metadata')
10const uuidv4 = require('uuid/v4');
11var session = require('express-session')
12
13//const port = 3306;
14
15//module.exports = {
16//getHomePage: (req, res) => {
17//app.post('/api/getHomePage', (req,res) => {
18function getHomePage() {
19 let query = "SELECT * FROM `bookmark` ORDER BY BID ASC";
20
21 console.log('Bookmark results');
22
23 // execute query
24 db.query(query, (err, result) => {
25 if (err) {
26 res.redirect('/landing');
27 }
28 console.log(result);
29 });
30}
31
32global.searchQuery = {};
33global.getQuery = {};
34
35var allSessionUsers = {}
36
37//FOR TESTING REMOVE
38function loginValidation(){
39//app.post('/api/login', function (req,res) {
40 //TEST DATA
41 var userName = 'smarty';
42 var password = 'pants';
43 var uid = 'z';
44
45 //Return to front end. Contains login status and message
46 var returnValue = [{
47 success: '0',
48 message:'0'
49 }];
50 var loginReport= [{
51 status:false,
52 message:"No action"
53 }];
54
55 var userQuery = "SELECT * FROM `user` WHERE Username = '" + userName + "'";
56
57 db.query(userQuery, (error, userResults) => {
58 //Report query error
59 if (error) {
60 //res.redirect('/');
61 loginReport = [{
62 status:false,
63 message:"There is an error with the query"
64 }];
65
66 returnValue = [{
67 success: '0',
68 message:'0'
69 }];
70 }
71
72 //Check user input password against database information
73 else if(userResults.length >0){
74
75 //Check username for matching letter case
76 var dbName = userResults[0].Username;
77
78 var matchCase = '0';
79 if (userName === dbName){
80 matchCase = '1';
81 }
82
83 if(matchCase == '1'){
84 if(password==userResults[0].Password){
85 //res.redirect('/');
86
87 uid = userResults[0].UID;
88 console.log("UID logged in as");
89 console.log(uid);
90
91 loginReport = [{
92 status:true,
93 message:"Successfully authenticated"
94 }];
95
96 returnValue = [{
97 success: '1',
98 message: uid
99 }];
100 }
101
102 else{
103 //res.redirect('/');
104 loginReport = [{
105 status:false,
106 message:"Username and password does not match"
107 }];
108
109 returnValue = [{
110 success: '0',
111 message: '0'
112 }];
113 }
114 }
115
116 else{
117 loginReport = [{
118 status:false,
119 message:"Username and password does not match"
120 }];
121
122 returnValue = [{
123 success: '0',
124 message: '0'
125 }];
126 }
127 }
128
129 //Report nonexistent user
130 else{
131 //res.redirect('/');
132 loginReport = [{
133 status:false,
134 message:"Username does not exits"
135 }];
136
137 returnValue = [{
138 success: '0',
139 message: '0'
140 }];
141 //res.send(returnValue);
142 }
143
144 //Return results to front-end
145 console.log(loginReport);
146 console.log(returnValue);
147 });
148}
149
150//REMOVE TESTING
151function registrationValidation(){
152 var Username = 'smarty';
153 var Password = 'pants';
154 var FName = 'Add';
155 var LName = 'Me';
156
157 var dateObj = new Date();
158 var month = dateObj.getUTCMonth() + 1; //months from 1-12
159 var day = dateObj.getUTCDate();
160 var year = dateObj.getUTCFullYear();
161 var newdate = year + "/" + month + "/" + day;
162
163 var Admin = false;
164
165 //To be returned to front end. Contains regisration status and message
166 var registerReport = [{
167 status:false,
168 message:"No actions done"
169 }];
170 var UIDReport;
171 var returnValue = [{
172 success: '0',
173 message:'0'
174 }];
175 var UIDDeterminer = 0;
176 var userCount = 0;
177
178 var UIDQuery = "SELECT * FROM `user` ORDER BY UID ASC";
179 var userQuery = "SELECT * FROM `user` WHERE Username = '" + Username + "'";
180
181 db.query(UIDQuery, (errorA, UIDResults) => {
182 //Report query error
183 if (errorA) {
184 UIDReport = [{
185 status:false,
186 message:"There is an error with the query for UID"
187 }];
188
189 returnValue = [{
190 success: '0',
191 message:'0'
192 }];
193 console.log('Return registration result');
194 console.log(returnValue);
195 }
196
197 //Report ids found
198 else if(UIDResults.length >0){
199 console.log('Current Users');
200 console.log(UIDResults);
201 UIDReport = [{
202 status:true,
203 message:"Ids found."
204 }];
205
206 UIDDeterminer = 1;
207 userCount = UIDResults.length;
208 UID = (UIDResults[userCount - 1].UID) + 1;
209
210 console.log('Largerst Current UID');
211 console.log(UIDResults[userCount - 1].UID);
212 console.log('New UID');
213 console.log(UID);
214 }
215
216 //Create id for empty table
217 else{
218 UIDReport = [{
219 status:true,
220 message:"No action"
221 }];
222
223 UIDDeterminer = 1;
224 UID = 1;
225 }
226
227 if (UIDDeterminer == 1){
228 db.query(userQuery, (errorB, userResults) => {
229 //Report query error
230 if (errorB) {
231 //res.redirect('/');
232 registerReport = [{
233 status:false,
234 message:"There is an error with the query"
235 }];
236
237 returnValue = [{
238 success: '0',
239 message:'0'
240 }];
241 console.log('Return registration query error result');
242 console.log(returnValue);
243 }
244
245 //Report username already exists
246 else if(userResults.length >0){
247 registerReport = [{
248 status:false,
249 message:"User name is already taken. Please enter another username."
250 }];
251
252 returnValue = [{
253 success: '0',
254 message:'0'
255 }];
256 console.log('Return registration user name taken result');
257 console.log(returnValue);
258 }
259
260 //Insert new user
261 else{
262 //res.redirect('/');
263 var insertUser = "INSERT INTO user(UID, Username, Password, FName, LName, RegDate, Admin) VALUES (" + UID + ", '" + Username + "', '" + Password + "', '" + FName + "', '" + LName + "', '" + newdate + "', " + Admin + ")";
264
265 console.log(insertUser);
266
267 db.query(insertUser, (err2, inserted) => {
268 //Report query error
269 if (err2) {
270 //throw err;
271 registerReport = [{
272 status:false,
273 message:"Error registering."
274 }];
275
276 returnValue = [{
277 success: '0',
278 message:'0'
279 }];
280 console.log('Return registration error registering result'); console.log(returnValue);
281 }
282
283 //Report user registration success
284 else{
285 registerReport = [{
286 status:true,
287 message:"Thank you! You are successfully registered."
288 }];
289
290 returnValue = [{
291 success: '1',
292 message:UID
293 }];
294 console.log('Return successful registration registration result');
295 console.log(returnValue);
296 }
297 });
298 }
299
300 console.log('Return registration report');
301 console.log(registerReport);
302 console.log('Return registration result');
303 console.log(returnValue);
304 });
305 }
306 });
307}
308
309function addBookmark(){
310 var UID = 111;
311 //var BID = ???
312 // new BID determined by max BID + 1
313
314 var Title = "mytitle2";
315 var URL = "umdearborn.edu";
316 var Priority = 1;
317 var Description = "My cool website2.";
318
319 var dateObj = new Date();
320 var month = dateObj.getUTCMonth() + 1; //months from 1-12
321 var day = dateObj.getUTCDate();
322 var year = dateObj.getUTCFullYear();
323
324 var newdate = year + "/" + month + "/" + day;
325
326 var bookmarkQuery = "SELECT * FROM `bookmark` WHERE URL = '" + URL + "'";
327 var maxQuery = "SELECT MAX(BID) as BID FROM `bookmark`";
328
329 var bookmarkReport;
330
331 // Query to find new BID
332 db.query(maxQuery, (error, result, fields) => {
333 if (error) {
334 //res.redirect('/');
335 bookmarkReport = [{
336 status:false,
337 message:"There is an error with the query"
338 }];
339 console.log(bookmarkReport);
340 }
341 else{
342 console.log("BID: " + JSON.stringify(result[0].BID));
343
344 var newBID = 0;
345
346 if (result[0].BID != null) {
347 newBID = result[0].BID + 1;
348 }
349
350 // Query to find if BID already created
351 db.query(bookmarkQuery, (error, results) => {
352 if (error) {
353 //res.redirect('/');
354 bookmarkReport = [{
355 status:false,
356 message:"There is an error with the query"
357 }];
358 }
359
360 else if(results.length >0){
361 console.log(results);
362 bookmarkReport = [{
363 status:false,
364 message:"Bookmark is already created."
365 }];
366 }
367
368 else{
369 var insertBookmark = "INSERT INTO bookmark(BID, UID, Title, URL, Priority, Description, Date) VALUES (" + newBID + ", " + UID + ", '" + Title + "', '" + URL + "', '" + Priority + "', '" + Description + "', " + newdate + ")";
370
371 console.log(insertBookmark);
372 db.query(insertBookmark, (err2, inserted) => {
373 if (err2) {
374 //throw err;
375 bookmarkReport = [{
376 status:false,
377 message:"Error creating bookmark."
378 }];
379 }
380
381 else{
382 bookmarkReport = [{
383 status:true,
384 message:"Bookmark added."
385 }];
386 }
387
388
389 });
390 }
391 console.log(bookmarkReport);
392 });
393 }
394 });
395
396
397}
398
399
400function scrapeTags(BID, URL) {
401 scrape(URL, (err, meta) => {
402 if (meta != null) {
403 var str = "";
404 if (meta.title != null) {
405 str =+ meta.title;
406 }
407 if (meta.description != null) {
408 str =+ " " + meta.description;
409 } else if (meta.twitterDescription != null) {
410 str =+ " " + meta.twitterDescription;
411 }
412 console.log("META: " + str);
413 var splits = meta.title.split(/[.,\/ -!()]/);
414 for (var i = 0; i < splits.length; i++) {
415 console.log("Word:" + splits[i]);
416 if (splits[i] == "") {
417 console.log("empty!");
418 } else if (splits[i] == " ") {
419 console.log("space!");
420 }
421 } // TODO: remove tags that are less than a few letters, or not all caps, or don't include any symbols, or "I, my, me", etc
422
423 let unique = [...new Set(splits)]; // put it into a set to avoid duplicates
424 console.log(unique)
425
426 /*function addEachTag(tag) {
427 console.log("(1)BID: " + BID + ", tag: " + tag);
428 addTagToBookmark(BID, tag)
429 }
430
431 unique.forEach(addEachTag);*/
432 addNewTags(BID, unique);
433 }
434 })
435}
436
437function addNewTags(BID, Tags) {
438 //console.log("(2)BID: " + BID + ", tag: " + TagName);
439 var maxQuery = "SELECT MAX(TID) as TID FROM `bkhastag`";
440
441 var tagReport;
442
443 // Query to find new TID in bkhastag
444 db.query(maxQuery, (error, result, fields) => {
445 if (error) {
446 //res.redirect('/');
447 tagReport = [{
448 status:false,
449 message:"There is an error with the query"
450 }];
451 console.log(tagReport);
452 }
453 else{
454
455 var newTID = 0;
456 if (result[0].TID != null) {
457 newTID = result[0].TID + 1;
458 }
459
460 console.log("TID: " + newTID);
461
462 function addEachTag(tag) {
463 console.log("(1)TID: " + newTID + ", tag: " + tag);
464 addTagToBookmark(BID, newTID, tag)
465
466 newTID += 1;
467 }
468
469 Tags.forEach(addEachTag);
470 }
471 console.log(tagReport);
472 });
473}
474
475function addTagToBookmark(BID, TID, TagName) {
476 console.log("TID: " + TID);
477
478 // Insert new TID
479 var insertTag = "INSERT INTO bkhastag(BID, TID) VALUES (" + BID + ", " + TID + ")";
480
481 console.log(insertTag);
482 db.query(insertTag, (err2, inserted) => {
483 if (err2) {
484 //throw err;
485 tagReport = [{
486 status:false,
487 message:"Error creating Tag."
488 }];
489 console.log(tagReport);
490 }
491
492 else{
493 // Also add Tag Name to tag table
494 var insertTagName = "INSERT INTO tag(TID, TagName) VALUES (" + TID + ", '" + TagName + "')";
495
496 console.log(insertTagName);
497 db.query(insertTagName, (err2, inserted) => {
498 if (err2) {
499 //throw err;
500 console.log(err2);
501 tagReport = [{
502 status:false,
503 message:"Error creating Tag Name."
504 }];
505 console.log(tagReport);
506 }
507
508 else{
509 tagReport = [{
510 status:true,
511 message:"Tag Name added."
512 }];
513 console.log(tagReport);
514 }
515 });
516
517
518 tagReport = [{
519 status:true,
520 message:"Tag added."
521 }];
522 console.log(tagReport);
523 }
524 });
525}
526
527// create connection to database
528// the mysql.createConnection function takes in a configuration object which contains host, user, password and the database name.
529/*const db = mysql.createConnection ({
530 host: 'localhost',
531 user: 'root',
532 password: '',
533 database: 'bookmarkmanager'
534});*/
535
536/*
537const db = mysql.createConnection ({
538 host: 'localhost',
539 user: 'group',
540 password: 'abcd',
541 database: 'BookmarkTool'
542});
543*/
544
545const db = mysql.createConnection ({
546 host: 'localhost',
547 user: 'BookmarkUser',
548 password: 'obeyempty',
549 database: 'OBMTDatabase10'
550});
551
552// connect to database
553db.connect((err) => {
554 if (err) {
555 throw err;
556 }
557 console.log('Connected to database');
558
559 //getHomePage();
560 //loginValidation();
561 //registrationValidation();
562});
563
564global.db = db;
565
566// configure middleware
567//app.set('port', process.env.port || port); // set express to use this port
568app.set('views', __dirname + '/views'); // set express to look in this folder to render our view
569app.set('view engine', 'ejs'); // configure template engine
570app.use(bodyParser.urlencoded({ extended: false }));
571app.use(bodyParser.json()); // parse form data client
572app.use(express.static(path.join(__dirname, 'public'))); // configure express to use public folder
573app.use(fileUpload()); // configure fileupload
574app.use(session({
575 secret: 'keyboard cat',
576 cookie: { maxAge: 100000000 },
577 genid: function(req) {
578 return uuidv4(); // use UUIDs for session IDs
579 }
580}));
581
582app.use(function(req, res, next) {
583 res.header('Access-Control-Allow-Origin', '*');
584 res.header('Access-Control-Allow-Headers', '*');
585 res.header('Content-Type'm 'application/x-www-form-urlencoded');
586 res.header('Accept': 'application/json');
587 next();
588});
589
590// routes for the app
591/*
592app.get('/', getHomePage);
593app.get('/add', addPlayerPage);
594app.get('/edit/:id', editPlayerPage);
595app.get('/delete/:id', deletePlayer);
596app.post('/add', addPlayer);
597app.post('/edit/:id', editPlayer);
598*/
599
600// set the app to listen on the port
601//app.listen(port, () => {
602 // console.log(`Server running on port: ${port}`);
603//});
604
605
606
607
608// Serve the static files from the React app
609app.use(express.static(path.join(__dirname, 'client/build')));
610
611// An api endpoint that returns a short list of items
612/*app.get('/api/getList', (req,res) => {
613 var list = ["item1", "item2", "item3"];
614 res.json(list);
615 console.log('Sent list of items');
616});
617*/
618
619
620//TEST CONNECTION TO FRONT-END
621app.get('/api/getList', (req,res) => {
622 var list = ["item1", "item2", "item3"];
623
624 console.log(req.username);
625 if(req.username == "blue")
626 {
627 list = ["apple", "climb", "jump"];
628 }
629
630 res.json(list);
631 console.log('Sent');
632});
633/*
634// An api endpoint that returns a short list of items
635app.get('/api/getList', (req,res) => {
636
637
638 var list = [{Title: "Book Test",URL:"test.com" , Prioriyty:"5" , Description:"Test bookmark" , Date: "11-26"}];
639 res.json(list);
640 console.log('Sent list of items');
641});*/
642
643app.post('/api/login', function (req,res) {
644 //TEST DATA
645 var username = req.body.username;
646 var password = req.body.password;
647
648 console.log(username);
649 console.log(password);
650 var uid = 'z';
651
652 //Return to front end. Contains login status and message
653 var returnValue = [{
654 success: '0',
655 message:'0'
656 }];
657 var loginReport= [{
658 status:false,
659 message:"No action"
660 }];
661
662 var userQuery = "SELECT * FROM `user` WHERE Username = '" + username + "'";
663 console.log(userQuery);
664
665 db.query(userQuery, (error, userResults) => {
666 //Report query error
667 if (error) {
668 //res.redirect('/');
669 loginReport = [{
670 status:false,
671 message:"There is an error with the query"
672 }];
673
674 // res.send('0');
675 res.json(returnValue);
676 }
677
678 //Check user input password against database information
679 else if(userResults.length >0){
680
681 //Check username for matching letter case
682 var dbName = userResults[0].Username;
683
684 var matchCase = '0';
685 if (username === dbName){
686 matchCase = '1';
687 }
688
689 //Check valid username password
690 if(matchCase == '1'){
691 //Report matching information
692 if(password==userResults[0].Password){
693 //res.redirect('/');
694
695 uid = userResults[0].UID;
696 console.log("UID logged in as");
697 console.log(uid);
698
699 loginReport = [{
700 status:true,
701 message:"Successfully authenticated"
702 }];
703
704 returnValue = [{
705 success: '1',
706 message: uid
707 }];
708
709 res.json(returnValue);
710
711 allSessionUsers[req.sessionID] = {
712 login: true,
713 UID: uid
714 };
715
716 //console.log(JSON.stringify(allSessionUsers));
717 }
718
719 //Report mismatched information
720 else{
721 //res.redirect('/');
722 loginReport = [{
723 status:false,
724 message:"Username and password does not match"
725 }];
726
727 // res.send('0');
728 res.json(loginReport);
729 }
730 }
731
732 //Report mismatched information
733 else{
734 loginReport = [{
735 status:false,
736 message:"Username and password does not match"
737 }];
738
739 // res.send('0');
740 res.json(loginReport);
741 }
742 }
743
744 //Report nonexistent user
745 else{
746 //res.redirect('/');
747 loginReport = [{
748 status:false,
749 message:"Username does not exits"
750 }];
751
752 // res.send('0');
753 res.json(loginReport);
754 }
755
756 //Return results to front-end
757 console.log('Login report');
758 console.log(loginReport);
759 console.log(returnValue);
760 });
761});
762
763app.post('/api/CallRegisterLogin', function (req,res) {
764 //TEST DATA- NEED FROM FRONT-END Username, Password, FName, LName
765 var Username = req.body.username;
766 var Password = req.body.password;
767 var FName = req.body.firstname;
768 var LName = req.body.lastname;
769
770 var dateObj = new Date();
771 var month = dateObj.getUTCMonth() + 1; //months from 1-12
772 var day = dateObj.getUTCDate();
773 var year = dateObj.getUTCFullYear();
774 var newdate = year + "/" + month + "/" + day;
775
776 var Admin = false;
777
778 //To be returned to front end. Contains registration status and message
779 var registerReport= [{
780 status:false,
781 message:"No actions done"
782 }];
783 var UIDReport;
784 var returnValue = [{
785 success: '0',
786 message:'0'
787 }];
788 var UIDDeterminer = 0;
789 var userCount = 0;
790
791 var UIDQuery = "SELECT * FROM `user` ORDER BY UID ASC";
792 var userQuery = "SELECT * FROM `user` WHERE Username = '" + Username + "'";
793
794 db.query(UIDQuery, (errorA, UIDResults) => {
795 //Report query error
796 if (errorA) {
797 //res.redirect('/');
798 UIDReport = [{
799 status:false,
800 message:"There is an error with the query for UID"
801 }];
802 }
803
804 //Report ids found
805 else if(UIDResults.length >0){
806 console.log('Current Users');
807 console.log(UIDResults);
808 UIDReport = [{
809 status:true,
810 message:"Ids found."
811 }];
812
813 UIDDeterminer = 1;
814 userCount = UIDResults.length;
815 UID = (UIDResults[userCount - 1].UID) + 1;
816
817 console.log('Largerst Current UID');
818 console.log(UIDResults[userCount - 1].UID);
819 console.log('New UID');
820 console.log(UID);
821 }
822
823 //Create id for empty table
824 else{
825 UIDReport = [{
826 status:true,
827 message:"No current Ids found."
828 }];
829
830 UIDDeterminer = 1;
831 UID = 1;
832 }
833
834 //Check registration details
835 if (UIDDeterminer == 1){
836 db.query(userQuery, (errorB, userResults) => {
837 //Report query error
838 if (errorB) {
839 //res.redirect('/');
840 registerReport = [{
841 status:false,
842 message:"There is an error with the query"
843 }];
844
845 returnValue = [{
846 success: '0',
847 message:'1'
848 }];
849 console.log(returnValue);
850 res.json(returnValue);
851 }
852
853 //Report username already exists
854 else if(userResults.length >0){
855 registerReport = [{
856 status:false,
857 message:"Username is already taken. Please enter another username."
858 }];
859
860 returnValue = [{
861 success: '0',
862 message:'2'
863 }];
864 console.log(returnValue);
865 res.json(returnValue);
866 }
867
868 //Insert new user
869 else{
870 //res.redirect('/');
871 var insertUser = "INSERT INTO user(UID, Username, Password, FName, LName, RegDate, Admin) VALUES (" + UID + ", '" + Username + "', '" + Password + "', '" + FName + "', '" + LName + "', '" + newdate + "', " + Admin + ")";
872
873 console.log(insertUser);
874
875 db.query(insertUser, (err2, inserted) => {
876 //Report query error
877 if (err2) {
878 //throw err;
879 registerReport = [{
880 status:false,
881 message:"Error registering."
882 }];
883
884 returnValue = [{
885 success: '0',
886 message:'3'
887 }];
888 console.log(returnValue);
889 res.json(returnValue);
890 }
891
892 //Report user registration success
893 else{
894 registerReport = [{
895 status:true,
896 message:"Thank you! You are successfully registered."
897 }];
898
899 returnValue = [{
900 success: '1',
901 message:UID
902 }];
903
904 allSessionUsers[req.sessionID] = {
905 login: true,
906 UID: UID
907 };
908
909 console.log('Return registration report');
910 console.log(registerReport);
911 console.log(returnValue);
912 res.json(returnValue);
913 }
914 });
915 }
916 });
917 }
918
919 else{
920 console.log('FINAL- Return registration result');
921 console.log(returnValue);
922 res.json(returnValue);
923 }
924 });
925});
926
927async function sendGetResults(res, UID, bookmarks) {
928 await new Promise(resolve => setTimeout(resolve, 2000));
929 //console.log("2 seconds passed!");
930
931 var BIDToReturn = {};
932 var returnBID = [];
933
934 for (BID in global.getQuery[UID]) {
935 var searchScore = 0;
936 console.log("BID: " + BID);
937 console.log(JSON.parse(JSON.stringify(global.getQuery[UID][BID])));
938
939 var tags = JSON.parse(JSON.stringify(global.getQuery[UID][BID]));
940 // TODO: base search score on the most recently created
941 /*for (var i = 0; i < tags.length; i++) {
942 console.log("Parsed tag: " + JSON.stringify(tags[i][0]));
943
944 for (var j = 0; j < searchStrings.length; j++) {
945 if (tags[i][0] != null) {
946 //console.log(tags[i][0].TagName + " vs " + searchStrings[j])
947 if (tags[i][0].TagName.toLowerCase() == searchStrings[j].toLowerCase() && searchStrings[j] != "") {
948 searchScore += 1;
949 }
950 }
951 }
952 }
953 console.log("Search score: " + searchScore)*/
954
955 //if (searchScore > 0) {
956 BIDToReturn[BID] = searchScore;
957 returnBID.push(BID);
958 //}
959 }
960
961 returnBID.sort(function(a, b){return BIDToReturn[b]-BIDToReturn[a]});
962
963 console.log(returnBID);
964
965 //res.send()
966 //return returnBID;
967
968 var returnBookmarks = []
969
970 for (var i = 0; i < bookmarks.length; i++) {
971 //console.log(bookmarks[i].BID);
972 //console.log(JSON.stringify(bookmarks[i].BID));
973 for (var j = 0; j < returnBID.length; j++) {
974 console.log(bookmarks[i].BID + " vs " + returnBID[j]);
975 if (bookmarks[i].BID == returnBID[j]) {
976 bookmarks[i].Priority = j;
977 bookmarks[i].Tags = JSON.parse(JSON.stringify(global.getQuery[UID][bookmarks[i].BID]));
978 returnBookmarks.push(bookmarks[i]);
979 }
980 }
981 }
982
983 console.log(returnBookmarks);
984 returnBookmarks.sort(function(a, b){return a.Priority-b.Priority});
985
986 var returnValue = {
987 success: '1',
988 bookmarks: returnBookmarks
989 }
990
991 res.json(returnValue);
992}
993
994// Requires UID parameter
995// returns result as {success='0',bookmarks={...}}
996app.post('/api/getBookmarks', function (req,res) {
997 console.log("REQ BODY:" + JSON.stringify(req.session.userId));
998 console.log("REQ:" + JSON.stringify(allSessionUsers));
999 console.log("REQ:" + JSON.stringify(req.session));
1000 console.log("REQ:" + req.sessionID);
1001 //var UID = 111;//req.body.UID;
1002
1003 var loggedIn = false;
1004 var UID;
1005
1006 if (req.sessionID != null && allSessionUsers[req.sessionID] != null) {
1007 loggedIn = allSessionUsers[req.sessionID].login;
1008 UID = allSessionUsers[req.sessionID].UID;
1009 }
1010
1011 if (req.sessionID == null || allSessionUsers[req.sessionID] == null) {
1012 var returnValue = {
1013 success: '0',
1014 message: "Invalid session: Are you logged in?"
1015 };
1016 res.json(returnValue);
1017 } else if (!loggedIn) {
1018 var returnValue = {
1019 success: '0',
1020 message: "Error: Not logged in."
1021 };
1022 res.json(returnValue);
1023 } else if (UID == null) {
1024 console.log("Null UID");
1025 console.log("Get bookmarks failed due to null parameter.");
1026
1027 var returnValue = {
1028 success: '0',
1029 }
1030 res.json(returnValue);
1031 } else {
1032 global.getQuery[UID] = {}
1033 var bookmarkQuery = "SELECT * FROM `bookmark` WHERE UID = '" + UID + "'";
1034
1035 // Query to get all of the user's bookmarks
1036 db.query(bookmarkQuery, (err2, results) => {
1037 if (err2) {
1038 //throw err;
1039 bookmarkReport = [{
1040 status:false,
1041 message:"Error retrieving bookmarks."
1042 }];
1043
1044 var returnValue = {
1045 success: '0',
1046 }
1047 res.json(returnValue);
1048 }
1049
1050 else{
1051 bookmarkReport = [{
1052 status:true,
1053 message:"Bookmarks retrieved."
1054 }];
1055
1056 //var returnValue = {
1057 // success: '1',
1058 // bookmarks: results
1059 //}
1060
1061 //res.json(returnValue);
1062
1063 // Alright so we have all the user's bookmarks. But we want to narrow it down by tag.
1064 // Each bookmark has a BID.
1065 console.log("Bookmarks found: " + results.length);
1066 for (var i = 0; i < results.length; i++) {
1067 var bookmarkTags = getTags(UID, results[i].BID, true);
1068 console.log(bookmarkTags);
1069 }
1070
1071 sendGetResults(res, UID, results);
1072 }
1073 });
1074 }
1075});
1076
1077function getTags(UID, BID, isGetBookmarks) {
1078 var tagQuery = "SELECT * FROM `bkhastag` WHERE BID = '" + BID + "'";
1079
1080 var bookmarkReport;
1081
1082 //var foundTagNames = [];
1083
1084 //console.log(tagQuery);
1085 // Query to find all Tag ID based on the bookmark
1086 db.query(tagQuery, (error, result, fields) => {
1087 if (error) {
1088 bookmarkReport = [{
1089 status:false,
1090 message:"Error finding tag id."
1091 }];
1092 var returnValue = {
1093 success: '0',
1094 }
1095 res.send(returnValue);
1096 } else {
1097 for (var i = 0; i < result.length; i++) {
1098 var TID = result[i].TID;
1099
1100 if (TID != null) {
1101 var getTagNameQuery = "SELECT `TagName` FROM `tag` WHERE TID = '" + TID + "'";
1102 console.log(getTagNameQuery);
1103
1104 db.query(getTagNameQuery, (error, tagName, fields) => {
1105 if (error) {
1106 bookmarkReport = [{
1107 status:false,
1108 message:"Error gettings TagName."
1109 }];
1110
1111 console.log(bookmarkReport);
1112 } else {
1113 bookmarkReport = [{
1114 status:true,
1115 message:"Success getting TagName."
1116 }];
1117
1118 //console.log("My tag name: " + JSON.stringify(tagName));
1119 //foundTagNames.push(tagName["TagName"]);
1120 if (isGetBookmarks == null || isGetBookmarks == false) {
1121 if (global.searchQuery[UID][BID] == null) {
1122 global.searchQuery[UID][BID] = []
1123 }
1124 global.searchQuery[UID][BID].push(tagName);
1125 } else {
1126 if (global.getQuery[UID][BID] == null) {
1127 global.getQuery[UID][BID] = []
1128 }
1129 global.getQuery[UID][BID].push(tagName);
1130 }
1131 //if (global.searchQuery[UID][BID] != null) {
1132 // console.log(JSON.parse(JSON.stringify(global.searchQuery[UID][BID])));
1133 //}
1134 }
1135 });
1136 }
1137 }
1138 }
1139 });
1140
1141 //console.log("WHOA: " + foundTagNames)
1142
1143 //return foundTagNames;
1144}
1145
1146async function sendSearchResults(res, UID, bookmarks, SearchString) {
1147 await new Promise(resolve => setTimeout(resolve, 2000));
1148 //console.log("2 seconds passed!");
1149
1150 var searchStrings = SearchString.split(/[.,\/ -!()]/);
1151
1152 var BIDToReturn = {};
1153 var returnBID = [];
1154
1155 for (BID in global.searchQuery[UID]) {
1156 var searchScore = 0;
1157 console.log("BID: " + BID);
1158 console.log(JSON.parse(JSON.stringify(global.searchQuery[UID][BID])));
1159
1160 var tags = JSON.parse(JSON.stringify(global.searchQuery[UID][BID]));
1161 for (var i = 0; i < tags.length; i++) {
1162 console.log("Parsed tag: " + JSON.stringify(tags[i][0]));
1163
1164 for (var j = 0; j < searchStrings.length; j++) {
1165 if (tags[i][0] != null) {
1166 //console.log(tags[i][0].TagName + " vs " + searchStrings[j])
1167 if (tags[i][0].TagName.toLowerCase() == searchStrings[j].toLowerCase() && searchStrings[j] != "") {
1168 searchScore += 1;
1169 }
1170 }
1171 }
1172 }
1173 console.log("Search score: " + searchScore)
1174
1175 if (searchScore > 0) {
1176 BIDToReturn[BID] = searchScore;
1177 returnBID.push(BID);
1178 }
1179 }
1180
1181 returnBID.sort(function(a, b){return BIDToReturn[b]-BIDToReturn[a]});
1182
1183 console.log(returnBID);
1184
1185 //res.send()
1186 //return returnBID;
1187
1188 var returnBookmarks = []
1189
1190 for (var i = 0; i < bookmarks.length; i++) {
1191 //console.log(bookmarks[i].BID);
1192 //console.log(JSON.stringify(bookmarks[i].BID));
1193 for (var j = 0; j < returnBID.length; j++) {
1194 console.log(bookmarks[i].BID + " vs " + returnBID[j]);
1195 if (bookmarks[i].BID == returnBID[j]) {
1196 bookmarks[i].Priority = j;
1197 bookmarks[i].Tags = JSON.parse(JSON.stringify(global.getQuery[UID][bookmarks[i].BID]));
1198 returnBookmarks.push(bookmarks[i]);
1199 }
1200 }
1201 }
1202
1203 console.log(returnBookmarks);
1204 returnBookmarks.sort(function(a, b){return a.Priority-b.Priority});
1205
1206 var returnValue = {
1207 success: '1',
1208 bookmarks: returnBookmarks
1209 }
1210
1211 res.json(returnValue);
1212}
1213
1214// Takes 2 seconds to try to retrieve all tags, then calculates which bookmarks best
1215// match the search string.
1216// It returns in the same format as getBookmarks, except Priority is filled out based on most relevant.
1217// Lower priority = more relevant. Priority will begin at 0-max and will not skip any values (goes up one at a time).
1218// And the totally unrelevant bookmarks (0 keyword matches) are not returned.
1219app.post('/api/searchBookmarks', function (req,res) {
1220 //var UID = 111;//req.body.UID;
1221 var SearchString = req.body.SearchString;
1222
1223 var loggedIn = false;
1224 var UID;
1225
1226 if (req.sessionID != null && allSessionUsers[req.sessionID] != null) {
1227 loggedIn = allSessionUsers[req.sessionID].login;
1228 UID = allSessionUsers[req.sessionID].UID;
1229 }
1230
1231 if (req.sessionID == null || allSessionUsers[req.sessionID] == null) {
1232 var returnValue = {
1233 success: '0',
1234 message: "Invalid session: Are you logged in?"
1235 };
1236 res.json(returnValue);
1237 } else if (!loggedIn) {
1238 var returnValue = {
1239 success: '0',
1240 message: "Error: Not logged in."
1241 };
1242 res.json(returnValue);
1243 } else if (UID == null) {
1244 console.log("Null UID");
1245 console.log("Get bookmarks failed due to null parameter.");
1246
1247 var returnValue = {
1248 success: '0',
1249 }
1250 res.json(returnValue);
1251 } else if (SearchString == null) {
1252 console.log("Null SearchString");
1253 console.log("Get bookmarks failed due to null parameter.");
1254
1255 var returnValue = {
1256 success: '0',
1257 }
1258 res.json(returnValue);
1259 } else {
1260 global.searchQuery[UID] = {}
1261 var bookmarkQuery = "SELECT * FROM `bookmark` WHERE UID = '" + UID + "'";
1262
1263 // Query to get all of the user's bookmarks
1264 db.query(bookmarkQuery, (err2, results) => {
1265 if (err2) {
1266 //throw err;
1267 bookmarkReport = [{
1268 status:false,
1269 message:"Error retrieving bookmarks."
1270 }];
1271
1272 var returnValue = {
1273 success: '0',
1274 }
1275 res.json(returnValue);
1276 }
1277
1278 else{
1279 bookmarkReport = [{
1280 status:true,
1281 message:"Bookmarks retrieved."
1282 }];
1283
1284 //var returnValue = {
1285 // success: '1',
1286 // bookmarks: results
1287 //}
1288
1289 //res.json(returnValue);
1290
1291 // Alright so we have all the user's bookmarks. But we want to narrow it down by tag.
1292 // Each bookmark has a BID.
1293 console.log("Bookmarks found: " + results.length);
1294 for (var i = 0; i < results.length; i++) {
1295 var bookmarkTags = getTags(UID, results[i].BID);
1296 console.log(bookmarkTags);
1297 }
1298
1299 sendSearchResults(res, UID, results, SearchString);
1300 }
1301 });
1302 }
1303});
1304
1305// Returns {success: '0'} or {success: '1'}
1306app.post('/api/addBookmark', function (req,res) {
1307 var Title = req.body.Title;
1308 var URL = req.body.URL;
1309 var Priority = 1;
1310 var Description = req.body.Description;
1311
1312 var dateObj = new Date();
1313 var month = dateObj.getUTCMonth() + 1; //months from 1-12
1314 var day = dateObj.getUTCDate();
1315 var year = dateObj.getUTCFullYear();
1316
1317 var newdate = year + "/" + month + "/" + day;
1318
1319 //if (UID == null) {
1320 // console.log("Null UID");
1321 //}
1322 if (Title == null) {
1323 console.log("Null Title");
1324 }
1325 if (URL == null) {
1326 console.log("Null URL");
1327 }
1328 if (Priority == null) {
1329 console.log("Null Priority");
1330 }
1331 if (Description == null) {
1332 console.log("Null Description");
1333 }
1334
1335 var loggedIn = false;
1336 var UID;
1337
1338 if (req.sessionID != null && allSessionUsers[req.sessionID] != null) {
1339 loggedIn = allSessionUsers[req.sessionID].login;
1340 UID = allSessionUsers[req.sessionID].UID;
1341 }
1342
1343 if (req.sessionID == null || allSessionUsers[req.sessionID] == null) {
1344 var returnValue = {
1345 success: '0',
1346 message: "Invalid session: Are you logged in?"
1347 };
1348 res.json(returnValue);
1349 } else if (!loggedIn) {
1350 var returnValue = {
1351 success: '0',
1352 message: "Error: Not logged in."
1353 };
1354 res.json(returnValue);
1355 } else if (UID == null || Title == null || URL == null || Priority == null || Description == null) {
1356 var returnValue = {
1357 success: '0',
1358 }
1359 res.send(returnValue);
1360 console.log("Add bookmark failed due to null parameter.");
1361 } else {
1362 // new BID determined by max BID + 1
1363 //var UID = 111;
1364 //var Title = "mytitle2";
1365 //var URL = "umdearborn.edu";
1366 //var Priority = 1;
1367 //var Description = "My cool website2.";
1368
1369
1370//var newdate = '2019-12-05';
1371 var bookmarkQuery = "SELECT * FROM `bookmark` WHERE URL = '" + URL + "'";
1372 var maxQuery = "SELECT MAX(BID) as BID FROM `bookmark`";
1373
1374 var bookmarkReport;
1375
1376 // Query to find new BID
1377 db.query(maxQuery, (error, result, fields) => {
1378 if (error) {
1379 //res.redirect('/');
1380 bookmarkReport = [{
1381 status:false,
1382 message:"There is an error with the query"
1383 }];
1384 console.log(bookmarkReport);
1385 var returnValue = {
1386 success: '0',
1387 }
1388 res.send(returnValue);
1389 }
1390 else{
1391 console.log("BID: " + JSON.stringify(result[0].BID));
1392
1393 var newBID = 0;
1394
1395 if (result[0].BID != null) {
1396 newBID = result[0].BID + 1;
1397 }
1398
1399 scrapeTags(newBID, URL);
1400
1401 // Query to find if BID already created
1402 db.query(bookmarkQuery, (error, results) => {
1403 if (error) {
1404 //res.redirect('/');
1405 bookmarkReport = [{
1406 status:false,
1407 message:"There is an error with the query"
1408 }];
1409 var returnValue = {
1410 success: '0',
1411 }
1412 res.send(returnValue);
1413 }
1414
1415 else if(results.length >0){
1416 console.log(results);
1417 bookmarkReport = [{
1418 status:false,
1419 message:"Bookmark is already created."
1420 }];
1421 var returnValue = {
1422 success: '0',
1423 }
1424 res.send(returnValue);
1425 }
1426
1427 else{
1428 var insertBookmark = "INSERT INTO bookmark(BID, UID, Title, URL, Priority, Description, Date) VALUES (" + newBID + ", " + UID + ", '" + Title + "', '" + URL + "', '" + Priority + "', '" + Description + "', '" + newdate + "')";
1429
1430 console.log(insertBookmark);
1431 db.query(insertBookmark, (err2, inserted) => {
1432 if (err2) {
1433 //throw err;
1434 bookmarkReport = [{
1435 status:false,
1436 message:"Error creating bookmark."
1437 }];
1438 var returnValue = {
1439 success: '0',
1440 }
1441 res.send(returnValue);
1442 }
1443
1444 else{
1445 bookmarkReport = [{
1446 status:true,
1447 message:"Bookmark added."
1448 }];
1449 var returnValue = {
1450 success: '1',
1451 }
1452 res.send(returnValue);
1453 }
1454
1455
1456 });
1457 }
1458 console.log(bookmarkReport);
1459 });
1460 }
1461 });
1462 }
1463});
1464
1465// Returns {success: '0'} or {success: '1'}
1466// All Bookmark parameters required -- BID, Title, URL, Description
1467app.post('/api/editBookmark', function (req,res) {
1468 var BID = req.body.BID;
1469 var Title = req.body.Title;
1470 var URL = req.body.URL;
1471 var Priority = 1;
1472 var Description = req.body.Description;
1473
1474 console.log("REQ:" + JSON.stringify(allSessionUsers));
1475 console.log("REQ:" + req.sessionID);
1476
1477 if (BID != null && (Title != null && URL != null && Description != null)) {
1478 // new BID determined by max BID + 1
1479 //var UID = 111;
1480 //var Title = "mytitle2";
1481 //var URL = "umdearborn.edu";
1482 //var Priority = 1;
1483 //var Description = "My cool website2.";
1484
1485 var bookmarkQuery = "SELECT * FROM `bookmark` WHERE BID = '" + BID + "'";
1486 var bookmarkEditQuery = "UPDATE `bookmark` SET Title = '" + Title + "', URL = '" + URL + "', Description = '" + Description + "' WHERE BID = '" + BID + "'";
1487 console.log(bookmarkEditQuery);
1488
1489 var bookmarkReport;
1490
1491 // Query to verify BID exists
1492 db.query(bookmarkQuery, (error, result, fields) => {
1493 if (error) {
1494 bookmarkReport = [{
1495 status:false,
1496 message:"There is an error with the query: bookmark Query"
1497 }];
1498 console.log(bookmarkReport);
1499 var returnValue = {
1500 success: '0',
1501 }
1502 res.send(returnValue);
1503 }
1504 else {
1505 console.log("BID found: " + JSON.stringify(result.length));
1506
1507 if (result.length > 0) {
1508 // Proceed with edit
1509
1510 // Query to find if BID already created
1511 db.query(bookmarkEditQuery, (error, results) => {
1512 if (error) {
1513 console.log(error);
1514 bookmarkReport = [{
1515 status:false,
1516 message:"There is an error with the query: Bookmark Edit Query"
1517 }];
1518 var returnValue = {
1519 success: '0',
1520 }
1521 res.send(returnValue);
1522 }
1523
1524 else {
1525 console.log(results);
1526 bookmarkReport = [{
1527 status:true,
1528 message:"Bookmark edit successful."
1529 }];
1530 var returnValue = {
1531 success: '1',
1532 }
1533 res.send(returnValue);
1534 }
1535
1536
1537 console.log(bookmarkReport);
1538 });
1539 } else {
1540 // No bookmark found of this BID
1541 BIDReport = [{
1542 status:false,
1543 message:"No bookmark exists with this BID."
1544 }];
1545 var returnValue = {
1546 success: '0',
1547 }
1548 res.send(returnValue);
1549 console.log(BIDReport);
1550 }
1551 }
1552 console.log(bookmarkReport);
1553 });
1554 } else {
1555 var returnValue = {
1556 success: '0',
1557 }
1558 res.send(returnValue);
1559 console.log("Edit bookmark failed due to no parameters to modify.");
1560 }
1561});
1562
1563// Returns {success: '1'} if bookmark deletion is successful. This only guarantees the bookmark delete itself works.
1564// It does not represent if all associated tags are deleted. (But it attempts to remove them as well).
1565app.post('/api/deleteBookmark', function (req,res) {
1566 var BID = req.body.BID;
1567
1568 console.log("REQ:" + JSON.stringify(allSessionUsers));
1569 console.log("REQ:" + req.sessionID);
1570
1571 if (BID == null) {
1572 console.log("Null BID");
1573 console.log("Delete bookmark failed due to null parameter.");
1574 } else {
1575 var deleteBookmarkQuery = "DELETE FROM `bookmark` WHERE BID = '" + BID + "'";
1576 var tagQuery = "SELECT * FROM `bkhastag` WHERE BID = '" + BID + "'";
1577
1578 var bookmarkReport;
1579
1580 //console.log(tagQuery);
1581
1582 // Query to find all Tag ID based on the bookmark
1583 db.query(tagQuery, (error, result, fields) => {
1584 if (error) {
1585 bookmarkReport = [{
1586 status:false,
1587 message:"Error finding tag id."
1588 }];
1589 var returnValue = {
1590 success: '0',
1591 }
1592 res.send(returnValue);
1593 } else {
1594 for (var i = 0; i < result.length; i++) {
1595 var TID = result[i].TID;
1596
1597 if (TID != null) {
1598 var deleteTagKeyQuery = "DELETE FROM `bkhastag` WHERE TID = '" + TID + "'";
1599 var deleteTagQuery = "DELETE FROM `tag` WHERE TID = '" + TID + "'";
1600 //console.log(deleteTagKeyQuery)
1601
1602 db.query(deleteTagQuery, (error, result, fields) => {
1603 if (error) {
1604 bookmarkReport = [{
1605 status:false,
1606 message:"Error deleting Tag ID."
1607 }];
1608 } else {
1609 bookmarkReport = [{
1610 status:true,
1611 message:"Success deleting Tag ID."
1612 }];
1613 }
1614 console.log(bookmarkReport);
1615 });
1616
1617 db.query(deleteTagKeyQuery, (error, result, fields) => {
1618 if (error) {
1619 bookmarkReport = [{
1620 status:false,
1621 message:"Error deleting Tag ID Key."
1622 }];
1623 } else {
1624 bookmarkReport = [{
1625 status:true,
1626 message:"Success deleting Tag ID Key."
1627 }];
1628 }
1629 console.log(bookmarkReport);
1630 });
1631 }
1632 }
1633 }
1634
1635 console.log(bookmarkReport);
1636 });
1637
1638 db.query(deleteBookmarkQuery, (error, result, fields) => {
1639 if (error) {
1640 bookmarkReport = [{
1641 status:false,
1642 message:"Error deleting bookmark."
1643 }];
1644 var returnValue = {
1645 success: '0',
1646 }
1647 res.send(returnValue);
1648 } else {
1649 var returnValue = {
1650 success: '1',
1651 }
1652 res.send(returnValue);
1653 }
1654 });
1655 }
1656});
1657
1658// Handles any requests that don't match the ones above
1659app.get('*', (req,res) =>{
1660 res.sendFile(path.join(__dirname+'/client/build/index.html'));
1661});
1662
1663const port2 = process.env.PORT || 5000;
1664app.listen(port2);
1665
1666console.log('App is listening on port ' + port2);