diff --git a/api/server.js b/api/server.js new file mode 100644 index 0000000..0e855f1 --- /dev/null +++ b/api/server.js @@ -0,0 +1,44 @@ +const express = require("express"); +const cors = require("cors"); +const fs = require("fs"); +const https = require("https"); +const http = require("http"); +const path = require("path"); +const ping = require("ping"); +const status = require("./status/server") + +const app = express(); +const PORT = 2589; + +const key = "/etc/letsencrypt/live/blahaj.tr/privkey.pem" +const cert = "/etc/letsencrypt/live/blahaj.tr/fullchain.pem" + +app.use(cors()); +app.use("/status", status); + +// Try to load SSL Certificates +try { + const sslOptions = { + key: fs.readFileSync(key), + cert: fs.readFileSync(cert), + }; + + // Start HTTPS Server if certificates are available + https.createServer(sslOptions, app).listen(PORT, () => { + console.log(`API running securely at https://localhost:${PORT}`); + }); +} catch (e) { + // If certificate loading fails, start HTTP server instead + if (e.code === 'ENOENT') { + console.warn(`SSL certificate file(s) not found: ${e.path}`); + } else { + console.warn(`Error loading SSL certificates: ${e.message}`); + } + + console.log("Starting server without SSL..."); + + // Start HTTP Server as fallback + http.createServer(app).listen(PORT, () => { + console.log(`API running insecurely at http://localhost:${PORT}`); + }); +} diff --git a/api/status/server.js b/api/status/server.js index d8c6e2c..441bf41 100644 --- a/api/status/server.js +++ b/api/status/server.js @@ -1,14 +1,9 @@ const express = require("express"); const cors = require("cors"); -const fs = require("fs"); -const https = require("https"); -const path = require("path"); const ping = require("ping"); -const app = express(); -const PORT = 2589; -const key = "/etc/letsencrypt/live/blahaj.tr/privkey.pem" -const cert = "/etc/letsencrypt/live/blahaj.tr/fullchain.pem" +const router = express.Router(); + const REMOTE_SERVERS = [ { name: "blahaj.tr", host: "blahaj.tr" }, { name: "xargana.com", host: "xargana.com" }, @@ -26,8 +21,6 @@ REMOTE_SERVERS.forEach(server => { }; }); -app.use(cors()); - async function checkServers() { for (const server of REMOTE_SERVERS) { const startTime = Date.now(); @@ -46,21 +39,8 @@ async function checkServers() { setInterval(checkServers, CHECK_INTERVAL); checkServers(); -app.get("/status", (req, res) => { +router.get("/", (req, res) => { res.json(serversStatus); }); -// Load SSL Certificates -const sslOptions = { - key: fs.readFileSync(key), - cert: fs.readFileSync(cert), -}; - -// Start HTTPS Server -try { - https.createServer(sslOptions, app).listen(PORT, () => { - console.log(`API running at https://localhost:${PORT}`); - }); -} catch (e) { - console.error("Error starting server:", e); -} \ No newline at end of file +module.exports = router; \ No newline at end of file