-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserver.js
More file actions
141 lines (118 loc) · 4.04 KB
/
server.js
File metadata and controls
141 lines (118 loc) · 4.04 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
const express = require("express");
const http = require("http");
const path = require("path");
const fs = require("fs");
const { Server } = require("socket.io");
const cors = require("cors");
const helmet = require("helmet");
const config = require("./config");
// Clean up old cache file (if exists)
const oldCachePath = path.join(config.DATA_DIR, "antigravity-models.json");
if (fs.existsSync(oldCachePath)) {
try {
fs.unlinkSync(oldCachePath);
} catch {}
}
const keyService = require("./services/keyService");
const geminiService = require("./services/geminiService");
const statsService = require("./services/statsService");
const usageCapService = require("./services/usageCapService");
const updateService = require("./services/updateService");
const apiRoutes = require("./routes/apiRoutes");
const logger = require("./utils/logger");
const app = express();
const server = http.createServer(app);
const io = new Server(server, { cors: { origin: "*" } });
logger.setIo(io);
io.on("connection", (socket) => {
socket.emit("stats_update", keyService.getSafeKeyPool());
socket.emit("stats_update_full", statsService.getStats());
logger.info("Dashboard connected to live socket stream");
});
const PORT = config.PORT;
app.use(helmet({ contentSecurityPolicy: false }));
app.use(cors());
app.use(express.json({ limit: "50mb" }));
app.use((req, res, next) => {
const start = Date.now();
const reqBody = req.body;
// Capture response body for verbose logging
const originalJson = res.json.bind(res);
let resBody = null;
res.json = function (body) {
resBody = body;
return originalJson(body);
};
res.on("finish", () => {
const duration = Date.now() - start;
logger.http(req, res, duration);
// Verbose logging with request/response bodies
if (config.VERBOSE_LOGGING) {
logger.httpVerbose(req, res, duration, reqBody, resBody);
}
});
next();
});
try {
// Run models.json migration if needed
const { migrateModelsJson } = require("./src/cli/migrateModelsJson");
migrateModelsJson();
statsService.initialize();
keyService.loadKeys();
geminiService.initializeModelFetching();
// Start background quota refresh for OAuth keys
const quotaRefreshService = require("./services/quotaRefreshService");
quotaRefreshService.startQuotaRefresh();
} catch (error) {
console.error("Failed to initialize services:", error);
process.exit(1);
}
updateService.backgroundCheck(logger, config.AUTO_UPDATE).catch(() => {});
// Ensure dashboard is built
const dashboardPath = path.join(__dirname, "public");
if (!fs.existsSync(dashboardPath)) {
console.log("Building dashboard (first run)...");
try {
require("child_process").execSync("npm run build", { stdio: "inherit" });
} catch {
console.error("Failed to build dashboard. Run 'npm run build' manually.");
}
}
// Serve built dashboard at /dashboard
if (fs.existsSync(dashboardPath)) {
// Explicitly serve static assets at the root level before any API routes
app.use(
express.static(dashboardPath, {
index: false,
extensions: ["html", "htm", "webp", "svg", "png", "jpg"],
}),
);
app.use("/dashboard", express.static(dashboardPath));
// SPA fallback — send index.html for any /dashboard/* route not matched as a file
app.get(/^\/dashboard(\/.*)?$/, (req, res) => {
res.sendFile(path.join(dashboardPath, "index.html"));
});
}
app.use("/", apiRoutes(io));
// Initialize usage cap service
usageCapService.initialize();
app.use((err, req, res, _next) => {
logger.error("Unhandled error", err);
res.status(500).json({ error: "Internal Server Error" });
});
const shutdown = () => {
console.log("");
logger.info("Shutting down gracefully...");
server.close(() => {
logger.info("Server closed");
process.exit(0);
});
};
process.on("SIGTERM", shutdown);
process.on("SIGINT", shutdown);
server.listen(PORT, () => {
console.log(`\n===========================================`);
console.log(`GemiNitro is running`);
console.log(`Local: http://localhost:${PORT}`);
console.log(`===========================================\n`);
});