chipchoc/server.js
Badri Sunderarajan 393e9c2652 Allow changing of root subdirectory
So that the app can be deployed anywhere! Just change the
environment variable `CHIPCHOC_BASE_URL` and you're all set 😉
2021-06-04 23:47:24 +05:30

108 lines
2.7 KiB
JavaScript

const express = require('express')
const nodemailer = require('nodemailer')
require('dotenv').config()
// handle debug mode
let DEBUG
if (process.env.DEBUG || process.env.CHIPCHOC_DEBUG) {
DEBUG = true
} else {
DEBUG = false
}
if (DEBUG) console.log('Starting ChipChoc in debug mode')
// set up nodemailer
const perumal = nodemailer.createTransport({
// (that's the name of badri's postmaster, in case you were wondering ;)
host: process.env.CHIPCHOC_EMAIL_HOST,
port: process.env.CHIPCHOC_EMAIL_PORT || 587,
secure: process.env.CHIPCHOC_EMAIL_SECURE == 'false' ? false : true,
auth: {
user: process.env.CHIPCHOC_EMAIL_USER,
pass: process.env.CHIPCHOC_EMAIL_PASSWORD,
},
})
// decide base url for app (can be configured)
let baseUrl = process.env.CHIPCHOC_BASE_URL || '/'
const app = express()
var expressWs = require('express-ws')(app)
const router = express.Router()
app.use(baseUrl, router)
const port = process.env.CHIPCHOC_PORT || 5000
const cors = require('cors')
const path = require('path')
app.use(cors())
router.get('/air', (req, res) => {
console.log(`Searching for contacts with the term: ${req.query.name}`)
res.send({
success: true,
data: [],
})
})
router.ws('/hit-send', (ws, request) => {
console.log('Hitting send on some emails!')
ws.on('message', async (message) => {
try {
message = JSON.parse(message)
} catch(err) {
ws.send(JSON.stringify({
success: false,
error: "We can't understand what you're saying! Me speak JSON only.",
}))
return
}
if (DEBUG) {
console.log(`\n\n-------------------------- BEGIN EMAIL --------------------------\n`)
console.log(`From: ${message.from}\nTo:${message.to}\nSubject:${message.subject||'(no subject)'}\n\n${message.text}`)
console.log(`\n--------------------------- END EMAIL ---------------------------`)
} else {
console.log(`Sending email: ${message.from} -> ${message.to}`)
// actually send the email
let receipt = await perumal.sendMail({
from: message.from || process.env.CHIPCHOC_DEFAULT_SENDER,
to: message.to,
bcc: message.from || process.env.CHIPCHOC_DEFAULT_SENDER,
subject: message.subject,
text: message.text,
html: message.html,
})
}
setTimeout(() => {
ws.send(JSON.stringify({
success: true,
from: message.from,
to: message.to,
}))
}, 2000)
})
ws.on('close', () => {
console.log('socket closed')
})
})
app.use(express.static('public'))
router.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'public', 'index.html'))
})
app.listen(port, () => {
console.log(`Server is up at port ${port}`)
})