Advertisement
Guest User

Untitled

a guest
Sep 30th, 2016
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 44.71 KB | None | 0 0
  1.  
  2. import {Router} from 'express';
  3. import models from '../models/index';
  4. import Promise from 'bluebird';
  5. import uuid from 'uuid';
  6. import reactCookie from 'react-cookie';
  7.  
  8. var join = Promise.join;
  9.  
  10. var router = Router();
  11.  
  12. import _ from 'underscore';
  13.  
  14. // AWS SDK
  15. import AWS from 'aws-sdk';
  16. import fs from 'fs';
  17. import zlib from 'zlib';
  18.  
  19.  
  20. /***** WRITE API REQUESTS *****/
  21.  
  22. // ====== QUERY USERs EVERY KEYSTROKE =======
  23. router.post('/participant', function(req, res){
  24.  
  25. return models.FirstConnection.findAll({
  26. where: {
  27. AccountId: req.user.id
  28. },
  29. attributes: {
  30. exclude: ['createdAt','updatedAt','cType']
  31. },
  32. include: [
  33. {
  34. model: models.Account,
  35. as: "Friend",
  36. attributes: {
  37. exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
  38. },
  39. where: {
  40. $or: [
  41. {
  42. firstName: {
  43. $iLike: req.body.name + "%"
  44. }
  45. },
  46. {
  47. lastName: {
  48. $iLike: req.body.name + "%"
  49. }
  50. }
  51. ]
  52. },
  53. include: [
  54. {
  55. model: models.UserAvatar,
  56. attributes: ['imgUrl']
  57. }
  58. ]
  59. }
  60. ]
  61. }).then(function(users){
  62. res.json(users);
  63. })
  64. })
  65.  
  66.  
  67.  
  68. // ===== Query ALL ParticipantsInChat to use ChatSocketRoomId ======
  69. router.get('/channels', function(req, res){
  70. return models.ParticipantsInChat.findAll({
  71. where: {
  72. AccountId: req.user.id
  73. }
  74. }).then(function(channels){
  75. res.json(channels);
  76. })
  77. })
  78.  
  79.  
  80. // === QUERY CHANNELS (NEW) ===
  81. router.get('/', function(req, res){
  82. return models.ParticipantsInChat.findAll({
  83. where: {
  84. AccountId: req.user.id
  85. },
  86. include: [
  87. {
  88. model: models.Chat,
  89. include: [
  90. {
  91. model: models.MessageReplica,
  92. where: {
  93. AccountId: req.user.id
  94. },
  95. // attributes: ['updatedAt'],
  96. required: false,
  97. include: [
  98. {
  99. model: models.Message,
  100. include: [
  101. {
  102. model: models.Account,
  103. attributes: {
  104. exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
  105. },
  106. include: [
  107. {
  108. model: models.UserAvatar,
  109. attributes: ['imgUrl']
  110. },
  111. {
  112. model: models.UserType,
  113. }
  114. ]
  115. }
  116. ],
  117. required: false,
  118. // attributes: ['content']
  119. }
  120. ]
  121. },
  122. {
  123. model: models.ParticipantsInChat,
  124. include: [
  125. {
  126. model: models.Account,
  127. where: {
  128. id: {
  129. $not: req.user.id
  130. }
  131. },
  132. attributes: {
  133. exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
  134. },
  135. include: [
  136. {
  137. model: models.Email,
  138. },
  139. {
  140. model: models.UserAvatar,
  141. attributes: ['imgUrl']
  142. },
  143. {
  144. model: models.UserType,
  145. }
  146. ]
  147. },
  148. {
  149. model: models.ChatMemo,
  150. include: [
  151. {
  152. model: models.Account,
  153. as: "AboutUser",
  154. attributes: {
  155. exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
  156. },
  157. // include: [
  158. // {
  159. // model: models.UserAvatar,
  160. // attributes: ['imgUrl']
  161. // }
  162. // ]
  163. }
  164. ]
  165.  
  166. }
  167. ]
  168. }
  169. ]
  170. }
  171. ],
  172. order: [['updatedAt', 'DESC'], [models.Chat, models.MessageReplica, 'createdAt']]
  173. })
  174. .catch(function(err){
  175. console.log("shiiiiiiit, we querying: ")
  176. console.log(err);
  177. }).then(function(result){
  178. res.json(result);
  179. });
  180. });
  181.  
  182. // ========== CREATE CHANNEL =================
  183.  
  184. // run a check to see if there is a channel that already exists
  185. // that has the same users inside
  186.  
  187. router.post('/', function(req,res){
  188.  
  189. var userIds = [];
  190. var result;
  191. userIds.push(req.user.id); // push my own ID
  192. return Promise.map(req.body.participants, (i)=>{
  193. // push all other user IDs
  194. userIds.push(i.id)
  195. }).then(function(){
  196.  
  197. // console.log(" ============= ")
  198. // console.log("the IDs in arr incoming from client side: ")
  199. // console.log(typeof userIds, userIds)
  200. // // the IDs in arr incoming from client side:
  201. // // object [ 1, 2 ]
  202. // console.log(" ============= ")
  203. // query all my ParticipantsInChats
  204. return models.ParticipantsInChat.findAll({
  205. where: {
  206. AccountId: req.user.id,
  207. },
  208. attributes: ['ChatSocketRoomId']
  209. }).then(function(channels){
  210. // map through each channel
  211. if(channels.length === 0){
  212.  
  213. var ChatSocketRoomId = uuid.v4();
  214. // have to restructure participants obj
  215. var listOfParticipants = [];
  216. var participantIds = [];
  217. // console.log("===============")
  218. // console.log("these are the participants in req.body: ")
  219. // console.log(req.body.participants)
  220. // console.log("===============")
  221. var participants = req.body.participants;
  222.  
  223. return models.Account.findOne({
  224. where: {
  225. id: req.user.id,
  226.  
  227. },
  228. attributes: {
  229. exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
  230. },
  231. }).then(function(account){
  232. // console.log(email.emailAddress)
  233. participants.unshift(account);
  234. // console.log("===========")
  235. // console.log("these are the participants: ")
  236. // console.log(participants);
  237. // console.log("===========")
  238. }).then(function(){
  239. // console.log("===========")
  240. // console.log("these are the participants to map through: ")
  241. // console.log(participants);
  242. // console.log("===========")
  243. Promise.map(participants, function(i){
  244. var user;
  245. return models.Account.findOne({
  246. where: {
  247. id: i.id
  248. },
  249. attributes: {
  250. exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
  251. },
  252. }).then(function(queriedAccount){
  253. user = queriedAccount;
  254. user.ChatSocketRoomId = ChatSocketRoomId
  255. user.AccountId = queriedAccount.id
  256. // console.log("==============")
  257. // console.log("account to be pushed into listOfParticipants:")
  258. // console.log(user);
  259. // console.log("==============")
  260. listOfParticipants.push(user);
  261. participantIds.push(user.AccountId)
  262. // console.log("==============")
  263. // console.log("these are the participants: ")
  264. // console.log(listOfParticipants);
  265. // console.log("==============")
  266. });
  267. }).then(function(){
  268. // take listOfParticipants and do a bulkCreate
  269. // console.log("==============")
  270. // console.log("this is the length of participants list: ")
  271. // console.log(listOfParticipants.length);
  272. // console.log(typeof(listOfParticipants.length));
  273. // console.log("==============")
  274. return models.Chat.create({
  275. socketRoomId: ChatSocketRoomId,
  276. participants: participantIds,
  277. }).then(function(){
  278. if(listOfParticipants.length >= 2){
  279. return models.GroupChat.create({
  280. ChatSocketRoomId: ChatSocketRoomId
  281. })
  282. } else {
  283.  
  284. return models.PeerToPeerChat.create({
  285. ChatSocketRoomId: ChatSocketRoomId
  286. })
  287. }
  288.  
  289. }).then(function(){
  290.  
  291. // console.log("==============")
  292. // console.log("can i access the participants?: ")
  293. // console.log(listOfParticipants);
  294. // console.log("==============")
  295. // console.log("==============")
  296. // console.log("AccountId of first participant: ")
  297. // console.log(listOfParticipants[0].id);
  298. // console.log(typeof(listOfParticipants[0].id))
  299. // console.log("==============")
  300. // need to add more columns and place in the right order??
  301. return models.ParticipantsInChat.bulkCreate(listOfParticipants, { fields: ['AccountId','ChatSocketRoomId'] })
  302. .then(function(chatParticipants){
  303. // console.log("===============")
  304. // console.log("the chat participants are: ", chatParticipants)
  305. // console.log("===============")
  306. return models.ParticipantsInChat.findAll({
  307. where: {
  308. ChatSocketRoomId: ChatSocketRoomId
  309. }
  310. }).then(function(allChatParticipants){
  311. // console.log("~~~~~~~~ ALL CHAT PARTICIPANTS ~~~~~~~~")
  312. // console.log(allChatParticipants)
  313. // console.log("~~~~~~~~~~~~~~~~")
  314. return Promise.map(allChatParticipants, function(i){
  315. var chatMemos = [];
  316. models.ImportantChat.create({
  317. AccountId: i.AccountId,
  318. ChatSocketRoomId: ChatSocketRoomId
  319. })
  320. Promise.map(allChatParticipants, function(x){
  321. var memoObj = {};
  322. if(i.AccountId !== x.AccountId){
  323. memoObj.ChatSocketRoomId = ChatSocketRoomId,
  324. memoObj.AccountId = x.AccountId,
  325. memoObj.AboutUserId = i.AccountId,
  326. memoObj.ParticipantsInChatId = i.id // can not find ParticipantsInChat.id
  327. chatMemos.push(memoObj);
  328. }
  329.  
  330. }).then(function(){
  331. // console.log("===============")
  332. // console.log("the chat memos arr: ")
  333. // console.log(chatMemos)
  334. // console.log("===============")
  335. return models.ChatMemo.bulkCreate(chatMemos,{fields:["ChatSocketRoomId","AccountId","AboutUserId","ParticipantsInChatId"]})
  336. })
  337. })
  338. }).then(function(){
  339.  
  340. /***
  341. - probably should update and only return necessary information
  342. ***/
  343. return models.ParticipantsInChat.findAll({
  344. where: {
  345. AccountId: req.user.id
  346. },
  347. include: [
  348. {
  349. model: models.Chat,
  350. include: [
  351. {
  352. model: models.MessageReplica,
  353. where: {
  354. AccountId: req.user.id
  355. },
  356. // attributes: ['updatedAt'],
  357. required: false,
  358. include: [
  359. {
  360. model: models.Message,
  361. include: [
  362. {
  363. model: models.Account,
  364. attributes: {
  365. exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
  366. },
  367. include: [
  368. {
  369. model: models.UserAvatar,
  370. attributes: ['imgUrl']
  371. },
  372. {
  373. model: models.UserType,
  374. }
  375. ]
  376. }
  377. ],
  378. required: false,
  379. // attributes: ['content']
  380. }
  381. ]
  382. },
  383. {
  384. model: models.ParticipantsInChat,
  385. include: [
  386. {
  387. model: models.Account,
  388. where: {
  389. id: {
  390. $not: req.user.id
  391. }
  392. },
  393. attributes: {
  394. exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
  395. },
  396. include: [
  397. {
  398. model: models.Email,
  399. },
  400. {
  401. model: models.UserAvatar,
  402. attributes: ['imgUrl']
  403. },
  404. {
  405. model: models.UserType,
  406. },
  407.  
  408. ]
  409. },
  410. {
  411. model: models.ChatMemo,
  412. include: [
  413. {
  414. model: models.Account,
  415. as: "AboutUser",
  416. attributes: {
  417. exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
  418. },
  419. // include: [
  420. // {
  421. // model: models.UserAvatar,
  422. // attributes: ['imgUrl']
  423. // }
  424. // ]
  425. }
  426. ]
  427.  
  428. }
  429. ]
  430. }
  431. ]
  432. }
  433. ],
  434. order: [['updatedAt', 'DESC'], [models.Chat, models.MessageReplica, 'createdAt']]
  435. })
  436. .catch(function(err){
  437. console.log("shiiiiiiit, we querying: ")
  438. console.log(err);
  439. }).then(function(result){
  440. res.json(result);
  441. });
  442. })
  443. })
  444. });
  445. })
  446. })
  447. } else {
  448.  
  449. console.log("we are mapping through the channels")
  450. return Promise.map(channels, (x)=>{
  451. return models.Chat.findOne({
  452. where: {
  453. socketRoomId: x.ChatSocketRoomId,
  454. }
  455. }).then(function(channel){
  456. // console.log("===========")
  457. // console.log("the IDs of participants in pre-existing channel: ")
  458. // console.log(typeof channel.participants, channel.participants);
  459. // the IDs of participants in pre-existing channel:
  460. // object [ 1, 2 ]
  461.  
  462. console.log("===========")
  463. console.log("comparing the two arrs: ")
  464. console.log(channel.participants, userIds);
  465. // var created = _.isEqual(channel.participants, userIds)
  466.  
  467. // console.log('are the two objects equal', created);
  468. if(userIds.length === channel.participants.length){
  469.  
  470. var x = _.difference(userIds, channel.participants);
  471. var y = _.difference(channel.participants, userIds);
  472. if(x.length === 0 && y.length === 0){
  473. result = true; // if true, that means there is already a channel that matches
  474. console.log('the two objects are true so set result=true', result)
  475. }
  476.  
  477.  
  478. // return result;
  479. }
  480.  
  481. })
  482. }).then(function(){
  483. if(result){
  484. res.json({
  485. channelExists: true,
  486. msg: "A channel already exists.",
  487. })
  488. } else {
  489.  
  490. var ChatSocketRoomId = uuid.v4();
  491. // have to restructure participants obj
  492. var listOfParticipants = [];
  493. var participantIds = [];
  494. var participants = req.body.participants;
  495.  
  496. return models.Account.findOne({
  497. where: {
  498. id: req.user.id,
  499.  
  500. },
  501. attributes: {
  502. exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
  503. },
  504. }).then(function(account){
  505. // console.log(email.emailAddress)
  506. participants.unshift(account);
  507.  
  508. }).then(function(){
  509.  
  510. Promise.map(participants, function(i){
  511. var user;
  512. return models.Account.findOne({
  513. where: {
  514. id: i.id
  515. },
  516. attributes: {
  517. exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
  518. },
  519. }).then(function(queriedAccount){
  520. user = queriedAccount;
  521. user.ChatSocketRoomId = ChatSocketRoomId
  522. user.AccountId = queriedAccount.id
  523.  
  524. listOfParticipants.push(user);
  525. participantIds.push(user.AccountId)
  526.  
  527. });
  528. }).then(function(){
  529. // take listOfParticipants and do a bulkCreate
  530.  
  531. return models.Chat.create({
  532. socketRoomId: ChatSocketRoomId,
  533. participants: participantIds,
  534. }).then(function(){
  535. if(listOfParticipants.length >= 2){
  536. return models.GroupChat.create({
  537. ChatSocketRoomId: ChatSocketRoomId
  538. })
  539. } else {
  540.  
  541. return models.PeerToPeerChat.create({
  542. ChatSocketRoomId: ChatSocketRoomId
  543. })
  544. }
  545.  
  546. }).then(function(){
  547.  
  548.  
  549. // need to add more columns and place in the right order??
  550. return models.ParticipantsInChat.bulkCreate(listOfParticipants, { fields: ['AccountId','ChatSocketRoomId'] })
  551. .then(function(chatParticipants){
  552.  
  553. return models.ParticipantsInChat.findAll({
  554. where: {
  555. ChatSocketRoomId: ChatSocketRoomId
  556. }
  557. }).then(function(allChatParticipants){
  558.  
  559. return Promise.map(allChatParticipants, function(i){
  560. var chatMemos = [];
  561. models.ImportantChat.create({
  562. AccountId: i.AccountId,
  563. ChatSocketRoomId: ChatSocketRoomId
  564. })
  565. Promise.map(allChatParticipants, function(x){
  566. var memoObj = {};
  567. if(i.AccountId !== x.AccountId){
  568. memoObj.ChatSocketRoomId = ChatSocketRoomId,
  569. memoObj.AccountId = x.AccountId,
  570. memoObj.AboutUserId = i.AccountId,
  571. memoObj.ParticipantsInChatId = i.id // can not find ParticipantsInChat.id
  572. chatMemos.push(memoObj);
  573. }
  574.  
  575. }).then(function(){
  576.  
  577. return models.ChatMemo.bulkCreate(chatMemos,{fields:["ChatSocketRoomId","AccountId","AboutUserId","ParticipantsInChatId"]})
  578. })
  579. })
  580. }).then(function(){
  581.  
  582. /***
  583. - probably should update and only return necessary information
  584. ***/
  585. return models.ParticipantsInChat.findAll({
  586. where: {
  587. AccountId: req.user.id
  588. },
  589. include: [
  590. {
  591. model: models.Chat,
  592. include: [
  593. {
  594. model: models.MessageReplica,
  595. where: {
  596. AccountId: req.user.id
  597. },
  598. // attributes: ['updatedAt'],
  599. required: false,
  600. include: [
  601. {
  602. model: models.Message,
  603. include: [
  604. {
  605. model: models.Account,
  606. attributes: {
  607. exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
  608. },
  609. include: [
  610. {
  611. model: models.UserAvatar,
  612. attributes: ['imgUrl']
  613. },
  614. {
  615. model: models.UserType,
  616. }
  617. ]
  618. }
  619. ],
  620. required: false,
  621. // attributes: ['content']
  622. }
  623. ]
  624. },
  625. {
  626. model: models.ParticipantsInChat,
  627. include: [
  628. {
  629. model: models.Account,
  630. attributes: {
  631. exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
  632. },
  633. where: {
  634. id: {
  635. $not: req.user.id
  636. }
  637. },
  638. include: [
  639. {
  640. model: models.Email,
  641. },
  642. {
  643. model: models.UserAvatar,
  644. attributes: ['imgUrl']
  645. },
  646. {
  647. model: models.UserType,
  648. }
  649. ]
  650. },
  651. {
  652. model: models.ChatMemo,
  653. include: [
  654. {
  655. model: models.Account,
  656. as: "AboutUser",
  657. attributes: {
  658. exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
  659. },
  660. // include: [
  661. // {
  662. // model: models.UserAvatar,
  663. // attributes: ['imgUrl']
  664. // }
  665. // ]
  666. }
  667. ]
  668.  
  669. }
  670. ]
  671. }
  672. ]
  673. }
  674. ],
  675. order: [['updatedAt', 'DESC'], [models.Chat, models.MessageReplica, 'createdAt']]
  676. })
  677. .catch(function(err){
  678. console.log("shiiiiiiit, we querying: ")
  679. console.log(err);
  680. }).then(function(result){
  681. res.json(result);
  682. });
  683. })
  684. })
  685. });
  686. })
  687. })
  688. }
  689. })
  690. }
  691. })
  692. })
  693.  
  694.  
  695. });
  696.  
  697.  
  698.  
  699. // ====== QUERY SINGLE CHANNEL ========
  700.  
  701. router.get('/:socketRoomId', function(req, res){
  702. // write a check to see if the User is actually allowed to enter chat???
  703. console.log("~~~~~~~~~~")
  704. console.log("socketRoomId param: ")
  705. console.log(req.params.socketRoomId);
  706. console.log(typeof req.params.socketRoomId)
  707. console.log("~~~~~~~~~~")
  708.  
  709. return models.ParticipantsInChat.findOne({
  710. where: {
  711. AccountId: req.user.id,
  712. ChatSocketRoomId: req.params.socketRoomId
  713. },
  714. include: [
  715. {
  716. model: models.Chat,
  717. include: [
  718. {
  719. model: models.MessageReplica,
  720. where: {
  721. AccountId: req.user.id
  722. },
  723. required: false,
  724. include: [
  725. {
  726. model: models.Message,
  727. include: [
  728. {
  729. model: models.Account,
  730. attributes: {
  731. exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
  732. },
  733. include: [
  734. {
  735. model: models.UserAvatar,
  736. attributes: ['imgUrl']
  737. },
  738. {
  739. model: models.UserType,
  740. }
  741. ]
  742. }
  743. ],
  744. required: false,
  745. // attributes: ['content']
  746. }
  747. ]
  748. },
  749. {
  750. model: models.ParticipantsInChat,
  751. include: [
  752. {
  753. model: models.Account,
  754. attributes: {
  755. exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
  756. },
  757. where: {
  758. id: {
  759. $not: req.user.id
  760. }
  761. },
  762. attributes: ['id','firstName','lastName','individualSocketId'],
  763. include: [
  764. {
  765. model: models.Email,
  766. },
  767. {
  768. model: models.UserAvatar,
  769. attributes: ['imgUrl']
  770. },
  771. {
  772. model: models.UserType,
  773. }
  774. ]
  775. },
  776. {
  777. model: models.ChatMemo,
  778. include: [
  779. {
  780. model: models.Account,
  781. as: "AboutUser",
  782. attributes: {
  783. exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
  784. },
  785. // include: [
  786. // {
  787. // model: models.UserAvatar,
  788. // attributes: ['imgUrl']
  789. // }
  790. // ]
  791. }
  792. ]
  793.  
  794. }
  795. ]
  796. }
  797. ]
  798. }
  799. ],
  800. order: [[models.Chat, models.MessageReplica, 'createdAt']]
  801.  
  802. })
  803. .catch(function(err){
  804. console.log("shiiiiiiit, we querying: ")
  805. console.log(err);
  806. }).then(function(result){
  807. res.json(result);
  808. });
  809.  
  810. });
  811.  
  812.  
  813.  
  814. // ============== CREATE SINGLE MESSAGE =================
  815. // * * * AWS Stuff * * * //
  816. // AWS Variables
  817.  
  818. var s3 = new AWS.S3();
  819.  
  820.  
  821. // * * * get signed url for PUT/POST * * * //
  822. function fetchSignedPutUrl (filename, filetype) {
  823. console.log(filename, filetype);
  824. var params = {
  825. Bucket: process.env.AWS_BUCKET,
  826. Key: filename,
  827. Expires: 6000,
  828. ContentType: filetype
  829. };
  830. var result;
  831. // s3.getSignedUrl('putObject', params, (err, data) => {
  832. s3.getSignedUrl('putObject', params, (err, data) => {
  833. if (err) {
  834. console.log('Err from getSignedUrl: ', err);
  835. result = err
  836. }
  837. else {
  838. console.log('data from getSignedUrl: ');
  839. console.log(data);
  840. result = data
  841. }
  842. })
  843. return result
  844. };
  845.  
  846. router.post('/:socketRoomId/message', function(req,res){
  847. var options;
  848. var signedUrl;
  849. var imgUrl;
  850.  
  851. if(req.body.img) {
  852. options = {
  853. headers: { 'Content-Type': req.body.fileType } // {'Content-Type: image/png'}
  854. }
  855.  
  856. signedUrl = fetchSignedPutUrl(req.body.fileName, req.body.fileType);
  857. console.log("signedUrl from fetchSignedPutUrl: ", signedUrl)
  858. console.log("-------------------")
  859. imgUrl = `https://s3-${process.env.AWS_REGION}.amazonaws.com/${process.env.AWS_BUCKET}/${req.body.fileName}`;
  860. } else {
  861. imgUrl = null;
  862. signedUrl = null;
  863. }
  864.  
  865.  
  866.  
  867. return models.Message.create({
  868. content: req.body.content,
  869. imgUrl: imgUrl,
  870. AccountId: req.user.id,
  871. ChatSocketRoomId: req.params.socketRoomId
  872. }).then(function(message){
  873. var messageId = message.id;
  874. return models.Chat.update(
  875. {
  876. updatedAt: message.createdAt
  877. },{
  878. where: {
  879. socketRoomId: req.params.socketRoomId
  880. }
  881. }
  882.  
  883. ).then(function(){
  884. return models.ParticipantsInChat.findAll({
  885. where: {
  886. ChatSocketRoomId: req.params.socketRoomId
  887. },
  888. attributes: ['AccountId', 'ChatSocketRoomId']
  889. }).then(function(participants){
  890. return Promise.map(participants, function(x){
  891. return models.ParticipantsInChat.update(
  892. {
  893. updatedAt: new Date()
  894. }, {
  895. where: {
  896. AccountId: x.AccountId,
  897. ChatSocketRoomId: req.params.socketRoomId
  898. }
  899. }
  900. )
  901. }).then(function(){
  902. console.log("~~~~~ new participants ~~~~~~")
  903. console.log(participants)
  904. console.log("~~~~~~~~~~~")
  905. var allParticipants = [];
  906. Promise.map(participants, function(i){
  907. i.dataValues.MessageId = messageId;
  908. allParticipants.push(i.dataValues);
  909. }).then(function(){
  910. console.log("=========")
  911. console.log(allParticipants);
  912. console.log("=========")
  913. return models.MessageReplica.bulkCreate(allParticipants,{ fields: ['AccountId','ChatSocketRoomId','MessageId'] })
  914. .then(function(){
  915. return models.ParticipantsInChat.findAll({
  916. where: {
  917. AccountId: req.user.id
  918. },
  919. include: [
  920. {
  921. model: models.Chat,
  922. include: [
  923. {
  924. model: models.MessageReplica,
  925. where: {
  926. AccountId: req.user.id
  927. },
  928. // attributes: ['updatedAt'],
  929. required: false,
  930. include: [
  931. {
  932. model: models.Message,
  933. include: [
  934. {
  935. model: models.Account,
  936. attributes: {
  937. exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
  938. },
  939. include: [
  940. {
  941. model: models.UserAvatar,
  942. attributes: ['imgUrl']
  943. },
  944. {
  945. model: models.UserType,
  946. }
  947. ]
  948. }
  949. ],
  950. required: false,
  951. // attributes: ['content']
  952. }
  953. ]
  954. },
  955. {
  956. model: models.ParticipantsInChat,
  957. include: [
  958. {
  959. model: models.Account,
  960. where: {
  961. id: {
  962. $not: req.user.id
  963. }
  964. },
  965. attributes: {
  966. exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
  967. },
  968. include: [
  969. {
  970. model: models.Email,
  971. },
  972. {
  973. model: models.UserAvatar,
  974. attributes: ['imgUrl']
  975. },
  976. {
  977. model: models.UserType,
  978. }
  979. ]
  980. },
  981. {
  982. model: models.ChatMemo,
  983. include: [
  984. {
  985. model: models.Account,
  986. as: "AboutUser",
  987. attributes: {
  988. exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
  989. },
  990. // include: [
  991. // {
  992. // model: models.UserAvatar,
  993. // attributes: ['imgUrl']
  994. // }
  995. // ]
  996. }
  997. ]
  998.  
  999. }
  1000. ]
  1001. }
  1002. ]
  1003. }
  1004. ],
  1005. order: [['updatedAt', 'DESC'], [models.Chat, models.MessageReplica, 'createdAt']]
  1006. })
  1007. .then(function(chats){
  1008. return models.MessageReplica.update(
  1009. {
  1010. isRead: true,
  1011. }, {
  1012. where: {
  1013. AccountId: req.user.id,
  1014. MessageId: messageId,
  1015. }
  1016. }
  1017. )
  1018. .then(() => {
  1019. return models.MessageReplica.findOne({
  1020. where: {
  1021. AccountId: req.user.id,
  1022. MessageId: messageId,
  1023. },
  1024. include: [
  1025. {
  1026. model: models.Message,
  1027. include: [
  1028. {
  1029. model: models.Account,
  1030. attributes: {
  1031. exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
  1032. },
  1033. include: [
  1034. {
  1035. model: models.UserAvatar,
  1036. attributes: ['imgUrl']
  1037. },
  1038. {
  1039. model: models.UserType,
  1040. }
  1041. ]
  1042. }
  1043. ]
  1044. }
  1045. ]
  1046. }).then((singleMessage) => {
  1047. res.json({
  1048. message: singleMessage,
  1049. chats: chats,
  1050. signedUrl: signedUrl
  1051. });
  1052. })
  1053. })
  1054. });
  1055. });
  1056. });
  1057. });
  1058. });
  1059. });
  1060. });
  1061. });
  1062.  
  1063.  
  1064. // ======== FETCH CHAT MEMO ========
  1065. router.post('/memo/', function(req, res){
  1066. return models.ChatMemo.findOne({
  1067. where: {
  1068. AccountId: req.user.id,
  1069. AboutUserId: req.body.AboutUserId,
  1070. ChatSocketRoomId: req.body.ChatSocketRoomId
  1071. },
  1072. include: [
  1073. {
  1074. model: models.Account,
  1075. as: "AboutUser",
  1076. required: false,
  1077. attributes: {
  1078. exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
  1079. },
  1080. include: [
  1081. {
  1082. model: models.UserAvatar,
  1083. attributes: ['imgUrl']
  1084. },
  1085. {
  1086. model: models.EdExperience,
  1087. required: false
  1088. },
  1089. {
  1090. model: models.WorkExperience,
  1091. required: false
  1092. },
  1093. {
  1094. model: models.Email,
  1095. required: false,
  1096. where: {
  1097. isPrimary: true
  1098. },
  1099. attributes: ['emailAddress']
  1100. },
  1101. {
  1102. model: models.UserType,
  1103. }
  1104. ]
  1105. }
  1106. ]
  1107. }).then(function(memo){
  1108. res.json(memo);
  1109. })
  1110. })
  1111. // ======== CREATE CHAT MEMO ========
  1112.  
  1113. router.post('/:memoId/update', function(req, res){
  1114. console.log("====== inside backend trying to update memo ======")
  1115. console.log(req.body)
  1116. console.log("++++++++++++++++++")
  1117. return models.ChatMemo.update(
  1118. {
  1119. content: req.body.newContent
  1120. }, {
  1121. where: {
  1122.  
  1123. id: req.params.memoId,
  1124. AccountId: req.user.id,
  1125. AboutUserId: req.body.memo.AboutUserId,
  1126. ChatSocketRoomId: req.body.memo.ChatSocketRoomId
  1127.  
  1128. }
  1129. }
  1130. ).then(function(){
  1131. return models.ChatMemo.findOne({
  1132. where: {
  1133. id: req.params.memoId,
  1134. AccountId: req.user.id,
  1135. AboutUserId: req.body.memo.AboutUserId,
  1136. ChatSocketRoomId: req.body.memo.ChatSocketRoomId
  1137. },
  1138. include: [
  1139. {
  1140. model: models.Account,
  1141. as: "AboutUser",
  1142. attributes: {
  1143. exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
  1144. },
  1145. required: false,
  1146. include: [
  1147. {
  1148. model: models.UserAvatar,
  1149. attributes: ['imgUrl']
  1150. },
  1151. {
  1152. model: models.UserType,
  1153. }
  1154. ]
  1155. }
  1156. ]
  1157. }).then(function(memo){
  1158. res.json(memo);
  1159. })
  1160. })
  1161. })
  1162.  
  1163.  
  1164. // ========== QUERY UNREAD MESSAGES ONLY =========
  1165. router.get('/messages/unread', function(req,res){
  1166. return models.MessageReplica.findAll({
  1167. where: {
  1168. AccountId: req.user.id,
  1169. isRead: false,
  1170. },
  1171. include: [
  1172. {
  1173. model: models.Message,
  1174.  
  1175. // *** to not include the ones you are the author of (???) ***
  1176.  
  1177. // where: {
  1178. // $not: {
  1179. // AccountId: req.user.id
  1180. // }
  1181. // },
  1182. include: [
  1183. {
  1184. model: models.Account,
  1185. attributes: {
  1186. exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
  1187. },
  1188. include: [
  1189. {
  1190. model: models.UserAvatar,
  1191. attributes: ['imgUrl']
  1192. },
  1193. {
  1194. model: models.UserType,
  1195. }
  1196. ]
  1197. }
  1198. ]
  1199. }
  1200. ]
  1201. }).then((unreadMessages)=>{
  1202. console.log('grabbed the unread messages!!')
  1203. res.json(unreadMessages)
  1204. })
  1205. })
  1206.  
  1207. // =========== UPDATE MESSAGES TO isRead=True =======
  1208. router.post('/:ChatSocketRoomId/messages/read', function(req, res){
  1209. return models.MessageReplica.findAll({
  1210. where: {
  1211. AccountId: req.user.id,
  1212. ChatSocketRoomId: req.params.ChatSocketRoomId
  1213. }
  1214. }).then((messages)=>{
  1215. // console.log("all my message replicas: ")
  1216. // console.log(messages);
  1217.  
  1218. return Promise.map(messages, (i)=>{
  1219. return i.update(
  1220. {
  1221. isRead: true,
  1222. }
  1223. )
  1224. })
  1225. }).then(()=>{
  1226. console.log('!+!+@!+@+!@')
  1227. console.log('updated messages isRead stats!!!')
  1228. console.log('!+!+@!+@+!@')
  1229. res.json('updated messages isRead status')
  1230. })
  1231. })
  1232.  
  1233. // ========= DELETE MESSAGE FROM CHANNEL ==========
  1234. router.post('/:channelId/:messageReplicaId/delete', function(req,res){
  1235. return models.MessageReplica.findOne({
  1236. where: {
  1237.  
  1238. id: req.params.messageReplicaId,
  1239. ChatSocketRoomId: req.params.channelId,
  1240. AccountId: req.user.id,
  1241. MessageId: req.body.obj.MessageId
  1242.  
  1243. }
  1244. }).then((message) => {
  1245. return message.destroy();
  1246. }).then(() => {
  1247. res.json({
  1248. messageDeleted: true,
  1249. msg: "Message has been deleted."
  1250. })
  1251. })
  1252. })
  1253.  
  1254.  
  1255.  
  1256.  
  1257.  
  1258. module.exports = router;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement