SMSReader/server.js
2019-12-31 09:59:21 +01:00

94 lines
2.4 KiB
JavaScript
Executable file

#!/usr/bin/env node
// vim: set ts=2 sw=2 et tw=80:
require('dotenv').config()
const http = require('http');
const url = require('url');
const fetch = require('node-fetch');
const express = require('express')
const app = express()
const { HOST, PORT, PREFIX, API } = process.env;
app.get(PREFIX, (req, res) => res.redirect(PREFIX + '/contacts'));
app.get(PREFIX + '/contacts', (req, res) => {
fetch(API + '?api=GetSMSContactList', {
method: 'POST',
body: JSON.stringify({
jsonrpc: "2.0",
method: "GetSMSContactList",
params: {
Page: req.query.page || 0,
},
id: "6.2"
})
}).then(e => e.json())
.then(e => {
let html = `<html>
<body>
<h1>Contatti dei messaggi</h1>`;
for (const m of e.result.SMSContactList) {
html += `<h4><a href="${PREFIX}/messages/${m.ContactId}">
${m.PhoneNumber[0]}</a></h4>
<p>${m.SMSContent}...</p>`;
}
html += `</body></html>`;
res.header('Content-Type', 'text/html').end(html);
})
.catch(e => e.status(400).json({ error: e.toString() }));
});
app.get(PREFIX + '/messages/:id', (req, res) => {
let id;
if (!req.params.id || isNaN(id = parseInt(req.params.id))) {
res.status(400).json({ error: `"${req.params.id}" is not a valid id` });
return;
}
const page = parseInt(req.query.page) || 0;
fetch(API + '?api=GetSMSContentList', {
method: 'POST',
body: JSON.stringify({
jsonrpc: "2.0",
method: "GetSMSContentList",
params: {
Page: page,
ContactId: id
},
id: "6.3"
})
}).then(e => e.json())
.then(e => {
let html = `<html>
<body>
<h1>Messaggi da: ${e.result.PhoneNumber[0]}</h1>`;
for (const m of e.result.SMSContentList) {
html += `<h4>${m.SMSTime}</h4>
<p>${m.SMSContent}</p>`;
}
if (page > 0) {
html += `<p>
<a href="/messages/${req.params.id}?page=${page-1}>Previous</a>
</p>`
}
if (page + 1 < e.result.TotalPageCount) {
html += `<p>
<a href="/messages/${req.params.id}?page=${page+1}>Next</a>
</p>`
}
html += `</body></html>`;
res.header('Content-Type', 'text/html').end(html);
})
.catch(e => res.status(500).json({ error: e.toString() }));
});
app.listen(PORT, HOST,
() => console.log(`SMSReader listening on port ${HOST}:${PORT}!`));