Luca448 commited on
Commit
a8e2cad
·
1 Parent(s): ae5b54e

Savestate: Merge Hugging Face main changes (Notes AI proxy, 127.0.0.1 binding) into master

Browse files
Files changed (1) hide show
  1. server.js +563 -503
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
- // Web Search Proxy
174
- app.get('/api/proxy/search', async (req, res) => {
175
- const query = req.query.q;
176
- if (!query) return res.status(400).json({ error: 'Missing q' });
177
- try {
178
- const ddgRes = await fetch(`https://html.duckduckgo.com/html/?q=${encodeURIComponent(query)}`);
179
- const html = await ddgRes.text();
180
- res.setHeader('Content-Type', 'text/html; charset=utf-8');
181
- res.send(html);
182
- } catch (e) {
183
- res.status(500).send(e.message);
184
- }
185
- });
186
-
187
- // Gravity Browser Agent Proxy (Traffic Cop)
188
- app.use('/api/agent', async (req, res) => {
189
- try {
190
- const targetUrl = 'http://127.0.0.1:8765' + req.originalUrl.replace('/api/agent', '');
191
- const fetchOptions = {
192
- method: req.method,
193
- headers: { ...req.headers }
194
- };
195
- // Remove host to avoid conflicts
196
- delete fetchOptions.headers.host;
197
- delete fetchOptions.headers['content-length'];
198
- delete fetchOptions.headers['content-type'];
199
-
200
- if (['POST', 'PUT', 'PATCH'].includes(req.method)) {
201
- fetchOptions.body = JSON.stringify(req.body);
202
- fetchOptions.headers['Content-Type'] = 'application/json';
203
- }
204
-
205
- const response = await fetch(targetUrl, fetchOptions);
206
- const text = await response.text();
207
-
208
- res.status(response.status);
209
- for (const [key, value] of response.headers.entries()) {
210
- res.setHeader(key, value);
211
- }
212
- res.send(text);
213
- } catch (error) {
214
- console.error('Agent Proxy Error:', error);
215
- res.status(502).json({ error: 'Browser Agent is offline or unreachable' });
216
- }
217
- });
218
-
219
- // JSON-based DuckDuckGo endpoint using cheerio
220
- app.get('/api/ddg-search', async (req, res) => {
221
- const query = req.query.q;
222
- if (!query) return res.status(400).json({ error: 'Missing query' });
223
- try {
224
- const cheerio = await import('cheerio');
225
- // Using html.duckduckgo.com
226
- const response = await fetch(`https://html.duckduckgo.com/html/?q=${encodeURIComponent(query)}`, {
227
- headers: {
228
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
229
- }
230
- });
231
- const html = await response.text();
232
- const $ = cheerio.load(html);
233
- const results = [];
234
- $('.result__body').each((i, el) => {
235
- if (i >= 10) return; // limit to top 10
236
- const title = $(el).find('.result__title .result__a').text().trim();
237
- const link = $(el).find('.result__title .result__a').attr('href');
238
- const snippet = $(el).find('.result__snippet').text().trim();
239
- if (title && link) {
240
- // DDG wraps links in //duckduckgo.com/l/?uddg=...
241
- let realLink = link;
242
- if (link.includes('uddg=')) {
243
- try {
244
- const urlObj = new URL(link, 'https://duckduckgo.com');
245
- realLink = decodeURIComponent(urlObj.searchParams.get('uddg'));
246
- } catch(e) {}
247
- }
248
- results.push({ title, link: realLink, snippet });
249
- }
250
- });
251
- res.json({ results });
252
- } catch (e) {
253
- res.status(500).json({ error: e.message });
254
- }
255
- });
256
-
257
- // Web Image Search API
258
- app.get('/api/search-image', async (req, res) => {
259
- const query = req.query.q;
260
- if (!query) return res.status(400).json({ error: 'Missing query' });
261
- try {
262
- const cheerio = await import('cheerio');
263
- const url = `https://www.google.com/search?tbm=isch&q=${encodeURIComponent(query)}`;
264
- const response = await fetch(url, {
265
- headers: {
266
- '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'
267
- }
268
- });
269
- const html = await response.text();
270
- const $ = cheerio.load(html);
271
-
272
- let imageUrl = null;
273
- let sourceLink = `https://www.google.com/search?tbm=isch&q=${encodeURIComponent(query)}`;
274
-
275
- $('img').each((i, el) => {
276
- const src = $(el).attr('src');
277
- if (src && src.startsWith('https://encrypted-tbn0.gstatic.com/images')) {
278
- if (!imageUrl) imageUrl = src;
279
- }
280
- });
281
-
282
- if (imageUrl) {
283
- res.json({ imageUrl, sourceLink });
284
- } else {
285
- res.status(404).json({ error: 'No image found' });
286
- }
287
- } catch (e) {
288
- res.status(500).json({ error: e.message });
289
- }
290
- });
291
-
292
- // Shopping Search Proxy
293
- app.get('/api/proxy/shop', async (req, res) => {
294
- const targetUrl = req.query.url;
295
- if (!targetUrl) return res.status(400).json({ error: 'Missing url' });
296
- try {
297
- const shopRes = await fetch(targetUrl, {
298
- headers: {
299
- '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',
300
- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
301
- 'Accept-Language': 'de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7',
302
- 'Sec-Ch-Ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
303
- 'Sec-Ch-Ua-Mobile': '?0',
304
- 'Sec-Ch-Ua-Platform': '"Windows"',
305
- 'Sec-Fetch-Dest': 'document',
306
- 'Sec-Fetch-Mode': 'navigate',
307
- 'Sec-Fetch-Site': 'none',
308
- 'Sec-Fetch-User': '?1',
309
- 'Upgrade-Insecure-Requests': '1'
310
- }
311
- });
312
- const text = await shopRes.text();
313
- res.setHeader('Content-Type', 'text/html; charset=utf-8');
314
- res.send(text);
315
- } catch (e) {
316
- res.status(500).send(e.message);
317
- }
318
- });
319
-
320
- // Reader/Scrape Proxy
321
- app.get('/api/proxy/scrape', async (req, res) => {
322
- const targetUrl = req.query.url;
323
- if (!targetUrl) return res.status(400).json({ error: 'Missing url' });
324
- try {
325
- const jinaRes = await fetch(`https://r.jina.ai/${targetUrl}`);
326
- const text = await jinaRes.text();
327
- res.setHeader('Content-Type', 'text/plain; charset=utf-8');
328
- res.send(text);
329
- } catch (e) {
330
- res.status(500).send(e.message);
331
- }
332
- });
333
-
334
- // IServ Puppeteer Endpoint
335
- app.post('/api/iserv', async (req, res) => {
336
- try {
337
- const { fetchIServTasks } = await import('./src/api/iserv.js');
338
- const { url, username, password } = req.body;
339
- if (!url || !username || !password) {
340
- return res.status(400).json({ error: 'Missing credentials' });
341
- }
342
- const tasks = await fetchIServTasks(url, username, password);
343
- res.setHeader('Content-Type', 'application/json');
344
- res.json(tasks);
345
- } catch (e) {
346
- res.status(500).json({ error: e.message || 'Scraping failed' });
347
- }
348
- });
349
-
350
- // PDF Generation Endpoint
351
- app.post('/api/pdf', async (req, res) => {
352
- try {
353
- const { markdown, title } = req.body;
354
- if (!markdown) {
355
- return res.status(400).json({ error: "Missing markdown content" });
356
- }
357
- const { generatePdf } = await import('./src/api/pdf.js');
358
- const pdfBuffer = await generatePdf(markdown, title);
359
- res.setHeader('Content-Type', 'application/pdf');
360
- res.setHeader('Content-Disposition', `attachment; filename="${encodeURIComponent(title || 'loesung')}.pdf"`);
361
- res.send(pdfBuffer);
362
- } catch (e) {
363
- console.error("PDF generation failed:", e);
364
- res.status(500).json({ error: e.message });
365
- }
366
- });
367
-
368
- // YouTube Search API
369
- app.get('/api/youtube-search', async (req, res) => {
370
- const query = req.query.q;
371
- if (!query) return res.status(400).send('Missing query');
372
- try {
373
- const { default: ytSearch } = await import('youtube-sr');
374
-
375
- // Force IPv4 for YouTube requests to bypass HF IPv6 blocks
376
- const dns = await import('dns');
377
- dns.setDefaultResultOrder('ipv4first');
378
-
379
- // Helper to fetch via DDG HTML
380
- const fetchFromDDG = async () => {
381
- const controller = new AbortController();
382
- const timeoutId = setTimeout(() => controller.abort(), 8000);
383
- try {
384
- const response = await fetch(`https://html.duckduckgo.com/html/?q=site:youtube.com+${encodeURIComponent(query)}`, {
385
- headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' },
386
- signal: controller.signal
387
- });
388
- clearTimeout(timeoutId);
389
- const html = await response.text();
390
- const matches = Array.from(html.matchAll(/v=([a-zA-Z0-9_-]{11})/g));
391
- if (matches.length > 0) return matches[0][1];
392
- } catch(err) {
393
- clearTimeout(timeoutId);
394
- console.error('DDG fallback error:', err.message);
395
- }
396
- return null;
397
- };
398
-
399
- // Race ytSearch against a 10s timeout
400
- let videoId = null;
401
- try {
402
- const ytPromise = ytSearch.YouTube.search(query, { limit: 1 }).then(v => v && v.length > 0 ? v[0].id : null);
403
- const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error('Timeout')), 10000));
404
- videoId = await Promise.race([ytPromise, timeoutPromise]);
405
- } catch (e) {
406
- console.warn('ytSearch failed or timed out:', e.message);
407
- }
408
-
409
- if (!videoId) {
410
- console.warn('Falling back to DDG...');
411
- videoId = await fetchFromDDG();
412
- }
413
-
414
- if (videoId) {
415
- if (req.query.json) {
416
- res.setHeader('Content-Type', 'application/json');
417
- res.json({ videoId });
418
- } else {
419
- res.redirect(`https://www.youtube.com/embed/${videoId}?autoplay=1&mute=1`);
420
- }
421
- } else {
422
- res.status(404).send('No videos found');
423
- }
424
- } catch (err) {
425
- res.status(500).send(err.message);
426
- }
427
- });
428
-
429
- // Deep Research Search Proxy (Google News RSS)
430
- app.get('/api/research/search', async (req, res) => {
431
- const query = req.query.q;
432
- if (!query) return res.status(400).json({ error: 'Missing query' });
433
- try {
434
- const cheerio = await import('cheerio');
435
- const url = `https://news.google.com/rss/search?q=${encodeURIComponent(query)}&hl=de&gl=DE&ceid=DE:de`;
436
- const response = await fetch(url);
437
- const xml = await response.text();
438
- const $ = cheerio.load(xml, { xmlMode: true });
439
-
440
- const results = [];
441
- $('item').each((i, el) => {
442
- if (i >= 5) return;
443
- const title = $(el).find('title').text();
444
- const link = $(el).find('link').text();
445
- const description = $(el).find('description').text();
446
- const snippet = cheerio.load(description).text().trim() || title;
447
-
448
- if (title && link) {
449
- results.push({ title, body: snippet, href: link });
450
- }
451
- });
452
- res.json({ results });
453
- } catch (e) {
454
- res.status(500).json({ error: e.message });
455
- }
456
- });
457
-
458
- // YouTube Transcript API
459
- app.get('/api/youtube-transcript', async (req, res) => {
460
- const videoId = req.query.v;
461
- if (!videoId) return res.status(400).json({ error: 'Missing video ID' });
462
- try {
463
- const { YoutubeTranscript } = await import('youtube-transcript');
464
- const transcript = await YoutubeTranscript.fetchTranscript(videoId);
465
- res.setHeader('Content-Type', 'application/json');
466
- res.json(transcript);
467
- } catch (err) {
468
- res.status(500).json({ error: err.message });
469
- }
470
- });
471
-
472
- // Fallback for SPA routing - only for navigation requests, NOT for assets
473
- app.use((req, res) => {
474
- // If the request looks like a static asset (has a file extension), return 404
475
- if (req.path.match(/\.\w+$/)) {
476
- return res.status(404).send('Not found');
477
- }
478
- res.sendFile(path.join(__dirname, 'dist', 'index.html'));
479
- });
480
-
481
- // Start Server
482
- const PORT = process.env.PORT || 7860; // Force Hugging Face Spaces port unless set
483
-
484
- // Preload Piper into RAM disk for faster generation
485
- try {
486
- if (fs.existsSync('/dev/shm')) {
487
- const shmModelPath = '/dev/shm/de_DE-thorsten-high.onnx';
488
- const shmConfigPath = '/dev/shm/de_DE-thorsten-high.onnx.json';
489
- if (!fs.existsSync(shmModelPath)) {
490
- console.log('Copying Piper model to RAM disk (/dev/shm)...');
491
- fs.copyFileSync(path.join(__dirname, 'piper_tts', 'de_DE-thorsten-high.onnx'), shmModelPath);
492
- }
493
- if (!fs.existsSync(shmConfigPath)) {
494
- fs.copyFileSync(path.join(__dirname, 'piper_tts', 'de_DE-thorsten-high.onnx.json'), shmConfigPath);
495
- }
496
- }
497
- } catch (e) {
498
- console.log('Failed to copy Piper model to RAM disk:', e.message);
499
- }
500
-
501
- app.listen(PORT, '0.0.0.0', () => {
502
- console.log(`🚀 SchoolMind AI Server is running on port ${PORT}`);
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
+ });