98 lines
2.7 KiB
JavaScript
98 lines
2.7 KiB
JavaScript
|
|
/**
|
|
* Edit API for doors
|
|
*/
|
|
|
|
exports.handler = async function(context, event, callback) {
|
|
const response = new Twilio.Response();
|
|
|
|
let door = event.door;
|
|
let approvalId = event.approvalId;
|
|
let newConfig = event.newConfig;
|
|
|
|
const ddbPath = Runtime.getFunctions()['common/ddb'].path;
|
|
const discordPath = Runtime.getFunctions()['common/discord'].path;
|
|
const ddb = require(ddbPath);
|
|
const discord = require(discordPath);
|
|
const client = ddb.createDDBClient(context);
|
|
|
|
// approve path
|
|
if (door && approvalId) {
|
|
const newConfig = await client.send(ddb.getDoorConfigUpdateCommand(door));
|
|
|
|
if (!newConfig || newConfig.Item.approvalId.S !== approvalId) {
|
|
response.setStatusCode(400);
|
|
return callback(null, response);
|
|
}
|
|
|
|
await client.send(ddb.replaceDoorConfigWithUpdateItem(newConfig));
|
|
|
|
// send update to discord users
|
|
const updateMessage = `Configuration change \`${approvalId}\` was approved @ Door "${door}"`;
|
|
|
|
const discordPromises = newConfig.Item.discordUsers.SS.map((user) => {
|
|
return discord.sendMessageToUser(
|
|
context,
|
|
user,
|
|
updateMessage,
|
|
).catch(e => console.error(e))
|
|
});
|
|
|
|
await Promise.all(discordPromises);
|
|
|
|
response.setStatusCode(200);
|
|
return callback(null, response);
|
|
}
|
|
|
|
if (!door || !newConfig) {
|
|
response.setStatusCode(400);
|
|
return callback(null, response);
|
|
}
|
|
|
|
newConfig = JSON.parse(event.newConfig);
|
|
|
|
const config = await client.send(ddb.getDoorConfigCommand(door));
|
|
|
|
if (!config.Item) {
|
|
response.setStatusCode(404);
|
|
return callback(null, response);
|
|
}
|
|
|
|
// set to old PIN if it is missing
|
|
if (newConfig.pin === "") {
|
|
newConfig.pin = config.Item.pin.S;
|
|
}
|
|
|
|
const input = ddb.putDoorUpdateConfigCommand(door, newConfig);
|
|
|
|
const update = await client.send(input);
|
|
|
|
newConfig.discordUser = undefined;
|
|
newConfig.fallbackNumber = undefined;
|
|
newConfig.status = undefined;
|
|
|
|
const approvalUrl = `https://doorman.chromart.cc/api/door/edit?door=${door}&approvalId=${input.input.Item.approvalId.S}`;
|
|
console.log(approvalUrl);
|
|
|
|
// send update to discord users
|
|
const approvalMessage = `Configuration change requested @ Door "${door}" [click to approve it](${approvalUrl})\`\`\`${JSON.stringify(newConfig, null, 4)}\`\`\``;
|
|
|
|
const discordPromises = config.Item.discordUsers.SS.map((user) => {
|
|
return discord.sendMessageToUser(
|
|
context,
|
|
user,
|
|
approvalMessage,
|
|
).catch(e => console.error(e))
|
|
});
|
|
|
|
await Promise.all(discordPromises);
|
|
|
|
response
|
|
.setStatusCode(200)
|
|
.appendHeader('Content-Type', 'application/json')
|
|
.setBody({ msg: update });
|
|
|
|
await client.destroy();
|
|
return callback(null, response);
|
|
};
|