-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
246 lines (223 loc) · 6.92 KB
/
Copy pathapp.js
File metadata and controls
246 lines (223 loc) · 6.92 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
require("dotenv").config();
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const path = require("path");
const admin = require("firebase-admin");
if (!admin.apps.length && process.env.FIREBASE_SERVICE_ACCOUNT) {
try {
const serviceAccount = JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT);
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
console.log("Firebase Admin initialized successfully.");
} catch (error) {
console.error(
"Firebase Admin init error. Check your JSON format in Vercel:",
error,
);
}
}
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname, "public")));
// Process error handlers
process.on("unhandledRejection", (reason, promise) => {
console.log("Unhandled Rejection at:", promise, "reason:", reason);
});
process.on("uncaughtException", (error) => {
console.log("Uncaught Exception:", error);
});
// MongoDB connection
mongoose
.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 45000,
connectTimeoutMS: 10000,
})
.then(() => {
console.log("Successfully connected to MongoDB.");
})
.catch((err) => {
console.error("MongoDB connection error:", err);
});
// Schema with category field
const bdociSchema = new mongoose.Schema({
title: String,
document: String,
code: String,
category: {
type: String,
default: "Uncategorized",
},
});
const Doc = mongoose.model("Doc", bdociSchema);
// Middleware to get categories dynamically
app.use(async (req, res, next) => {
console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
try {
// Get all unique categories from database
const categories = await Doc.distinct("category");
res.locals.categories = categories.sort(); // Make categories available in all templates
} catch (error) {
console.error("Error fetching categories:", error);
res.locals.categories = ["Uncategorized"];
}
next();
});
// Routes
const linkify = (text) => {
if (!text) return "";
// Regex to find URLs not already inside href/src attributes
return text.replace(
/(?<!href="|src=")(https?:\/\/[^\s<]+(?<![.,?!]))/g,
(url) => {
let displayText = url;
try {
// Decode URI components (e.g., %20 to space) for better readability
displayText = decodeURIComponent(url);
// Truncate if extremely long
if (displayText.length > 80) {
displayText = displayText.substring(0, 77) + "...";
}
} catch (e) {
// Fallback to original URL if decoding fails
}
return `<a href="${url}" class="doc-link" target="_blank" rel="noopener noreferrer"><i class="bi bi-link-45deg"></i>${displayText}</a>`;
},
);
};
app.get("/", async (req, res) => {
try {
const { category } = req.query;
let filter = {};
// Filter by category if provided
if (category && category !== "all") {
filter.category = category;
}
const documents = await Doc.find(filter).sort({ title: 1 });
res.render("home", {
documents,
selectedCategory: category || "all",
});
} catch (error) {
console.error("Error fetching documents:", error);
res.status(500).send("Error loading documentation list");
}
});
// Endpoint to return all raw document data
app.get("/api/data", async (req, res) => {
try {
const allData = await Doc.find({});
res.json(allData);
} catch (error) {
console.error("Error fetching all data:", error);
res.status(500).json({ error: "Error fetching data" });
}
});
app.get("/admin", (req, res) => {
res.render("admin/admin");
});
app.post("/admin", async (req, res) => {
try {
if (
req.body.adminName === process.env.ADMIN_USERNAME &&
req.body.password === process.env.ADMIN_PASSWORD
) {
res.render("admin/compose");
} else {
return res.status(401).send("Invalid credentials");
}
} catch (error) {
console.error("Login error:", error);
res.status(500).send("An error occurred during login");
}
});
app.post("/compose", async (req, res) => {
try {
const document = new Doc({
title: req.body.title,
document: req.body.doc,
code: req.body.code,
category: req.body.newCategory || "Uncategorized",
});
await document.save();
if (admin.apps.length) {
try {
const message = {
notification: {
title: "New Note Uploaded! 🎉",
body: `Check out: ${document.title} in ${document.category}`,
},
topic: "new_docs",
};
// Send the push notification
await admin.messaging().send(message);
console.log(`Notification sent for: ${document.title}`);
} catch (fcmError) {
console.error("Failed to send Firebase notification:", fcmError);
// Notice we don't crash the server here. If the notification fails,
// the document is still saved safely in MongoDB.
}
}
res.render("admin/compose");
} catch (error) {
console.error("Error saving document:", error);
res.status(500).send("Error saving document");
}
});
app.get("/:title", async (req, res) => {
try {
const requestedTitle = req.params.title;
const document = await Doc.findOne({ title: requestedTitle });
if (!document) {
return res.status(404).render("404");
}
res.render("index", {
title: document.title,
documentation: linkify(document.document),
code: document.code,
category: document.category,
});
} catch (error) {
console.error("Error fetching document:", error);
res.status(500).send("Error loading documentation");
}
});
// Health check endpoints
app.get("/health", (req, res) => {
const dbStatus =
mongoose.connection.readyState === 1 ? "connected" : "disconnected";
res.json({
status: "ok",
timestamp: new Date(),
database: dbStatus,
});
});
app.get("/api/health", (req, res) => {
res.json({
status: "ok",
environment: process.env.NODE_ENV,
mongodb:
mongoose.connection.readyState === 1 ? "connected" : "disconnected",
timestamp: new Date().toISOString(),
});
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send("Something broke!");
});
// Start server
const PORT = process.env.PORT || 3000;
if (!process.env.VERCEL) {
app.listen(PORT, "0.0.0.0", () => {
console.log(`Server is Running at ${PORT}`);
});
}
module.exports = app;