Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {Router} from 'express';
- import models from '../models/index';
- import Promise from 'bluebird';
- import uuid from 'uuid';
- import reactCookie from 'react-cookie';
- var join = Promise.join;
- var router = Router();
- import _ from 'underscore';
- // AWS SDK
- import AWS from 'aws-sdk';
- import fs from 'fs';
- import zlib from 'zlib';
- /***** WRITE API REQUESTS *****/
- // ====== QUERY USERs EVERY KEYSTROKE =======
- router.post('/participant', function(req, res){
- return models.FirstConnection.findAll({
- where: {
- AccountId: req.user.id
- },
- attributes: {
- exclude: ['createdAt','updatedAt','cType']
- },
- include: [
- {
- model: models.Account,
- as: "Friend",
- attributes: {
- exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
- },
- where: {
- $or: [
- {
- firstName: {
- $iLike: req.body.name + "%"
- }
- },
- {
- lastName: {
- $iLike: req.body.name + "%"
- }
- }
- ]
- },
- include: [
- {
- model: models.UserAvatar,
- attributes: ['imgUrl']
- }
- ]
- }
- ]
- }).then(function(users){
- res.json(users);
- })
- })
- // ===== Query ALL ParticipantsInChat to use ChatSocketRoomId ======
- router.get('/channels', function(req, res){
- return models.ParticipantsInChat.findAll({
- where: {
- AccountId: req.user.id
- }
- }).then(function(channels){
- res.json(channels);
- })
- })
- // === QUERY CHANNELS (NEW) ===
- router.get('/', function(req, res){
- return models.ParticipantsInChat.findAll({
- where: {
- AccountId: req.user.id
- },
- include: [
- {
- model: models.Chat,
- include: [
- {
- model: models.MessageReplica,
- where: {
- AccountId: req.user.id
- },
- // attributes: ['updatedAt'],
- required: false,
- include: [
- {
- model: models.Message,
- include: [
- {
- model: models.Account,
- attributes: {
- exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
- },
- include: [
- {
- model: models.UserAvatar,
- attributes: ['imgUrl']
- },
- {
- model: models.UserType,
- }
- ]
- }
- ],
- required: false,
- // attributes: ['content']
- }
- ]
- },
- {
- model: models.ParticipantsInChat,
- include: [
- {
- model: models.Account,
- where: {
- id: {
- $not: req.user.id
- }
- },
- attributes: {
- exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
- },
- include: [
- {
- model: models.Email,
- },
- {
- model: models.UserAvatar,
- attributes: ['imgUrl']
- },
- {
- model: models.UserType,
- }
- ]
- },
- {
- model: models.ChatMemo,
- include: [
- {
- model: models.Account,
- as: "AboutUser",
- attributes: {
- exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
- },
- // include: [
- // {
- // model: models.UserAvatar,
- // attributes: ['imgUrl']
- // }
- // ]
- }
- ]
- }
- ]
- }
- ]
- }
- ],
- order: [['updatedAt', 'DESC'], [models.Chat, models.MessageReplica, 'createdAt']]
- })
- .catch(function(err){
- console.log("shiiiiiiit, we querying: ")
- console.log(err);
- }).then(function(result){
- res.json(result);
- });
- });
- // ========== CREATE CHANNEL =================
- // run a check to see if there is a channel that already exists
- // that has the same users inside
- router.post('/', function(req,res){
- var userIds = [];
- var result;
- userIds.push(req.user.id); // push my own ID
- return Promise.map(req.body.participants, (i)=>{
- // push all other user IDs
- userIds.push(i.id)
- }).then(function(){
- // console.log(" ============= ")
- // console.log("the IDs in arr incoming from client side: ")
- // console.log(typeof userIds, userIds)
- // // the IDs in arr incoming from client side:
- // // object [ 1, 2 ]
- // console.log(" ============= ")
- // query all my ParticipantsInChats
- return models.ParticipantsInChat.findAll({
- where: {
- AccountId: req.user.id,
- },
- attributes: ['ChatSocketRoomId']
- }).then(function(channels){
- // map through each channel
- if(channels.length === 0){
- var ChatSocketRoomId = uuid.v4();
- // have to restructure participants obj
- var listOfParticipants = [];
- var participantIds = [];
- // console.log("===============")
- // console.log("these are the participants in req.body: ")
- // console.log(req.body.participants)
- // console.log("===============")
- var participants = req.body.participants;
- return models.Account.findOne({
- where: {
- id: req.user.id,
- },
- attributes: {
- exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
- },
- }).then(function(account){
- // console.log(email.emailAddress)
- participants.unshift(account);
- // console.log("===========")
- // console.log("these are the participants: ")
- // console.log(participants);
- // console.log("===========")
- }).then(function(){
- // console.log("===========")
- // console.log("these are the participants to map through: ")
- // console.log(participants);
- // console.log("===========")
- Promise.map(participants, function(i){
- var user;
- return models.Account.findOne({
- where: {
- id: i.id
- },
- attributes: {
- exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
- },
- }).then(function(queriedAccount){
- user = queriedAccount;
- user.ChatSocketRoomId = ChatSocketRoomId
- user.AccountId = queriedAccount.id
- // console.log("==============")
- // console.log("account to be pushed into listOfParticipants:")
- // console.log(user);
- // console.log("==============")
- listOfParticipants.push(user);
- participantIds.push(user.AccountId)
- // console.log("==============")
- // console.log("these are the participants: ")
- // console.log(listOfParticipants);
- // console.log("==============")
- });
- }).then(function(){
- // take listOfParticipants and do a bulkCreate
- // console.log("==============")
- // console.log("this is the length of participants list: ")
- // console.log(listOfParticipants.length);
- // console.log(typeof(listOfParticipants.length));
- // console.log("==============")
- return models.Chat.create({
- socketRoomId: ChatSocketRoomId,
- participants: participantIds,
- }).then(function(){
- if(listOfParticipants.length >= 2){
- return models.GroupChat.create({
- ChatSocketRoomId: ChatSocketRoomId
- })
- } else {
- return models.PeerToPeerChat.create({
- ChatSocketRoomId: ChatSocketRoomId
- })
- }
- }).then(function(){
- // console.log("==============")
- // console.log("can i access the participants?: ")
- // console.log(listOfParticipants);
- // console.log("==============")
- // console.log("==============")
- // console.log("AccountId of first participant: ")
- // console.log(listOfParticipants[0].id);
- // console.log(typeof(listOfParticipants[0].id))
- // console.log("==============")
- // need to add more columns and place in the right order??
- return models.ParticipantsInChat.bulkCreate(listOfParticipants, { fields: ['AccountId','ChatSocketRoomId'] })
- .then(function(chatParticipants){
- // console.log("===============")
- // console.log("the chat participants are: ", chatParticipants)
- // console.log("===============")
- return models.ParticipantsInChat.findAll({
- where: {
- ChatSocketRoomId: ChatSocketRoomId
- }
- }).then(function(allChatParticipants){
- // console.log("~~~~~~~~ ALL CHAT PARTICIPANTS ~~~~~~~~")
- // console.log(allChatParticipants)
- // console.log("~~~~~~~~~~~~~~~~")
- return Promise.map(allChatParticipants, function(i){
- var chatMemos = [];
- models.ImportantChat.create({
- AccountId: i.AccountId,
- ChatSocketRoomId: ChatSocketRoomId
- })
- Promise.map(allChatParticipants, function(x){
- var memoObj = {};
- if(i.AccountId !== x.AccountId){
- memoObj.ChatSocketRoomId = ChatSocketRoomId,
- memoObj.AccountId = x.AccountId,
- memoObj.AboutUserId = i.AccountId,
- memoObj.ParticipantsInChatId = i.id // can not find ParticipantsInChat.id
- chatMemos.push(memoObj);
- }
- }).then(function(){
- // console.log("===============")
- // console.log("the chat memos arr: ")
- // console.log(chatMemos)
- // console.log("===============")
- return models.ChatMemo.bulkCreate(chatMemos,{fields:["ChatSocketRoomId","AccountId","AboutUserId","ParticipantsInChatId"]})
- })
- })
- }).then(function(){
- /***
- - probably should update and only return necessary information
- ***/
- return models.ParticipantsInChat.findAll({
- where: {
- AccountId: req.user.id
- },
- include: [
- {
- model: models.Chat,
- include: [
- {
- model: models.MessageReplica,
- where: {
- AccountId: req.user.id
- },
- // attributes: ['updatedAt'],
- required: false,
- include: [
- {
- model: models.Message,
- include: [
- {
- model: models.Account,
- attributes: {
- exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
- },
- include: [
- {
- model: models.UserAvatar,
- attributes: ['imgUrl']
- },
- {
- model: models.UserType,
- }
- ]
- }
- ],
- required: false,
- // attributes: ['content']
- }
- ]
- },
- {
- model: models.ParticipantsInChat,
- include: [
- {
- model: models.Account,
- where: {
- id: {
- $not: req.user.id
- }
- },
- attributes: {
- exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
- },
- include: [
- {
- model: models.Email,
- },
- {
- model: models.UserAvatar,
- attributes: ['imgUrl']
- },
- {
- model: models.UserType,
- },
- ]
- },
- {
- model: models.ChatMemo,
- include: [
- {
- model: models.Account,
- as: "AboutUser",
- attributes: {
- exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
- },
- // include: [
- // {
- // model: models.UserAvatar,
- // attributes: ['imgUrl']
- // }
- // ]
- }
- ]
- }
- ]
- }
- ]
- }
- ],
- order: [['updatedAt', 'DESC'], [models.Chat, models.MessageReplica, 'createdAt']]
- })
- .catch(function(err){
- console.log("shiiiiiiit, we querying: ")
- console.log(err);
- }).then(function(result){
- res.json(result);
- });
- })
- })
- });
- })
- })
- } else {
- console.log("we are mapping through the channels")
- return Promise.map(channels, (x)=>{
- return models.Chat.findOne({
- where: {
- socketRoomId: x.ChatSocketRoomId,
- }
- }).then(function(channel){
- // console.log("===========")
- // console.log("the IDs of participants in pre-existing channel: ")
- // console.log(typeof channel.participants, channel.participants);
- // the IDs of participants in pre-existing channel:
- // object [ 1, 2 ]
- console.log("===========")
- console.log("comparing the two arrs: ")
- console.log(channel.participants, userIds);
- // var created = _.isEqual(channel.participants, userIds)
- // console.log('are the two objects equal', created);
- if(userIds.length === channel.participants.length){
- var x = _.difference(userIds, channel.participants);
- var y = _.difference(channel.participants, userIds);
- if(x.length === 0 && y.length === 0){
- result = true; // if true, that means there is already a channel that matches
- console.log('the two objects are true so set result=true', result)
- }
- // return result;
- }
- })
- }).then(function(){
- if(result){
- res.json({
- channelExists: true,
- msg: "A channel already exists.",
- })
- } else {
- var ChatSocketRoomId = uuid.v4();
- // have to restructure participants obj
- var listOfParticipants = [];
- var participantIds = [];
- var participants = req.body.participants;
- return models.Account.findOne({
- where: {
- id: req.user.id,
- },
- attributes: {
- exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
- },
- }).then(function(account){
- // console.log(email.emailAddress)
- participants.unshift(account);
- }).then(function(){
- Promise.map(participants, function(i){
- var user;
- return models.Account.findOne({
- where: {
- id: i.id
- },
- attributes: {
- exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
- },
- }).then(function(queriedAccount){
- user = queriedAccount;
- user.ChatSocketRoomId = ChatSocketRoomId
- user.AccountId = queriedAccount.id
- listOfParticipants.push(user);
- participantIds.push(user.AccountId)
- });
- }).then(function(){
- // take listOfParticipants and do a bulkCreate
- return models.Chat.create({
- socketRoomId: ChatSocketRoomId,
- participants: participantIds,
- }).then(function(){
- if(listOfParticipants.length >= 2){
- return models.GroupChat.create({
- ChatSocketRoomId: ChatSocketRoomId
- })
- } else {
- return models.PeerToPeerChat.create({
- ChatSocketRoomId: ChatSocketRoomId
- })
- }
- }).then(function(){
- // need to add more columns and place in the right order??
- return models.ParticipantsInChat.bulkCreate(listOfParticipants, { fields: ['AccountId','ChatSocketRoomId'] })
- .then(function(chatParticipants){
- return models.ParticipantsInChat.findAll({
- where: {
- ChatSocketRoomId: ChatSocketRoomId
- }
- }).then(function(allChatParticipants){
- return Promise.map(allChatParticipants, function(i){
- var chatMemos = [];
- models.ImportantChat.create({
- AccountId: i.AccountId,
- ChatSocketRoomId: ChatSocketRoomId
- })
- Promise.map(allChatParticipants, function(x){
- var memoObj = {};
- if(i.AccountId !== x.AccountId){
- memoObj.ChatSocketRoomId = ChatSocketRoomId,
- memoObj.AccountId = x.AccountId,
- memoObj.AboutUserId = i.AccountId,
- memoObj.ParticipantsInChatId = i.id // can not find ParticipantsInChat.id
- chatMemos.push(memoObj);
- }
- }).then(function(){
- return models.ChatMemo.bulkCreate(chatMemos,{fields:["ChatSocketRoomId","AccountId","AboutUserId","ParticipantsInChatId"]})
- })
- })
- }).then(function(){
- /***
- - probably should update and only return necessary information
- ***/
- return models.ParticipantsInChat.findAll({
- where: {
- AccountId: req.user.id
- },
- include: [
- {
- model: models.Chat,
- include: [
- {
- model: models.MessageReplica,
- where: {
- AccountId: req.user.id
- },
- // attributes: ['updatedAt'],
- required: false,
- include: [
- {
- model: models.Message,
- include: [
- {
- model: models.Account,
- attributes: {
- exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
- },
- include: [
- {
- model: models.UserAvatar,
- attributes: ['imgUrl']
- },
- {
- model: models.UserType,
- }
- ]
- }
- ],
- required: false,
- // attributes: ['content']
- }
- ]
- },
- {
- model: models.ParticipantsInChat,
- include: [
- {
- model: models.Account,
- attributes: {
- exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
- },
- where: {
- id: {
- $not: req.user.id
- }
- },
- include: [
- {
- model: models.Email,
- },
- {
- model: models.UserAvatar,
- attributes: ['imgUrl']
- },
- {
- model: models.UserType,
- }
- ]
- },
- {
- model: models.ChatMemo,
- include: [
- {
- model: models.Account,
- as: "AboutUser",
- attributes: {
- exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
- },
- // include: [
- // {
- // model: models.UserAvatar,
- // attributes: ['imgUrl']
- // }
- // ]
- }
- ]
- }
- ]
- }
- ]
- }
- ],
- order: [['updatedAt', 'DESC'], [models.Chat, models.MessageReplica, 'createdAt']]
- })
- .catch(function(err){
- console.log("shiiiiiiit, we querying: ")
- console.log(err);
- }).then(function(result){
- res.json(result);
- });
- })
- })
- });
- })
- })
- }
- })
- }
- })
- })
- });
- // ====== QUERY SINGLE CHANNEL ========
- router.get('/:socketRoomId', function(req, res){
- // write a check to see if the User is actually allowed to enter chat???
- console.log("~~~~~~~~~~")
- console.log("socketRoomId param: ")
- console.log(req.params.socketRoomId);
- console.log(typeof req.params.socketRoomId)
- console.log("~~~~~~~~~~")
- return models.ParticipantsInChat.findOne({
- where: {
- AccountId: req.user.id,
- ChatSocketRoomId: req.params.socketRoomId
- },
- include: [
- {
- model: models.Chat,
- include: [
- {
- model: models.MessageReplica,
- where: {
- AccountId: req.user.id
- },
- required: false,
- include: [
- {
- model: models.Message,
- include: [
- {
- model: models.Account,
- attributes: {
- exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
- },
- include: [
- {
- model: models.UserAvatar,
- attributes: ['imgUrl']
- },
- {
- model: models.UserType,
- }
- ]
- }
- ],
- required: false,
- // attributes: ['content']
- }
- ]
- },
- {
- model: models.ParticipantsInChat,
- include: [
- {
- model: models.Account,
- attributes: {
- exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
- },
- where: {
- id: {
- $not: req.user.id
- }
- },
- attributes: ['id','firstName','lastName','individualSocketId'],
- include: [
- {
- model: models.Email,
- },
- {
- model: models.UserAvatar,
- attributes: ['imgUrl']
- },
- {
- model: models.UserType,
- }
- ]
- },
- {
- model: models.ChatMemo,
- include: [
- {
- model: models.Account,
- as: "AboutUser",
- attributes: {
- exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
- },
- // include: [
- // {
- // model: models.UserAvatar,
- // attributes: ['imgUrl']
- // }
- // ]
- }
- ]
- }
- ]
- }
- ]
- }
- ],
- order: [[models.Chat, models.MessageReplica, 'createdAt']]
- })
- .catch(function(err){
- console.log("shiiiiiiit, we querying: ")
- console.log(err);
- }).then(function(result){
- res.json(result);
- });
- });
- // ============== CREATE SINGLE MESSAGE =================
- // * * * AWS Stuff * * * //
- // AWS Variables
- var s3 = new AWS.S3();
- // * * * get signed url for PUT/POST * * * //
- function fetchSignedPutUrl (filename, filetype) {
- console.log(filename, filetype);
- var params = {
- Bucket: process.env.AWS_BUCKET,
- Key: filename,
- Expires: 6000,
- ContentType: filetype
- };
- var result;
- // s3.getSignedUrl('putObject', params, (err, data) => {
- s3.getSignedUrl('putObject', params, (err, data) => {
- if (err) {
- console.log('Err from getSignedUrl: ', err);
- result = err
- }
- else {
- console.log('data from getSignedUrl: ');
- console.log(data);
- result = data
- }
- })
- return result
- };
- router.post('/:socketRoomId/message', function(req,res){
- var options;
- var signedUrl;
- var imgUrl;
- if(req.body.img) {
- options = {
- headers: { 'Content-Type': req.body.fileType } // {'Content-Type: image/png'}
- }
- signedUrl = fetchSignedPutUrl(req.body.fileName, req.body.fileType);
- console.log("signedUrl from fetchSignedPutUrl: ", signedUrl)
- console.log("-------------------")
- imgUrl = `https://s3-${process.env.AWS_REGION}.amazonaws.com/${process.env.AWS_BUCKET}/${req.body.fileName}`;
- } else {
- imgUrl = null;
- signedUrl = null;
- }
- return models.Message.create({
- content: req.body.content,
- imgUrl: imgUrl,
- AccountId: req.user.id,
- ChatSocketRoomId: req.params.socketRoomId
- }).then(function(message){
- var messageId = message.id;
- return models.Chat.update(
- {
- updatedAt: message.createdAt
- },{
- where: {
- socketRoomId: req.params.socketRoomId
- }
- }
- ).then(function(){
- return models.ParticipantsInChat.findAll({
- where: {
- ChatSocketRoomId: req.params.socketRoomId
- },
- attributes: ['AccountId', 'ChatSocketRoomId']
- }).then(function(participants){
- return Promise.map(participants, function(x){
- return models.ParticipantsInChat.update(
- {
- updatedAt: new Date()
- }, {
- where: {
- AccountId: x.AccountId,
- ChatSocketRoomId: req.params.socketRoomId
- }
- }
- )
- }).then(function(){
- console.log("~~~~~ new participants ~~~~~~")
- console.log(participants)
- console.log("~~~~~~~~~~~")
- var allParticipants = [];
- Promise.map(participants, function(i){
- i.dataValues.MessageId = messageId;
- allParticipants.push(i.dataValues);
- }).then(function(){
- console.log("=========")
- console.log(allParticipants);
- console.log("=========")
- return models.MessageReplica.bulkCreate(allParticipants,{ fields: ['AccountId','ChatSocketRoomId','MessageId'] })
- .then(function(){
- return models.ParticipantsInChat.findAll({
- where: {
- AccountId: req.user.id
- },
- include: [
- {
- model: models.Chat,
- include: [
- {
- model: models.MessageReplica,
- where: {
- AccountId: req.user.id
- },
- // attributes: ['updatedAt'],
- required: false,
- include: [
- {
- model: models.Message,
- include: [
- {
- model: models.Account,
- attributes: {
- exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
- },
- include: [
- {
- model: models.UserAvatar,
- attributes: ['imgUrl']
- },
- {
- model: models.UserType,
- }
- ]
- }
- ],
- required: false,
- // attributes: ['content']
- }
- ]
- },
- {
- model: models.ParticipantsInChat,
- include: [
- {
- model: models.Account,
- where: {
- id: {
- $not: req.user.id
- }
- },
- attributes: {
- exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
- },
- include: [
- {
- model: models.Email,
- },
- {
- model: models.UserAvatar,
- attributes: ['imgUrl']
- },
- {
- model: models.UserType,
- }
- ]
- },
- {
- model: models.ChatMemo,
- include: [
- {
- model: models.Account,
- as: "AboutUser",
- attributes: {
- exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
- },
- // include: [
- // {
- // model: models.UserAvatar,
- // attributes: ['imgUrl']
- // }
- // ]
- }
- ]
- }
- ]
- }
- ]
- }
- ],
- order: [['updatedAt', 'DESC'], [models.Chat, models.MessageReplica, 'createdAt']]
- })
- .then(function(chats){
- return models.MessageReplica.update(
- {
- isRead: true,
- }, {
- where: {
- AccountId: req.user.id,
- MessageId: messageId,
- }
- }
- )
- .then(() => {
- return models.MessageReplica.findOne({
- where: {
- AccountId: req.user.id,
- MessageId: messageId,
- },
- include: [
- {
- model: models.Message,
- include: [
- {
- model: models.Account,
- attributes: {
- exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
- },
- include: [
- {
- model: models.UserAvatar,
- attributes: ['imgUrl']
- },
- {
- model: models.UserType,
- }
- ]
- }
- ]
- }
- ]
- }).then((singleMessage) => {
- res.json({
- message: singleMessage,
- chats: chats,
- signedUrl: signedUrl
- });
- })
- })
- });
- });
- });
- });
- });
- });
- });
- });
- // ======== FETCH CHAT MEMO ========
- router.post('/memo/', function(req, res){
- return models.ChatMemo.findOne({
- where: {
- AccountId: req.user.id,
- AboutUserId: req.body.AboutUserId,
- ChatSocketRoomId: req.body.ChatSocketRoomId
- },
- include: [
- {
- model: models.Account,
- as: "AboutUser",
- required: false,
- attributes: {
- exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
- },
- include: [
- {
- model: models.UserAvatar,
- attributes: ['imgUrl']
- },
- {
- model: models.EdExperience,
- required: false
- },
- {
- model: models.WorkExperience,
- required: false
- },
- {
- model: models.Email,
- required: false,
- where: {
- isPrimary: true
- },
- attributes: ['emailAddress']
- },
- {
- model: models.UserType,
- }
- ]
- }
- ]
- }).then(function(memo){
- res.json(memo);
- })
- })
- // ======== CREATE CHAT MEMO ========
- router.post('/:memoId/update', function(req, res){
- console.log("====== inside backend trying to update memo ======")
- console.log(req.body)
- console.log("++++++++++++++++++")
- return models.ChatMemo.update(
- {
- content: req.body.newContent
- }, {
- where: {
- id: req.params.memoId,
- AccountId: req.user.id,
- AboutUserId: req.body.memo.AboutUserId,
- ChatSocketRoomId: req.body.memo.ChatSocketRoomId
- }
- }
- ).then(function(){
- return models.ChatMemo.findOne({
- where: {
- id: req.params.memoId,
- AccountId: req.user.id,
- AboutUserId: req.body.memo.AboutUserId,
- ChatSocketRoomId: req.body.memo.ChatSocketRoomId
- },
- include: [
- {
- model: models.Account,
- as: "AboutUser",
- attributes: {
- exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
- },
- required: false,
- include: [
- {
- model: models.UserAvatar,
- attributes: ['imgUrl']
- },
- {
- model: models.UserType,
- }
- ]
- }
- ]
- }).then(function(memo){
- res.json(memo);
- })
- })
- })
- // ========== QUERY UNREAD MESSAGES ONLY =========
- router.get('/messages/unread', function(req,res){
- return models.MessageReplica.findAll({
- where: {
- AccountId: req.user.id,
- isRead: false,
- },
- include: [
- {
- model: models.Message,
- // *** to not include the ones you are the author of (???) ***
- // where: {
- // $not: {
- // AccountId: req.user.id
- // }
- // },
- include: [
- {
- model: models.Account,
- attributes: {
- exclude: ['noPassword','salt','password','registeredFrom','isActive','isPending','isSuspended','verified','createdAt','updatedAt','cType']
- },
- include: [
- {
- model: models.UserAvatar,
- attributes: ['imgUrl']
- },
- {
- model: models.UserType,
- }
- ]
- }
- ]
- }
- ]
- }).then((unreadMessages)=>{
- console.log('grabbed the unread messages!!')
- res.json(unreadMessages)
- })
- })
- // =========== UPDATE MESSAGES TO isRead=True =======
- router.post('/:ChatSocketRoomId/messages/read', function(req, res){
- return models.MessageReplica.findAll({
- where: {
- AccountId: req.user.id,
- ChatSocketRoomId: req.params.ChatSocketRoomId
- }
- }).then((messages)=>{
- // console.log("all my message replicas: ")
- // console.log(messages);
- return Promise.map(messages, (i)=>{
- return i.update(
- {
- isRead: true,
- }
- )
- })
- }).then(()=>{
- console.log('!+!+@!+@+!@')
- console.log('updated messages isRead stats!!!')
- console.log('!+!+@!+@+!@')
- res.json('updated messages isRead status')
- })
- })
- // ========= DELETE MESSAGE FROM CHANNEL ==========
- router.post('/:channelId/:messageReplicaId/delete', function(req,res){
- return models.MessageReplica.findOne({
- where: {
- id: req.params.messageReplicaId,
- ChatSocketRoomId: req.params.channelId,
- AccountId: req.user.id,
- MessageId: req.body.obj.MessageId
- }
- }).then((message) => {
- return message.destroy();
- }).then(() => {
- res.json({
- messageDeleted: true,
- msg: "Message has been deleted."
- })
- })
- })
- module.exports = router;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement