arnaucube
arnaucube/commonroutesServerPublic Self-hosted repository
commonroutesServer/controllers/travelController.js
controllers/travelController.jsRaw
  1var config = require('../config');
  2var pageSize=config.pageSize;
  3
  4//import data models
  5var mongoose = require('mongoose');
  6var userModel  = mongoose.model('userModel');
  7var notificationModel  = mongoose.model('notificationModel');
  8var travelModel  = mongoose.model('travelModel');
  9var commentModel  = mongoose.model('commentModel');
 10
 11exports.getAllTravels = function(req, res) {
 12	//get travels with futures dates ($gte - greater than and equal than)
 13	travelModel.find({date: {$gte: new Date()}})
 14	.sort('date')
 15    .limit(pageSize)
 16    .skip(pageSize * Number(req.query.page))
 17    .lean()
 18    .populate('user', 'username avatar validated')
 19    .exec(function (err, travels) {
 20        if (err) return res.send(500, err.message);
 21        res.status(200).jsonp(travels);
 22    });
 23};
 24
 25exports.getTravelById = function (req, res) {
 26    travelModel.findOne({_id: req.params.travelid})
 27    .lean()
 28    .populate('user', 'username avatar validated telegram phone')
 29    .populate('joins', 'username avatar')
 30    .populate('joinPetitions', 'username avatar')
 31    .populate('comments', 'comment user')
 32    .exec(function (err, travel) {
 33        if (err) return res.send(500, err.message);
 34        if (!travel) {
 35            res.json({success: false, message: 'travel not found.'});
 36        } else if (travel) {
 37
 38            res.status(200).jsonp(travel);
 39        }
 40    });
 41};
 42
 43exports.addTravel = function(req, res) {
 44	userModel.findOne({'token': req.headers['x-access-token']})
 45	.exec(function(err, user){
 46		if (err) return res.send(500, err.message);
 47		if (!user) {
 48			console.log("user not found");
 49            res.json({success: false, message: 'User not found.'});
 50        } else if (user) {
 51			var travel = new travelModel({
 52				title: req.body.title,
 53			    description:   req.body.description,
 54			    user:   user._id,
 55			    from:   req.body.from,
 56			    to:   req.body.to,
 57			    date:   req.body.date,
 58				periodic: req.body.periodic,
 59			    generateddate: Date(),
 60				seats: req.body.seats,
 61				package: req.body.package,
 62				collectivized: req.body.collectivized,
 63				type: req.body.type
 64			});
 65
 66			travel.save(function(err, travel) {
 67				if(err) return res.send(500, err.message);
 68
 69				user.travels.push(travel._id);
 70				user.save(function (err, user) {
 71                    if (err) return res.send(500, err.message);
 72					exports.getAllTravels(req, res);
 73                });
 74			});//end of travel.save
 75		}
 76	});//end of usermodel.find
 77
 78
 79};
 80
 81exports.updateTravel = function(req, res) {
 82	userModel.findOne({'token': req.headers['x-access-token']})
 83	.exec(function(err, user){
 84        if (err) return res.send(500, err.message);
 85        console.log(travel);
 86        travelModel.findOne({_id: travel._id})
 87        .lean()
 88        .populate('travels', 'title from to date')
 89        .exec(function (err, travel) {
 90            if (err) return res.send(500, err.message);
 91            if (!travel) {
 92                res.json({success: false, message: 'travel not found.'});
 93            } else if (travel) {
 94
 95                res.status(200).jsonp(travel);
 96            }
 97        });
 98    });
 99};
100
101exports.deleteTravel = function(req, res) {
102	userModel.findOne({'token': req.headers['x-access-token']})
103	.exec(function(err, user){
104		if (err) return res.send(500, err.message);
105		travelModel.findById(req.params.travelid, function(err, travel) {
106			if (err) return res.send(500, err.message);
107			if(travel.user.equals(user._id))
108			{
109				travel.remove(function(err) {
110					if(err) return res.send(500, err.message);
111
112					console.log("deleted");
113					exports.getAllTravels(req, res);
114				});
115			}
116		});
117	});
118};
119
120
121exports.addJoinPetition = function(req, res) {
122	userModel.findOne({'token': req.headers['x-access-token']})
123	.exec(function(err, userJoining){
124		if (err) return res.send(500, err.message);
125		if (!userJoining) {
126            res.json({success: false, message: 'User not found.'});
127        } else if (userJoining) {
128			travelModel.findOne({
129				_id: req.params.travelid,
130				user: {'$ne': userJoining._id},
131				joins: {'$ne': userJoining._id},
132				joinPetitions: {'$ne': userJoining._id}
133			})
134			.exec(function(err, travel){
135				if (err) return res.send(500, err.message);
136				if (!travel) {
137		            res.json({success: false, message: 'travel not found. You can not join a travel if you have created it, or if you have already joined'});
138		        } else if (travel) {
139					travel.joinPetitions.push(userJoining._id);
140					travel.save(function(err, travel) {
141						if(err) return res.send(500, err.message);
142
143						//start saving notification, get user owner of travel
144						userModel.findOne({_id: travel.user})
145						.exec(function(err, user){
146							if (err) return res.send(500, err.message);
147							if (!user) {
148					            res.json({success: false, message: 'User not found.'});
149					        } else if (user) {
150							//notification
151								var notification = new notificationModel({
152									concept: "join",
153									message: "user "+userJoining.username+" joins your travel "+travel.title,
154									date: new Date(),
155									icon: 'ion-person-add',
156									link: "travels/" + travel._id,
157			                        user: user._id
158								});
159								notification.save(function(err, notification) {
160									if (err) return res.send(500, err.message);
161									user.notifications.push(notification._id);
162									user.save(function(err, user) {
163										if (err) return res.send(500, err.message);
164
165										console.log("notification saved");
166										exports.getTravelById(req, res);
167									});
168								});
169							}
170						});//end saving notification
171					});
172				}//end of else if travel
173			});
174		}//end of else if user
175	});
176};
177
178exports.unJoin = function(req, res) {
179	userModel.findOne({'token': req.headers['x-access-token']})
180	.exec(function(err, userJoining){
181		if (!userJoining) {
182            res.json({success: false, message: 'userJoining not found.'});
183        } else if (userJoining) {
184			travelModel.findOne({
185				_id: req.params.travelid,
186				joinPetitions: userJoining._id
187			})
188			.exec(function(err, travel){
189				if (err) return res.send(500, err.message);
190				if (!travel) {
191		            res.json({success: false, message: 'can not unjoin this travel'});
192		        } else if (travel) {
193					for(var i=0; i<travel.joinPetitions.length; i++)
194					{
195						if(travel.joinPetitions[i].equals(userJoining._id))
196						{
197							travel.joinPetitions.splice(i, 1);
198						}
199					}
200					travel.save(function(err, travel) {
201						if(err) return res.send(500, err.message);
202						//start saving notification, get user owner of travel
203						userModel.findOne({_id: travel.user})
204						.exec(function(err, user){
205							if (err) return res.send(500, err.message);
206							if (!user) {
207				            res.json({success: false, message: 'User not found.'});
208				        } else if (user) {
209								//notification
210								var notification = new notificationModel({
211									concept: "unjoin",
212									message: "user "+userJoining.username+" unjoins your travel "+travel.title,
213									date: new Date(),
214									icon: 'ion-arrow-return-left',
215									link: "travels/" + travel._id,
216			                        user: user._id
217								});
218								notification.save(function(err, notification) {
219									if (err) return res.send(500, err.message);
220									user.notifications.push(notification._id);
221									user.save(function(err, user) {
222										if (err) return res.send(500, err.message);
223
224										console.log("notification saved");
225										exports.getTravelById(req, res);
226									});
227								});
228							}
229						});//end saving notification
230					});
231				}
232			});
233		}
234
235	});
236};
237
238
239exports.declineJoin = function(req, res) {
240	userModel.findOne({'token': req.headers['x-access-token']})
241	.exec(function(err, userOwner){
242		if (err) return res.send(500, err.message);
243		if (!userOwner) {
244            res.json({success: false, message: 'User not found.'});
245        } else if (userOwner) {
246			travelModel.findOne({
247				_id: req.params.travelid,
248				user: userOwner._id,
249				joinPetitions: req.body.userid
250			})
251			.exec(function(err, travel){
252				if (err) return res.send(500, err.message);
253				if (!travel) {
254		            res.json({success: false, message: 'travel not found. You can not join a travel if you have created it, or if you have already joined'});
255		        } else if (travel) {
256					var indexPetition=-1;
257					for(var i=0; i<travel.joinPetitions.length; i++)
258					{
259						if(travel.joinPetitions[i].equals(req.body.userid))
260						{
261							indexPetition=JSON.parse(JSON.stringify(i));
262						}
263					}
264					if(indexPetition>-1)
265					{
266						travel.joinPetitions.splice(indexPetition, 1);
267					}
268					travel.save(function(err, travel) {
269						if(err) return res.send(500, err.message);
270
271						//start saving notification, get user owner of travel
272						userModel.findOne({_id: req.body.userid})
273						.exec(function(err, user){
274							if (err) return res.send(500, err.message);
275							if (!user) {
276					            res.json({success: false, message: 'User not found.'});
277					        } else if (user) {
278							//notification
279								var notification = new notificationModel({
280									concept: "travel",
281									message: "user "+userOwner.username+" declines your petition for "+travel.title,
282									date: new Date(),
283									icon: 'ion-close',
284									link: "travels/" + travel._id,
285			                        user: user._id
286								});
287								notification.save(function(err, notification) {
288									if (err) return res.send(500, err.message);
289									user.notifications.push(notification._id);
290									user.save(function(err, user) {
291										if (err) return res.send(500, err.message);
292
293										console.log("notification saved");
294										exports.getTravelById(req, res);
295									});
296								});
297							}
298						});//end saving notification
299					});//end of travel save
300				}//end of else if travel
301			});
302		}//end of else if user
303	});
304};
305
306exports.acceptJoin = function(req, res) {
307	userModel.findOne({'token': req.headers['x-access-token']})
308	.exec(function(err, userOwner){
309		if (err) return res.send(500, err.message);
310		if (!userOwner) {
311            res.json({success: false, message: 'User not found.'});
312        } else if (userOwner) {
313			travelModel.findOne({
314				_id: req.params.travelid,
315				user: userOwner._id,
316				joinPetitions: req.body.userid
317			})
318			.exec(function(err, travel){
319				if (err) return res.send(500, err.message);
320				if (!travel) {
321		            res.json({success: false, message: 'travel not found. You can not join a travel if you have created it, or if you have already joined'});
322		        } else if (travel) {
323					var indexPetition=-1;
324					for(var i=0; i<travel.joinPetitions.length; i++)
325					{
326						if(travel.joinPetitions[i].equals(req.body.userid))
327						{
328							indexPetition=JSON.parse(JSON.stringify(i));
329						}
330					}
331					if(indexPetition>-1)
332					{
333						travel.joins.push(JSON.parse(JSON.stringify(travel.joinPetitions[indexPetition])));
334						travel.joinPetitions.splice(indexPetition, 1);
335						console.log(travel);
336					}
337					travel.save(function(err, travel) {
338						if(err) return res.send(500, err.message);
339
340						//start saving notification, get user owner of travel
341						userModel.findOne({_id: req.body.userid})
342						.exec(function(err, user){
343							if (err) return res.send(500, err.message);
344							if (!user) {
345				            res.json({success: false, message: 'User not found.'});
346				        } else if (user) {
347								//notification
348								var notification = new notificationModel({
349									concept: "travel",
350									message: "user "+userOwner.username+" accepts your petition for "+travel.title,
351									date: new Date(),
352									icon: 'ion-checkmark',
353									link: "travels/" + travel._id,
354			                        user: user._id
355								});
356								notification.save(function(err, notification) {
357									if (err) return res.send(500, err.message);
358									user.notifications.push(notification._id);
359									user.save(function(err, user) {
360										if (err) return res.send(500, err.message);
361
362										console.log("notification saved");
363										exports.getTravelById(req, res);
364									});
365								});
366							}
367						});//end saving notification
368					});//end of travel save
369				}//end of else if travel
370			});
371		}//end of else if user
372	});
373};
374
375exports.leave = function(req, res) {
376	userModel.findOne({'token': req.headers['x-access-token']})
377	.exec(function(err, userLeaving){
378		if (!userLeaving) {
379            res.json({success: false, message: 'userLeaving not found.'});
380        } else if (userLeaving) {
381			travelModel.findOne({
382				_id: req.params.travelid,
383				joins: userLeaving._id
384			})
385			.exec(function(err, travel){
386				if (err) return res.send(500, err.message);
387				if (!travel) {
388		            res.json({success: false, message: 'can not unjoin this travel'});
389		        } else if (travel) {
390					for(var i=0; i<travel.joins.length; i++)
391					{
392						if(travel.joins[i].equals(userLeaving._id))
393						{
394							travel.joins.splice(i, 1);
395						}
396					}
397					travel.save(function(err, travel) {
398						if(err) return res.send(500, err.message);
399						//start saving notification, get user owner of travel
400						userModel.findOne({_id: travel.user})
401						.exec(function(err, user){
402							if (err) return res.send(500, err.message);
403							if (!user) {
404					            res.json({success: false, message: 'User not found.'});
405					        } else if (user) {
406							//notification
407								var notification = new notificationModel({
408									concept: "leave",
409									message: "user "+userLeaving.username+" leaves your travel "+travel.title,
410									date: new Date(),
411									icon: 'ion-log-out',
412									link: "travels/" + travel._id,
413			                        user: user._id
414								});
415								notification.save(function(err, notification) {
416									if (err) return res.send(500, err.message);
417									user.notifications.push(notification._id);
418									user.save(function(err, user) {
419										if (err) return res.send(500, err.message);
420
421										console.log("notification saved");
422										exports.getTravelById(req, res);
423									});
424								});
425							}
426						});//end saving notification
427					});
428				}
429			});
430		}
431
432	});
433};
434
435
436
437
438
439//currently not used
440exports.addComment = function(req, res) {
441	/*var comment = new commentModel({
442		travelId: req.params.travelId,
443		commentUserId: req.body.commentUserId,
444		commentUsername: req.body.commentUsername,
445		comment: req.body.comment,
446		commentAvatar: req.body.commentAvatar
447	});
448
449	comment.save(function(err, comment) {
450		if(err) return res.send(500, err.message);
451    res.status(200).jsonp(comment);
452	});*/
453	userModel.find({
454		token: req.headers['x-access-token']
455	}, function(err, users){
456		var user=users[0];
457
458		travelModel.findById(req.params.travelId, function(err, travel){
459			console.log(travel.title);
460			var comment = {
461				commentUserId: user._id,
462				commentUsername: user.username,
463				comment: req.body.comment,
464				commentAvatar: user.avatar
465			};
466			travel.comments.push(comment);
467
468			travel.save(function(err, travel) {
469				if(err) return res.send(500, err.message);
470		    //res.status(200).jsonp(travel);
471				travelModel.find({date: {$gte: new Date()}}, function(err, travels) {
472				    if(err) res.send(500, err.message);
473						res.status(200).jsonp(travels);
474				});
475			});
476
477			//start saving notification, get user owner of travel
478			userModel.find({
479		      username: travel.owner
480		  }, function(err, userowners) {
481				var userowner=userowners[0];
482				//notification
483				var notification = {
484					concept: "comment",
485					otherusername: user.username,
486					description: "user "+user.username+" comments your travel "+travel.title,
487					date: new Date(),
488					link: "",
489					user: userowners[0]._id
490				};
491				userowner.notifications.push(notification);
492				userowner.save(function(err, userowner) {
493					console.log("notification saved");
494				});
495			});//end saving notification
496
497		});
498	});//end of userModel.find
499};
500//currently not used
501exports.getCommentsByTravelId = function(req, res) {
502    commentModel.find({
503      travelId: req.params.travelId
504  }, function(err, comments) {
505
506      if (err) throw err;
507
508      if (!comments) {
509        res.json({ success: false, message: 'no comments for travelId' });
510    } else if (comments) {
511          // return the information including token as JSON
512		 res.jsonp(comments);
513
514      }
515
516    });
517};