Merged in feature/IO-3182-Phone-Number-Consent (pull request #2324)
DO NOT MERGE JUST USING TO UNDO
This commit is contained in:
@@ -7,7 +7,7 @@ const { status, markConversationRead } = require("../sms/status");
|
||||
const validateFirebaseIdTokenMiddleware = require("../middleware/validateFirebaseIdTokenMiddleware");
|
||||
|
||||
// Twilio Webhook Middleware for production
|
||||
// TODO: Look into this because it technically is never validating anything
|
||||
// TODO: This is never actually doing anything, we should probably verify
|
||||
const twilioWebhookMiddleware = twilio.webhook({ validate: process.env.NODE_ENV === "PRODUCTION" });
|
||||
|
||||
router.post("/receive", twilioWebhookMiddleware, receive);
|
||||
|
||||
@@ -7,56 +7,17 @@ const {
|
||||
} = require("../graphql-client/queries");
|
||||
const { phone } = require("phone");
|
||||
const { admin } = require("../firebase/firebase-handler");
|
||||
const logger = require("../utils/logger");
|
||||
const InstanceManager = require("../utils/instanceMgr").default;
|
||||
|
||||
/**
|
||||
* Generate an array of media URLs from the request body
|
||||
* @param body
|
||||
* @returns {null|*[]}
|
||||
*/
|
||||
const generateMediaArray = (body) => {
|
||||
const { NumMedia } = body;
|
||||
if (parseInt(NumMedia) > 0) {
|
||||
const ret = [];
|
||||
for (let i = 0; i < parseInt(NumMedia); i++) {
|
||||
ret.push(body[`MediaUrl${i}`]);
|
||||
}
|
||||
return ret;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Handle errors during the message receiving process
|
||||
* @param req
|
||||
* @param error
|
||||
* @param res
|
||||
* @param context
|
||||
*/
|
||||
const handleError = (req, error, res, context) => {
|
||||
logger.log("sms-inbound-error", "ERROR", "api", null, {
|
||||
msid: req.body.SmsMessageSid,
|
||||
text: req.body.Body,
|
||||
image: !!req.body.MediaUrl0,
|
||||
image_path: generateMediaArray(req.body),
|
||||
messagingServiceSid: req.body.MessagingServiceSid,
|
||||
context,
|
||||
error
|
||||
});
|
||||
|
||||
res.status(500).json({ error: error.message || "Internal Server Error" });
|
||||
};
|
||||
|
||||
/**
|
||||
* Receive an inbound SMS message
|
||||
* Receive SMS messages from Twilio and process them
|
||||
* @param req
|
||||
* @param res
|
||||
* @returns {Promise<*>}
|
||||
*/
|
||||
const receive = async (req, res) => {
|
||||
const {
|
||||
logger,
|
||||
ioRedis,
|
||||
ioHelpers: { getBodyshopRoom, getBodyshopConversationRoom }
|
||||
} = req;
|
||||
@@ -65,7 +26,7 @@ const receive = async (req, res) => {
|
||||
msid: req.body.SmsMessageSid,
|
||||
text: req.body.Body,
|
||||
image: !!req.body.MediaUrl0,
|
||||
image_path: generateMediaArray(req.body)
|
||||
image_path: generateMediaArray(req.body, logger)
|
||||
};
|
||||
|
||||
logger.log("sms-inbound", "DEBUG", "api", null, loggerData);
|
||||
@@ -91,7 +52,7 @@ const receive = async (req, res) => {
|
||||
|
||||
const bodyshop = response.bodyshops[0];
|
||||
|
||||
// Sort conversations by `updated_at` (or `created_at`) and pick the last one
|
||||
// Step 4: Process conversation
|
||||
const sortedConversations = bodyshop.conversations.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
|
||||
const existingConversation = sortedConversations.length
|
||||
? sortedConversations[sortedConversations.length - 1]
|
||||
@@ -102,16 +63,13 @@ const receive = async (req, res) => {
|
||||
msid: req.body.SmsMessageSid,
|
||||
text: req.body.Body,
|
||||
image: !!req.body.MediaUrl0,
|
||||
image_path: generateMediaArray(req.body),
|
||||
image_path: generateMediaArray(req.body, logger),
|
||||
isoutbound: false,
|
||||
userid: null // Add additional fields as necessary
|
||||
userid: null
|
||||
};
|
||||
|
||||
if (existingConversation) {
|
||||
// Use the existing conversation
|
||||
conversationid = existingConversation.id;
|
||||
|
||||
// Unarchive the conversation if necessary
|
||||
if (existingConversation.archived) {
|
||||
await client.request(UNARCHIVE_CONVERSATION, {
|
||||
id: conversationid,
|
||||
@@ -119,7 +77,6 @@ const receive = async (req, res) => {
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Create a new conversation
|
||||
const newConversationResponse = await client.request(CREATE_CONVERSATION, {
|
||||
conversation: {
|
||||
bodyshopid: bodyshop.id,
|
||||
@@ -131,13 +88,12 @@ const receive = async (req, res) => {
|
||||
conversationid = createdConversation.id;
|
||||
}
|
||||
|
||||
// Ensure `conversationid` is added to the message
|
||||
newMessage.conversationid = conversationid;
|
||||
|
||||
// Step 3: Insert the message into the conversation
|
||||
// Step 5: Insert the message
|
||||
const insertresp = await client.request(INSERT_MESSAGE, {
|
||||
msg: newMessage,
|
||||
conversationid: conversationid
|
||||
conversationid
|
||||
});
|
||||
|
||||
const message = insertresp?.insert_messages?.returning?.[0];
|
||||
@@ -147,8 +103,7 @@ const receive = async (req, res) => {
|
||||
throw new Error("Conversation data is missing from the response.");
|
||||
}
|
||||
|
||||
// Step 4: Notify clients through Redis
|
||||
const broadcastRoom = getBodyshopRoom(conversation.bodyshop.id);
|
||||
// Step 6: Notify clients
|
||||
const conversationRoom = getBodyshopConversationRoom({
|
||||
bodyshopId: conversation.bodyshop.id,
|
||||
conversationId: conversation.id
|
||||
@@ -161,6 +116,8 @@ const receive = async (req, res) => {
|
||||
msid: message.sid
|
||||
};
|
||||
|
||||
const broadcastRoom = getBodyshopRoom(conversation.bodyshop.id);
|
||||
|
||||
ioRedis.to(broadcastRoom).emit("new-message-summary", {
|
||||
...commonPayload,
|
||||
existingConversation: !!existingConversation,
|
||||
@@ -176,7 +133,7 @@ const receive = async (req, res) => {
|
||||
summary: false
|
||||
});
|
||||
|
||||
// Step 5: Send FCM notification
|
||||
// Step 7: Send FCM notification
|
||||
const fcmresp = await admin.messaging().send({
|
||||
topic: `${message.conversation.bodyshop.imexshopid}-messaging`,
|
||||
notification: {
|
||||
@@ -202,10 +159,51 @@ const receive = async (req, res) => {
|
||||
|
||||
res.status(200).send("");
|
||||
} catch (e) {
|
||||
handleError(req, e, res, "RECEIVE_MESSAGE");
|
||||
handleError(req, e, res, "RECEIVE_MESSAGE", logger);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Generate media array from the request body
|
||||
* @param body
|
||||
* @param logger
|
||||
* @returns {null|*[]}
|
||||
*/
|
||||
const generateMediaArray = (body, logger) => {
|
||||
const { NumMedia } = body;
|
||||
if (parseInt(NumMedia) > 0) {
|
||||
const ret = [];
|
||||
for (let i = 0; i < parseInt(NumMedia); i++) {
|
||||
ret.push(body[`MediaUrl${i}`]);
|
||||
}
|
||||
return ret;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Handle error logging and response
|
||||
* @param req
|
||||
* @param error
|
||||
* @param res
|
||||
* @param context
|
||||
* @param logger
|
||||
*/
|
||||
const handleError = (req, error, res, context, logger) => {
|
||||
logger.log("sms-inbound-error", "ERROR", "api", null, {
|
||||
msid: req.body.SmsMessageSid,
|
||||
text: req.body.Body,
|
||||
image: !!req.body.MediaUrl0,
|
||||
image_path: generateMediaArray(req.body, logger),
|
||||
messagingServiceSid: req.body.MessagingServiceSid,
|
||||
context,
|
||||
error
|
||||
});
|
||||
|
||||
res.status(500).json({ error: error.message || "Internal Server Error" });
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
receive
|
||||
};
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
const twilio = require("twilio");
|
||||
const { phone } = require("phone");
|
||||
const { INSERT_MESSAGE } = require("../graphql-client/queries");
|
||||
const logger = require("../utils/logger");
|
||||
const client = twilio(process.env.TWILIO_AUTH_TOKEN, process.env.TWILIO_AUTH_KEY);
|
||||
const gqlClient = require("../graphql-client/graphql-client").client;
|
||||
|
||||
@@ -15,6 +14,7 @@ const send = async (req, res) => {
|
||||
const { to, messagingServiceSid, body, conversationid, selectedMedia, imexshopid } = req.body;
|
||||
const {
|
||||
ioRedis,
|
||||
logger,
|
||||
ioHelpers: { getBodyshopRoom, getBodyshopConversationRoom }
|
||||
} = req;
|
||||
|
||||
@@ -26,8 +26,8 @@ const send = async (req, res) => {
|
||||
conversationid,
|
||||
isoutbound: true,
|
||||
userid: req.user.email,
|
||||
image: req.body.selectedMedia.length > 0,
|
||||
image_path: req.body.selectedMedia.length > 0 ? selectedMedia.map((i) => i.src) : []
|
||||
image: selectedMedia.length > 0,
|
||||
image_path: selectedMedia.length > 0 ? selectedMedia.map((i) => i.src) : []
|
||||
});
|
||||
|
||||
if (!to || !messagingServiceSid || (!body && selectedMedia.length === 0) || !conversationid) {
|
||||
@@ -39,8 +39,8 @@ const send = async (req, res) => {
|
||||
conversationid,
|
||||
isoutbound: true,
|
||||
userid: req.user.email,
|
||||
image: req.body.selectedMedia.length > 0,
|
||||
image_path: req.body.selectedMedia.length > 0 ? selectedMedia.map((i) => i.src) : []
|
||||
image: selectedMedia.length > 0,
|
||||
image_path: selectedMedia.length > 0 ? selectedMedia.map((i) => i.src) : []
|
||||
});
|
||||
res.status(400).json({ success: false, message: "Missing required parameter(s)." });
|
||||
return;
|
||||
@@ -60,8 +60,8 @@ const send = async (req, res) => {
|
||||
conversationid,
|
||||
isoutbound: true,
|
||||
userid: req.user.email,
|
||||
image: req.body.selectedMedia.length > 0,
|
||||
image_path: req.body.selectedMedia.length > 0 ? selectedMedia.map((i) => i.src) : []
|
||||
image: selectedMedia.length > 0,
|
||||
image_path: selectedMedia.length > 0 ? selectedMedia.map((i) => i.src) : []
|
||||
};
|
||||
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user