Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
410 lines (357 loc) · 14.4 KB
/
Copy pathserver.js
File metadata and controls
410 lines (357 loc) · 14.4 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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
const express = require('express');
const path = require('path');
const https = require('https');
const fs = require('fs');
const { marked } = require('marked');
const matter = require('gray-matter'); // New dependency
// --- START OF NEW UTILITY/HELPER FUNCTIONS ---
// New: Function to log suspicious activity
const logSuspiciousActivity = (req, message) => {
const logMessage = `[${new Date().toISOString()}] SUSPICIOUS ACTIVITY: ${message} | IP: ${req.ip} | Path: ${req.path}\n`;
fs.appendFile('suspicious_activity.log', logMessage, (err) => {
if (err) console.error("Failed to write to suspicious log:", err);
});
};
// New: Function to log visitor activity
const logVisitor = (req) => {
const timestamp = new Date().toISOString();
const ip = req.ip || req.connection.remoteAddress || req.socket.remoteAddress || 'unknown';
const userAgent = req.get('User-Agent') || 'unknown';
const logMessage = `[${timestamp}] VISIT | IP: ${ip} | Path: ${req.path} | Method: ${req.method} | User-Agent: ${userAgent}\n`;
fs.appendFile('visitor_logs.log', logMessage, (err) => {
if (err) console.error("Failed to write to visitor log:", err);
});
// Send webhook notification if configured
const webhookUrl = ''; // Replace with your webhook URL
if (webhookUrl !== 'YOUR_WEBHOOK_URL_HERE') {
sendWebhookNotification(ip, req.path, timestamp, userAgent, webhookUrl);
}
};
// New: Function to send webhook notifications
const sendWebhookNotification = (ip, path, timestamp, userAgent, webhookUrl) => {
const payload = JSON.stringify({
content: `🔍 **New Visitor**\n**IP:** ${ip}\n**Path:** ${path}\n**Time:** ${timestamp}\n**User-Agent:** ${userAgent}`
});
const url = new URL(webhookUrl);
const options = {
hostname: url.hostname,
port: url.port || (url.protocol === 'https:' ? 443 : 80),
path: url.pathname + url.search,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(payload)
}
};
const protocol = url.protocol === 'https:' ? https : require('http');
const req = protocol.request(options, (res) => {
// Webhook sent successfully
});
req.on('error', (err) => {
console.error('Webhook error:', err.message);
});
req.write(payload);
req.end();
};
// New: Load image library from JSON file
const imageLibrary = JSON.parse(fs.readFileSync(path.join(__dirname, 'image_library.json'), 'utf8'));
// New: Function to load project data from the 'projects' directory
const getProjectsFromMarkdown = () => {
const projectsDir = path.join(__dirname, 'projects');
try {
const files = fs.readdirSync(projectsDir).filter(file => file.endsWith('.md'));
return files.map(file => {
const filePath = path.join(projectsDir, file);
const fileContent = fs.readFileSync(filePath, 'utf-8');
const { data, content } = matter(fileContent); // Use gray-matter to parse
// Resolve thumbnail from image library
if (data.thumbnail && imageLibrary.projectThumbnails[data.thumbnail]) {
data.thumbnail = imageLibrary.projectThumbnails[data.thumbnail];
}
return {
...data,
slug: path.parse(file).name,
customContent: content // The notes/to-do section
};
});
} catch (error) {
console.error("Could not read projects directory:", error);
return [];
}
};
// --- START OF CONFIGURATION ---
const config = {
homePage: {
title: '',
subtitle: '',
aboutMe: [
'Lorem',
'ipsum',
'i forgot the rest'
],
galleryImages: imageLibrary.galleryImages,
backgroundImages: imageLibrary.backgroundImages,
sideBanners: imageLibrary.sideBanners,
backgroundOpacity: 0.1,
bannerOpacity: 0.6
},
experience: [
{
role: 'Full Stack Developer',
company: 'Team 2073 Robotics FRC',
date: '2024 - Present',
description: ''
},
{
role: 'Full Stack Developer',
company: 'Zylink Tech',
date: '2023 - Present',
description: ''
},
],
projects: {
githubUsername: 'listingclown3',
fetchFromGitHub: true,
featuredRepoForActivity: 'blog'
},
socialLinks: [
{ name: 'GitHub', url: 'https://github.com/listingclown3' },
{ name: 'YouTube', url: 'https://www.youtube.com/@list3andtableofcontents112' },
],
pages: [
{ name: 'Home' },
{ name: 'Projects' },
{ name: 'Blog' },
]
};
// --- END OF CONFIGURATION ---
const app = express();
const port = 3000;
// Trust proxy to get real IP addresses
app.set('trust proxy', true);
// Middleware to log all visitors
app.use((req, res, next) => {
logVisitor(req);
next();
});
app.use(express.static(path.join(__dirname, 'public')));
// --- API Endpoints ---
app.get('/api/config', (req, res) => {
res.json(config);
});
// Modified: The Projects API now uses the Markdown-based system
app.get('/api/projects', async (req, res) => {
let finalProjects = [];
const localProjects = getProjectsFromMarkdown(); // Get projects from /projects/*.md
if (config.projects.fetchFromGitHub) {
try {
const githubRepos = await fetchGitHubRepos(config.projects.githubUsername);
finalProjects = githubRepos.map(repo => {
const localOverride = localProjects.find(p => p.name.toLowerCase() === repo.name.toLowerCase());
return localOverride ? { ...repo, ...localOverride } : repo;
});
// Add projects from Markdown that were not found on GitHub
localProjects.forEach(localProject => {
if (!finalProjects.some(p => p.name.toLowerCase() === localProject.name.toLowerCase())) {
finalProjects.push(localProject);
}
});
} catch (error) {
console.error("Failed to fetch from GitHub:", error.message);
logSuspiciousActivity(req, "GitHub API fetch failed.");
finalProjects = localProjects; // Fallback to local projects
}
} else {
finalProjects = localProjects;
}
res.json(finalProjects);
});
// Modified: The Project Detail API now includes custom content and related materials
app.get('/api/project/:name', async (req, res) => {
try {
const repoName = req.params.name;
const owner = config.projects.githubUsername;
const localProject = getProjectsFromMarkdown().find(p => p.slug.toLowerCase() === repoName.toLowerCase());
if (!localProject) {
logSuspiciousActivity(req, `Attempted to access non-existent project: ${repoName}`);
return res.status(404).json({ message: 'Project not found.' });
}
const customHtml = localProject.customContent ? marked(localProject.customContent) : '';
// If it's a custom project (no repoUrl), return only local data
if (!localProject.repoUrl) {
return res.json({
isCustom: true,
customHtml,
related: localProject.related || [],
name: localProject.name || repoName,
});
}
// If it's a GitHub project, fetch all details
const [readme, commits, branches] = await Promise.all([
fetchGitHubFile(owner, repoName, 'README.md'),
fetchGitHubCommits(owner, repoName),
fetchGitHubBranches(owner, repoName) // New: Fetch branches
]);
const readmeHtml = readme ? marked(readme) : '<p>No README file found for this project.</p>';
res.json({
readmeHtml,
customHtml,
related: localProject.related || [],
commits: commits ? commits.slice(0, 10) : [],
branches: branches || [], // Send branches
name: localProject.name || repoName,
});
} catch (error) {
console.error(`Error fetching project details for ${req.params.name}:`, error.message);
res.status(500).json({ message: 'Could not fetch project details.' });
}
});
// New: API endpoint for the homepage activity feed
app.get('/api/activity', (req, res) => {
const projects = getProjectsFromMarkdown()
.sort((a, b) => (fs.statSync(path.join(__dirname, 'projects', `${b.slug}.md`)).mtime) - (fs.statSync(path.join(__dirname, 'projects', `${a.slug}.md`)).mtime))
.slice(0, 3);
const blogs = getBlogPosts()
.slice(0, 2);
res.json({ recentProjects: projects, recentBlogs: blogs });
});
// New: API endpoint for the GitHub activity monitor
app.get('/api/github-activity', async (req, res) => {
const repoName = config.projects.featuredRepoForActivity;
if (!repoName) {
return res.status(404).json({ message: "No featured repository is set in the configuration." });
}
try {
const commits = await fetchGitHubCommits(config.projects.githubUsername, repoName);
res.json(commits.slice(0, 5)); // Send the latest 5 commits
} catch (error) {
console.error(`Could not fetch commits for ${repoName}:`, error);
res.status(500).json({ message: "Could not fetch GitHub activity." });
}
});
// Blog API endpoints (modified slightly for reuse)
const getBlogPosts = () => {
const blogsDir = path.join(__dirname, 'blogs');
try {
const files = fs.readdirSync(blogsDir).filter(file => file.endsWith('.md'));
return files.map(file => {
const metadata = getPostMetadata(path.join(blogsDir, file));
return { slug: path.parse(file).name, ...metadata };
}).sort((a, b) => new Date(b.date) - new Date(a.date));
} catch (error) {
console.error("Could not read blogs directory:", error);
return [];
}
};
app.get('/api/blogs', (req, res) => {
const posts = getBlogPosts();
if (posts.length === 0) {
return res.status(500).json({ message: "Error reading blog posts." });
}
res.json(posts);
});
app.get('/api/blogs/:slug', (req, res) => {
const slug = req.params.slug;
const filePath = path.join(__dirname, 'blogs', `${slug}.md`);
if (!fs.existsSync(filePath)) {
logSuspiciousActivity(req, `Attempted to access non-existent blog post: ${slug}`);
return res.status(404).json({ message: 'Blog post not found.' });
}
const fileContent = fs.readFileSync(filePath, 'utf-8');
const { content } = matter(fileContent); // Use gray-matter here as well for consistency
const htmlContent = marked(content);
res.json({ html: htmlContent });
});
// --- Helper Functions ---
function getPostMetadata(filePath) {
const fileContent = fs.readFileSync(filePath, 'utf-8');
const match = fileContent.match(/---([\s\S]+?)---/);
if (!match) return {};
const frontMatter = match[1];
const metadata = {};
frontMatter.split('\n').forEach(line => {
const [key, ...value] = line.split(':');
if (key && value.length > 0) {
metadata[key.trim()] = value.join(':').trim();
}
});
return metadata;
}
function fetchGitHubRepos(username) {
return new Promise((resolve, reject) => {
const options = {
hostname: 'api.github.com',
path: `/users/${username}/repos?sort=pushed`,
method: 'GET',
headers: { 'User-Agent': 'Node.js-Portfolio-App' }
};
const apiRequest = https.request(options, (apiRes) => {
let data = '';
apiRes.on('data', (chunk) => { data += chunk; });
apiRes.on('end', () => {
if (apiRes.statusCode === 200) {
const repos = JSON.parse(data).map(repo => ({
name: repo.name, description: repo.description, thumbnail: null, tags: repo.language ? [repo.language] : [], repoUrl: repo.html_url, liveUrl: repo.homepage || null,
}));
resolve(repos);
} else {
reject(new Error(`GitHub API responded with status ${apiRes.statusCode}`));
}
});
});
apiRequest.on('error', (e) => reject(e));
apiRequest.end();
});
}
function fetchGitHubFile(owner, repo, filePath) {
return new Promise((resolve) => {
const options = {
hostname: 'api.github.com',
path: `/repos/${owner}/${repo}/contents/${filePath}`,
headers: { 'User-Agent': 'Node.js-Portfolio-App' }
};
https.get(options, (res) => {
if (res.statusCode !== 200) return resolve(null); // File not found, resolve with null
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
const content = JSON.parse(data).content;
resolve(Buffer.from(content, 'base64').toString('utf8'));
});
}).on('error', () => resolve(null));
});
}
function fetchGitHubCommits(owner, repo) {
return new Promise((resolve, reject) => {
const options = {
hostname: 'api.github.com',
path: `/repos/${owner}/${repo}/commits`,
headers: { 'User-Agent': 'Node.js-Portfolio-App' }
};
https.get(options, (res) => {
if (res.statusCode !== 200) return reject(new Error(`GitHub API responded with ${res.statusCode}`));
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => resolve(JSON.parse(data)));
}).on('error', e => reject(e));
});
}
function fetchGitHubBranches(owner, repo) {
return new Promise((resolve, reject) => {
const options = {
hostname: 'api.github.com',
path: `/repos/${owner}/${repo}/branches`,
headers: { 'User-Agent': 'Node.js-Portfolio-App' }
};
https.get(options, (res) => {
if (res.statusCode !== 200) return reject(new Error(`GitHub API for branches responded with ${res.statusCode}`));
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => resolve(JSON.parse(data)));
}).on('error', e => reject(e));
});
}
// Start server
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});