88 lines
2.8 KiB
JavaScript
88 lines
2.8 KiB
JavaScript
require("dotenv").config();
|
|
const client = require("../graphql-client/graphql-client").client;
|
|
const queries = require("../graphql-client/queries");
|
|
const phone = require("phone");
|
|
|
|
exports.receive = (req, res) => {
|
|
//Perform request validation
|
|
if (
|
|
!!!req.body ||
|
|
!!!req.body.MessagingServiceSid ||
|
|
!!!req.body.SmsMessageSid
|
|
) {
|
|
res.status(400);
|
|
res.json({ success: false, error: "Malformed Request" });
|
|
} else {
|
|
client
|
|
.request(queries.FIND_BODYSHOP_BY_MESSAGING_SERVICE_SID, {
|
|
mssid: req.body.MessagingServiceSid,
|
|
phone: phone(req.body.From)[0]
|
|
})
|
|
.then(response => {
|
|
//TODO Add logic for handling MMS.
|
|
let newMessage = { msid: req.body.SmsMessageSid, text: req.body.Body };
|
|
if (response.bodyshops[0]) {
|
|
//Found a bodyshop - should always happen.
|
|
if (response.bodyshops[0].conversations.length === 0) {
|
|
//No conversation Found, create one.
|
|
console.log("[SMS Receive] No conversation found. Creating one.");
|
|
newMessage.conversation = {
|
|
data: {
|
|
bodyshopid: response.bodyshops[0].id,
|
|
phone_num: phone(req.body.From)[0]
|
|
}
|
|
};
|
|
} else if (response.bodyshops[0].conversations.length === 1) {
|
|
//Just add it to the conversation
|
|
console.log("[SMS Receive] Conversation found. Added ID.");
|
|
newMessage.conversationid =
|
|
response.bodyshops[0].conversations[0].id;
|
|
} else {
|
|
//We should never get here.
|
|
console.log(
|
|
"Massive Error: Duplicate Phone Numbers for MSSID: " +
|
|
req.body.MessagingServiceSid
|
|
);
|
|
}
|
|
|
|
client
|
|
.request(queries.INSERT_MESSAGE, { msg: newMessage })
|
|
.then(r2 => {
|
|
res.status(200).end();
|
|
})
|
|
.catch(e2 => {
|
|
console.log("e2", e2);
|
|
res.status(500).json(e2);
|
|
});
|
|
}
|
|
})
|
|
.catch(e1 => {
|
|
console.log("e1", e1);
|
|
res.status(500).json(e1);
|
|
});
|
|
}
|
|
};
|
|
|
|
// const sampleMessage: {
|
|
// "ToCountry": "CA",
|
|
// "ToState": "BC",
|
|
// "SmsMessageSid": "SMad7bddaf3454c0904999d6018b1e8f49",
|
|
// "NumMedia": "0",
|
|
// "ToCity": "Vancouver",
|
|
// "FromZip": "",
|
|
// "SmsSid": "SMad7bddaf3454c0904999d6018b1e8f49",
|
|
// "FromState": "BC",
|
|
// "SmsStatus": "received",
|
|
// "FromCity": "VANCOUVER",
|
|
// "Body": "Hi",
|
|
// "FromCountry": "CA",
|
|
// "To": "+16043301606",
|
|
// "MessagingServiceSid": "MG6e259e2add04ffa0d0aa355038670ee1",
|
|
// "ToZip": "",
|
|
// "NumSegments": "1",
|
|
// "MessageSid": "SMad7bddaf3454c0904999d6018b1e8f49",
|
|
// "AccountSid": "AC6c09d337d6b9c68ab6488c2052bd457c",
|
|
// "From": "+16049992002",
|
|
// "ApiVersion": "2010-04-01"
|
|
// }
|