-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
201 lines (168 loc) · 7.51 KB
/
Copy pathserver.js
File metadata and controls
201 lines (168 loc) · 7.51 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
import { createServer } from 'node:http';
import next from 'next';
import { Server } from 'socket.io';
import path from 'path';
import fs from 'fs/promises';
import { v4 as uuidv4 } from 'uuid';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
// ESM __dirname equivalent for reliable absolute paths
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Import your DB helpers
import { insertMemory, getAllMemories } from './server/db.js';
const dev = process.env.NODE_ENV !== 'production';
const hostname = process.env.HOST || '0.0.0.0';
const port = 3000;
const DEBUG = process.env.NODE_ENV !== 'production';
const app = next({ dev, hostname, port });
const handler = app.getRequestHandler();
console.log('⌛ Starting Memory Wall Server...');
app.prepare().then(() => {
const httpServer = createServer((req, res) => {
handler(req, res);
});
const io = new Server(httpServer, {
cors: {
origin: '*',
methods: ['GET', 'POST'],
},
transports: ['websocket', 'polling'],
});
console.log('✅ Socket.IO server initialized');
io.on('connection', (socket) => {
if (DEBUG) console.log(`[Socket.IO] 🎨… Client connected: ${socket.id}`);
// Send current memories from DB to the newly connected client
try {
const memories = getAllMemories();
socket.emit('initial-memories', memories);
if (DEBUG) console.log(`[Socket.IO] 🎨 Sent ${memories.length} initial memories to ${socket.id}`);
} catch (err) {
console.error('[Socket.IO] 🖼️ Error loading initial memories:', err);
}
// Allow clients to explicitly request the latest wall data
socket.on('request-initial-memories', () => {
try {
const memories = getAllMemories();
socket.emit('initial-memories', memories);
if (DEBUG) console.log(`[Socket.IO] 🎨 Re-sent ${memories.length} initial memories to ${socket.id}`);
} catch (err) {
console.error('[Socket.IO] ⌠Error handling request-initial-memories:', err);
}
});
// When client submits a new memory
socket.on('new-memory', async (payload) => {
if (DEBUG) console.log(`[Socket.IO] 📨 Received new-memory from ${socket.id}`);
try {
const { name, message, email, photoBase64, compositeBase64 } = payload;
// Validate required fields
if (!name?.trim()) {
console.error('[Socket.IO] 🖼️ Missing name');
socket.emit('memory-saved', { success: false, error: 'Name is required' });
return;
}
if (!message?.trim()) {
console.error('[Socket.IO] 🖼️ Missing message');
socket.emit('memory-saved', { success: false, error: 'Message is required' });
return;
}
if (!photoBase64 && !compositeBase64) {
console.error('[Socket.IO] 🖼️ Missing images');
socket.emit('memory-saved', { success: false, error: 'Image is required' });
return;
}
const id = uuidv4();
const now = Date.now();
if (DEBUG) console.log(`[Socket.IO] 🎨 Generated ID: ${id}`);
let photoUrl = null;
let compositeUrl = null;
// ✅ FIX #1: Save the RAW PHOTO (for avatar display)
if (photoBase64) {
try {
const matches = photoBase64.match(/^data:(.+);base64,(.+)$/);
if (matches?.length === 3) {
const mimeType = matches[1];
const ext = mimeType.split('/')[1] || 'webp';
const buffer = Buffer.from(matches[2], 'base64');
// Save to photos directory using __dirname for reliable path
const photoDir = path.join(__dirname, 'public', 'memories', 'photos');
await fs.mkdir(photoDir, { recursive: true });
const photoFilePath = path.join(photoDir, `${id}.${ext}`);
await fs.writeFile(photoFilePath, buffer);
photoUrl = `/memories/photos/${id}.${ext}`;
if (DEBUG) console.log(`[Socket.IO] 💾 Saved photo: ${photoUrl}`);
} else {
console.error('[Socket.IO] 🖼️ Invalid photo base64 format');
}
} catch (fileErr) {
console.error('[Socket.IO] 🖼️ Photo save error:', fileErr);
}
}
// ✅ FIX #2: Save the COMPOSITE CARD (full card screenshot)
if (compositeBase64) {
try {
const matches = compositeBase64.match(/^data:(.+);base64,(.+)$/);
if (matches?.length === 3) {
const mimeType = matches[1];
const ext = mimeType.split('/')[1] || 'png';
const buffer = Buffer.from(matches[2], 'base64');
// Save to composite directory using __dirname for reliable path
const compositeDir = path.join(__dirname, 'public', 'memories', 'composite');
await fs.mkdir(compositeDir, { recursive: true });
const compositeFilePath = path.join(compositeDir, `${id}.${ext}`);
await fs.writeFile(compositeFilePath, buffer);
compositeUrl = `/memories/composite/${id}.${ext}`;
if (DEBUG) console.log(`[Socket.IO] 💾 Saved composite: ${compositeUrl}`);
} else {
console.error('[Socket.IO] 🖼️ Invalid composite base64 format');
}
} catch (fileErr) {
console.error('[Socket.IO] 🖼️ Composite save error:', fileErr);
}
}
// ✅ FIX #3: Store PHOTO as imageUrl, COMPOSITE as fPhotoUrl
const memory = {
id,
name: name.trim(),
message: message.trim().slice(0, 80),
email: email?.trim() || null,
imageUrl: photoUrl || '/icon.png', //🖼️ RAW PHOTO for avatar
fPhotoUrl: compositeUrl || photoUrl, // 🖼️ COMPOSITE CARD
createdAt: now,
};
if (DEBUG) console.log(`[Socket.IO] 🎨 Inserting memory into DB...`);
insertMemory(memory);
if (DEBUG) console.log(`[Socket.IO] 🖼️… Successfully saved to DB: ${id}`);
// Broadcast only persisted memory metadata/URLs to keep payloads lightweight.
io.emit('memory-created', memory);
if (DEBUG) console.log(`[Socket.IO] 🖼️¡ Broadcasted memory-created to ${io.engine.clientsCount} clients`);
// Confirm to sender
socket.emit('memory-saved', { success: true, id });
if (DEBUG) console.log(`[Socket.IO] 🎨… Confirmed to sender: ${socket.id}`);
} catch (err) {
console.error('[Socket.IO] 🖼️ Error in new-memory handler:', err);
socket.emit('memory-saved', {
success: false,
error: err.message || 'Server error',
});
}
});
socket.on('disconnect', (reason) => {
if (DEBUG) console.log(`[Socket.IO] ⌠Client disconnected: ${socket.id} (${reason})`);
});
socket.on('error', (error) => {
console.error(`[Socket.IO] ⌛ Socket error for ${socket.id}:`, error);
});
});
httpServer
.listen(port, () => {
console.log(`✅ Server ready on http://localhost:${port}`);
console.log(`🎨 Submit page: http://localhost:${port}/submit`);
console.log(`🖼️ Wall page: http://localhost:${port}/wall`);
console.log(`\n⌛ Waiting for connections...\n`);
})
.on('error', (err) => {
console.error('⌛ Server failed:', err);
process.exit(1);
});
});