-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
104 lines (85 loc) · 2.7 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
const {exec, execFile} = require('child_process');
const express = require('express');
const fs = require('fs');
const https = require('https');
const path = require('path');
const app = express();
app.use(express.json());
let tmpFileHeader;
let tslFile;
//https://gist.github.com/aerrity/fd393e5511106420fba0c9602cc05d35
app.use(express.static("./public"));
//try with https, if files found, go to app.listen
try {
const httpsOptions = {
cert: fs.readFileSync("/etc/letsencrypt/live/tslsynthesissynthesizer.com/fullchain.pem"),
// ca: fs.readFileSync(""),
key: fs.readFileSync("/etc/letsencrypt/live/tslsynthesissynthesizer.com/privkey.pem")
};
const httpsServer = https.createServer(httpsOptions, app);
httpsServer.listen(443, 'tslsynthesissynthesizer.com');
console.log("Service started on on https://tslsynthesissynthesizer.com.");
} catch {
//to run locally
const PORT = 4747;
app.listen(PORT, () => {
console.log(`Service started on port ${PORT}.`);
});
}
// Serve the homepage
app.get('/', (req, res) => {
let htmlPath = path.join(__dirname, './views/index.html');
res.sendFile(htmlPath);
});
// GET and POST
app.get('/synthesized', async (req, res) => {
let synthesized = await synthesize();
await deleteTmpFiles();
res.send({result:synthesized});
})
app.post('/spec', async (req, res) => {
await writeTmpFile(req.body.spec);
res.sendStatus(201);
})
function writeTmpFile(spec){
tmpFileHeader = "tmp" + Math.random().toString().slice(2,8);
tslFile = tmpFileHeader + ".tsl";
return new Promise(resolve => {
fs.writeFile(tslFile, spec, function (err) {
if (err) throw err;
else
console.log('Temp file creation successful.');
resolve();
});
})
}
function deleteTmpFiles(){
const shellCmd = "rm " + tmpFileHeader + "*";
return new Promise(resolve => {
exec(shellCmd,
function(err, data){
if (err)
console.log("Temp file deletions unsuccessful.\nPlease manually delete them.");
else
console.log("Temp files deletion successful.");
resolve();
})
})
}
// Function to synthesize TSL spec
function synthesize() {
return new Promise(resolve => {
execFile('bash', ['synthesize.sh', tslFile],
function (err, data) {
let returnValue;
// XXX
if (err) {
returnValue = "ERROR" + err;
}
else {
returnValue = data.toString();
}
resolve(returnValue);
})
})
}