deliveries/index.mjs

70 lines
2.0 KiB
JavaScript

import { Client } from 'ssh2';
import {
SecretsManagerClient,
GetSecretValueCommand,
} from "@aws-sdk/client-secrets-manager";
export const handler = async (event) => {
let result = "did not send";
if (event.subject == "You have deliveries" || event.subject == "You have a delivery") {
// Trigger home notification
console.info("Matched Subject, pull key");
const keyClient = new SecretsManagerClient({ region: "us-west-2" });
let keyResponse;
try {
keyResponse = await keyClient.send(new GetSecretValueCommand({
SecretId: process.env.TRIGGER_SECRET
}));
keyResponse = JSON.parse(keyResponse.SecretString);
keyResponse = keyResponse["carbon-key"].replaceAll(" ", "\n");
} catch (err) {
console.warn(err);
result = err;
}
const command = `ssh ${process.env.INTERNAL_HOST} "/usr/bin/tmux neww -d \"/usr/bin/mplayer '${process.env.INTERNAL_FILE}'\""`;
console.info("Import ssh2");
const connection = new Client();
console.info("Set Conn Info");
connection.on('ready', () => {
console.info("Connection READY")
connection.exec(command, (error, stream) => {
if (error) {
console.warn(error);
result = JSON.stringify(error);
}
stream.on('end', () => {
console.info("Stream ended");
const response = {
statusCode: 200,
body: {
result
},
};
return response;
});
stream.on('close', (code, signal) => {
// COMPLETE
console.info("Trigger completed", code, signal)
result = code;
}).stderr.on('data', (data) => {
// STDERR
console.warn(data);
});
});
}).connect({
host: process.env.TRIGGER_HOST,
port: 22,
username: process.env.TRIGGER_USERNAME,
privateKey: keyResponse.SecretStrin,
});
}else{
const response = {
statusCode: 200,
body: {
result
},
};
return response;
}
};