Spaces:
Paused
Paused
Savestate: Merge Hugging Face main changes (Notes AI proxy, 127.0.0.1 binding) into master
Browse files
server.js
CHANGED
|
@@ -1,503 +1,563 @@
|
|
| 1 |
-
const originalConsoleLog = console.log;
|
| 2 |
-
const originalConsoleError = console.error;
|
| 3 |
-
const originalConsoleWarn = console.warn;
|
| 4 |
-
const originalConsoleInfo = console.info;
|
| 5 |
-
|
| 6 |
-
console.log = function(...args) { originalConsoleLog.apply(console, ['[SCHOOLMIND]', ...args]); };
|
| 7 |
-
console.error = function(...args) { originalConsoleError.apply(console, ['[SCHOOLMIND]', ...args]); };
|
| 8 |
-
console.warn = function(...args) { originalConsoleWarn.apply(console, ['[SCHOOLMIND]', ...args]); };
|
| 9 |
-
console.info = function(...args) { originalConsoleInfo.apply(console, ['[SCHOOLMIND]', ...args]); };
|
| 10 |
-
|
| 11 |
-
console.log("--- server.js loading started ---");
|
| 12 |
-
import express from 'express';
|
| 13 |
-
import cors from 'cors';
|
| 14 |
-
import path from 'path';
|
| 15 |
-
import { fileURLToPath } from 'url';
|
| 16 |
-
import { spawn } from 'child_process';
|
| 17 |
-
import fs from 'fs';
|
| 18 |
-
|
| 19 |
-
console.log("--- Imports loaded ---");
|
| 20 |
-
|
| 21 |
-
const __filename = fileURLToPath(import.meta.url);
|
| 22 |
-
const __dirname = path.dirname(__filename);
|
| 23 |
-
|
| 24 |
-
const app = express();
|
| 25 |
-
console.log("--- Express app created ---");
|
| 26 |
-
|
| 27 |
-
// Increase JSON payload limit to avoid Payload Too Large errors for PDFs
|
| 28 |
-
app.use(express.json({ limit: '50mb' }));
|
| 29 |
-
app.use(cors());
|
| 30 |
-
|
| 31 |
-
// Serve static files from the dist directory
|
| 32 |
-
app.use(express.static(path.join(__dirname, 'dist')));
|
| 33 |
-
// Also serve public/ as fallback for assets downloaded during Docker build (e.g. sql-wasm.wasm)
|
| 34 |
-
app.use(express.static(path.join(__dirname, 'public')));
|
| 35 |
-
|
| 36 |
-
// ==========================================
|
| 37 |
-
// Proxy Middlewares (Migrated from vite.config.js)
|
| 38 |
-
// ==========================================
|
| 39 |
-
|
| 40 |
-
import { initNewsService, registerNewsRoutes } from './server/news-service.js';
|
| 41 |
-
|
| 42 |
-
// Init News Service
|
| 43 |
-
console.log("--- initNewsService calling ---");
|
| 44 |
-
initNewsService();
|
| 45 |
-
console.log("--- initNewsService called ---");
|
| 46 |
-
registerNewsRoutes(app);
|
| 47 |
-
console.log("--- registerNewsRoutes called ---");
|
| 48 |
-
|
| 49 |
-
// Open Source Piper TTS Proxy (Local)
|
| 50 |
-
app.get('/api/tts', async (req, res) => {
|
| 51 |
-
const text = req.query.text;
|
| 52 |
-
if (!text) return res.status(400).json({ error: 'Missing text' });
|
| 53 |
-
|
| 54 |
-
try {
|
| 55 |
-
const piperPath = path.join(__dirname, 'piper_tts', 'piper');
|
| 56 |
-
let modelPath = path.join(__dirname, 'piper_tts', 'de_DE-thorsten-high.onnx');
|
| 57 |
-
|
| 58 |
-
// Check if model is in RAM disk (Linux /dev/shm)
|
| 59 |
-
const shmModelPath = '/dev/shm/de_DE-thorsten-high.onnx';
|
| 60 |
-
if (fs.existsSync(shmModelPath)) {
|
| 61 |
-
modelPath = shmModelPath;
|
| 62 |
-
}
|
| 63 |
-
|
| 64 |
-
// Wenn Piper lokal nicht existiert (z.B. im lokalen Windows Dev-Server)
|
| 65 |
-
if (!fs.existsSync(piperPath)) {
|
| 66 |
-
console.warn("Piper executable not found at " + piperPath);
|
| 67 |
-
return res.status(503).json({error: 'TTS Engine offline (Piper not installed locally)'});
|
| 68 |
-
}
|
| 69 |
-
|
| 70 |
-
res.setHeader('Content-Type', 'audio/wav');
|
| 71 |
-
|
| 72 |
-
// Clean text to prevent Piper from choking on URLs or Emojis
|
| 73 |
-
let cleanText = text;
|
| 74 |
-
cleanText = cleanText.replace(/https?:\/\/[^\s]+/g, ' Link.');
|
| 75 |
-
cleanText = cleanText.replace(/[\u{1F600}-\u{1F64F}]/gu, '');
|
| 76 |
-
cleanText = cleanText.replace(/[\u{1F300}-\u{1F5FF}]/gu, '');
|
| 77 |
-
cleanText = cleanText.replace(/[\u{1F680}-\u{1F6FF}]/gu, '');
|
| 78 |
-
cleanText = cleanText.replace(/[\u{1F700}-\u{1F77F}]/gu, '');
|
| 79 |
-
cleanText = cleanText.replace(/[\u{1F780}-\u{1F7FF}]/gu, '');
|
| 80 |
-
cleanText = cleanText.replace(/[\u{1F800}-\u{1F8FF}]/gu, '');
|
| 81 |
-
cleanText = cleanText.replace(/[\u{1F900}-\u{1F9FF}]/gu, '');
|
| 82 |
-
cleanText = cleanText.replace(/[\u{1FA00}-\u{1FA6F}]/gu, '');
|
| 83 |
-
cleanText = cleanText.replace(/[\u{1FA70}-\u{1FAFF}]/gu, '');
|
| 84 |
-
cleanText = cleanText.replace(/[\u{2600}-\u{26FF}]/gu, '');
|
| 85 |
-
cleanText = cleanText.replace(/[\u{2700}-\u{27BF}]/gu, '');
|
| 86 |
-
|
| 87 |
-
// Piper liest von stdin und schreibt die WAV an stdout
|
| 88 |
-
const piper = spawn(piperPath, ['--model', modelPath, '--output_file', '-'], {
|
| 89 |
-
cwd: path.join(__dirname, 'piper_tts')
|
| 90 |
-
});
|
| 91 |
-
|
| 92 |
-
piper.stdout.pipe(res);
|
| 93 |
-
|
| 94 |
-
piper.stderr.on('data', (data) => {
|
| 95 |
-
// Piper debug output is written to stderr, can be ignored or logged
|
| 96 |
-
// console.log(`Piper log: ${data}`);
|
| 97 |
-
});
|
| 98 |
-
|
| 99 |
-
piper.on('close', (code) => {
|
| 100 |
-
if (code !== 0) console.error(`Piper exited with code ${code}`);
|
| 101 |
-
});
|
| 102 |
-
|
| 103 |
-
piper.stdin.write(cleanText.trim());
|
| 104 |
-
piper.stdin.end();
|
| 105 |
-
} catch (error) {
|
| 106 |
-
console.error('TTS Error:', error);
|
| 107 |
-
if (!res.headersSent) res.status(500).json({ error: error.message });
|
| 108 |
-
}
|
| 109 |
-
});
|
| 110 |
-
|
| 111 |
-
// TTS Debug Endpoint
|
| 112 |
-
app.get('/api/tts/debug', (req, res) => {
|
| 113 |
-
try {
|
| 114 |
-
const piperPath = path.join(__dirname, 'piper_tts', 'piper');
|
| 115 |
-
const modelPath = path.join(__dirname, 'piper_tts', 'de_DE-thorsten-high.onnx');
|
| 116 |
-
const configPath = path.join(__dirname, 'piper_tts', 'de_DE-thorsten-high.onnx.json');
|
| 117 |
-
|
| 118 |
-
res.json({
|
| 119 |
-
piperExists: fs.existsSync(piperPath),
|
| 120 |
-
modelExists: fs.existsSync(modelPath),
|
| 121 |
-
configExists: fs.existsSync(configPath),
|
| 122 |
-
piperPath,
|
| 123 |
-
dirname: __dirname,
|
| 124 |
-
stats: fs.existsSync(piperPath) ? fs.statSync(piperPath) : null
|
| 125 |
-
});
|
| 126 |
-
} catch (err) {
|
| 127 |
-
res.status(500).json({ error: err.message });
|
| 128 |
-
}
|
| 129 |
-
});
|
| 130 |
-
|
| 131 |
-
// WebUntis Proxy
|
| 132 |
-
import { WebUntis } from 'webuntis';
|
| 133 |
-
|
| 134 |
-
app.post('/api/untis', async (req, res) => {
|
| 135 |
-
const { school, username, password, server, date } = req.body;
|
| 136 |
-
if (!school || !username || !password || !server) {
|
| 137 |
-
return res.status(400).json({ error: 'Missing credentials' });
|
| 138 |
-
}
|
| 139 |
-
|
| 140 |
-
// Clean server string in case user pasted a full URL
|
| 141 |
-
let cleanServer = server.replace(/^https?:\/\//, '').replace(/\/.*$/, '').trim();
|
| 142 |
-
|
| 143 |
-
const untis = new WebUntis(school, username, password, cleanServer);
|
| 144 |
-
|
| 145 |
-
try {
|
| 146 |
-
await untis.login();
|
| 147 |
-
|
| 148 |
-
// Parse date if provided, else use today
|
| 149 |
-
const targetDate = date ? new Date(date) : new Date();
|
| 150 |
-
|
| 151 |
-
// Week range Monday–Sunday containing targetDate
|
| 152 |
-
const weekStart = new Date(targetDate);
|
| 153 |
-
const dayOfWeek = weekStart.getDay(); // 0 = Sunday
|
| 154 |
-
const diffToMonday = dayOfWeek === 0 ? -6 : 1 - dayOfWeek;
|
| 155 |
-
weekStart.setDate(weekStart.getDate() + diffToMonday);
|
| 156 |
-
weekStart.setHours(0, 0, 0, 0);
|
| 157 |
-
const weekEnd = new Date(weekStart);
|
| 158 |
-
weekEnd.setDate(weekEnd.getDate() + 6);
|
| 159 |
-
|
| 160 |
-
const timetable = await untis.getOwnTimetableForRange(weekStart, weekEnd);
|
| 161 |
-
|
| 162 |
-
// Optionally fetch more data like subject names or teachers, but the timetable usually contains what we need
|
| 163 |
-
await untis.logout();
|
| 164 |
-
|
| 165 |
-
res.json({ success: true, timetable });
|
| 166 |
-
} catch (error) {
|
| 167 |
-
console.error('Untis API Error:', error);
|
| 168 |
-
// If login fails, webuntis usually throws an error
|
| 169 |
-
res.status(401).json({ error: error.message || 'Login failed' });
|
| 170 |
-
}
|
| 171 |
-
});
|
| 172 |
-
|
| 173 |
-
//
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
const
|
| 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 |
-
const
|
| 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 |
-
res.
|
| 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 |
-
const
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
};
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
if (
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
//
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
const
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
const
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
});
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
}
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const originalConsoleLog = console.log;
|
| 2 |
+
const originalConsoleError = console.error;
|
| 3 |
+
const originalConsoleWarn = console.warn;
|
| 4 |
+
const originalConsoleInfo = console.info;
|
| 5 |
+
|
| 6 |
+
console.log = function(...args) { originalConsoleLog.apply(console, ['[SCHOOLMIND]', ...args]); };
|
| 7 |
+
console.error = function(...args) { originalConsoleError.apply(console, ['[SCHOOLMIND]', ...args]); };
|
| 8 |
+
console.warn = function(...args) { originalConsoleWarn.apply(console, ['[SCHOOLMIND]', ...args]); };
|
| 9 |
+
console.info = function(...args) { originalConsoleInfo.apply(console, ['[SCHOOLMIND]', ...args]); };
|
| 10 |
+
|
| 11 |
+
console.log("--- server.js loading started ---");
|
| 12 |
+
import express from 'express';
|
| 13 |
+
import cors from 'cors';
|
| 14 |
+
import path from 'path';
|
| 15 |
+
import { fileURLToPath } from 'url';
|
| 16 |
+
import { spawn } from 'child_process';
|
| 17 |
+
import fs from 'fs';
|
| 18 |
+
|
| 19 |
+
console.log("--- Imports loaded ---");
|
| 20 |
+
|
| 21 |
+
const __filename = fileURLToPath(import.meta.url);
|
| 22 |
+
const __dirname = path.dirname(__filename);
|
| 23 |
+
|
| 24 |
+
const app = express();
|
| 25 |
+
console.log("--- Express app created ---");
|
| 26 |
+
|
| 27 |
+
// Increase JSON payload limit to avoid Payload Too Large errors for PDFs
|
| 28 |
+
app.use(express.json({ limit: '50mb' }));
|
| 29 |
+
app.use(cors());
|
| 30 |
+
|
| 31 |
+
// Serve static files from the dist directory
|
| 32 |
+
app.use(express.static(path.join(__dirname, 'dist')));
|
| 33 |
+
// Also serve public/ as fallback for assets downloaded during Docker build (e.g. sql-wasm.wasm)
|
| 34 |
+
app.use(express.static(path.join(__dirname, 'public')));
|
| 35 |
+
|
| 36 |
+
// ==========================================
|
| 37 |
+
// Proxy Middlewares (Migrated from vite.config.js)
|
| 38 |
+
// ==========================================
|
| 39 |
+
|
| 40 |
+
import { initNewsService, registerNewsRoutes } from './server/news-service.js';
|
| 41 |
+
|
| 42 |
+
// Init News Service
|
| 43 |
+
console.log("--- initNewsService calling ---");
|
| 44 |
+
initNewsService();
|
| 45 |
+
console.log("--- initNewsService called ---");
|
| 46 |
+
registerNewsRoutes(app);
|
| 47 |
+
console.log("--- registerNewsRoutes called ---");
|
| 48 |
+
|
| 49 |
+
// Open Source Piper TTS Proxy (Local)
|
| 50 |
+
app.get('/api/tts', async (req, res) => {
|
| 51 |
+
const text = req.query.text;
|
| 52 |
+
if (!text) return res.status(400).json({ error: 'Missing text' });
|
| 53 |
+
|
| 54 |
+
try {
|
| 55 |
+
const piperPath = path.join(__dirname, 'piper_tts', 'piper');
|
| 56 |
+
let modelPath = path.join(__dirname, 'piper_tts', 'de_DE-thorsten-high.onnx');
|
| 57 |
+
|
| 58 |
+
// Check if model is in RAM disk (Linux /dev/shm)
|
| 59 |
+
const shmModelPath = '/dev/shm/de_DE-thorsten-high.onnx';
|
| 60 |
+
if (fs.existsSync(shmModelPath)) {
|
| 61 |
+
modelPath = shmModelPath;
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
// Wenn Piper lokal nicht existiert (z.B. im lokalen Windows Dev-Server)
|
| 65 |
+
if (!fs.existsSync(piperPath)) {
|
| 66 |
+
console.warn("Piper executable not found at " + piperPath);
|
| 67 |
+
return res.status(503).json({error: 'TTS Engine offline (Piper not installed locally)'});
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
res.setHeader('Content-Type', 'audio/wav');
|
| 71 |
+
|
| 72 |
+
// Clean text to prevent Piper from choking on URLs or Emojis
|
| 73 |
+
let cleanText = text;
|
| 74 |
+
cleanText = cleanText.replace(/https?:\/\/[^\s]+/g, ' Link.');
|
| 75 |
+
cleanText = cleanText.replace(/[\u{1F600}-\u{1F64F}]/gu, '');
|
| 76 |
+
cleanText = cleanText.replace(/[\u{1F300}-\u{1F5FF}]/gu, '');
|
| 77 |
+
cleanText = cleanText.replace(/[\u{1F680}-\u{1F6FF}]/gu, '');
|
| 78 |
+
cleanText = cleanText.replace(/[\u{1F700}-\u{1F77F}]/gu, '');
|
| 79 |
+
cleanText = cleanText.replace(/[\u{1F780}-\u{1F7FF}]/gu, '');
|
| 80 |
+
cleanText = cleanText.replace(/[\u{1F800}-\u{1F8FF}]/gu, '');
|
| 81 |
+
cleanText = cleanText.replace(/[\u{1F900}-\u{1F9FF}]/gu, '');
|
| 82 |
+
cleanText = cleanText.replace(/[\u{1FA00}-\u{1FA6F}]/gu, '');
|
| 83 |
+
cleanText = cleanText.replace(/[\u{1FA70}-\u{1FAFF}]/gu, '');
|
| 84 |
+
cleanText = cleanText.replace(/[\u{2600}-\u{26FF}]/gu, '');
|
| 85 |
+
cleanText = cleanText.replace(/[\u{2700}-\u{27BF}]/gu, '');
|
| 86 |
+
|
| 87 |
+
// Piper liest von stdin und schreibt die WAV an stdout
|
| 88 |
+
const piper = spawn(piperPath, ['--model', modelPath, '--output_file', '-'], {
|
| 89 |
+
cwd: path.join(__dirname, 'piper_tts')
|
| 90 |
+
});
|
| 91 |
+
|
| 92 |
+
piper.stdout.pipe(res);
|
| 93 |
+
|
| 94 |
+
piper.stderr.on('data', (data) => {
|
| 95 |
+
// Piper debug output is written to stderr, can be ignored or logged
|
| 96 |
+
// console.log(`Piper log: ${data}`);
|
| 97 |
+
});
|
| 98 |
+
|
| 99 |
+
piper.on('close', (code) => {
|
| 100 |
+
if (code !== 0) console.error(`Piper exited with code ${code}`);
|
| 101 |
+
});
|
| 102 |
+
|
| 103 |
+
piper.stdin.write(cleanText.trim());
|
| 104 |
+
piper.stdin.end();
|
| 105 |
+
} catch (error) {
|
| 106 |
+
console.error('TTS Error:', error);
|
| 107 |
+
if (!res.headersSent) res.status(500).json({ error: error.message });
|
| 108 |
+
}
|
| 109 |
+
});
|
| 110 |
+
|
| 111 |
+
// TTS Debug Endpoint
|
| 112 |
+
app.get('/api/tts/debug', (req, res) => {
|
| 113 |
+
try {
|
| 114 |
+
const piperPath = path.join(__dirname, 'piper_tts', 'piper');
|
| 115 |
+
const modelPath = path.join(__dirname, 'piper_tts', 'de_DE-thorsten-high.onnx');
|
| 116 |
+
const configPath = path.join(__dirname, 'piper_tts', 'de_DE-thorsten-high.onnx.json');
|
| 117 |
+
|
| 118 |
+
res.json({
|
| 119 |
+
piperExists: fs.existsSync(piperPath),
|
| 120 |
+
modelExists: fs.existsSync(modelPath),
|
| 121 |
+
configExists: fs.existsSync(configPath),
|
| 122 |
+
piperPath,
|
| 123 |
+
dirname: __dirname,
|
| 124 |
+
stats: fs.existsSync(piperPath) ? fs.statSync(piperPath) : null
|
| 125 |
+
});
|
| 126 |
+
} catch (err) {
|
| 127 |
+
res.status(500).json({ error: err.message });
|
| 128 |
+
}
|
| 129 |
+
});
|
| 130 |
+
|
| 131 |
+
// WebUntis Proxy
|
| 132 |
+
import { WebUntis } from 'webuntis';
|
| 133 |
+
|
| 134 |
+
app.post('/api/untis', async (req, res) => {
|
| 135 |
+
const { school, username, password, server, date } = req.body;
|
| 136 |
+
if (!school || !username || !password || !server) {
|
| 137 |
+
return res.status(400).json({ error: 'Missing credentials' });
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
// Clean server string in case user pasted a full URL
|
| 141 |
+
let cleanServer = server.replace(/^https?:\/\//, '').replace(/\/.*$/, '').trim();
|
| 142 |
+
|
| 143 |
+
const untis = new WebUntis(school, username, password, cleanServer);
|
| 144 |
+
|
| 145 |
+
try {
|
| 146 |
+
await untis.login();
|
| 147 |
+
|
| 148 |
+
// Parse date if provided, else use today
|
| 149 |
+
const targetDate = date ? new Date(date) : new Date();
|
| 150 |
+
|
| 151 |
+
// Week range Monday–Sunday containing targetDate
|
| 152 |
+
const weekStart = new Date(targetDate);
|
| 153 |
+
const dayOfWeek = weekStart.getDay(); // 0 = Sunday
|
| 154 |
+
const diffToMonday = dayOfWeek === 0 ? -6 : 1 - dayOfWeek;
|
| 155 |
+
weekStart.setDate(weekStart.getDate() + diffToMonday);
|
| 156 |
+
weekStart.setHours(0, 0, 0, 0);
|
| 157 |
+
const weekEnd = new Date(weekStart);
|
| 158 |
+
weekEnd.setDate(weekEnd.getDate() + 6);
|
| 159 |
+
|
| 160 |
+
const timetable = await untis.getOwnTimetableForRange(weekStart, weekEnd);
|
| 161 |
+
|
| 162 |
+
// Optionally fetch more data like subject names or teachers, but the timetable usually contains what we need
|
| 163 |
+
await untis.logout();
|
| 164 |
+
|
| 165 |
+
res.json({ success: true, timetable });
|
| 166 |
+
} catch (error) {
|
| 167 |
+
console.error('Untis API Error:', error);
|
| 168 |
+
// If login fails, webuntis usually throws an error
|
| 169 |
+
res.status(401).json({ error: error.message || 'Login failed' });
|
| 170 |
+
}
|
| 171 |
+
});
|
| 172 |
+
|
| 173 |
+
// Notes-App AI Agent/Chat Proxy � keeps OPENROUTER_API_KEY server-side.
|
| 174 |
+
// The client (Notizen-App) only ever sees this URL, never the key.
|
| 175 |
+
app.post('/api/notes/chat/completions', async (req, res) => {
|
| 176 |
+
const accessToken = process.env.NOTES_ACCESS_TOKEN;
|
| 177 |
+
if (accessToken) {
|
| 178 |
+
const provided = req.headers['x-app-key'] || (req.headers.authorization || '').replace(/^Bearer\s+/i, '');
|
| 179 |
+
if (provided !== accessToken) {
|
| 180 |
+
return res.status(401).json({ error: { message: 'Zugriffsschluessel fehlt oder ist falsch' } });
|
| 181 |
+
}
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
const apiKey = process.env.OPENROUTER_API_KEY;
|
| 185 |
+
if (!apiKey) {
|
| 186 |
+
return res.status(500).json({ error: { message: 'OPENROUTER_API_KEY ist im Space nicht gesetzt' } });
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
const messages = Array.isArray(req.body.messages) ? req.body.messages : [];
|
| 190 |
+
if (messages.length === 0 || messages.length > 60) {
|
| 191 |
+
return res.status(400).json({ error: { message: 'messages fehlt oder ist zu lang' } });
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
const NOTES_TEXT_MODELS = ['deepseek/deepseek-v4-flash-0731', 'deepseek/deepseek-v4-flash'];
|
| 195 |
+
const NOTES_VISION_MODEL = 'deepseek/deepseek-v4-flash-vision-exp';
|
| 196 |
+
const hasImage = messages.some(
|
| 197 |
+
(message) =>
|
| 198 |
+
Array.isArray(message.content) &&
|
| 199 |
+
message.content.some((part) => part?.type === 'image_url'),
|
| 200 |
+
);
|
| 201 |
+
const models = process.env.NOTES_MODEL
|
| 202 |
+
? [process.env.NOTES_MODEL]
|
| 203 |
+
: hasImage
|
| 204 |
+
? [NOTES_VISION_MODEL]
|
| 205 |
+
: NOTES_TEXT_MODELS;
|
| 206 |
+
|
| 207 |
+
try {
|
| 208 |
+
const upstream = await fetch('https://openrouter.ai/api/v1/chat/completions', {
|
| 209 |
+
method: 'POST',
|
| 210 |
+
headers: {
|
| 211 |
+
Authorization: Bearer ,
|
| 212 |
+
'Content-Type': 'application/json',
|
| 213 |
+
},
|
| 214 |
+
body: JSON.stringify({
|
| 215 |
+
model: models[0],
|
| 216 |
+
models,
|
| 217 |
+
messages,
|
| 218 |
+
...(Array.isArray(req.body.tools) && req.body.tools.length
|
| 219 |
+
? { tools: req.body.tools, tool_choice: 'auto' }
|
| 220 |
+
: {}),
|
| 221 |
+
provider: { data_collection: 'deny', sort: 'price' },
|
| 222 |
+
reasoning: { enabled: false },
|
| 223 |
+
}),
|
| 224 |
+
});
|
| 225 |
+
const data = await upstream.json();
|
| 226 |
+
res.status(upstream.status).json(data);
|
| 227 |
+
} catch (error) {
|
| 228 |
+
console.error('Notes agent proxy error:', error);
|
| 229 |
+
res.status(502).json({ error: { message: OpenRouter nicht erreichbar: } });
|
| 230 |
+
}
|
| 231 |
+
});
|
| 232 |
+
|
| 233 |
+
// Web Search Proxy
|
| 234 |
+
app.get('/api/proxy/search', async (req, res) => {
|
| 235 |
+
const query = req.query.q;
|
| 236 |
+
if (!query) return res.status(400).json({ error: 'Missing q' });
|
| 237 |
+
try {
|
| 238 |
+
const ddgRes = await fetch(`https://html.duckduckgo.com/html/?q=${encodeURIComponent(query)}`);
|
| 239 |
+
const html = await ddgRes.text();
|
| 240 |
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
| 241 |
+
res.send(html);
|
| 242 |
+
} catch (e) {
|
| 243 |
+
res.status(500).send(e.message);
|
| 244 |
+
}
|
| 245 |
+
});
|
| 246 |
+
|
| 247 |
+
// Gravity Browser Agent Proxy (Traffic Cop)
|
| 248 |
+
app.use('/api/agent', async (req, res) => {
|
| 249 |
+
try {
|
| 250 |
+
const targetUrl = 'http://127.0.0.1:8765' + req.originalUrl.replace('/api/agent', '');
|
| 251 |
+
const fetchOptions = {
|
| 252 |
+
method: req.method,
|
| 253 |
+
headers: { ...req.headers }
|
| 254 |
+
};
|
| 255 |
+
// Remove host to avoid conflicts
|
| 256 |
+
delete fetchOptions.headers.host;
|
| 257 |
+
delete fetchOptions.headers['content-length'];
|
| 258 |
+
delete fetchOptions.headers['content-type'];
|
| 259 |
+
|
| 260 |
+
if (['POST', 'PUT', 'PATCH'].includes(req.method)) {
|
| 261 |
+
fetchOptions.body = JSON.stringify(req.body);
|
| 262 |
+
fetchOptions.headers['Content-Type'] = 'application/json';
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
const response = await fetch(targetUrl, fetchOptions);
|
| 266 |
+
const text = await response.text();
|
| 267 |
+
|
| 268 |
+
res.status(response.status);
|
| 269 |
+
for (const [key, value] of response.headers.entries()) {
|
| 270 |
+
res.setHeader(key, value);
|
| 271 |
+
}
|
| 272 |
+
res.send(text);
|
| 273 |
+
} catch (error) {
|
| 274 |
+
console.error('Agent Proxy Error:', error);
|
| 275 |
+
res.status(502).json({ error: 'Browser Agent is offline or unreachable' });
|
| 276 |
+
}
|
| 277 |
+
});
|
| 278 |
+
|
| 279 |
+
// JSON-based DuckDuckGo endpoint using cheerio
|
| 280 |
+
app.get('/api/ddg-search', async (req, res) => {
|
| 281 |
+
const query = req.query.q;
|
| 282 |
+
if (!query) return res.status(400).json({ error: 'Missing query' });
|
| 283 |
+
try {
|
| 284 |
+
const cheerio = await import('cheerio');
|
| 285 |
+
// Using html.duckduckgo.com
|
| 286 |
+
const response = await fetch(`https://html.duckduckgo.com/html/?q=${encodeURIComponent(query)}`, {
|
| 287 |
+
headers: {
|
| 288 |
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
|
| 289 |
+
}
|
| 290 |
+
});
|
| 291 |
+
const html = await response.text();
|
| 292 |
+
const $ = cheerio.load(html);
|
| 293 |
+
const results = [];
|
| 294 |
+
$('.result__body').each((i, el) => {
|
| 295 |
+
if (i >= 10) return; // limit to top 10
|
| 296 |
+
const title = $(el).find('.result__title .result__a').text().trim();
|
| 297 |
+
const link = $(el).find('.result__title .result__a').attr('href');
|
| 298 |
+
const snippet = $(el).find('.result__snippet').text().trim();
|
| 299 |
+
if (title && link) {
|
| 300 |
+
// DDG wraps links in //duckduckgo.com/l/?uddg=...
|
| 301 |
+
let realLink = link;
|
| 302 |
+
if (link.includes('uddg=')) {
|
| 303 |
+
try {
|
| 304 |
+
const urlObj = new URL(link, 'https://duckduckgo.com');
|
| 305 |
+
realLink = decodeURIComponent(urlObj.searchParams.get('uddg'));
|
| 306 |
+
} catch(e) {}
|
| 307 |
+
}
|
| 308 |
+
results.push({ title, link: realLink, snippet });
|
| 309 |
+
}
|
| 310 |
+
});
|
| 311 |
+
res.json({ results });
|
| 312 |
+
} catch (e) {
|
| 313 |
+
res.status(500).json({ error: e.message });
|
| 314 |
+
}
|
| 315 |
+
});
|
| 316 |
+
|
| 317 |
+
// Web Image Search API
|
| 318 |
+
app.get('/api/search-image', async (req, res) => {
|
| 319 |
+
const query = req.query.q;
|
| 320 |
+
if (!query) return res.status(400).json({ error: 'Missing query' });
|
| 321 |
+
try {
|
| 322 |
+
const cheerio = await import('cheerio');
|
| 323 |
+
const url = `https://www.google.com/search?tbm=isch&q=${encodeURIComponent(query)}`;
|
| 324 |
+
const response = await fetch(url, {
|
| 325 |
+
headers: {
|
| 326 |
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
|
| 327 |
+
}
|
| 328 |
+
});
|
| 329 |
+
const html = await response.text();
|
| 330 |
+
const $ = cheerio.load(html);
|
| 331 |
+
|
| 332 |
+
let imageUrl = null;
|
| 333 |
+
let sourceLink = `https://www.google.com/search?tbm=isch&q=${encodeURIComponent(query)}`;
|
| 334 |
+
|
| 335 |
+
$('img').each((i, el) => {
|
| 336 |
+
const src = $(el).attr('src');
|
| 337 |
+
if (src && src.startsWith('https://encrypted-tbn0.gstatic.com/images')) {
|
| 338 |
+
if (!imageUrl) imageUrl = src;
|
| 339 |
+
}
|
| 340 |
+
});
|
| 341 |
+
|
| 342 |
+
if (imageUrl) {
|
| 343 |
+
res.json({ imageUrl, sourceLink });
|
| 344 |
+
} else {
|
| 345 |
+
res.status(404).json({ error: 'No image found' });
|
| 346 |
+
}
|
| 347 |
+
} catch (e) {
|
| 348 |
+
res.status(500).json({ error: e.message });
|
| 349 |
+
}
|
| 350 |
+
});
|
| 351 |
+
|
| 352 |
+
// Shopping Search Proxy
|
| 353 |
+
app.get('/api/proxy/shop', async (req, res) => {
|
| 354 |
+
const targetUrl = req.query.url;
|
| 355 |
+
if (!targetUrl) return res.status(400).json({ error: 'Missing url' });
|
| 356 |
+
try {
|
| 357 |
+
const shopRes = await fetch(targetUrl, {
|
| 358 |
+
headers: {
|
| 359 |
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
|
| 360 |
+
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
|
| 361 |
+
'Accept-Language': 'de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7',
|
| 362 |
+
'Sec-Ch-Ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
|
| 363 |
+
'Sec-Ch-Ua-Mobile': '?0',
|
| 364 |
+
'Sec-Ch-Ua-Platform': '"Windows"',
|
| 365 |
+
'Sec-Fetch-Dest': 'document',
|
| 366 |
+
'Sec-Fetch-Mode': 'navigate',
|
| 367 |
+
'Sec-Fetch-Site': 'none',
|
| 368 |
+
'Sec-Fetch-User': '?1',
|
| 369 |
+
'Upgrade-Insecure-Requests': '1'
|
| 370 |
+
}
|
| 371 |
+
});
|
| 372 |
+
const text = await shopRes.text();
|
| 373 |
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
| 374 |
+
res.send(text);
|
| 375 |
+
} catch (e) {
|
| 376 |
+
res.status(500).send(e.message);
|
| 377 |
+
}
|
| 378 |
+
});
|
| 379 |
+
|
| 380 |
+
// Reader/Scrape Proxy
|
| 381 |
+
app.get('/api/proxy/scrape', async (req, res) => {
|
| 382 |
+
const targetUrl = req.query.url;
|
| 383 |
+
if (!targetUrl) return res.status(400).json({ error: 'Missing url' });
|
| 384 |
+
try {
|
| 385 |
+
const jinaRes = await fetch(`https://r.jina.ai/${targetUrl}`);
|
| 386 |
+
const text = await jinaRes.text();
|
| 387 |
+
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
| 388 |
+
res.send(text);
|
| 389 |
+
} catch (e) {
|
| 390 |
+
res.status(500).send(e.message);
|
| 391 |
+
}
|
| 392 |
+
});
|
| 393 |
+
|
| 394 |
+
// IServ Puppeteer Endpoint
|
| 395 |
+
app.post('/api/iserv', async (req, res) => {
|
| 396 |
+
try {
|
| 397 |
+
const { fetchIServTasks } = await import('./src/api/iserv.js');
|
| 398 |
+
const { url, username, password } = req.body;
|
| 399 |
+
if (!url || !username || !password) {
|
| 400 |
+
return res.status(400).json({ error: 'Missing credentials' });
|
| 401 |
+
}
|
| 402 |
+
const tasks = await fetchIServTasks(url, username, password);
|
| 403 |
+
res.setHeader('Content-Type', 'application/json');
|
| 404 |
+
res.json(tasks);
|
| 405 |
+
} catch (e) {
|
| 406 |
+
res.status(500).json({ error: e.message || 'Scraping failed' });
|
| 407 |
+
}
|
| 408 |
+
});
|
| 409 |
+
|
| 410 |
+
// PDF Generation Endpoint
|
| 411 |
+
app.post('/api/pdf', async (req, res) => {
|
| 412 |
+
try {
|
| 413 |
+
const { markdown, title } = req.body;
|
| 414 |
+
if (!markdown) {
|
| 415 |
+
return res.status(400).json({ error: "Missing markdown content" });
|
| 416 |
+
}
|
| 417 |
+
const { generatePdf } = await import('./src/api/pdf.js');
|
| 418 |
+
const pdfBuffer = await generatePdf(markdown, title);
|
| 419 |
+
res.setHeader('Content-Type', 'application/pdf');
|
| 420 |
+
res.setHeader('Content-Disposition', `attachment; filename="${encodeURIComponent(title || 'loesung')}.pdf"`);
|
| 421 |
+
res.send(pdfBuffer);
|
| 422 |
+
} catch (e) {
|
| 423 |
+
console.error("PDF generation failed:", e);
|
| 424 |
+
res.status(500).json({ error: e.message });
|
| 425 |
+
}
|
| 426 |
+
});
|
| 427 |
+
|
| 428 |
+
// YouTube Search API
|
| 429 |
+
app.get('/api/youtube-search', async (req, res) => {
|
| 430 |
+
const query = req.query.q;
|
| 431 |
+
if (!query) return res.status(400).send('Missing query');
|
| 432 |
+
try {
|
| 433 |
+
const { default: ytSearch } = await import('youtube-sr');
|
| 434 |
+
|
| 435 |
+
// Force IPv4 for YouTube requests to bypass HF IPv6 blocks
|
| 436 |
+
const dns = await import('dns');
|
| 437 |
+
dns.setDefaultResultOrder('ipv4first');
|
| 438 |
+
|
| 439 |
+
// Helper to fetch via DDG HTML
|
| 440 |
+
const fetchFromDDG = async () => {
|
| 441 |
+
const controller = new AbortController();
|
| 442 |
+
const timeoutId = setTimeout(() => controller.abort(), 8000);
|
| 443 |
+
try {
|
| 444 |
+
const response = await fetch(`https://html.duckduckgo.com/html/?q=site:youtube.com+${encodeURIComponent(query)}`, {
|
| 445 |
+
headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' },
|
| 446 |
+
signal: controller.signal
|
| 447 |
+
});
|
| 448 |
+
clearTimeout(timeoutId);
|
| 449 |
+
const html = await response.text();
|
| 450 |
+
const matches = Array.from(html.matchAll(/v=([a-zA-Z0-9_-]{11})/g));
|
| 451 |
+
if (matches.length > 0) return matches[0][1];
|
| 452 |
+
} catch(err) {
|
| 453 |
+
clearTimeout(timeoutId);
|
| 454 |
+
console.error('DDG fallback error:', err.message);
|
| 455 |
+
}
|
| 456 |
+
return null;
|
| 457 |
+
};
|
| 458 |
+
|
| 459 |
+
// Race ytSearch against a 10s timeout
|
| 460 |
+
let videoId = null;
|
| 461 |
+
try {
|
| 462 |
+
const ytPromise = ytSearch.YouTube.search(query, { limit: 1 }).then(v => v && v.length > 0 ? v[0].id : null);
|
| 463 |
+
const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error('Timeout')), 10000));
|
| 464 |
+
videoId = await Promise.race([ytPromise, timeoutPromise]);
|
| 465 |
+
} catch (e) {
|
| 466 |
+
console.warn('ytSearch failed or timed out:', e.message);
|
| 467 |
+
}
|
| 468 |
+
|
| 469 |
+
if (!videoId) {
|
| 470 |
+
console.warn('Falling back to DDG...');
|
| 471 |
+
videoId = await fetchFromDDG();
|
| 472 |
+
}
|
| 473 |
+
|
| 474 |
+
if (videoId) {
|
| 475 |
+
if (req.query.json) {
|
| 476 |
+
res.setHeader('Content-Type', 'application/json');
|
| 477 |
+
res.json({ videoId });
|
| 478 |
+
} else {
|
| 479 |
+
res.redirect(`https://www.youtube.com/embed/${videoId}?autoplay=1&mute=1`);
|
| 480 |
+
}
|
| 481 |
+
} else {
|
| 482 |
+
res.status(404).send('No videos found');
|
| 483 |
+
}
|
| 484 |
+
} catch (err) {
|
| 485 |
+
res.status(500).send(err.message);
|
| 486 |
+
}
|
| 487 |
+
});
|
| 488 |
+
|
| 489 |
+
// Deep Research Search Proxy (Google News RSS)
|
| 490 |
+
app.get('/api/research/search', async (req, res) => {
|
| 491 |
+
const query = req.query.q;
|
| 492 |
+
if (!query) return res.status(400).json({ error: 'Missing query' });
|
| 493 |
+
try {
|
| 494 |
+
const cheerio = await import('cheerio');
|
| 495 |
+
const url = `https://news.google.com/rss/search?q=${encodeURIComponent(query)}&hl=de&gl=DE&ceid=DE:de`;
|
| 496 |
+
const response = await fetch(url);
|
| 497 |
+
const xml = await response.text();
|
| 498 |
+
const $ = cheerio.load(xml, { xmlMode: true });
|
| 499 |
+
|
| 500 |
+
const results = [];
|
| 501 |
+
$('item').each((i, el) => {
|
| 502 |
+
if (i >= 5) return;
|
| 503 |
+
const title = $(el).find('title').text();
|
| 504 |
+
const link = $(el).find('link').text();
|
| 505 |
+
const description = $(el).find('description').text();
|
| 506 |
+
const snippet = cheerio.load(description).text().trim() || title;
|
| 507 |
+
|
| 508 |
+
if (title && link) {
|
| 509 |
+
results.push({ title, body: snippet, href: link });
|
| 510 |
+
}
|
| 511 |
+
});
|
| 512 |
+
res.json({ results });
|
| 513 |
+
} catch (e) {
|
| 514 |
+
res.status(500).json({ error: e.message });
|
| 515 |
+
}
|
| 516 |
+
});
|
| 517 |
+
|
| 518 |
+
// YouTube Transcript API
|
| 519 |
+
app.get('/api/youtube-transcript', async (req, res) => {
|
| 520 |
+
const videoId = req.query.v;
|
| 521 |
+
if (!videoId) return res.status(400).json({ error: 'Missing video ID' });
|
| 522 |
+
try {
|
| 523 |
+
const { YoutubeTranscript } = await import('youtube-transcript');
|
| 524 |
+
const transcript = await YoutubeTranscript.fetchTranscript(videoId);
|
| 525 |
+
res.setHeader('Content-Type', 'application/json');
|
| 526 |
+
res.json(transcript);
|
| 527 |
+
} catch (err) {
|
| 528 |
+
res.status(500).json({ error: err.message });
|
| 529 |
+
}
|
| 530 |
+
});
|
| 531 |
+
|
| 532 |
+
// Fallback for SPA routing - only for navigation requests, NOT for assets
|
| 533 |
+
app.use((req, res) => {
|
| 534 |
+
// If the request looks like a static asset (has a file extension), return 404
|
| 535 |
+
if (req.path.match(/\.\w+$/)) {
|
| 536 |
+
return res.status(404).send('Not found');
|
| 537 |
+
}
|
| 538 |
+
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
|
| 539 |
+
});
|
| 540 |
+
|
| 541 |
+
// Start Server
|
| 542 |
+
const PORT = process.env.PORT || 7860; // Force Hugging Face Spaces port unless set
|
| 543 |
+
|
| 544 |
+
// Preload Piper into RAM disk for faster generation
|
| 545 |
+
try {
|
| 546 |
+
if (fs.existsSync('/dev/shm')) {
|
| 547 |
+
const shmModelPath = '/dev/shm/de_DE-thorsten-high.onnx';
|
| 548 |
+
const shmConfigPath = '/dev/shm/de_DE-thorsten-high.onnx.json';
|
| 549 |
+
if (!fs.existsSync(shmModelPath)) {
|
| 550 |
+
console.log('Copying Piper model to RAM disk (/dev/shm)...');
|
| 551 |
+
fs.copyFileSync(path.join(__dirname, 'piper_tts', 'de_DE-thorsten-high.onnx'), shmModelPath);
|
| 552 |
+
}
|
| 553 |
+
if (!fs.existsSync(shmConfigPath)) {
|
| 554 |
+
fs.copyFileSync(path.join(__dirname, 'piper_tts', 'de_DE-thorsten-high.onnx.json'), shmConfigPath);
|
| 555 |
+
}
|
| 556 |
+
}
|
| 557 |
+
} catch (e) {
|
| 558 |
+
console.log('Failed to copy Piper model to RAM disk:', e.message);
|
| 559 |
+
}
|
| 560 |
+
|
| 561 |
+
app.listen(PORT, '127.0.0.1', () => {
|
| 562 |
+
console.log(`🚀 SchoolMind AI Server is running on port ${PORT}`);
|
| 563 |
+
});
|