-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
1725 lines (1489 loc) · 55.8 KB
/
app.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";
/*
This is the controller that actually has the entry point code of project.In any express application, there are basically three main files in the
directory, the first one is called the app.js which contains the code for the entry point(routing and so on) of the application and project, the node
modules sub dir which contains the modules for express and any other modules that we have installed using npm for instance and package.json
package.json is a file that contains the dependencies. When you install express using npm package.json is not created. We need to create package.json
file (see documentation of node for that) automatically or manually. After this if we delete node modules dir, we can simply install express by command
'node install' and using the package.json file it is gonna install express and create node modules directory for us again.
The package.json file can be created using the command 'npm init' in our node command line.
*/
var express=require('express');//includes express module.
var fs=require('fs');
var path=require('path');//includes path modules
var helper=require('helper.js');//custom directory for a few helper functions.
var chalk=require('chalk');
var mime=require('mime');//for file uploads
// var session=require('express-session');//this is actually for the session storage for the user.
var session=require('express-session');//this is using the mozilla library or module called express-sessions.
var mysql=require('mysql');
var escape=require('html-escape');//this is just for escaping special characters.
var passHash=require('password-hash');//this module will be required for hashing the password into the table.
var bodyParser=require('body-parser');//for handling post requests we need to use body parser.
var multer = require('multer');//for uploading files(images and videos)
var app=express();//making an instance of express module and we can call various functions from within express using app.<function name>
var server=app.listen(1337,function(){
console.log("listening at port 1337");
});//listening at port 1337
var io=require('socket.io').listen(server);//this is essentially gonna be the socket.io library that we are gonna use for real time form feed
//listen to the same server for the web socket connection
// TODO: use sequelize library instead for interacting with the database. use replication server support in sequelize
// TODO: use winston logger with morgan
// TODO: use node-cache
// TODO:
const settings_path = process.env.APP_SETTINGS || path.join(__dirname, "conf.json");
const settings = require(settings_path).settings;
var connection = mysql.createConnection({
host: settings.MYSQL_HOST,
user: settings.MYSQL_USER,
password: settings.MYSQL_PASSWORD,
database: settings.MYSQL_DB
});
connection.connect(function(err){
if(err)
{
console.error('error connecting to the database: '+err.stack);
//this will also show the error.
}
else {
console.log("connection established successfully");
}
});
/*
This is the database integration part of the application.
host is by default localhost, username and password must match with those running on the server and database must be defined.
port number for mysql server is set by default 3306 which is also the default port number set by this library.
*/
app.set('view engine','ejs');//this is for a plugin support for express.there are various technologies that we can plugin into our application
/*
A template engine enables you to use static template files in your application. At runtime, the template engine replaces variables in a
template file with actual values,and transforms the template into an HTML file sent to the client.
This approach makes it easier to design an HTML page.
The use of this is similar to the concept of rendering views.
we can do app.set('view engine','pug');//pug is a template engine for express.
we can now write our render function in the following way:
app.get('/',function(req,res){res.render('index',{title:'Hey',message:'Hello there!!!'})});
Now inside the index.pug file we can simply use title and message as variables and it will be replaced with their corresponding values rendered
with the render function in the controller.
*/
//our code here is setting the view engine or template engine to 'ejs'
app.use(express.static(path.join(__dirname,'public')));//middleware
//app.use(app.Router);//here this simply means that we are using routes.
//app.use(cookieParser());
/*
Middleware is just code that you inject into the request-response lifecyle of our application.
It just means that you are telling the server to do something in between when the request is sent by the client and the reponse is
generated by the server.
*/
/*
In our code this tells us that if we have a static request that comes in then go ahead and assume it lives in the public directory.
Here static content simply means images, css, js that are directly being used by the views or web pages.
*/
//another middleware. This time its about sessions...
app.use(session({
cookieName:'session',
secret:'myShare50WorldBeatsOnThisLineDoNotTamper',
duration:30*60*1000,
activeDuration:5*60*1000
}));
//this is the middleware that sets up cookies for the user(client side).
/*
genid it is a new generated session id
cookieName is the name given to every cookie.
secret is a string that is used to encrypt the cookie. meanwhile the library internally will encrypt and decrypt the secret so that the
cookie remains safe in the user's browser.
the duration is the time(in ms) that the cookie will remain active
activeDuration is the time(in ms) that the cookie will remain active after the the user has clicked has reloaded the page.
*/
app.use(bodyParser());
/*
This is the middleware that will be required for the purpose of form handling and post request handling.
*/
var param={};
function startSession(req,email,uid)
{
req.session.email=email;
console.log("email of session object is:"+email);
req.session.uid=uid;
// var param={};
param["email"]=email;
param["uid"]=uid;
return param;
}
function setParam(email,userId)
{
// var param={};
param["email"]=email;
param["uid"]=userId;
return param;
}
app.get('/',function(req,res){
/*console.log('Cookies:',req.cookies);
now this is important here because if we get a session that had been set already then we must redirect the user to the index page
and not the landing page.
If however the session data does not exist we can redirect the user to the landing page.
*/
var userId;
if(req.session&&req.session.email)//this simply checks if the session exists...
{
console.log(chalk.blue("/ GET:session found"));//DEBUG
//so we need to pass both the email and the id to index the user
connection.query("SELECT * FROM users WHERE email=?",[req.session.email],function(err, results,fields){
userId=results[0].uid;
param=setParam(req.session.email,userId);
helper.renderPage(app,fs,res,io,connection,'index',param);
console.log(chalk.blue("/ GET:index page rendered..."));
});
}
else
{
console.log(chalk.blue("/ GET:no session found"));//DEBUG
console.log(chalk.blue("/ GET:landing page being rendered"));
res.render('landing');
}
});
app.get('/emailCheck',function(req,res){
//this function is for ajax checking whether the email that was entered by the user actually exists
var jsonRes;
console.log(chalk.blue("/emailCheck GET:ajax emailCheck request made."));//DEBUG
var email=req.query.email;
connection.query('SELECT * FROM users WHERE email=?',[email],function(err,results,fields){
if(err){
res.send(JSON.stringify({emailFound:0}));
console.log(chalk.red("oops, something went wrong", err));//DEBUG
}
else if(Object.keys(results).length>0){
//turns out that results is an object that has key value pairs here.
res.send(JSON.stringify({emailFound:1}));//send a json response
console.log(chalk.green("/emailCheck GET:email found"));//DEBUG
}
else {
console.log(chalk.green("/emailCheck GET:no emails found"));//DEBUG
res.send(JSON.stringify({emailFound:0}));//send a json response
}
});
});
app.get("/indexRequest",function(req,res){
console.log(chalk.green("/wellContentRequest GET:ajax request received "));
if(req.session.email&&req.session)
{
connection.query("SELECT * FROM users WHERE email=?",[req.session.email],function(err,results,fields){
var uid=results[0].uid;
connection.query("SELECT * FROM friends WHERE (uid=? OR fuid=?) AND isAccepted=?",[uid,uid,1],function(err,results,fields){
var hasFriends=Object.keys(results).length;
// console.log("hasFriends:"+hasFriends);
res.json({hasFriends:hasFriends});
});
});
console.log(chalk.green('/wellContentRequest GET:response sent'));//this is just sending the uid but i can potentially send many more
//things like whole data based on what the friends of the person are and what photos and videos the friends have shared
}
else {
console.log(chalk.red('/wellContentRequest GET:no session found'));
res.render('landing');
}
});
app.get("/searchFriends",function(req,res){//ajax for searching friends
if(!(req.session&&req.session.email))
{
res.render('landing');
}
else{
var friend=req.query.friend;
var userid=req.query.uid;
console.log("/searchFriends GET:friend:"+friend);
friend="%"+friend+"%";
connection.query("SELECT * FROM users WHERE name LIKE ? AND email NOT IN (?)",[friend,req.session.email],function(err,results,fields){
if(err)
{
console.log("/searchFriends GET:error searching from database:"+err.stack);
}
else {
var num=Object.keys(results).length;
if(num>0){
var val,uid;
var i=0;
param={};
param["num"]=num;
while(i<num)
{
val="val"+i.toString();
param[val]=results[i].name;
uid="uid"+i.toString();
param[uid]=results[i].uid;
i++;
}
//param now contains the list of the name and uids of the users having similar names (except the user logged in)
// helper.checkFriendList(chalk,res,param,userid,connection);
res.send(JSON.stringify(param));
}
else {
param["num"]=0;
res.send(JSON.stringify(param));
}
}
});
}
});
app.post("/friendRequest",function(req,res){
if(!(req.session&&req.session.email))
{
res.render('landing');
}
else{
var uid=req.body.friendList;
console.log(chalk.blue("/friendRequest GET:req.query.friendList returned:"+uid));
var userid;
connection.query("SELECT * FROM users WHERE email=?",[req.session.email],function(err,results,fields){
userid=results[0].uid;
var date=getDateToday();
connection.query("SELECT * FROM friends WHERE ((fuid=? AND uid=?) OR (uid=? AND fuid=?)) AND isAccepted=?",[uid,userid,uid,userid,1],function(errNew, resultsNew,fieldsNew){
if(Object.keys(results).length>0){
connection.query("SELECT * FROM users WHERE uid=?",[uid],function(e,r,f){//here uid is the friend's uid.
var name=r[0].name;
var pageName="Hey check out!!!";
console.log("error, seems you are trying to insert into database again...");
res.render('friendRequestPageError',{page:pageName,friend:name});
});}
});
connection.query("INSERT INTO friends (uid,fuid,isAccepted,timeOfCreation) VALUES (?,?,?,?)",[userid,uid,0,date],function(err,results,fields){
if(err)//the most probability of this error is only when you are trying to make a friend request that already exists
{
console.log(chalk.red("/friendRequest GET:could not insert into database"+err.stack));
param=setParam(req.session.email,userid);
// helper.renderPage(app,fs,res,io,connection,'index',param);
// console.log("uid now:"+uid);
}
else {
console.log(chalk.green("/friendRequest GET:successfully inserted into database"));
param=setParam(req.session.email,userid);
// helper.renderPage(app,fs,res,io,connection,'index',param);
var pageName="friend Request Sent";
res.render("friendRequestSent",{page:pageName});
}
});
});
}
});
app.get("/checkFriendReq",function(req,res){
if(!(req.session&&req.session.email))
{
res.render('landing');
}
else{
connection.query("SELECT * FROM users WHERE email=?",[req.session.email],function(err,results,fields){
var userid=results[0].uid;
console.log("/checkFriendReq GET: user id of the user logged in is:"+userid);
connection.query("SELECT * FROM friends WHERE fuid=? AND isAccepted=?",[userid,0],function(err,results,fields){
if(err)
{
console.log(chalk.red("/checkFriendReq GET:error in selecting from db"+err.stack));
param=setParam(req.session.email,userid);
helper.renderPage(app,fs,res,io,connection,'index',param);
}
else {
console.log(chalk.green("/checkFriendReq GET:successfully retrieved from db"));
var requests=Object.keys(results).length;
res.send(JSON.stringify({hasRequests:requests}));
}
});
});
}
});
app.get("/friendRequestPage",function(req,res){
if(!(req.session&&req.session.email))
{
res.render('landing');
}
else{
var pageName="friendRequestPage";
var uid=req.query.uid;
res.render("friendRequestPage",{page:pageName,uid:uid});}
});
app.get("/showFriendRequests",function(req,res){
if(!(req.session&&req.session.email))
{
res.render('landing');
}
else{
console.log(chalk.blue("/showFriendRequests GET:ajax request received"));
var uid;
// connection.query("SELECT * FROM users WHERE email=?",[req.session.email],function(err,results,fields){
connection.query("SELECT users.name,users.email FROM friends INNER JOIN users ON friends.uid=users.uid WHERE friends.fuid=? AND friends.isAccepted=?",[req.query.uid,0],function(err,results,fields){
var i=0;
var data={};
var uid,name,email;
console.log("results:"+Object.keys(results).length);
if(Object.keys(results).length==0)
{
console.log(chalk.green("/showFriendRequests GET: no friend reqs pending"));
// param=setParam(req.session.email,req.query.uid);
res.send(JSON.stringify({name0:null}));
// helper.renderPage(app,fs,res,io,connection,'index',param);//this is the uid of the user logged in
}
else {
while(i<Object.keys(results).length)
{
uid="uid"+i.toString();
name="name"+i.toString();
email="email"+i.toString();
// data[uid]=results[i].uid;
data[name]=results[i].name;
data[email]=results[i].email;
i++;
}
res.send(JSON.stringify(data));
// helper.respondNames(chalk,connection,res,data);//only for grabbing the names and emails before sending a json response to the client
}
});
}
});
app.get("/acceptFriendRequest",function(req,res){
if(!(req.session&&req.session.email))
{
res.render('landing');
}
else{
console.log(chalk.blue("acceptFriendRequest GET:request sent to accept friend by email:"+req.query.email));
connection.query("SELECT * FROM users WHERE email=?",[req.query.email],function(err,results,fields){
var uid=results[0].uid;
connection.query("UPDATE friends SET isAccepted=? WHERE uid=? AND fuid=?",[1,uid,req.query.uid],function(err,results,fields){
if(err)//here req.query.uid is the uid of the user logged in currently
{
console.log(chalk.red("could not update the database"));
}
else {
console.log(chalk.green("updated the database successfully"));
var pageName="friendRequestPage";
uid=req.query.uid;
res.render("friendRequestPage",{page:pageName,uid:uid});
}
});
});
}
})
app.post('/signIn',function(req,res){
//now if the user signs in successfully then we need to check from the database whether the user exists or not...
console.log(chalk.blue("/signIn POST:sign in request made"));//DEBUG
var userId;
if(req.session && req.session.email)
{
console.log(chalk.blue("/signIn POST:session exists"));//DEBUG
connection.query("SELECT * FROM users WHERE email=?",[req.session.email],function(err, results,fields){
userId=results[0].uid;
// console.log("/signIn GET:user id returned is"+userId);
param=setParam(req.session.email,userId);
helper.renderPage(app,fs,res,io,connection,'index',param);
});
}
else {
console.log(chalk.blue("/signIn POST:session does not exist"));//DEBUG
email=escape(req.body.email);
// console.log(chalk.blue("/signIn POST:email received:"+email));
password=escape(req.body.password);
// console.log(chalk.blue("/signIn POST:password received:"+password));
connection.query("SELECT * FROM users WHERE email=?",[email],function(err,results,fields){
if(err)
{
console.log(chalk.red("/signIn POST:could not run query:"+err.stack));//DEBUG
}
else {
if(Object.keys(results).length==0)
{
//so the only way is if the email is incorrect...
var pageName="emailNotFound";
res.render('emailNotFound',{page:pageName});
}
else {
console.log(chalk.green("/signIn POST:query successful"));//DEBUG
if(passHash.verify(password,results[0].password))
{
//start a session and render index page
console.log(chalk.green("/signIn POST:login successful, session started"));//DEBUG
param=startSession(req,email,results[0].uid);//custom function
helper.renderPage(app,fs,res,io,connection,'index',param);
}
else {
console.log(chalk.red("/signIn POST:login unsuccessful, rendered loginError page"));//DEBUG
res.render('loginError',{email:email});//render a page called log in error
}
}
}
});
}
});
app.post("/signInError",function(req,res){
var email=escape(req.query.email);
var password=escape(req.body.password);
connection.query("SELECT * FROM users WHERE email=?",[email],function(err,results,fields){
if(err)
{
console.log(chalk.red("/signIn POST:could not run query:"+err.stack));//DEBUG
}
else {
console.log(chalk.green("/signIn POST:query successful"));//DEBUG
if(passHash.verify(password,results[0].password))
{
//start a session and render index page
console.log(chalk.green("/signIn POST:login successful, session started"));//DEBUG
param=startSession(req,email,results[0].uid);//custom function
helper.renderPage(app,fs,res,io,connection,'index',param);
}
else {
console.log(chalk.red("/signIn POST:login unsuccessful, rendered loginError page"));//DEBUG
res.render('loginError',{email:email});//render a page called log in error
}
}
});
});
app.post('/signUp',function(req,res){
console.log("/signUp POST:sign up request made");
var userId;
if(req.session&&req.session.email)//if session exits.
{
console.log(chalk.red("/signUp POST:session found"));//DEBUG
connection.query("SELECT * FROM users WHERE email=?",[req.session.email],function(err, results,fields){
userId=results[0].uid;
param=setParam(req.session.email,userId);
helper.renderPage(app,fs,res,io,connection,'index',param);
console.log(chalk.red("/signUp POST:index page rendered"));//DEBUG
});
}
else {
//error checking
console.log(chalk.green("/signUp POST:signUp post request made"));//DEBUG
//if the user signs up, we need to make sure that he has registered...
//connection to the database will be made here and we will register the user...
// console.log("connection established successfully");
var firstName=escape(req.body.firstName);
var lastName=escape(req.body.lastName);
var name=firstName+" "+lastName;
var email=escape(req.body.email);
var date=req.body.date;
// console.log('date:'+date);
var month=req.body.month;
// console.log('month:'+month);
var year=req.body.year;
var dob=year.toString()+"-"+month.toString()+"-"+date.toString();
//from reading the documentation of mysql i know that date accpets yyyy-mm-dd as a string
var gender=req.body.gender;
if(gender==undefined)
{
gender=1;
}
var password;
var rawPass=req.body.checkPass;
// console.log("email is: "+email);
// console.log("dob: "+dob);
// console.log("password given by user: "+rawPass);
password=passHash.generate(rawPass);
connection.query('INSERT INTO users (name,email,dob,gender,password) VALUES (?,?,?,?,?)',[name,email,dob,gender,password],function(err,results,fields){
var id;
connection.query('SELECT * FROM users WHERE email=?',[email],function(errNew,resultsNew,fieldsNew){
id=resultsNew[0].uid;//getting the id of the user and setting the user accordingly...
console.log(chalk.blue("/signUp POST:user id retrieved from db:"+id));//DEBUG
//results will contain the results of the query.
//fields will contain the information about the returned results.
if(errNew)
{
console.log(chalk.red("/signUp POST:error encountered",err.stack));//DEBUG
}
else {
//another thing to be inserted is user data in userimages field.
connection.query("INSERT INTO userimages VALUES (?,?)",[id,0],function(errN,resultsN,fieldsN){});
console.log(chalk.green("/signUp POST:successfully inserted into database"));//DEBUG
//after we get the details inside the database we need to start a session and redirect the user to the index.ejs view.
console.log(chalk.green("/signUp POST:successfully added sessions and started it."));//DEBUG
console.log("id now is:"+id);
param=startSession(req,email,id);
helper.renderPage(app,fs,res,io,connection,'index',param);//this function defined in helper.js actually will be used for rendering the index page
//of the user with the account email.
// res.render('index');
}
});
});
//for info on queries follow:https://github.com/mysqljs/mysql#performing-queries*/
}
});
var storage=multer.diskStorage({destination:function(req,file,cb){
//cb is callback
cb(null,'public/images/acc/');
},filename:function(req,file,cb){
// console.log("inisde diskStorage callback, file obtained is :"+file.originalname);
// var date=new Date();
connection.query("SELECT * FROM users WHERE email=?",[req.session.email],function(err,results,fields){
if(err)
{
console.log("error in file storage");
}
else {
var userid=results[0].uid;
cb(null,file.fieldname+userid+"."+mime.extension(file.mimetype));
}
});
}});
var upload = multer({ storage:storage });
//so below we are essentially defining 2 different things, the destination and the filenames of the corresponding images
var imageStorageTours=multer.diskStorage({
destination:function(req,file,cb){
cb(null,'public/images/tours');
},
filename:function(req,file,cb){
var uid=req.session.uid;
var images=0;
var name;
connection.query("SELECT * FROM userimages WHERE uid=?",[uid],function(err,results,fields){
console.log(chalk.blue("inside imageStorageTours: the noOfImages returned is:"+results[0].noOfImages));
images=results[0].noOfImages+1;
name=uid.toString()+images.toString()+"."+mime.extension(file.mimetype);
cb(null,name);
});
}
});
var uploadImageTours=multer({storage:imageStorageTours});
var imageStorageParties=multer.diskStorage({
destination:function(req,file,cb){
cb(null,'public/images/parties');
},
filename:function(req,file,cb){
var uid=req.session.uid;
var images=0;
var name;
connection.query("SELECT * FROM userimages WHERE uid=?",[uid],function(err,results,fields){
images=results[0].noOfImages+1;
name=uid.toString()+images.toString()+"."+mime.extension(file.mimetype);
cb(null,name);
});
}
});
var uploadImageParties=multer({storage:imageStorageParties});
app.get('/profile',function(req,res){
if(req.session.email&&req.session)
{
param={};
// var name;
console.log(chalk.green("/profile GET:session found"));
var userId;
connection.query("SELECT * FROM users WHERE email=?",[req.session.email],function(err,results,fields){
// console.log("inside profile name is:"+results[0].name);
param["name"]=results[0].name;
// console.log("inside profile now object is:"+param.name);
param["email"]=results[0].email;
param["dob"]=results[0].dob.toString().substring(0,15);
if(results[0].profilePicPath==null)
{
param["profileSrc"]="images/acc/emoticonNoFace.png";
}
else {
var path="images/acc/"+results[0].profilePicPath;
// path=path.substring(7);//we are omiting public/ from our path
var mime=results[0].profilePicMime;
/*switch(mime)
{
case "image/jpeg":
{
path=path+".jpg";
break;
}
case "image/bmp":
{
path=path+".bmp";
break;
}
case "image/x-windows-bmp":
{
path=path+".bmp";
break;
}
case "image/png":
{
path+=".png";
break;
}
}*/
param["profileSrc"]=path;
}
userId=results[0].uid;
param["userid"]=userId;
connection.query("SELECT * FROM tours WHERE uid=?",[userId],function(err,results,fields){
if(Object.keys(results).length>0)
{
param["tourNum"]=Object.keys(results).length;
}
else {
//console.log(chalk.blue("tour number is 0"));
param["tourNum"]=0;
}
});
connection.query("SELECT * FROM party WHERE uid=?",[userId],function(err,results,fields){
if(Object.keys(results).length>0)
{
param["partyNum"]=Object.keys(results).length;
}
else {
param["partyNum"]=0;
}
});
connection.query("SELECT * FROM friends WHERE (uid=? OR fuid=?) AND isAccepted=?",[userId,userId,1],function(err,results,fields){
if(Object.keys(results).length>0)
{
console.log("friends is not zero")
param["friends"]=Object.keys(results).length;
}
else {
param["friends"]=0;
}
helper.renderPage(app,fs,res,io,connection,'profile',param);
});
// helper.renderPage(app,fs,res,io,connection,'profile',param);
});
}
else {
console.log(chalk.red("/profile GET:session not found"));
res.render('landing');
}
});
app.post("/profilePicUpload",upload.single('pic'),function(req,res){//upload.single(<fieldname>) fieldname is the name of the field from wehere we are trying to upload the file(form field name)
if(!(req.session&&req.session.email))
{
res.render('landing');
}
else {
var pic=req.file;//this is an object that contains attributes like path that we can use for storing in the database
// console.log("")
// console.log("mime type currently is:"+pic.mimetype);
//we can use a modeule mmmagic of express that can check mime types of files, make sure to see this from github
if(pic==undefined)
{
var pageName="Hey check out";
res.render("fileNotChosen",{page:pageName});
return;
}
connection.query("UPDATE users SET profilePicPath=?,profilePicMime=? WHERE email=?",[pic.filename,pic.mimetype,req.session.email],function(err,results,fields){
if(err)
{
console.log(chalk.red("error inserting into database:"+err.stack));
}
else {
console.log(chalk.green("successfully inserted into database"));
connection.query("SELECT * FROM users WHERE email=?",[req.session.email],function(errNew,resultsNew,fieldsNew){
var userid=resultsNew[0].uid;
param=setParam(req.session.email,userid);
helper.renderPage(app,fs,res,io,connection,'index',param);
});
}
});
}
});
app.get("/tours",function(req,res){
if(req.session&&req.session.email)
helper.renderPage(app,fs,res,io,connection,'tours',param);
else {
res.render('landing');
}
});
app.get("/parties",function(req,res){
if(req.session.email&&req.session.email)
helper.renderPage(app,fs,res,io,connection,'parties',param);
else {
res.render('landing');
}
});
function getDateToday(){//sync function
var dateToday=new Date();//there is a class named Date in js that has getter functions to get the day, month and year
var day=dateToday.getDate();
var month=dateToday.getMonth()+1;//since jan is 0
var year=dateToday.getFullYear();
if(day<10) {
day='0'+day;
}
if(month<10) {
month='0'+month;
}
return year+"-"+month+"-"+day;
}
app.get("/dateSent",function(req,res){
//this is actually gonna check from the database if the user has any party or tour scheduled
if(!(req.session&&req.session.email))
{
res.render('landing');
}
else {
console.log(chalk.blue("/dateSent GET: ajax request recieved"));
var day=req.query.day;
var month=req.query.month;
var year=req.query.year;
var userid;
var date=year+"-"+month+"-"+day;
// console.log("date is:"+date);
var page=req.query.reqPage;
// console.log("page is:"+page);
connection.query("SELECT * FROM users WHERE email=?",[req.session.email],function(err,results,fields){
if(err)
console.log("error in selection itself");
userid=results[0].uid;
if(page=="tours")
helper.toursCheck(res,userid,connection,date);
else {
helper.partyCheck(res,userid,connection,date);
}
});
}
});
app.get('/friendList',function(req,res){
//so according to the email of of the session that will be existing in the server the friendlist of the person will be prepared and sent
if(!(req.session&&req.session.email))
{
res.render('landing');
}
else {
connection.query("SELECT * FROM users WHERE email=?",[req.session.email],function(err,results,fields){
var id=results[0].uid;
connection.query("SELECT users.uid,users.email,users.name FROM friends INNER JOIN users ON (friends.uid=users.uid OR friends.fuid=users.uid) WHERE (friends.uid=? OR friends.fuid=?) AND friends.isAccepted=1",[id,id],function(err,results,fields){
var friendList={};
var i,name,email,uid,id;
friendList["elements"]=Object.keys(results).length;
for(i=0;i<Object.keys(results).length;i++)
{
if(results[i].email.localeCompare(req.session.email)!=0)
{
name="name"+i;
email="email"+i;
id="id"+i;
friendList[name]=results[i].name;
friendList[id]=results[i].uid;
friendList[email]=results[i].email;
}
}
//here we have the array called friendList, lets store that data in the session object
//here we only send the ids of the friends
// helper.sendFriendList(chalk,connection,res,friendList);
req.session.friendList=friendList;
res.send(JSON.stringify(friendList));
});
});
}
});
app.post('/partiesCreate',function(req,res){
//partiesCreate is a get request originated from tours.ejs page.
//so the following are the informations that we receive: destination, leaving, return, description and a bunch of emails.
if(!(req.session&&req.session.email))
{
res.render('landing');
}
else {
var destination=req.body.destination;
var leavingDate=req.body.leaving;
var returnDate=req.body.return;
var description=req.body.description;
//first lets check how many friends does the guy have
connection.query("SELECT * FROM users WHERE email=?",[req.session.email],function(err,results,fields){
var uid=results[0].uid;
var randomVal=Math.random();
connection.query("INSERT INTO party(uid,Description,start,end,destination,popularity,randomVal,isOver) VALUES (?,?,?,?,?,0,?,0) ",[uid,description,leavingDate,returnDate,destination,randomVal],function(err,results,fields){
if(err)
{
console.log(chalk.red("could not enter into the database:"+err.stack));
}
else
console.log(chalk.green("successfully entered into the database:"));
});
connection.query("SELECT * FROM party WHERE uid=? AND randomVal=?",[uid,randomVal],function(err,results,fields){
var pid=results[0].pid;
/*if(req.session.friendList==null)//error checking
console.log("req.session.friendList is null");
else {
console.log("req.session.friendList is not null, voila");
}*/
var friendList=req.session.friendList;
var checkBoxName;
for(var key in friendList)
{
if(key.substring(0,2).localeCompare("id")==0)
{
console.log(chalk.blue("friendList value is:"+friendList[key]));
checkBoxName=friendList[key];
var value=req.body[checkBoxName];
if(value==null)
{
console.log(chalk.blue("friendList[key]:"+friendList[key]+"has a value of undefined"));
//do not add as a visitor
}
else {
//add as a visitor
console.log(chalk.blue("friendList[key]:"+friendList[key]+"has a defined value"));
connection.query("INSERT INTO visitor(pid,uid,visitorId,isAccepted) VALUES (?,?,?,0)",[pid,uid,checkBoxName],function(err,results,fields){
if(err)
{
console.log(chalk.red("error inserting into the database:"+err.stack));
}
else{console.log(chalk.green("successfully inserted into visitor table"));}
});
}
}
}
});
});
var pageName="PartyCreated";
res.render('partyCreated',{page:pageName});
}
});
app.post('/toursCreate',function(req,res){
if(!(req.session&&req.session.email))
{
res.render('landing');
}
else {
var destination=req.body.destination;
console.log(chalk.blue("destination accepted:"+destination));
var leavingDate=req.body.leaving;
console.log(chalk.blue("leaving date accepted:"+leavingDate));
var returnDate=req.body.return;
console.log(chalk.blue("returnDate accepted:"+returnDate));
var description=req.body.description;
console.log(chalk.blue("description accepted:"+description));
//first lets check how many friends does the guy have
connection.query("SELECT * FROM users WHERE email=?",[req.session.email],function(err,results,fields){