-
-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathserver.js
370 lines (317 loc) · 10.9 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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
const express = require('express');
const cron = require('node-cron');
const path = require('path');
const fs = require('fs').promises;
const config = require('./config/config');
const paperlessService = require('./services/paperlessService');
const AIServiceFactory = require('./services/aiServiceFactory');
const documentModel = require('./models/document');
const setupService = require('./services/setupService');
const setupRoutes = require('./routes/setup');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const Logger = require('./services/loggerService');
const { max } = require('date-fns');
const htmlLogger = new Logger({
logFile: 'logs.html',
format: 'html',
timestamp: true,
maxFileSize: 1024 * 1024 * 10
});
const txtLogger = new Logger({
logFile: 'logs.txt',
format: 'txt',
timestamp: true,
maxFileSize: 1024 * 1024 * 10
});
const app = express();
let runningTask = false;
const corsOptions = {
origin: true,
methods: ['GET', 'POST', 'OPTIONS'],
allowedHeaders: [
'Content-Type',
'x-api-key',
'Access-Control-Allow-Private-Network'
],
credentials: false
};
app.use(cors(corsOptions));
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, x-api-key, Access-Control-Allow-Private-Network');
res.header('Access-Control-Allow-Private-Network', 'true');
if (req.method === 'OPTIONS') {
return res.status(200).end();
}
next();
});
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb', extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
// View engine setup
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Layout middleware
app.use((req, res, next) => {
const originalRender = res.render;
res.render = function (view, locals = {}) {
originalRender.call(this, view, locals, (err, html) => {
if (err) return next(err);
originalRender.call(this, 'layout', { content: html, ...locals });
});
};
next();
});
// Initialize data directory
async function initializeDataDirectory() {
const dataDir = path.join(process.cwd(), 'data');
try {
await fs.access(dataDir);
} catch {
console.log('Creating data directory...');
await fs.mkdir(dataDir, { recursive: true });
}
}
// Document processing functions
async function processDocument(doc, existingTags, existingCorrespondentList, ownUserId) {
const isProcessed = await documentModel.isDocumentProcessed(doc.id);
if (isProcessed) return null;
const documentOwnerId = await paperlessService.getOwnerOfDocument(doc.id);
if (documentOwnerId !== ownUserId && documentOwnerId !== null) {
console.log(`[DEBUG] Document belongs to: ${documentOwnerId}, skipping analysis`);
console.log(`[DEBUG] Document ${doc.id} not owned by user, skipping analysis`);
return null;
}
let [content, originalData] = await Promise.all([
paperlessService.getDocumentContent(doc.id),
paperlessService.getDocument(doc.id)
]);
if (!content || !content.length >= 10) {
console.log(`[DEBUG] Document ${doc.id} has no content, skipping analysis`);
return null;
}
if (content.length > 50000) {
content = content.substring(0, 50000);
}
const aiService = AIServiceFactory.getService();
const analysis = await aiService.analyzeDocument(content, existingTags, existingCorrespondentList, doc.id);
if (analysis.error) {
throw new Error(`[ERROR] Document analysis failed: ${analysis.error}`);
}
return { analysis, originalData };
}
async function buildUpdateData(analysis, doc) {
const { tagIds, errors } = await paperlessService.processTags(analysis.document.tags);
if (errors.length > 0) {
console.warn('[ERROR] Some tags could not be processed:', errors);
}
const updateData = {
tags: tagIds,
title: analysis.document.title || doc.title,
created: analysis.document.document_date || doc.created,
};
if (analysis.document.correspondent) {
try {
const correspondent = await paperlessService.getOrCreateCorrespondent(analysis.document.correspondent);
if (correspondent) {
updateData.correspondent = correspondent.id;
}
} catch (error) {
console.error(`[ERROR] Error processing correspondent:`, error);
}
}
if (analysis.document.language) {
updateData.language = analysis.document.language;
}
return updateData;
}
async function saveDocumentChanges(docId, updateData, analysis, originalData) {
const { tags: originalTags, correspondent: originalCorrespondent, title: originalTitle } = originalData;
await Promise.all([
documentModel.saveOriginalData(docId, originalTags, originalCorrespondent, originalTitle),
paperlessService.updateDocument(docId, updateData),
documentModel.addProcessedDocument(docId, updateData.title),
documentModel.addOpenAIMetrics(
docId,
analysis.metrics.promptTokens,
analysis.metrics.completionTokens,
analysis.metrics.totalTokens
),
documentModel.addToHistory(docId, updateData.tags, updateData.title, analysis.document.correspondent)
]);
}
// Main scanning functions
async function scanInitial() {
try {
const isConfigured = await setupService.isConfigured();
if (!isConfigured) {
console.log('[ERROR] Setup not completed. Skipping document scan.');
return;
}
let [existingTags, documents, ownUserId, existingCorrespondentList] = await Promise.all([
paperlessService.getTags(),
paperlessService.getAllDocuments(),
paperlessService.getOwnUserID(),
paperlessService.listCorrespondentsNames()
]);
//get existing correspondent list
existingCorrespondentList = existingCorrespondentList.map(correspondent => correspondent.name);
for (const doc of documents) {
try {
const result = await processDocument(doc, existingTags, existingCorrespondentList, ownUserId);
if (!result) continue;
const { analysis, originalData } = result;
const updateData = await buildUpdateData(analysis, doc);
await saveDocumentChanges(doc.id, updateData, analysis, originalData);
} catch (error) {
console.error(`[ERROR] processing document ${doc.id}:`, error);
}
}
} catch (error) {
console.error('[ERROR] during initial document scan:', error);
}
}
async function scanDocuments() {
if (runningTask) {
console.log('[DEBUG] Task already running');
return;
}
runningTask = true;
try {
let [existingTags, documents, ownUserId, existingCorrespondentList] = await Promise.all([
paperlessService.getTags(),
paperlessService.getAllDocuments(),
paperlessService.getOwnUserID(),
paperlessService.listCorrespondentsNames()
]);
//get existing correspondent list
existingCorrespondentList = existingCorrespondentList.map(correspondent => correspondent.name);
for (const doc of documents) {
try {
const result = await processDocument(doc, existingTags, existingCorrespondentList, ownUserId);
if (!result) continue;
const { analysis, originalData } = result;
const updateData = await buildUpdateData(analysis, doc);
await saveDocumentChanges(doc.id, updateData, analysis, originalData);
} catch (error) {
console.error(`[ERROR] processing document ${doc.id}:`, error);
}
}
} catch (error) {
console.error('[ERROR] during document scan:', error);
} finally {
runningTask = false;
console.log('[INFO] Task completed');
}
}
// Routes
app.use('/', setupRoutes);
app.get('/', async (req, res) => {
try {
res.redirect('/dashboard');
} catch (error) {
console.error('[ERROR] in root route:', error);
res.status(500).send('Error processing request');
}
});
app.get('/health', async (req, res) => {
try {
const isConfigured = await setupService.isConfigured();
if (!isConfigured) {
return res.status(503).json({
status: 'not_configured',
message: 'Application setup not completed'
});
}
await documentModel.isDocumentProcessed(1);
res.json({ status: 'healthy' });
} catch (error) {
console.error('Health check failed:', error);
res.status(503).json({
status: 'error',
message: error.message
});
}
});
// Error handler
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
// Start scanning
async function startScanning() {
try {
const isConfigured = await setupService.isConfigured();
if (!isConfigured) {
console.log('Setup not completed. Visit http://your-ip-or-host.com:3000/setup to complete setup.');
return;
}
const userId = await paperlessService.getOwnUserID();
if (!userId) {
console.error('Failed to get own user ID. Aborting scanning.');
return;
}
console.log('Configured scan interval:', config.scanInterval);
console.log(`Starting initial scan at ${new Date().toISOString()}`);
await scanInitial();
cron.schedule(config.scanInterval, async () => {
console.log(`Starting scheduled scan at ${new Date().toISOString()}`);
await scanDocuments();
});
} catch (error) {
console.error('[ERROR] in startScanning:', error);
}
}
// Error handlers
// process.on('SIGTERM', async () => {
// console.log('Received SIGTERM. Starting graceful shutdown...');
// try {
// console.log('Closing database...');
// await documentModel.closeDatabase(); // Jetzt warten wir wirklich auf den Close
// console.log('Database closed successfully');
// process.exit(0);
// } catch (error) {
// console.error('[ERROR] during shutdown:', error);
// process.exit(1);
// }
// });
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception:', error);
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
process.exit(1);
});
async function gracefulShutdown(signal) {
console.log(`[DEBUG] Received ${signal} signal. Starting graceful shutdown...`);
try {
console.log('[DEBUG] Closing database...');
await documentModel.closeDatabase();
console.log('[DEBUG] Database closed successfully');
process.exit(0);
} catch (error) {
console.error(`[ERROR] during ${signal} shutdown:`, error);
process.exit(1);
}
}
// Handle both SIGTERM and SIGINT
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
// Start server
async function startServer() {
try {
await initializeDataDirectory();
app.listen(3000, () => {
console.log('Server running on port 3000');
startScanning();
});
} catch (error) {
console.error('Failed to start server:', error);
process.exit(1);
}
}
startServer();