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