-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
167 lines (149 loc) · 6.24 KB
/
server.js
File metadata and controls
167 lines (149 loc) · 6.24 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
const http = require('http');
const fs = require('fs').promises;
const path = require('path');
const url = require('url');
const PORT = 8080;
const GALLERY_DATA_FILE = path.join(__dirname, 'gallery-data.json');
const IMAGES_DIR = path.join(__dirname, 'images');
// MIME types
const mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon'
};
const server = http.createServer(async (req, res) => {
const parsedUrl = url.parse(req.url, true);
const pathname = parsedUrl.pathname;
// Enable CORS
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
// Handle preflight requests
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
// API endpoints
if (pathname === '/api/server-status' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok', hasAPI: true }));
return;
}
if (pathname === '/api/save-data' && req.method === 'POST') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', async () => {
try {
const data = JSON.parse(body);
await fs.writeFile(GALLERY_DATA_FILE, JSON.stringify(data, null, 2));
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ success: true }));
console.log('✅ Saved gallery-data.json');
} catch (error) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: error.message }));
}
});
return;
}
if (pathname === '/api/load-data' && req.method === 'GET') {
try {
const data = await fs.readFile(GALLERY_DATA_FILE, 'utf8');
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(data);
} catch (error) {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'File not found' }));
}
return;
}
if (pathname === '/api/load-images' && req.method === 'GET') {
try {
const files = await fs.readdir(IMAGES_DIR);
const imageFiles = files.filter(file =>
/\.(jpg|jpeg|png|gif|webp)$/i.test(file) && !file.startsWith('.')
);
const images = await Promise.all(imageFiles.map(async (filename) => {
const filePath = path.join(IMAGES_DIR, filename);
const data = await fs.readFile(filePath);
const base64 = data.toString('base64');
const ext = path.extname(filename).toLowerCase();
const mimeType = ext === '.jpg' || ext === '.jpeg' ? 'image/jpeg' : `image/${ext.slice(1)}`;
// Extract ID from filename if it follows the pattern
const match = filename.match(/image_(\d+\.?\d*)_/);
const id = match ? parseFloat(match[1]) : Date.now() + Math.random();
return {
id: id,
src: `data:${mimeType};base64,${base64}`,
originalFilename: filename
};
}));
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(images));
} catch (error) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: error.message }));
}
return;
}
if (pathname === '/api/save-image' && req.method === 'POST') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', async () => {
try {
const { filename, data } = JSON.parse(body);
const base64Data = data.replace(/^data:image\/\w+;base64,/, '');
const buffer = Buffer.from(base64Data, 'base64');
const filePath = path.join(IMAGES_DIR, filename);
await fs.writeFile(filePath, buffer);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ success: true }));
console.log(`✅ Saved image: ${filename}`);
} catch (error) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: error.message }));
}
});
return;
}
if (pathname.startsWith('/api/delete-image/') && req.method === 'DELETE') {
try {
const filename = decodeURIComponent(pathname.split('/').pop());
const filePath = path.join(IMAGES_DIR, filename);
await fs.unlink(filePath);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ success: true }));
console.log(`🗑️ Deleted image: ${filename}`);
} catch (error) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: error.message }));
}
return;
}
// Serve static files
let filePath = pathname === '/' ? '/index.html' : pathname;
filePath = path.join(__dirname, filePath);
try {
const data = await fs.readFile(filePath);
const ext = path.extname(filePath);
const contentType = mimeTypes[ext] || 'application/octet-stream';
res.writeHead(200, { 'Content-Type': contentType });
res.end(data);
} catch (error) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
}
});
server.listen(PORT, () => {
console.log(`🚀 Gallery server running at http://localhost:${PORT}`);
console.log('📁 Serving files from:', __dirname);
console.log('💾 Gallery data file:', GALLERY_DATA_FILE);
});