forked from mycumycu/X4-External-App
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
201 lines (175 loc) · 6.05 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
const fs = require('fs');
const path = require('path');
const dotenvAbsolutePath = path.join(__dirname, '.env');
require('dotenv').config({ path: dotenvAbsolutePath });
let express = require('express');
const portfinder = require("portfinder");
let app = express();
const hostname = process.env.APP_HOST || '127.0.0.1';
const port = process.env.APP_PORT || 8080;
const chalk = require('chalk');
class Server {
dataObject = {};
updatePending = false;
lastOutputMessage = null;
invalidDataStreamTimeout = null;
constructor(app, hostname, port) {
this.app = app;
this.hostname = hostname;
this.port = port;
}
/**
* Check if new release is out
*/
checkVersion() {
const versionCheck = require('github-version-checker');
const { version } = require('./package.json');
const options = {
token: '',
repo: 'X4-External-App',
owner: 'mycumycu',
currentVersion: version,
};
versionCheck(options, null).then((update) => {
if (update) { // update is null if there is no update available, so check here
this.outputMessage("An update is available! " + update.name);
this.outputMessage("You are on version " + options.currentVersion + "!");
this.updatePending = true;
} else {
this.outputMessage(chalk.green(`You are up to date.`));
}
}).catch(function (error) {
console.error(chalk.red(`Couldn't connect to github server to check updates.`));
});
this.outputMessage(chalk.green(`X4 External App Server v${version}`));
}
/**
*
*/
serve() {
let serveStatic = require('serve-static');
let portfinder = require('portfinder');
let localIpV4Address = require("local-ipv4-address");
localIpV4Address().then((ipAddress) => {
portfinder.getPort({ port: this.port }, (err, port) => {
this.app.use(serveStatic(__dirname + "/dist"));
this.app.listen(port, () => {
require('child_process').exec(`start http://${this.hostname}:${port}`);
this.outputMessage(`*****************************`);
this.outputMessage(`** Server running at http://${this.hostname}:${port}/`);
this.outputMessage(`** LAN access: http://${ipAddress}:${port}/`);
this.outputMessage(`*****************************`);
});
});
});
}
/**
* Read from a named pipe or file
*/
dataFeed() {
process.env.DATA_SOURCE === 'pipe' ? this.readFromPipe() : this.readFromFile();
}
/**
*
*/
readFromPipe() {
try {
const fd = fs.openSync(process.env.PIPE_NAME, 'r+')
const stream = fs.createReadStream(null, { fd })
//stream.setEncoding('utf8');
stream.on('data', (d) => {
try {
let buffer = Buffer.from(d);
this.dataObject = JSON.parse(buffer.toString());
this.outputMessage('Correct data stream received.');
this.endInvalidStreamTimer();
} catch (e) {
this.outputMessage('Invalid data stream format.');
this.startInvalidStreamTimer()
}
if (d.toString().trim() === '[stdin end]') {
return process.nextTick(() => {
console.log(process.argv.slice(2))
})
}
process.argv.push(d.toString())
}).on('error', () => {
this.dataObject = null;
this.outputMessage('Disconnected from pipe. Retrying...')
this.readFromPipe();
})
} catch (e) {
this.dataObject = null;
this.outputMessage('Pipe data stream not yet ready. Retrying... ');
setTimeout(() => {
this.readFromPipe();
}, 2000)
}
}
/**
* Development method
*/
readFromFile() {
const chokidar = require('chokidar')
chokidar.watch(process.env.DEV_FILE_PATH).on('all', (event, path) => {
fs.readFile(process.env.DEV_FILE_PATH, 'utf8', (err, data) => {
if (err) {
console.error(err)
return
}
try {
data = data.replace(/\\/g, '')
this.dataObject = JSON.parse(data);
this.outputMessage(`${chalk.yellowBright('Development mode')} - reading data from file successful`);
this.endInvalidStreamTimer();
} catch (e) {
this.outputMessage('Invalid data stream format.');
this.startInvalidStreamTimer()
}
});
})
}
/**
*
*/
setApi() {
this.app.get('/api/data', (req, res) => {
if (this.dataObject) {
this.dataObject.updatePending = this.updatePending;
}
res.json(this.dataObject);
});
}
/**
* Output console messages in non-spammer style
* @param message
*/
outputMessage(message) {
if (this.lastOutputMessage !== message) {
console.log(message)
this.lastOutputMessage = message;
}
}
/**
* Show "there's no water" message if there's incorrect data for long enough
*/
startInvalidStreamTimer() {
if (!this.invalidDataStreamTimeout) {
this.invalidDataStreamTimeout = setTimeout(() => {
this.dataObject = null;
}, 10000)
}
}
/**
*
*/
endInvalidStreamTimer() {
clearTimeout(this.invalidDataStreamTimeout);
this.invalidDataStreamTimeout = null;
}
}
let server = new Server(app, hostname, port);
server.checkVersion();
server.dataFeed();
server.setApi();
server.serve();