-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserver.ts
More file actions
145 lines (128 loc) · 4.19 KB
/
server.ts
File metadata and controls
145 lines (128 loc) · 4.19 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
import express from "express";
import { createServer as createViteServer } from "vite";
import path from "path";
import { fileURLToPath } from "url";
import Database from "better-sqlite3";
import yahooFinance from 'yahoo-finance2';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const db = new Database("neuro_os.db");
// Initialize Database
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
username TEXT UNIQUE,
password_hash TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS apps (
id TEXT PRIMARY KEY,
name TEXT,
icon TEXT,
config TEXT,
user_id TEXT,
FOREIGN KEY(user_id) REFERENCES users(id)
);
CREATE TABLE IF NOT EXISTS agents (
id TEXT PRIMARY KEY,
name TEXT,
system_prompt TEXT,
model TEXT,
user_id TEXT,
FOREIGN KEY(user_id) REFERENCES users(id)
);
CREATE TABLE IF NOT EXISTS files (
id TEXT PRIMARY KEY,
name TEXT,
content TEXT,
type TEXT,
parent_id TEXT,
user_id TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(user_id) REFERENCES users(id)
);
`);
async function startServer() {
const app = express();
const PORT = 3000;
app.use(express.json());
// API Routes
app.get("/api/health", (req, res) => {
res.json({ status: "ok", system: "NeuroOS" });
});
// Stock API
app.get("/api/stocks/:symbol", async (req, res) => {
const symbol = req.params.symbol;
try {
console.log(`Fetching stock data for: ${symbol}`);
const quote = await yahooFinance.quote(symbol);
console.log(`Successfully fetched stock data for: ${symbol}`);
res.json(quote);
} catch (error) {
console.error(`Stock API Quote Error for ${symbol}:`, error);
try {
console.log(`Attempting fallback search for: ${symbol}`);
const searchResult = await yahooFinance.search(symbol) as any;
if (searchResult.quotes && searchResult.quotes.length > 0) {
const firstQuote = searchResult.quotes[0];
res.json({
symbol: firstQuote.symbol,
regularMarketPrice: firstQuote.regularMarketPrice || 0,
regularMarketChangePercent: firstQuote.regularMarketChangePercent || 0,
shortName: firstQuote.shortName || symbol
});
return;
}
} catch (searchError) {
console.error(`Stock API Search Fallback Error for ${symbol}:`, searchError);
}
res.status(500).json({ error: "Failed to fetch stock data", details: error instanceof Error ? error.message : String(error) });
}
});
// News API (Yahoo Finance News)
app.get("/api/news", async (req, res) => {
try {
console.log("Fetching news data...");
const result = await yahooFinance.search('finance') as any;
console.log("Successfully fetched news data");
res.json(result.news || []);
} catch (error) {
console.error('News API error:', error);
res.json([]);
}
});
// Simple Auth Mock
app.post("/api/auth/login", (req, res) => {
const { username } = req.body;
res.json({ id: "user_1", username: username || "guest", token: "mock_token" });
});
// File System API
app.get("/api/files", (req, res) => {
const files = db.prepare("SELECT * FROM files").all();
res.json(files);
});
app.post("/api/files", (req, res) => {
const { name, content, type, parent_id } = req.body;
const id = Math.random().toString(36).substr(2, 9);
db.prepare("INSERT INTO files (id, name, content, type, parent_id) VALUES (?, ?, ?, ?, ?)")
.run(id, name, content, type, parent_id || null);
res.json({ id, name });
});
// Vite middleware for development
if (process.env.NODE_ENV !== "production") {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: "spa",
});
app.use(vite.middlewares);
} else {
app.use(express.static(path.join(__dirname, "dist")));
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "dist", "index.html"));
});
}
app.listen(PORT, "0.0.0.0", () => {
console.log(`NeuroOS Server running on http://localhost:${PORT}`);
});
}
startServer();