-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
191 lines (175 loc) · 6.43 KB
/
server.js
File metadata and controls
191 lines (175 loc) · 6.43 KB
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
// ============================================================================
// EyeLS — Node.js (Express) server
//
// Responsibilities:
// 1. Serve the static front-end (HTML / CSS / JS / eyels.js).
// 2. Expose a small REST API:
// POST /api/stats text -> JSON stats (delegated to the C++ binary)
// POST /api/sessions persist a typed session
// GET /api/sessions list all persisted sessions
// GET /api/sessions/:id fetch one session
// DELETE /api/sessions/:id
// GET /api/health basic introspection (stack info)
//
// The /api/stats endpoint shells out to ./tools/stats (a C++ program) so that
// the heavy text-crunching happens in native code — Node just streams data
// in and pipes JSON back out.
// ============================================================================
'use strict';
const express = require('express');
const path = require('path');
const fs = require('fs');
const { spawn } = require('child_process');
const ROOT = __dirname;
const STATS_BIN = path.join(ROOT, 'tools', 'stats');
const DATA_DIR = path.join(ROOT, 'data');
const SESSIONS_FILE = path.join(DATA_DIR, 'sessions.json');
const PORT = Number(process.env.PORT) || 3000;
const app = express();
app.use(express.json({ limit: '2mb' }));
// --------------------------------------------------------------------------
// Static front-end
// --------------------------------------------------------------------------
app.use(
express.static(ROOT, {
// Don't auto-serve index.html from /; we want explicit routes below so
// the URL bar reflects the active view.
index: false,
extensions: ['html'],
})
);
app.get('/', (_req, res) => res.sendFile(path.join(ROOT, 'index.html')));
app.get('/stats', (_req, res) => res.sendFile(path.join(ROOT, 'stats.html')));
app.get('/settings', (_req, res) =>
res.sendFile(path.join(ROOT, 'settings.html'))
);
// --------------------------------------------------------------------------
// Sessions persistence (simple JSON file — fine for a personal app)
// --------------------------------------------------------------------------
function loadSessions() {
try {
return JSON.parse(fs.readFileSync(SESSIONS_FILE, 'utf-8'));
} catch {
return [];
}
}
function saveSessions(sessions) {
fs.mkdirSync(DATA_DIR, { recursive: true });
fs.writeFileSync(SESSIONS_FILE, JSON.stringify(sessions, null, 2));
}
// --------------------------------------------------------------------------
// /api/stats — shell out to the C++ binary
// --------------------------------------------------------------------------
function runStats(text) {
return new Promise((resolve, reject) => {
if (!fs.existsSync(STATS_BIN)) {
return reject(
new Error(
'C++ stats binary not found. Build it with: `make -C tools` ' +
'(or `npm run build:cpp`).'
)
);
}
const child = spawn(STATS_BIN, [], { stdio: ['pipe', 'pipe', 'pipe'] });
let out = '';
let err = '';
child.stdout.on('data', (d) => (out += d.toString('utf8')));
child.stderr.on('data', (d) => (err += d.toString('utf8')));
child.on('error', (e) => reject(e));
child.on('close', (code) => {
if (code !== 0) {
return reject(
new Error(`stats binary exited ${code}: ${err.trim() || '(no stderr)'}`)
);
}
try {
resolve(JSON.parse(out));
} catch (parseErr) {
reject(new Error(`invalid JSON from stats binary: ${parseErr.message}`));
}
});
child.stdin.end(text || '');
});
}
app.post('/api/stats', async (req, res) => {
const text = typeof req.body.text === 'string' ? req.body.text : '';
try {
const stats = await runStats(text);
res.json({ ok: true, stats, generatedBy: 'C++ (./tools/stats)' });
} catch (e) {
res.status(500).json({ ok: false, error: e.message });
}
});
// --------------------------------------------------------------------------
// /api/sessions
// --------------------------------------------------------------------------
app.get('/api/sessions', (_req, res) => {
res.json({ ok: true, sessions: loadSessions() });
});
app.get('/api/sessions/:id', (req, res) => {
const id = String(req.params.id);
const session = loadSessions().find((s) => String(s.id) === id);
if (!session) return res.status(404).json({ ok: false, error: 'not found' });
res.json({ ok: true, session });
});
app.post('/api/sessions', (req, res) => {
const text = typeof req.body.text === 'string' ? req.body.text : '';
if (!text.trim()) {
return res.status(400).json({ ok: false, error: 'empty text' });
}
const sessions = loadSessions();
const session = {
id: Date.now(),
timestamp: new Date().toISOString(),
text,
characters: text.length,
};
sessions.unshift(session);
// Keep the last 100 sessions to avoid unbounded growth.
if (sessions.length > 100) sessions.length = 100;
saveSessions(sessions);
res.json({ ok: true, session });
});
app.delete('/api/sessions/:id', (req, res) => {
const id = String(req.params.id);
const sessions = loadSessions();
const next = sessions.filter((s) => String(s.id) !== id);
if (next.length === sessions.length) {
return res.status(404).json({ ok: false, error: 'not found' });
}
saveSessions(next);
res.json({ ok: true });
});
// --------------------------------------------------------------------------
// /api/health — for debugging which pieces of the stack are reachable
// --------------------------------------------------------------------------
app.get('/api/health', (_req, res) => {
res.json({
ok: true,
node: process.version,
statsBinaryAvailable: fs.existsSync(STATS_BIN),
stack: {
server: 'Node.js + Express',
stats: 'C++ (./tools/stats)',
mainApp: 'Vanilla JS + eyels.js gaze tracker',
dashboard: 'Angular (/stats)',
settings: 'Vue 3 (/settings)',
},
});
});
// --------------------------------------------------------------------------
// Boot
// --------------------------------------------------------------------------
app.listen(PORT, () => {
// eslint-disable-next-line no-console
console.log(`\n EyeLS server running at http://localhost:${PORT}`);
console.log(
` Stack: Node.js (Express) + C++ stats + Angular + Vue + Vanilla JS\n`
);
if (!fs.existsSync(STATS_BIN)) {
console.warn(
` ⚠ C++ stats binary missing at ${STATS_BIN}.\n` +
` Build it with: npm run build:cpp\n`
);
}
});