You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

791 lines
33 KiB

7 years ago
  1. var express = require('express');
  2. var app = express();
  3. var router = express.Router();
  4. var jwt = require('jsonwebtoken');
  5. var config = require('../config/config');
  6. var crypto = require('crypto');
  7. var formidable = require('formidable');
  8. var fs = require('fs');
  9. var https = require('https');
  10. app.set('superSecret', config.secret);
  11. /*******MODELS*********/
  12. var publicationModel = require('../models/publicationModel');
  13. var userModel = require('../models/userModel');
  14. var dietModel = require('../models/dietModel');
  15. var routineModel = require('../models/routineModel');
  16. /** POST '/users/register' **/
  17. exports.register = function (req, res) {
  18. console.log(req.body);
  19. var user = new userModel({
  20. name: req.body.name,
  21. role: req.body.role,
  22. password: crypto.createHash('sha256').update(req.body.password).digest('base64'),
  23. email: req.body.email,
  24. description: "Hi, i'm here to train.",
  25. avatar: 'img/user.png',
  26. background: 'img/background.png',
  27. attributes: {
  28. height: req.body.height,
  29. weight: req.body.weight,
  30. gender: req.body.gender,
  31. age: req.body.age
  32. },
  33. points: {
  34. total: 0
  35. }
  36. });
  37. /* gamification */
  38. var reward = {
  39. concept: "account created",
  40. date: Date(),
  41. value: +1
  42. };
  43. user.points.history.push(reward);
  44. user.points.total = user.points.total + 1;
  45. /* end of gamification */
  46. /*notification*/
  47. var notification = {
  48. state: "pendent",
  49. message: "Wellcome! this is your profile, update the Profile picture to let other members recognize you",
  50. link: "editUser/" + user._id,
  51. icon: "newpetition.png",
  52. date: Date()
  53. };
  54. user.notifications.push(notification);
  55. /* end of notification*/
  56. user.save(function (err, user) {
  57. if (err) {
  58. console.log(err.message);
  59. return res.status(500).send(err.message);
  60. }
  61. //res.status(200).jsonp(user); en comptes de retoranr la data del signup, fem el login directament
  62. console.log("signup fet correctament, redirigint al login internament automàtic");
  63. exports.login(req, res);
  64. });
  65. };
  66. var SECRET = "6LcyxhIUAAAAAPkCdz5HoBPN5--RhP7mpIE-V2CL";
  67. function verifyRecaptcha(key, callback) {
  68. https.get("https://www.google.com/recaptcha/api/siteverify?secret=" + SECRET + "&response=" + key, function(res) {
  69. var data = "";
  70. res.on('data', function (chunk) {
  71. data += chunk.toString();
  72. });
  73. res.on('end', function() {
  74. try {
  75. var parsedData = JSON.parse(data);
  76. callback(parsedData.success);
  77. } catch (e) {
  78. callback(false);
  79. }
  80. });
  81. });
  82. }
  83. /** POST '/users/login' **/
  84. exports.login = function (req, res) {
  85. verifyRecaptcha(req.body["g-recaptcha-response"], function() {
  86. userModel.findOne({
  87. email: req.body.email
  88. })
  89. .select('+password')
  90. .exec(function (err, user) {
  91. if (err) throw err;
  92. if (!user) {
  93. res.json({success: false, message: 'Authentication failed. User not found.'});
  94. } else if (user) {
  95. req.body.password = crypto.createHash('sha256').update(req.body.password).digest('base64');
  96. if (user.password != req.body.password) {
  97. res.json({success: false, message: 'Authentication failed. Wrong password.'});
  98. } else {
  99. var indexToken = -1;
  100. for (var i = 0; i < user.tokens.length; i++) {
  101. if (user.tokens[i].userAgent == req.body.userAgent) {
  102. indexToken = JSON.parse(JSON.stringify(i));//stringify i parse pq es faci una còpia de la variable i, enlloc de una referència
  103. }
  104. }
  105. console.log(indexToken);
  106. if (indexToken == -1) {//userAgent no exist
  107. var tokenGenerated = jwt.sign({foo: 'bar'}, app.get('superSecret'), {
  108. // expiresIn: 86400 // expires in 24 hours
  109. });
  110. var newToken = {
  111. userAgent: req.body.userAgent,
  112. token: tokenGenerated,
  113. os: req.body.os,
  114. browser: req.body.browser,
  115. device: req.body.device,
  116. os_version: req.body.os_version,
  117. browser_version: req.body.browser_version,
  118. ip: req.body.ip,
  119. lastLogin: Date()
  120. };
  121. user.tokens.push(newToken);
  122. } else {//userAgent already exist
  123. user.tokens[indexToken].token = "";
  124. var tokenGenerated = jwt.sign({foo: 'bar'}, app.get('superSecret'), {
  125. // expiresIn: 86400 // expires in 24 hours
  126. });
  127. user.tokens[indexToken].token = tokenGenerated;
  128. user.tokens[indexToken].ip = req.body.ip;
  129. user.tokens[indexToken].lastLogin = Date();
  130. }
  131. user.save(function (err, user) {
  132. if (err) return res.send(500, err.message);
  133. // return the information including token as JSON
  134. user.password = "";
  135. res.json({
  136. user: user,
  137. success: true,
  138. message: 'Enjoy your token!',
  139. token: tokenGenerated
  140. });
  141. });
  142. }
  143. }
  144. });
  145. })};
  146. /** POST '/logout' **/
  147. exports.logout = function (req, res, callback) {
  148. var token = req.headers.authorization;
  149. var decoded = verify(token);
  150. if (decoded) {
  151. db.get(decoded.auth, function (err, record) {
  152. if (err) throw err;
  153. var updated = JSON.parse(record);
  154. updated.valid = false;
  155. db.put(decoded.auth, updated, function (err) {
  156. if (err) throw err;
  157. res.writeHead(200, {'content-type': 'text/plain'});
  158. res.end('Logged Out!');
  159. return callback(res);
  160. });
  161. });
  162. } else {
  163. authFail(res, done);
  164. return callback(res);
  165. }
  166. };
  167. /*** Building a File Uploader with NodeJs
  168. * https://coligo.io/building-ajax-file-uploader-with-node/
  169. */
  170. /** POST '/users/upload' **/
  171. exports.avatarUpload = function (req, res) {/* no sé si s'ha provat si funciona, per ara almenys no està linkat ni es fa servir */
  172. // create an incoming form object
  173. var form = new formidable.IncomingForm();
  174. // specify that we want to allow the user to upload multiple files in a single request
  175. form.multiples = true;
  176. // store all uploads in the /uploads directory
  177. form.uploadDir = path.join(__dirname, '/uploads');
  178. // every time a file has been uploaded successfully,
  179. // rename it to it's orignal name
  180. form.on('file', function (field, file) {
  181. fs.rename(file.path, path.join(form.uploadDir, file.name));
  182. });
  183. // log any errors that occur
  184. form.on('error', function (err) {
  185. console.log('An error has occured: \n' + err);
  186. });
  187. // once all the files have been uploaded, send a response to the client
  188. form.on('end', function () {
  189. res.end('success');
  190. });
  191. // parse the incoming request containing the form data
  192. form.parse(req);
  193. };
  194. /** PUT '/users/:userid' **/
  195. exports.updateUser = function (req, res) {//funciona
  196. var id = req.params.userid;
  197. var user = req.body;
  198. userModel.update({'tokens.token': req.headers['x-access-token']}, user,
  199. function (err) {
  200. if (err) return console.log(err);
  201. console.log(user);
  202. res.status(200).jsonp(user);
  203. });
  204. };
  205. /** DELETE '/users/:userid' **/
  206. exports.deleteUserById = function (req, res) {
  207. userModel.findByIdAndRemove({_id: req.params.userid}, function (err) {
  208. if (err) return res.send(500, err.message);
  209. res.status(200).send("Deleted");
  210. });
  211. };
  212. /** GET '/users/' **/
  213. exports.getUsers = function (req, res) {
  214. userModel.find({role: 'user'})
  215. .limit(Number(req.query.pageSize))
  216. .skip(Number(req.query.pageSize) * Number(req.query.page))
  217. .exec(function (err, users) {
  218. if (err) return res.send(500, err.message);
  219. res.status(200).jsonp(users);
  220. });
  221. };
  222. /** GET '/users/:userid' **/
  223. exports.getUserById = function (req, res) {
  224. userModel.findOne({_id: req.params.userid})
  225. .lean()
  226. .populate('diets', 'title description')
  227. .populate('routines', 'title description')
  228. .populate('trainers', 'name avatar description disciplines')
  229. .populate('clients.client', 'name avatar')
  230. .populate('publications')
  231. .exec(function (err, user) {
  232. if (err) return res.send(500, err.message);
  233. if (!user) {
  234. res.json({success: false, message: 'User not found.'});
  235. } else if (user) {
  236. /* aquí va el carro de bucle per acabar retornant només les peticions pendents */
  237. var pendentNumber=0;
  238. for (var i = 0; i < user.notifications.length; i++) {
  239. if (user.notifications[i].state == "pendent") {
  240. pendentNumber++;
  241. }
  242. }
  243. user.pendentNotificationsNumber=pendentNumber;
  244. /* fi del carro de bucle de peticions pendents */
  245. res.status(200).jsonp(user);
  246. }
  247. });
  248. };
  249. exports.getUserByToken = function (req, res) {
  250. console.log(req.params.tok);
  251. userModel.findOne({'tokens.token': req.params.tok})
  252. .lean()
  253. .populate('diets', 'title description')
  254. .populate('routines', 'title description')
  255. .populate('trainers', 'name avatar description disciplines')
  256. .populate('clients.client', 'name avatar')
  257. .populate('publications')
  258. .exec(function (err, user) {
  259. if (err) return res.send(500, err.message);
  260. if (!user) {
  261. res.json({success: false, message: 'User not found.'});
  262. } else if (user) {
  263. /* aquí va el carro de bucle per acabar retornant només les peticions pendents */
  264. var pendentNumber=0;
  265. for (var i = 0; i < user.notifications.length; i++) {
  266. if (user.notifications[i].state == "pendent") {
  267. pendentNumber++;
  268. }
  269. }
  270. user.pendentNotificationsNumber=pendentNumber;
  271. /* fi del carro de bucle de peticions pendents */
  272. res.status(200).jsonp(user);
  273. }
  274. });
  275. };
  276. /** GET '/users/:userid/network' **/
  277. exports.getUserNetworkById = function (req, res) {
  278. userModel.findOne({_id: req.params.userid})
  279. .lean()
  280. .populate('followers', 'name avatar description')
  281. .populate('following', 'name avatar description')
  282. .exec(function (err, user) {
  283. if (err) return res.send(500, err.message);
  284. res.status(200).jsonp(user);
  285. });
  286. };
  287. /** GET '/users/:userid/suggestions' **/
  288. exports.getUserSuggestionsById = function (req, res) {
  289. userModel.findOne({'tokens.token': req.headers['x-access-token']})
  290. .exec(function (err, user) {
  291. if (err) return res.send(500, err.message);
  292. userModel.find({
  293. $and: [
  294. {_id: { $nin: user._id}},
  295. {_id: { $nin: user.following}}
  296. ],
  297. city: user.city})
  298. .limit(Number(req.query.pageSize))
  299. .skip(Number(req.query.pageSize) * Number(req.query.page))
  300. .select('name role email description avatar')
  301. .exec(function (err, users) {
  302. if (err) return res.send(500, err.message);
  303. console.log(users);
  304. if (users.length>0) {
  305. res.status(200).jsonp(users);
  306. } else {
  307. //si no té users a la ciutat, li tornem users igualment (tot i no ser de la mateixa ciutat)
  308. userModel.find({
  309. $and: [
  310. {_id: { $nin: user._id}},
  311. {_id: { $nin: user.following}}
  312. ]})
  313. .limit(Number(req.query.pageSize))
  314. .skip(Number(req.query.pageSize) * Number(req.query.page))
  315. .select('name role email description avatar')
  316. .exec(function (err, users) {
  317. res.status(200).jsonp(users);
  318. });
  319. }
  320. });
  321. });
  322. };
  323. /** GET '/users/:userid/diets' **/
  324. exports.getDietsFromUserId = function (req, res) {
  325. userModel.findOne({_id: req.params.userid})
  326. .populate('diets')
  327. .exec(function (err, user) {
  328. if (err) return res.send(500, err.message);
  329. res.status(200).jsonp(user.diets);
  330. });
  331. };
  332. /** GET '/users/:userid/routines' **/
  333. exports.getRoutinesFromUserId = function (req, res) {
  334. userModel.findOne({_id: req.params.userid})
  335. .populate('routines')
  336. .exec(function (err, user) {
  337. if (err) return res.send(500, err.message);
  338. res.status(200).jsonp(user.routines);
  339. });
  340. };
  341. /** POST '/users/sendPetitionToTrainer/:trainerid' **/
  342. exports.sendPetitionToTrainer = function (req, res) {
  343. userModel.findOne({'tokens.token': req.headers['x-access-token']}, function (err, user) {
  344. if (err) return res.send(500, err.message);
  345. if (!user) {
  346. res.json({success: false, message: 'sending petition failed. user not found.'});
  347. } else if (user) {
  348. console.log(user.name);//aquí potser caldria comprovar que la routine és la que han creat per l'user
  349. //ara busquem el trainer
  350. userModel.findOne({_id: req.params.trainerid}, function (err, trainer) {
  351. if (err) return res.send(500, err.message);
  352. if (!trainer) {
  353. res.json({success: false, message: 'sending petition failed. trainer not found.'});
  354. } else if (trainer) {
  355. var newPetition = {
  356. clientid: user._id,
  357. message: req.body.message,
  358. state: "pendent"
  359. };
  360. trainer.clientsPetitions.push(newPetition);
  361. /*notification*/
  362. var notification = {
  363. state: "pendent",
  364. message: "client has sent a petition to you",
  365. link: "dashboard",
  366. icon: "newpetition.png",
  367. date: Date()
  368. };
  369. trainer.notifications.push(notification);
  370. /* end of notification*/
  371. trainer.save(function (err) {
  372. if (err) return res.send(500, err.message);
  373. res.status(200).jsonp(trainer);
  374. });
  375. }//end else if
  376. });
  377. }//end else if
  378. });
  379. };
  380. exports.getNumberOfNotifications = function (req, res) {
  381. userModel.findOne({'tokens.token': req.headers['x-access-token']})
  382. .exec(function (err, user) {
  383. if (err) return res.send(500, err.message);
  384. if (!user) {
  385. res.json({success: false, message: 'User not found.'});
  386. } else if (user) {
  387. /* aquí va el carro de bucle per acabar retornant només les peticions pendents */
  388. var pendentNumber=0;
  389. for (var i = 0; i < user.notifications.length; i++) {
  390. if (user.notifications[i].state == "pendent") {
  391. pendentNumber++;
  392. }
  393. }
  394. /* fi del carro de bucle de peticions pendents */
  395. res.status(200).jsonp(pendentNumber);
  396. }
  397. });
  398. };
  399. /** GET '/users/:userid/getNotifications' **/
  400. exports.getNotifications = function (req, res) {
  401. userModel.findOne({'tokens.token': req.headers['x-access-token']})
  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. var viewed=[];
  408. var pendent=[];
  409. for (var i = 0; i < user.notifications.length; i++) {
  410. if (user.notifications[i].state == "pendent") {
  411. pendent.push(user.notifications[i]);
  412. user.notifications[i].state = "viewed";
  413. user.notifications[i].dateviewed = Date();
  414. }else{
  415. viewed.push(user.notifications[i]);
  416. }
  417. }
  418. user.save(function (err) {
  419. if (err) return res.send(500, err.message);
  420. res.status(200).jsonp({
  421. pendent: pendent,
  422. viewed: viewed
  423. });
  424. });
  425. }
  426. });
  427. };
  428. /** POST '/users/:userid/deleteSelectedTokens' **/
  429. exports.deleteSelectedTokens = function (req, res) {
  430. userModel.findOne({'tokens.token': req.headers['x-access-token']}, function (err, user) {
  431. if (err) return res.send(500, err.message);
  432. if (!user) {
  433. res.json({success: false, message: 'user not found.'});
  434. } else if (user) {
  435. console.log(user);
  436. for (var i = 0; i < req.body.devicesToDelete.length; i++) {
  437. for (var j = 0; j < user.tokens.length; j++) {
  438. if (user.tokens[j].userAgent == req.body.devicesToDelete[i].userAgent) {
  439. user.tokens.splice(j, 1);
  440. }
  441. }
  442. }
  443. user.save(function (err) {
  444. if (err) return res.send(500, err.message);
  445. res.status(200).jsonp(user);
  446. });
  447. }//end else if
  448. });
  449. };
  450. /**
  451. userA: el que fa l'acció de seguir --> se li posa userB a following
  452. userB: el que reb el seguiment --> se li posa el userA al followers
  453. **/
  454. /** POST '/users/follow' **/
  455. exports.follow = function (req, res) {
  456. userModel.findOne({'tokens.token': req.headers['x-access-token']}, function (err, userA) {
  457. if (err) return res.send(500, err.message);
  458. if (!userA) {
  459. res.json({success: false, message: 'userA not found.'});
  460. } else if (userA) {
  461. //ara busquem el userB
  462. userModel.findOne({_id: req.body.userid}, function (err, userB) {
  463. if (err) return res.send(500, err.message);
  464. if (!userB) {
  465. res.json({success: false, message: 'userB not found.'});
  466. } else if (userB) {
  467. userB.followers.push(userA._id);
  468. /*notification*/
  469. var notification = {
  470. state: "pendent",
  471. message: userA.name + " followed you",
  472. link: "dashboard",
  473. icon: "follower.png",
  474. date: Date()
  475. };
  476. userB.notifications.push(notification);
  477. /* end of notification*/
  478. /* gamification */
  479. var reward = {
  480. concept: userA.name + " followed you",
  481. date: Date(),
  482. value: +1
  483. };
  484. userB.points.history.push(reward);
  485. userB.points.total = userB.points.total + 1;
  486. /* end of gamification */
  487. userB.save(function (err) {
  488. if (err) return res.send(500, err.message);
  489. userA.following.push(userB._id);
  490. /* gamification */
  491. var reward = {
  492. concept: "followed " + userB.name,
  493. date: Date(),
  494. value: +1
  495. };
  496. userA.points.history.push(reward);
  497. userA.points.total = userA.points.total + 1;
  498. /* end of gamification */
  499. userA.save(function (err) {
  500. if (err) return res.send(500, err.message);
  501. userModel.findOne({_id: userA._id}).lean().populate('following', 'name avatar')
  502. .exec(function (err, userA) {
  503. if (err) return res.send(500, err.message);
  504. console.log("user followed" + userB.name);
  505. res.status(200).jsonp(userB);
  506. });
  507. });
  508. });
  509. }//end else if
  510. });
  511. }//end else if
  512. });
  513. };
  514. /**
  515. userA: el que fa l'acció de deixar de seguir --> se li treu userB de following
  516. userB: el que deixa de tenir el seguiment --> se li treu l'userA del followers
  517. **/
  518. /** POST '/users/unfollow' **/
  519. exports.unfollow = function (req, res) {
  520. userModel.findOne({'tokens.token': req.headers['x-access-token']}, function (err, userA) {
  521. if (err) return res.send(500, err.message);
  522. if (!userA) {
  523. res.json({success: false, message: 'userA not found.'});
  524. } else if (userA) {
  525. //ara busquem el userB
  526. userModel.findOne({_id: req.body.userid}, function (err, userB) {
  527. if (err) return res.send(500, err.message);
  528. if (!userB) {
  529. res.json({success: false, message: 'userB not found.'});
  530. } else if (userB) {
  531. var indexFollower = -1;
  532. for (var i = 0; i < userB.followers.length; i++) {
  533. if (userB.followers[i].equals(userA._id)) {
  534. indexFollower = JSON.parse(JSON.stringify(i));
  535. }
  536. }
  537. if (indexFollower > -1) {
  538. userB.followers.splice(indexFollower, 1);
  539. /*notification*/
  540. var notification = {
  541. state: "pendent",
  542. message: userA.name + " unfollowed you",
  543. link: "dashboard",
  544. icon: "unfollower.png",
  545. date: Date()
  546. };
  547. userB.notifications.push(notification);
  548. /* end of notification*/
  549. /* gamification */
  550. var reward = {
  551. concept: userA.name + " unfollowed you",
  552. date: Date(),
  553. value: -1
  554. };
  555. userB.points.history.push(reward);
  556. userB.points.total = userB.points.total - 1;
  557. /* end of gamification */
  558. userB.save(function (err) {
  559. if (err) return res.send(500, err.message);
  560. var indexFollower = -1;
  561. for (var i = 0; i < userA.following.length; i++) {
  562. if (userA.following[i].equals(userB._id)) {
  563. indexFollower = JSON.parse(JSON.stringify(i));
  564. }
  565. }
  566. if (indexFollower > -1) {
  567. userA.following.splice(indexFollower, 1);
  568. /* gamification */
  569. var reward = {
  570. concept: "unfollowed " + userB.name,
  571. date: Date(),
  572. value: -1
  573. };
  574. userA.points.history.push(reward);
  575. userA.points.total = userA.points.total - 1;
  576. /* end of gamification */
  577. userA.save(function (err) {
  578. if (err) return res.send(500, err.message);
  579. userModel.findOne(userA).lean().populate('following', 'name avatar')
  580. .exec(function (err, userA) {
  581. if (err) return res.send(500, err.message);
  582. console.log("user followed" + userB.name);
  583. res.status(200).jsonp(userB);
  584. });
  585. });
  586. } else {//else de indexFollower>-1
  587. res.status(200).jsonp({message: 'not found'});
  588. }
  589. });
  590. } else {//else de indexFollower>-1
  591. res.status(200).jsonp({message: 'not found'});
  592. }
  593. }//end else if
  594. });
  595. }//end else if
  596. });
  597. };
  598. /**GET '/search/:searchstring' **/
  599. exports.search = function (req, res) {
  600. userModel.find({
  601. name: new RegExp(req.params.searchstring, "i"),
  602. role: 'user'
  603. })//perquè retorni tots els objectes que continguin l'string sense necessitat de que sigui exactament la mateixa string
  604. .limit(Number(req.query.pageSize))
  605. .skip(Number(req.query.pageSize) * Number(req.query.page))
  606. .exec(function (err, users) {
  607. if (err) return res.send(500, err.message);
  608. userModel.find({
  609. name: new RegExp(req.params.searchstring, "i"),
  610. role: 'trainer'
  611. })//perquè retorni tots els objectes que continguin l'string sense necessitat de que sigui exactament la mateixa string
  612. .limit(Number(req.query.pageSize))
  613. .skip(Number(req.query.pageSize) * Number(req.query.page))
  614. .exec(function (err, trainers) {
  615. if (err) return res.send(500, err.message);
  616. routineModel.find({title: new RegExp(req.params.searchstring, "i")})//perquè retorni tots els objectes que continguin l'string sense necessitat de que sigui exactament la mateixa string
  617. .limit(Number(req.query.pageSize))
  618. .skip(Number(req.query.pageSize) * Number(req.query.page))
  619. .exec(function (err, routines) {
  620. if (err) return res.send(500, err.message);
  621. dietModel.find({title: new RegExp(req.params.searchstring, "i")})//perquè retorni tots els objectes que continguin l'string sense necessitat de que sigui exactament la mateixa string
  622. .limit(Number(req.query.pageSize))
  623. .skip(Number(req.query.pageSize) * Number(req.query.page))
  624. .exec(function (err, diets) {
  625. if (err) return res.send(500, err.message);
  626. res.json({
  627. users: users,
  628. trainers: trainers,
  629. routines: routines,
  630. diets: diets
  631. });
  632. });//diets
  633. });//routines
  634. });//trainers
  635. });//users
  636. };
  637. /** POST '/users/newMark' **/
  638. exports.newMark = function (req, res) {
  639. userModel.findOne({'tokens.token': req.headers['x-access-token']}, function (err, user) {
  640. if (err) return res.send(500, err.message);
  641. if (!user) {
  642. res.json({success: false, message: 'user not found.'});
  643. } else if (user) {
  644. var newmark = {
  645. title: req.body.title,
  646. unit: req.body.unit
  647. };
  648. user.marks.push(newmark);
  649. /* gamification */
  650. var reward = {
  651. concept: "new mark created: " + newmark.title,
  652. date: Date(),
  653. value: +3
  654. };
  655. user.points.history.push(reward);
  656. user.points.total = user.points.total + 3;
  657. /* end of gamification */
  658. user.save(function (err) {
  659. if (err) return res.send(500, err.message);
  660. res.status(200).jsonp(user.marks);
  661. });
  662. }//end else if user
  663. });
  664. };
  665. /** DELETE /users/markid'**/
  666. exports.deleteUserMark = function (req, res) {
  667. userModel.findOne({'tokens.token': req.headers['x-access-token']}, function (err, user) {
  668. if (err) return res.send(500, err.message);
  669. if (!user) {
  670. res.json({success: false, message: 'user not found.'});
  671. } else if (user) {
  672. var indexMark=-1;
  673. for (var i = 0; i < user.marks.length; i++) {
  674. if (user.marks[i]._id == req.params.markid) {
  675. indexMark = JSON.parse(JSON.stringify(i));
  676. }
  677. }
  678. if(indexMark>-1)
  679. {
  680. user.marks.splice(indexMark, 1);
  681. /* gamification */
  682. var reward = {
  683. concept: "mark deleted",
  684. date: Date(),
  685. value: -3
  686. };
  687. user.points.history.push(reward);
  688. user.points.total = user.points.total - 3;
  689. /* end of gamification */
  690. user.save(function (err, user) {//guardem el trainer amb la rutina treta
  691. if (err) return res.send(500, err.message);
  692. userModel.findOne({_id: user._id})
  693. .lean()
  694. .populate('diets', 'title description')
  695. .populate('routines', 'title description')
  696. .populate('trainers', 'name avatar description disciplines')
  697. .populate('clients.client', 'name avatar')
  698. .populate('publications')
  699. .exec(function (err, user) {
  700. if (err) return res.send(500, err.message);
  701. res.status(200).jsonp(user);
  702. });
  703. });
  704. }else{
  705. res.status(200).jsonp({message: 'mark not found'});
  706. }
  707. }
  708. });
  709. }
  710. /**
  711. cal rebre:
  712. _id
  713. value: 10
  714. **/
  715. /** POST '/users/:markid/addDayToMark' **/
  716. exports.addDayToMark = function (req, res) {
  717. userModel.findOne({'tokens.token': req.headers['x-access-token']}, function (err, user) {
  718. if (err) return res.send(500, err.message);
  719. if (!user) {
  720. res.json({success: false, message: 'user not found.'});
  721. } else if (user) {
  722. var indexMark = -1;
  723. var indexDay = -1;
  724. for (var i = 0; i < user.marks.length; i++) {
  725. if (user.marks[i]._id == req.params.markid) {
  726. indexMark = JSON.parse(JSON.stringify(i));
  727. for (var j = 0; j < user.marks[i].days.length; j++) {
  728. if (user.marks[i].days[j].date == Date()) {
  729. indexDay = JSON.parse(JSON.stringify(j));
  730. }
  731. }
  732. }
  733. }
  734. if (indexMark > -1)//si la mark existeix
  735. {
  736. if (indexDay == -1)//però el dia no existeix encara
  737. {
  738. var newday = {
  739. date: Date(),
  740. value: req.body.value
  741. };
  742. user.marks[indexMark].days.push(newday);
  743. /* gamification */
  744. var reward = {
  745. concept: "day value added to mark: " + user.marks[indexMark].title,
  746. date: Date(),
  747. value: +1
  748. };
  749. user.points.history.push(reward);
  750. user.points.total = user.points.total + 1;
  751. /* end of gamification */
  752. user.save(function (err) {
  753. if (err) return res.send(500, err.message);
  754. res.status(200).jsonp(user.marks);
  755. });
  756. } else {
  757. res.status(200).jsonp({message: 'mark of day already registered'});
  758. }
  759. } else {
  760. res.status(200).jsonp({message: 'mark not registered'});
  761. }
  762. }//end else if user
  763. });
  764. };