-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
423 lines (382 loc) · 14.4 KB
/
server.js
File metadata and controls
423 lines (382 loc) · 14.4 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
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
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
415
416
417
418
419
420
421
422
423
import dotenv from 'dotenv';
import express from 'express';
import multer from 'multer';
import fetch from 'node-fetch';
import cors from 'cors';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { initDB, getDB } from './src/utils/db.js';
import { addSpotifyLink, getSpotifyLinks } from './src/utils/db.js';
import sharp from 'sharp';
import { upsertUser, getUser, saveWidgetPositions, getWidgetPositions, deleteWidgetPosition, setUserName } from './src/utils/db.js';
dotenv.config({ path: resolve(dirname(fileURLToPath(import.meta.url)), '.env') });
const AI = false;
await initDB();
await import('./src/utils/rfid.js');
const app = express();
const upload = multer({ limits: { fileSize: 10 * 1024 * 1024 } });
app.use(cors({
origin: [
'http://localhost:5173',
'http://localhost:4173',
'http://127.0.0.1:5173',
'http://127.0.0.1:4173',
],
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type']
}));
app.use(express.json());
app.use(express.static('public'));
const FALLBACK_COMPLIMENTS = [
'You have a great presence.',
'You look fantastic today.',
'Your smile is genuinely uplifting.',
'You have a really positive vibe.',
'You look confident and stylish.',
'You look insanely good today.',
'Not gonna lie, you’re kinda distracting.',
'You’ve got that main character energy.',
'You look like trouble… the good kind.',
'I like your vibe a lot.',
'You’re effortlessly attractive.',
'You’ve got a really charming smile.',
'You look like someone I’d get along with way too well.',
'There’s something about you.',
'You look dangerously good.',
'You’ve got style, I like that.',
'You’re kinda hard to ignore.',
'You look confident as hell.',
'You’ve got a really nice aura.',
'You’re lowkey stunning.',
'I could look at you for a while.',
'You’ve got that spark.',
'You look like you know exactly what you’re doing.',
'You’re giving off good energy.',
'You look like a whole vibe.',
'You’re definitely someone people notice.',
'You’ve got a really attractive presence.',
'You look like you’d break hearts without trying.',
'I like the way you carry yourself.',
'You’re kinda mesmerizing.',
'You’ve got that “wow” factor.',
'You look like you’d be fun to be around.',
'You’re effortlessly cool.',
'You’ve got a really nice face, not gonna lie.',
'You look like you’d make someone’s day just by showing up.',
'You’ve got that confident glow.',
'You’re pretty hard to forget.',
'You look like you know your worth.',
'You’ve got a smooth vibe.',
'You’re kinda addictive to look at.'
];
function getFallbackCompliment() {
return FALLBACK_COMPLIMENTS[Math.floor(Math.random() * FALLBACK_COMPLIMENTS.length)];
}
app.get('/api/rfid/last', (req, res) => {
res.json({
uid: global.lastRFIDUid || null,
uuid: global.lastRFIDUuid || null,
user: global.lastRFIDUser || null,
time: global.lastRFIDTime || null,
});
});
app.post('/api/rfid/clear', (req, res) => {
global.lastRFIDUid = null;
global.lastRFIDUuid = null;
global.lastRFIDUser = null;
global.lastRFIDTime = null;
res.json({ success: true });
});
function getFinnhubToken() {
return (
process.env.FINNHUB_API_KEY ||
process.env.VITE_FINNHUB_API_KEY ||
process.env.FINNHUB_TOKEN ||
process.env.VITE_STOCKS_API_KEY ||
''
);
}
function getSymbolsFromEnv() {
return (process.env.FINNHUB_SYMBOLS || 'AAPL,MSFT,NVDA,TSLA,AMZN,GOOGL,BINANCE:BTCUSDT,BINANCE:ETHUSDT')
.split(',')
.map((s) => s.trim())
.filter(Boolean);
}
function extractSpotifyTrackId(url = '') {
if (!url) return null;
const patterns = [
/(?:open\.spotify\.com\/)(?:embed\/)?track\/([a-zA-Z0-9]+)/,
/spotify:track:([a-zA-Z0-9]+)/,
];
for (const pattern of patterns) {
const match = String(url).match(pattern);
if (match?.[1]) return match[1];
}
return null;
}
function buildSpotifyMetadataFallback(url) {
return { url, title: 'Unbekannt', artist: '', cover: null };
}
async function fetchSpotifyTrackMetadata(url) {
const trackId = extractSpotifyTrackId(url);
const canonicalUrl = trackId ? `https://open.spotify.com/track/${trackId}` : url;
const oembedUrls = [
`https://open.spotify.com/oembed?url=${encodeURIComponent(canonicalUrl)}`,
`https://embed.spotify.com/oembed/?url=${encodeURIComponent(canonicalUrl)}`,
];
for (const oembedUrl of oembedUrls) {
try {
const oembedRes = await fetch(oembedUrl, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36',
'Accept-Language': 'en-US,en;q=0.9'
}
});
if (oembedRes.ok) {
const data = await oembedRes.json();
return {
url,
title: data?.title || 'Unbekannt',
artist: data?.author_name || '',
cover: data?.thumbnail_url || null
};
}
} catch (error) {
console.error('Spotify oEmbed Fehler:', error.message);
}
}
if (!trackId) return buildSpotifyMetadataFallback(url);
try {
const pageRes = await fetch(`https://open.spotify.com/track/${trackId}`, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36',
'Accept-Language': 'en-US,en;q=0.9'
}
});
if (!pageRes.ok) throw new Error(`Spotify page status ${pageRes.status}`);
const html = await pageRes.text();
const title = html.match(/<meta property="og:title" content="([^"]+)"/)?.[1] ?? 'Unbekannt';
const cover = html.match(/<meta property="og:image" content="([^"]+)"/)?.[1] ?? null;
const description = html.match(/<meta property="og:description" content="([^"]+)"/)?.[1] ?? '';
const descriptionParts = description.split(' · ');
const artist = descriptionParts[1] ?? description.split(' - ')[1] ?? '';
return { url, title, artist, cover };
} catch (error) {
console.error('Spotify Fallback Fehler:', error.message);
return buildSpotifyMetadataFallback(url);
}
}
app.get('/api/users', async (req, res) => {
try {
const db = getDB();
const users = await db.all('SELECT * FROM users ORDER BY created_at DESC');
res.json(users);
} catch (err) {
console.error('Users get Fehler:', err);
res.status(500).json({ error: 'Kann Users nicht laden' });
}
});
app.post('/api/users', async (req, res) => {
const { uuid } = req.body;
if (!uuid) return res.status(400).json({ error: 'UUID fehlt' });
try {
const user = await upsertUser(uuid);
res.json(user);
} catch (err) {
console.error('User upsert Fehler:', err);
res.status(500).json({ error: 'Kann User nicht speichern' });
}
});
app.get('/api/users/:uuid', async (req, res) => {
try {
const user = await getUser(req.params.uuid);
if (!user) return res.status(404).json({ error: 'User nicht gefunden' });
res.json(user);
} catch (err) {
console.error('User get Fehler:', err);
res.status(500).json({ error: 'Kann User nicht laden' });
}
});
app.put('/api/users/:uuid/name', async (req, res) => {
const rawName = req.body?.name;
const name = typeof rawName === 'string' ? rawName.trim() : '';
if (!name) return res.status(400).json({ error: 'Name fehlt' });
try {
const user = await setUserName(req.params.uuid, name);
if (!user) return res.status(404).json({ error: 'User nicht gefunden' });
res.json(user);
} catch (err) {
console.error('User name set Fehler:', err);
res.status(500).json({ error: 'Kann Usernamen nicht speichern' });
}
});
app.get('/api/widget-positions/:uuid', async (req, res) => {
try {
const positions = await getWidgetPositions(req.params.uuid);
res.json(positions);
} catch (err) {
console.error('Widget positions get Fehler:', err);
res.status(500).json({ error: 'Kann Positionen nicht laden' });
}
});
app.post('/api/widget-positions/:uuid', async (req, res) => {
const { widgets } = req.body;
if (!Array.isArray(widgets)) return res.status(400).json({ error: 'widgets Array fehlt' });
try {
await saveWidgetPositions(req.params.uuid, widgets);
res.json({ success: true });
} catch (err) {
console.error('Widget positions save Fehler:', err);
res.status(500).json({ error: 'Kann Positionen nicht speichern' });
}
});
app.delete('/api/widget-positions/:uuid/:instanceId', async (req, res) => {
try {
await deleteWidgetPosition(req.params.uuid, req.params.instanceId);
res.json({ success: true });
} catch (err) {
console.error('Widget position delete Fehler:', err);
res.status(500).json({ error: 'Kann Position nicht löschen' });
}
});
app.get('/api/test', (req, res) => {
res.send('Server is running!');
});
app.post('/api/compliment', upload.single('image'), async (req, res) => {
console.log('Received compliment request');
if (!AI) {
console.log('AI is disabled – returning fallback compliment');
return res.send(getFallbackCompliment());
}
if (!req.file) {
console.error('No image file in request');
return res.status(400).send('No image uploaded');
}
console.log(`Image received: ${req.file.originalname}, size: ${req.file.size} bytes, mimetype: ${req.file.mimetype}`);
try {
const resized = await sharp(req.file.buffer).resize(128).jpeg({ quality: 30 }).toBuffer();
const base64 = resized.toString('base64');
console.log('Converted to base64, length:', base64.length);
try {
console.log('Sending request to Ollama...');
const ollamaRes = await fetch('http://localhost:11434/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'qwen3-vl:2b-instruct',
stream: false,
messages: [
{
role: 'system',
content: 'You give very short compliments (max 1 sentence 15 words). Be natural.'
},
{
role: 'user',
content: 'Give a short compliment about this person. based on what they are wearing tell them the colors be direct and honest tell them if they are ugly. Talk like a human not too much like a robot. Very short sentences. Be direct and honest. Do not be afraid to tell them if they are ugly. Be flirty. Talk like a human, not too much like a robot. Dont make weird references like coffeshops, dreamy or anything. Be very Flirty.',
images: [base64]
}
],
options: { temperature: 0.6, num_predict: 30 }
})
});
if (ollamaRes.ok) {
const data = await ollamaRes.json();
const compliment = data?.message?.content || 'You look great :)';
console.log('Ollama Antwort:', compliment);
return res.send(compliment);
} else {
console.warn('Ollama nicht erreichbar – Fallback wird verwendet.');
}
} catch {
console.warn('Ollama nicht erreichbar – Fallback wird verwendet.');
}
res.send(getFallbackCompliment());
} catch (err) {
console.error('Server error:', err);
res.send(getFallbackCompliment());
}
});
app.get('/weather', async (req, res) => {
const location = req.query.q || 'Brixen';
try {
const response = await fetch(
`https://api.weatherapi.com/v1/forecast.json?key=${process.env.VITE_WEATHER_API_KEY}&q=${location}&days=7&lang=de`
);
if (!response.ok) throw new Error(`WeatherAPI ${response.status}`);
const data = await response.json();
res.json(data);
} catch (error) {
console.error('WeatherAPI Fehler:', error.message);
res.status(500).json({ error: error.message });
}
});
app.get('/stocks/config', (req, res) => {
const token = getFinnhubToken();
const symbols = getSymbolsFromEnv();
if (!token) {
res.status(500).json({ error: 'FINNHUB_API_KEY fehlt in .env' });
return;
}
res.json({ wsUrl: `wss://ws.finnhub.io?token=${token}`, symbols });
});
app.get('/stocks/quotes', async (req, res) => {
const token = getFinnhubToken();
const symbols = getSymbolsFromEnv();
if (!token) {
res.status(500).json({ error: 'FINNHUB_API_KEY fehlt in .env' });
return;
}
try {
const results = await Promise.all(
symbols.map(async (symbol) => {
const url = `https://finnhub.io/api/v1/quote?symbol=${encodeURIComponent(symbol)}&token=${token}`;
const r = await fetch(url);
const data = await r.json();
if (!r.ok || data?.error) return { symbol, price: null, change_percent: null };
const current = typeof data.c === 'number' && data.c > 0 ? data.c : null;
const prevClose = typeof data.pc === 'number' && data.pc > 0 ? data.pc : null;
const changePercent = current != null && prevClose != null
? ((current - prevClose) / prevClose) * 100
: null;
return { symbol, price: current, change_percent: changePercent };
})
);
res.json(results);
} catch (error) {
console.error('Finnhub Quote Fehler:', error.message);
res.status(500).json({ error: 'Quotes konnten nicht geladen werden' });
}
});
app.get('/api/spotify-links', async (req, res) => {
try {
const links = await getSpotifyLinks();
const enriched = await Promise.all(links.map((link) => fetchSpotifyTrackMetadata(link.url)));
res.json(enriched);
} catch (err) {
console.error('DB Fehler:', err);
res.status(500).json({ error: 'Kann Spotify Links nicht laden' });
}
});
app.post('/api/spotify-links', async (req, res) => {
const { url } = req.body;
if (!url) return res.status(400).json({ error: 'Keine URL angegeben' });
try {
await addSpotifyLink(url);
res.json({ success: true });
} catch (err) {
console.error('DB Fehler:', err);
res.status(500).json({ error: 'Kann Spotify Link nicht speichern' });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server läuft auf http://localhost:${PORT}`);
console.log(`Test endpoint: http://localhost:${PORT}/api/test`);
console.log(`Compliment API: http://localhost:${PORT}/api/compliment`);
console.log(`Weather API: http://localhost:${PORT}/weather`);
console.log(`Stocks API: http://localhost:${PORT}/stocks/config`);
console.log(`Spotify Links API: http://localhost:${PORT}/api/spotify-links`);
console.log(`Users API: http://localhost:${PORT}/api/users`);
console.log(`Widget Positions API: http://localhost:${PORT}/api/widget-positions/:uuid`);
console.log(`RFID API: http://localhost:${PORT}/api/rfid/last. Up And RUNNINGGGG!!!`);
});