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				// search if the travel exist for that user
 86				travelModel.findOne({_id: req.body._id, user: user._id})
 87				.exec(function(err, travel){
 88					if (!travel) {
 89							res.send(500, 'travel not found.');
 90					} else if (travel) {
 91						// now update travel
 92						travelModel.update({
 93							_id: req.body._id, user: user._id
 94						}, req.body,
 95						function(err, travel) {
 96							if (err) {
 97								res.send(500, 'travel not found.');
 98							}
 99							console.log(travel);
100							res.status(200).jsonp(travel);
101						});
102					}
103				});
104
105
106    });
107};
108
109exports.deleteTravel = function(req, res) {
110	userModel.findOne({'token': req.headers['x-access-token']})
111	.exec(function(err, user){
112		if (err) return res.send(500, err.message);
113		travelModel.findById(req.params.travelid, function(err, travel) {
114			if (err) return res.send(500, err.message);
115			if(travel.user.equals(user._id))
116			{
117				travel.remove(function(err) {
118					if(err) return res.send(500, err.message);
119
120					console.log("deleted");
121					exports.getAllTravels(req, res);
122				});
123			}
124		});
125	});
126};
127
128
129exports.addJoinPetition = function(req, res) {
130	userModel.findOne({'token': req.headers['x-access-token']})
131	.exec(function(err, userJoining){
132		if (err) return res.send(500, err.message);
133		if (!userJoining) {
134            res.json({success: false, message: 'User not found.'});
135        } else if (userJoining) {
136			travelModel.findOne({
137				_id: req.params.travelid,
138				user: {'$ne': userJoining._id},
139				joins: {'$ne': userJoining._id},
140				joinPetitions: {'$ne': userJoining._id}
141			})
142			.exec(function(err, travel){
143				if (err) return res.send(500, err.message);
144				if (!travel) {
145		            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'});
146		        } else if (travel) {
147					travel.joinPetitions.push(userJoining._id);
148					travel.save(function(err, travel) {
149						if(err) return res.send(500, err.message);
150
151						//start saving notification, get user owner of travel
152						userModel.findOne({_id: travel.user})
153						.exec(function(err, user){
154							if (err) return res.send(500, err.message);
155							if (!user) {
156					            res.json({success: false, message: 'User not found.'});
157					        } else if (user) {
158							//notification
159								var notification = new notificationModel({
160									concept: "join",
161									message: "user "+userJoining.username+" joins your travel "+travel.title,
162									date: new Date(),
163									icon: 'ion-person-add',
164									link: "travels/" + travel._id,
165			                        user: user._id
166								});
167								notification.save(function(err, notification) {
168									if (err) return res.send(500, err.message);
169									user.notifications.push(notification._id);
170									user.save(function(err, user) {
171										if (err) return res.send(500, err.message);
172
173										console.log("notification saved");
174										exports.getTravelById(req, res);
175									});
176								});
177							}
178						});//end saving notification
179					});
180				}//end of else if travel
181			});
182		}//end of else if user
183	});
184};
185
186exports.unJoin = function(req, res) {
187	userModel.findOne({'token': req.headers['x-access-token']})
188	.exec(function(err, userJoining){
189		if (!userJoining) {
190            res.json({success: false, message: 'userJoining not found.'});
191        } else if (userJoining) {
192			travelModel.findOne({
193				_id: req.params.travelid,
194				joinPetitions: userJoining._id
195			})
196			.exec(function(err, travel){
197				if (err) return res.send(500, err.message);
198				if (!travel) {
199		            res.json({success: false, message: 'can not unjoin this travel'});
200		        } else if (travel) {
201					for(var i=0; i<travel.joinPetitions.length; i++)
202					{
203						if(travel.joinPetitions[i].equals(userJoining._id))
204						{
205							travel.joinPetitions.splice(i, 1);
206						}
207					}
208					travel.save(function(err, travel) {
209						if(err) return res.send(500, err.message);
210						//start saving notification, get user owner of travel
211						userModel.findOne({_id: travel.user})
212						.exec(function(err, user){
213							if (err) return res.send(500, err.message);
214							if (!user) {
215				            res.json({success: false, message: 'User not found.'});
216				        } else if (user) {
217								//notification
218								var notification = new notificationModel({
219									concept: "unjoin",
220									message: "user "+userJoining.username+" unjoins your travel "+travel.title,
221									date: new Date(),
222									icon: 'ion-arrow-return-left',
223									link: "travels/" + travel._id,
224			                        user: user._id
225								});
226								notification.save(function(err, notification) {
227									if (err) return res.send(500, err.message);
228									user.notifications.push(notification._id);
229									user.save(function(err, user) {
230										if (err) return res.send(500, err.message);
231
232										console.log("notification saved");
233										exports.getTravelById(req, res);
234									});
235								});
236							}
237						});//end saving notification
238					});
239				}
240			});
241		}
242
243	});
244};
245
246
247exports.declineJoin = function(req, res) {
248	userModel.findOne({'token': req.headers['x-access-token']})
249	.exec(function(err, userOwner){
250		if (err) return res.send(500, err.message);
251		if (!userOwner) {
252            res.json({success: false, message: 'User not found.'});
253        } else if (userOwner) {
254			travelModel.findOne({
255				_id: req.params.travelid,
256				user: userOwner._id,
257				joinPetitions: req.body.userid
258			})
259			.exec(function(err, travel){
260				if (err) return res.send(500, err.message);
261				if (!travel) {
262		            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'});
263		        } else if (travel) {
264					var indexPetition=-1;
265					for(var i=0; i<travel.joinPetitions.length; i++)
266					{
267						if(travel.joinPetitions[i].equals(req.body.userid))
268						{
269							indexPetition=JSON.parse(JSON.stringify(i));
270						}
271					}
272					if(indexPetition>-1)
273					{
274						travel.joinPetitions.splice(indexPetition, 1);
275					}
276					travel.save(function(err, travel) {
277						if(err) return res.send(500, err.message);
278
279						//start saving notification, get user owner of travel
280						userModel.findOne({_id: req.body.userid})
281						.exec(function(err, user){
282							if (err) return res.send(500, err.message);
283							if (!user) {
284					            res.json({success: false, message: 'User not found.'});
285					        } else if (user) {
286							//notification
287								var notification = new notificationModel({
288									concept: "travel",
289									message: "user "+userOwner.username+" declines your petition for "+travel.title,
290									date: new Date(),
291									icon: 'ion-close',
292									link: "travels/" + travel._id,
293			                        user: user._id
294								});
295								notification.save(function(err, notification) {
296									if (err) return res.send(500, err.message);
297									user.notifications.push(notification._id);
298									user.save(function(err, user) {
299										if (err) return res.send(500, err.message);
300
301										console.log("notification saved");
302										exports.getTravelById(req, res);
303									});
304								});
305							}
306						});//end saving notification
307					});//end of travel save
308				}//end of else if travel
309			});
310		}//end of else if user
311	});
312};
313
314exports.acceptJoin = function(req, res) {
315	userModel.findOne({'token': req.headers['x-access-token']})
316	.exec(function(err, userOwner){
317		if (err) return res.send(500, err.message);
318		if (!userOwner) {
319            res.json({success: false, message: 'User not found.'});
320        } else if (userOwner) {
321			travelModel.findOne({
322				_id: req.params.travelid,
323				user: userOwner._id,
324				joinPetitions: req.body.userid
325			})
326			.exec(function(err, travel){
327				if (err) return res.send(500, err.message);
328				if (!travel) {
329		            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'});
330		        } else if (travel) {
331					var indexPetition=-1;
332					for(var i=0; i<travel.joinPetitions.length; i++)
333					{
334						if(travel.joinPetitions[i].equals(req.body.userid))
335						{
336							indexPetition=JSON.parse(JSON.stringify(i));
337						}
338					}
339					if(indexPetition>-1)
340					{
341						travel.joins.push(JSON.parse(JSON.stringify(travel.joinPetitions[indexPetition])));
342						travel.joinPetitions.splice(indexPetition, 1);
343						console.log(travel);
344					}
345					travel.save(function(err, travel) {
346						if(err) return res.send(500, err.message);
347
348						//start saving notification, get user owner of travel
349						userModel.findOne({_id: req.body.userid})
350						.exec(function(err, user){
351							if (err) return res.send(500, err.message);
352							if (!user) {
353				            res.json({success: false, message: 'User not found.'});
354				        } else if (user) {
355								//notification
356								var notification = new notificationModel({
357									concept: "travel",
358									message: "user "+userOwner.username+" accepts your petition for "+travel.title,
359									date: new Date(),
360									icon: 'ion-checkmark',
361									link: "travels/" + travel._id,
362			                        user: user._id
363								});
364								notification.save(function(err, notification) {
365									if (err) return res.send(500, err.message);
366									user.notifications.push(notification._id);
367									user.save(function(err, user) {
368										if (err) return res.send(500, err.message);
369
370										console.log("notification saved");
371										exports.getTravelById(req, res);
372									});
373								});
374							}
375						});//end saving notification
376					});//end of travel save
377				}//end of else if travel
378			});
379		}//end of else if user
380	});
381};
382
383exports.leave = function(req, res) {
384	userModel.findOne({'token': req.headers['x-access-token']})
385	.exec(function(err, userLeaving){
386		if (!userLeaving) {
387            res.json({success: false, message: 'userLeaving not found.'});
388        } else if (userLeaving) {
389			travelModel.findOne({
390				_id: req.params.travelid,
391				joins: userLeaving._id
392			})
393			.exec(function(err, travel){
394				if (err) return res.send(500, err.message);
395				if (!travel) {
396		            res.json({success: false, message: 'can not unjoin this travel'});
397		        } else if (travel) {
398					for(var i=0; i<travel.joins.length; i++)
399					{
400						if(travel.joins[i].equals(userLeaving._id))
401						{
402							travel.joins.splice(i, 1);
403						}
404					}
405					travel.save(function(err, travel) {
406						if(err) return res.send(500, err.message);
407						//start saving notification, get user owner of travel
408						userModel.findOne({_id: travel.user})
409						.exec(function(err, user){
410							if (err) return res.send(500, err.message);
411							if (!user) {
412					            res.json({success: false, message: 'User not found.'});
413					        } else if (user) {
414							//notification
415								var notification = new notificationModel({
416									concept: "leave",
417									message: "user "+userLeaving.username+" leaves your travel "+travel.title,
418									date: new Date(),
419									icon: 'ion-log-out',
420									link: "travels/" + travel._id,
421			                        user: user._id
422								});
423								notification.save(function(err, notification) {
424									if (err) return res.send(500, err.message);
425									user.notifications.push(notification._id);
426									user.save(function(err, user) {
427										if (err) return res.send(500, err.message);
428
429										console.log("notification saved");
430										exports.getTravelById(req, res);
431									});
432								});
433							}
434						});//end saving notification
435					});
436				}
437			});
438		}
439
440	});
441};
442
443
444
445
446
447//currently not used
448exports.addComment = function(req, res) {
449	/*var comment = new commentModel({
450		travelId: req.params.travelId,
451		commentUserId: req.body.commentUserId,
452		commentUsername: req.body.commentUsername,
453		comment: req.body.comment,
454		commentAvatar: req.body.commentAvatar
455	});
456
457	comment.save(function(err, comment) {
458		if(err) return res.send(500, err.message);
459    res.status(200).jsonp(comment);
460	});*/
461	userModel.find({
462		token: req.headers['x-access-token']
463	}, function(err, users){
464		var user=users[0];
465
466		travelModel.findById(req.params.travelId, function(err, travel){
467			console.log(travel.title);
468			var comment = {
469				commentUserId: user._id,
470				commentUsername: user.username,
471				comment: req.body.comment,
472				commentAvatar: user.avatar
473			};
474			travel.comments.push(comment);
475
476			travel.save(function(err, travel) {
477				if(err) return res.send(500, err.message);
478		    //res.status(200).jsonp(travel);
479				travelModel.find({date: {$gte: new Date()}}, function(err, travels) {
480				    if(err) res.send(500, err.message);
481						res.status(200).jsonp(travels);
482				});
483			});
484
485			//start saving notification, get user owner of travel
486			userModel.find({
487		      username: travel.owner
488		  }, function(err, userowners) {
489				var userowner=userowners[0];
490				//notification
491				var notification = {
492					concept: "comment",
493					otherusername: user.username,
494					description: "user "+user.username+" comments your travel "+travel.title,
495					date: new Date(),
496					link: "",
497					user: userowners[0]._id
498				};
499				userowner.notifications.push(notification);
500				userowner.save(function(err, userowner) {
501					console.log("notification saved");
502				});
503			});//end saving notification
504
505		});
506	});//end of userModel.find
507};
508//currently not used
509exports.getCommentsByTravelId = function(req, res) {
510    commentModel.find({
511      travelId: req.params.travelId
512  }, function(err, comments) {
513
514      if (err) throw err;
515
516      if (!comments) {
517        res.json({ success: false, message: 'no comments for travelId' });
518    } else if (comments) {
519          // return the information including token as JSON
520		 res.jsonp(comments);
521
522      }
523
524    });
525};