-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
366 lines (325 loc) · 11.7 KB
/
Copy pathserver.ts
File metadata and controls
366 lines (325 loc) · 11.7 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
import express from "express";
import { createServer as createViteServer } from "vite";
import path from "path";
import fs from "fs";
import Database from "better-sqlite3";
import cors from "cors";
import dotenv from "dotenv";
dotenv.config();
const dbPath = process.env.DATABASE_PATH || "/app/data/sweep.db";
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
const db = new Database(dbPath);
// Initialize Database
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
email TEXT,
last_login TEXT,
last_history_id TEXT,
allowed_folders TEXT
);
CREATE TABLE IF NOT EXISTS emails (
id TEXT PRIMARY KEY,
uid TEXT,
subject TEXT,
sender TEXT,
snippet TEXT,
timestamp TEXT,
labels TEXT,
is_rubbish INTEGER DEFAULT 0,
reason TEXT,
suggested_folder TEXT,
analyzed INTEGER DEFAULT 0,
analyze_count INTEGER DEFAULT 0,
created_at TEXT
);
`);
// Handle schema migrations if old tables exist
try { db.exec("ALTER TABLE emails ADD COLUMN analyze_count INTEGER DEFAULT 0;"); } catch (e) {}
try { db.exec("ALTER TABLE users ADD COLUMN last_history_id TEXT;"); } catch (e) {}
try { db.exec("ALTER TABLE users ADD COLUMN allowed_folders TEXT;"); } catch (e) {}
try { db.exec("ALTER TABLE emails ADD COLUMN labels TEXT;"); } catch (e) {}
async function startServer() {
const app = express();
const PORT = Number(process.env.PORT || 3000);
app.use(cors());
app.use(express.json({ limit: '50mb' }));
// Set COOP/COEP headers for Firebase Auth popups
app.use((req, res, next) => {
res.setHeader("Cross-Origin-Opener-Policy", "same-origin-allow-popups");
res.setHeader("Cross-Origin-Embedder-Policy", "unsafe-none");
next();
});
// API Routes
app.post("/api/users", (req, res) => {
const { id, email, lastLogin } = req.body;
// Use INSERT OR IGNORE to not overwrite last_history_id on login
const stmt = db.prepare("INSERT OR IGNORE INTO users (id, email, last_login) VALUES (?, ?, ?)");
stmt.run(id, email, lastLogin);
// Update last login
const updateStmt = db.prepare("UPDATE users SET last_login = ? WHERE id = ?");
updateStmt.run(lastLogin, id);
res.json({ success: true });
});
app.get("/api/users/:id", (req, res) => {
const stmt = db.prepare("SELECT * FROM users WHERE id = ?");
const user = stmt.get(req.params.id);
res.json(user || {});
});
app.patch("/api/users/:id", (req, res) => {
const { lastHistoryId, allowedFolders } = req.body;
if (lastHistoryId !== undefined) {
db.prepare("UPDATE users SET last_history_id = ? WHERE id = ?").run(lastHistoryId, req.params.id);
}
if (allowedFolders !== undefined) {
db.prepare("UPDATE users SET allowed_folders = ? WHERE id = ?").run(allowedFolders, req.params.id);
}
res.json({ success: true });
});
app.get("/api/prompts/:size/:variant", (req, res) => {
const { size, variant } = req.params;
const filePath = path.join(process.cwd(), "prompts", `batch_${size}_${variant}.md`);
try {
if (fs.existsSync(filePath)) {
const content = fs.readFileSync(filePath, "utf-8");
res.json({ content });
} else {
const fallbackPath = path.join(process.cwd(), "prompt.md");
const content = fs.readFileSync(fallbackPath, "utf-8");
res.json({ content });
}
} catch (err) {
res.status(500).json({ error: "Failed to read prompt" });
}
});
app.get("/api/emails/:uid", (req, res) => {
const {
limit = 100,
offset = 0,
search,
sender,
after,
before,
status, // 'analyzed' | 'unanalyzed' | 'all'
rubbish, // 'true' | 'false' | 'all'
folder,
suggestedFolder
} = req.query;
let query = `SELECT id, uid, subject, sender as "from", snippet, timestamp,
is_rubbish as isRubbish, reason, suggested_folder as suggestedFolder,
analyzed, analyze_count as analyzeCount, created_at as createdAt
FROM emails WHERE uid = ?`;
const params: any[] = [req.params.uid];
if (search) {
query += ` AND (subject LIKE ? OR snippet LIKE ?)`;
params.push(`%${search}%`, `%${search}%`);
}
if (sender) {
query += ` AND sender LIKE ?`;
params.push(`%${sender}%`);
}
if (after) {
query += ` AND timestamp >= ?`;
params.push(after);
}
if (before) {
query += ` AND timestamp <= ?`;
params.push(before);
}
if (status === 'analyzed') {
query += ` AND analyzed = 1`;
} else if (status === 'unanalyzed') {
query += ` AND analyzed = 0`;
}
if (rubbish === 'true') {
query += ` AND is_rubbish = 1`;
} else if (rubbish === 'false') {
query += ` AND is_rubbish = 0`;
}
if (folder) {
query += ` AND labels LIKE ?`;
params.push(`%${folder}%`);
}
if (suggestedFolder) {
query += ` AND suggested_folder = ?`;
params.push(suggestedFolder);
}
query += ` ORDER BY timestamp DESC LIMIT ? OFFSET ?`;
params.push(Number(limit), Number(offset));
const stmt = db.prepare(query);
const emails = stmt.all(...params);
res.json(emails.map((e: any) => ({ ...e, isRubbish: Boolean(e.isRubbish) })));
});
app.post("/api/emails/batch", (req, res) => {
const { emails } = req.body;
console.log(`[DEBUG] Received batch of ${emails?.length || 0} emails for insertion`);
const insert = db.prepare(`
INSERT OR REPLACE INTO emails
(id, uid, subject, sender, snippet, timestamp, labels, is_rubbish, reason, suggested_folder, analyzed, analyze_count, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
const transaction = db.transaction((emails) => {
for (const email of emails) {
insert.run(
email.id,
email.uid,
email.subject,
email.from,
email.snippet,
email.timestamp,
email.labels || "",
email.isRubbish ? 1 : 0,
email.reason || "",
email.suggestedFolder || "",
email.analyzed ? 1 : 0,
email.analyzeCount || 0,
email.createdAt || new Date().toISOString()
);
}
});
try {
transaction(emails);
res.json({ success: true });
} catch (error) {
console.error(`[DEBUG] Error processing email batch:`, error);
res.status(500).json({ error: "Failed to process batch" });
}
});
app.post("/api/emails/lookup", (req, res) => {
const { ids } = req.body;
if (!Array.isArray(ids) || ids.length === 0) return res.json([]);
const placeholders = ids.map(() => "?").join(",");
const stmt = db.prepare(`
SELECT id, is_rubbish as isRubbish, reason, suggested_folder as suggestedFolder,
analyzed, analyze_count as analyzeCount
FROM emails
WHERE id IN (${placeholders})
`);
const results = stmt.all(...ids);
res.json(results.map((e: any) => ({ ...e, isRubbish: Boolean(e.isRubbish) })));
});
app.patch("/api/emails/:id", (req, res) => {
const { isRubbish, reason, suggestedFolder, analyzed, analyzeCount } = req.body;
const stmt = db.prepare(`
UPDATE emails
SET is_rubbish = ?, reason = ?, suggested_folder = ?, analyzed = ?, analyze_count = ?
WHERE id = ?
`);
try {
stmt.run(isRubbish ? 1 : 0, reason, suggestedFolder, analyzed ? 1 : 0, analyzeCount, req.params.id);
res.json({ success: true });
} catch (error) {
console.error(`[DEBUG] Error updating email ${req.params.id}:`, error);
res.status(500).json({ error: "Failed to update email" });
}
});
app.delete("/api/emails/:id", (req, res) => {
const stmt = db.prepare("DELETE FROM emails WHERE id = ?");
try {
stmt.run(req.params.id);
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: "Failed to delete email" });
}
});
app.get("/api/emails/pending/:uid", (req, res) => {
const { limit = 1, offset = 0, folder } = req.query;
let query = `SELECT id, uid, subject, sender as "from", snippet, timestamp, labels,
is_rubbish as isRubbish, reason, suggested_folder as suggestedFolder,
analyzed, analyze_count as analyzeCount, created_at as createdAt
FROM emails
WHERE uid = ? AND analyzed = 0`;
const params: any[] = [req.params.uid];
if (folder) {
query += ` AND labels LIKE ?`;
params.push(`%${folder}%`);
}
query += ` ORDER BY timestamp DESC LIMIT ? OFFSET ?`;
params.push(Number(limit), Number(offset));
const emails = db.prepare(query).all(...params);
res.json(emails);
});
app.get("/api/stats/:uid", (req, res) => {
const stmt = db.prepare(`
SELECT
COUNT(*) as total,
SUM(CASE WHEN analyzed = 1 THEN 1 ELSE 0 END) as analyzed,
SUM(CASE WHEN is_rubbish = 1 THEN 1 ELSE 0 END) as rubbish
FROM emails
WHERE uid = ?
`);
const stats = stmt.get(req.params.uid);
res.json({
total: Number(stats?.total || 0),
analyzed: Number(stats?.analyzed || 0),
rubbish: Number(stats?.rubbish || 0)
});
});
app.get("/api/health", (_req, res) => {
res.json({ ok: true });
});
app.get("/api/prompt", (req, res) => {
try {
const content = fs.readFileSync(path.join(process.cwd(), "prompt.md"), "utf-8");
res.json({ content });
} catch (err) {
res.status(500).json({ error: "Failed to read prompt.md" });
}
});
app.post("/api/generate", async (req, res) => {
const { endpoint, method, headers, body } = req.body;
console.log(`[DEBUG] Proxying LLM request to: ${endpoint}`);
try {
const response = await fetch(endpoint, {
method: method || "POST",
headers: headers || { "Content-Type": "application/json" },
body: JSON.stringify(body)
});
if (!response.ok) {
const errorText = await response.text();
console.error(`[DEBUG] LLM Proxy Error (${response.status}):`, errorText);
return res.status(response.status).json({ error: errorText });
}
const data = await response.json();
res.json(data);
} catch (error: any) {
console.error("[DEBUG] Proxy execution error:", error);
res.status(500).json({ error: error.message });
}
});
app.get("/api/config", (req, res) => {
res.json({
localLlm: {
endpoint: process.env.LOCAL_LLM_ENDPOINT || "",
model: process.env.LOCAL_LLM_MODEL || ""
},
firebase: {
apiKey: process.env.VITE_FIREBASE_API_KEY || process.env.FIREBASE_API_KEY,
authDomain: process.env.VITE_FIREBASE_AUTH_DOMAIN || process.env.FIREBASE_AUTH_DOMAIN,
projectId: process.env.VITE_FIREBASE_PROJECT_ID || process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.VITE_FIREBASE_STORAGE_BUCKET || process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.VITE_FIREBASE_MESSAGING_SENDER_ID || process.env.FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.VITE_FIREBASE_APP_ID || process.env.FIREBASE_APP_ID,
firestoreDatabaseId: process.env.VITE_FIREBASE_FIRESTORE_DATABASE_ID || process.env.FIREBASE_FIRESTORE_DATABASE_ID || "(default)"
}
});
});
// Vite middleware for development
if (process.env.NODE_ENV !== "production") {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: "spa",
});
app.use(vite.middlewares);
} else {
const distPath = path.join(process.cwd(), "dist");
app.use(express.static(distPath));
app.get("*", (req, res) => {
res.sendFile(path.join(distPath, "index.html"));
});
}
app.listen(PORT, "0.0.0.0", () => {
console.log(`Server running on http://localhost:${PORT}`);
});
}
startServer();