-
-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathserver.js
More file actions
231 lines (200 loc) · 6.97 KB
/
server.js
File metadata and controls
231 lines (200 loc) · 6.97 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
import "./loadEnv.js";
import express from "express";
import cors from "cors";
import rateLimit from "express-rate-limit";
import helmet from "helmet";
import path from "path";
import fs from "fs";
import { createServer } from "http";
import { fileURLToPath } from "url";
import { createAuthMiddleware } from "./backend/middleware/auth.js";
import {
updateDiscoveryCache,
getDiscoveryCache,
getDiscoveryAutoRefreshHours,
} from "./backend/services/discoveryService.js";
import { websocketService } from "./backend/services/websocketService.js";
import { getAllDownloadStatuses } from "./backend/routes/library/handlers/downloads.js";
import { dbOps } from "./backend/config/db-helpers.js";
import settingsRouter from "./backend/routes/settings.js";
import onboardingRouter from "./backend/routes/onboarding.js";
import usersRouter from "./backend/routes/users.js";
import artistsRouter from "./backend/routes/artists.js";
import libraryRouter from "./backend/routes/library.js";
import discoveryRouter from "./backend/routes/discovery.js";
import requestsRouter from "./backend/routes/requests.js";
import healthRouter from "./backend/routes/health.js";
import weeklyFlowRouter from "./backend/routes/weeklyFlow.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
process.on("uncaughtException", (error) => {
console.error("Uncaught Exception:", error);
});
process.on("unhandledRejection", (reason, promise) => {
console.error("Unhandled Rejection:", reason);
});
const app = express();
const PORT = process.env.PORT || 3001;
const trustProxyValue =
process.env.TRUST_PROXY === undefined
? 1
: process.env.TRUST_PROXY === "true"
? true
: process.env.TRUST_PROXY === "false"
? false
: Number.isNaN(Number(process.env.TRUST_PROXY))
? process.env.TRUST_PROXY
: Number(process.env.TRUST_PROXY);
app.set("trust proxy", trustProxyValue);
app.use(cors());
app.use(
helmet({
contentSecurityPolicy: false,
frameguard: false,
}),
);
app.use(express.json());
app.use(createAuthMiddleware());
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 5000,
});
app.use("/api/", limiter);
app.use("/api/settings", settingsRouter);
app.use("/api/onboarding", onboardingRouter);
app.use("/api/users", usersRouter);
app.use("/api/search", artistsRouter);
app.use("/api/artists", artistsRouter);
app.use("/api/library", libraryRouter);
app.use("/api/discover", discoveryRouter);
app.use("/api/requests", requestsRouter);
app.use("/api/health", healthRouter);
app.use("/api/weekly-flow", weeklyFlowRouter);
const HOUR_MS = 60 * 60 * 1000;
setInterval(() => {
import("./backend/services/weeklyFlowScheduler.js")
.then((m) => m.runScheduledRefresh())
.catch((err) => console.error("Weekly flow scheduler error:", err.message));
}, HOUR_MS);
setTimeout(() => {
import("./backend/services/weeklyFlowScheduler.js")
.then((m) => m.startWorkerIfPending())
.catch((err) =>
console.error("Weekly flow startup check error:", err.message),
);
}, 5000);
const frontendDist = path.join(__dirname, "frontend", "dist");
if (fs.existsSync(frontendDist)) {
app.use(express.static(frontendDist));
app.get("*", (req, res) => {
if (req.path.startsWith("/api")) {
return res.status(404).json({ error: "Not found" });
}
res.sendFile(path.join(frontendDist, "index.html"));
});
} else {
app.get("*", (req, res) => {
if (req.path.startsWith("/api")) {
return res.status(404).json({ error: "Not found" });
}
res.status(503).send("Frontend not built. Run 'npm run build' first.");
});
}
setInterval(() => {
const discoveryCache = getDiscoveryCache();
const lastUpdated = discoveryCache?.lastUpdated;
const refreshHours = getDiscoveryAutoRefreshHours();
const refreshIntervalMs = refreshHours * 60 * 60 * 1000;
const parsedLastUpdated = lastUpdated ? new Date(lastUpdated).getTime() : 0;
const needsUpdate =
!Number.isFinite(parsedLastUpdated) ||
parsedLastUpdated <= 0 ||
Date.now() - parsedLastUpdated >= refreshIntervalMs;
if (!needsUpdate) return;
updateDiscoveryCache().catch((err) => {
console.error("Error in scheduled discovery update:", err.message);
});
}, 15 * 60 * 1000);
setTimeout(async () => {
const { getLastfmApiKey } = await import("./backend/services/apiClients.js");
const { libraryManager } =
await import("./backend/services/libraryManager.js");
const hasLastfm = !!getLastfmApiKey();
const libraryArtists = await libraryManager.getAllArtists();
const hasArtists = libraryArtists.length > 0;
if (!hasLastfm && !hasArtists) {
console.log(
"Discovery not configured (no Last.fm key and no artists). Clearing cache.",
);
try {
dbOps.updateDiscoveryCache({
recommendations: [],
globalTop: [],
basedOn: [],
topTags: [],
topGenres: [],
lastUpdated: null,
});
} catch (error) {
console.error("Failed to clear discovery cache:", error.message);
}
return;
}
const discoveryCache = dbOps.getDiscoveryCache();
const lastUpdated = discoveryCache?.lastUpdated;
const hasRecommendations =
discoveryCache.recommendations && discoveryCache.recommendations.length > 0;
const hasGenres =
discoveryCache.topGenres && discoveryCache.topGenres.length > 0;
const refreshHours = getDiscoveryAutoRefreshHours();
const staleCutoff = Date.now() - refreshHours * 60 * 60 * 1000;
const needsUpdate =
!lastUpdated ||
new Date(lastUpdated).getTime() < staleCutoff ||
!hasRecommendations ||
!hasGenres;
if (needsUpdate) {
console.log("Discovery cache needs update. Starting...");
updateDiscoveryCache().catch((err) => {
console.error("Error in initial discovery update:", err.message);
});
} else {
console.log(
`Discovery cache is fresh (last updated ${lastUpdated}). Skipping initial update.`,
);
}
}, 15000);
const httpServer = createServer(app);
websocketService.initialize(httpServer);
const DOWNLOAD_STATUS_INTERVAL_MS = 10000;
let lastDownloadStatusesPayload = null;
const broadcastDownloadStatuses = async () => {
try {
const statuses = await getAllDownloadStatuses();
const payload = JSON.stringify(statuses);
if (payload !== lastDownloadStatusesPayload) {
lastDownloadStatusesPayload = payload;
websocketService.broadcast("downloads", {
type: "download_statuses",
statuses,
});
}
} catch (error) {
console.warn("Failed to broadcast download statuses:", error.message);
}
};
broadcastDownloadStatuses();
setInterval(broadcastDownloadStatuses, DOWNLOAD_STATUS_INTERVAL_MS);
httpServer.listen(PORT, "0.0.0.0", async () => {
console.log(`Server running on port ${PORT}`);
});
httpServer.on("error", (error) => {
if (error.code === "EADDRINUSE") {
console.error(
`Port ${PORT} is already in use. Please stop the other process or use a different port.`,
);
process.exit(1);
} else {
console.error("Server error:", error);
}
});