Reaperxxxx commited on
Commit
bd6c812
·
verified ·
1 Parent(s): dc6da6c

Delete server.js

Browse files
Files changed (1) hide show
  1. server.js +0 -371
server.js DELETED
@@ -1,371 +0,0 @@
1
- const fs = require("fs");
2
- const express = require("express");
3
- const { makeWASocket, fetchLatestBaileysVersion, useMultiFileAuthState, makeInMemoryStore, downloadMediaMessage } = require("@whiskeysockets/baileys");
4
- const http = require("http");
5
- const socketIo = require("socket.io");
6
- const bodyParser = require("body-parser");
7
- const path = require("path");
8
- const VALID_KEY = 'test';
9
- const multer = require("multer");
10
-
11
- const app = express();
12
- const server = http.createServer(app);
13
- const io = socketIo(server);
14
- const PORT = process.env.PORT || 7860;
15
-
16
- const store = makeInMemoryStore({});
17
-
18
- // Paths
19
- const MESSAGES_FILE = "./messages.json";
20
- const SESSION_DIR = "./session"; // Directory to store session credentials
21
- const IMAGE_DIR = path.join(__dirname, "Temp");
22
- if (!fs.existsSync(IMAGE_DIR)) fs.mkdirSync(IMAGE_DIR);
23
- const upload = multer({
24
- dest: IMAGE_DIR, // Temporary storage location
25
- limits: { fileSize: 5 * 1024 * 1024 }, // 5 MB limit
26
- fileFilter: (req, file, cb) => {
27
- const allowedTypes = ["image/jpeg", "image/png"];
28
- if (!allowedTypes.includes(file.mimetype)) {
29
- return cb(new Error("Only JPEG and PNG images are allowed."));
30
- }
31
- cb(null, true);
32
- },
33
- });
34
-
35
- // Initialize Express
36
- // Middleware
37
- app.use(express.static("public"));
38
- app.use(bodyParser.json());
39
-
40
- // Load or initialize `messages.json`
41
- if (!fs.existsSync(MESSAGES_FILE)) fs.writeFileSync(MESSAGES_FILE, JSON.stringify([]));
42
- const loadMessages = () => JSON.parse(fs.readFileSync(MESSAGES_FILE));
43
- const saveMessages = (messages) => fs.writeFileSync(MESSAGES_FILE, JSON.stringify(messages));
44
-
45
- // Initialize Baileys with saved session keys
46
- const initBaileys = async () => {
47
- const { version } = await fetchLatestBaileysVersion();
48
- const { state, saveCreds } = await useMultiFileAuthState(SESSION_DIR);
49
-
50
- const socket = makeWASocket({
51
- auth: state,
52
- version,
53
- });
54
-
55
- store.bind(socket.ev);
56
-
57
- // Function to get the name for a chat
58
- const getChatName = async (jid) => {
59
- if (jid.endsWith("@g.us")) {
60
- // Fetch group metadata for group chats
61
- try {
62
- const metadata = await whatsappSocket.groupMetadata(jid);
63
- return metadata.subject || "Unknown Group";
64
- } catch (err) {
65
- console.error("Error fetching group metadata:", err);
66
- return "Unknown Group";
67
- }
68
- } else {
69
- // Use contact name for personal chats
70
- const contact = store.contacts[jid]; // Fetch from store
71
- return contact?.name || contact?.notify || jid; // Fallback to JID if name is not available
72
- }
73
- };
74
-
75
- // Listen for new messages
76
- socket.ev.on("messages.upsert", async ({ messages }) => {
77
- const allMessages = loadMessages();
78
-
79
- for (const msg of messages) {
80
- if (msg.message) {
81
- let content = "[Unsupported Message Type]";
82
- let filePath = null;
83
-
84
- if (msg.message.imageMessage) {
85
- // Download and save image messages
86
- const buffer = await whatsappSocket.downloadMediaMessage(msg);
87
- const fileName = `image_${Date.now()}.jpg`;
88
- filePath = path.join(IMAGE_DIR, fileName);
89
- fs.writeFileSync(filePath, buffer);
90
- content = msg.message.imageMessage.caption || "[Image]";
91
- } else if (msg.message.stickerMessage) {
92
- // Download and save sticker messages
93
- const buffer = await whatsappSocket.downloadMediaMessage(msg);
94
- const fileName = `sticker_${Date.now()}.webp`;
95
- filePath = path.join(IMAGE_DIR, fileName);
96
- fs.writeFileSync(filePath, buffer);
97
- content = "[Sticker]";
98
- } else if (msg.message.videoMessage) {
99
- // Handle video messages without downloading
100
- content = "[Video]";
101
- } else if (msg.message.audioMessage) {
102
- // Handle audio messages without downloading
103
- content = "[Audio]";
104
- } else if (msg.message.documentMessage) {
105
- // Handle document messages without downloading
106
- content = `[Document: ${msg.message.documentMessage.fileName || "Unknown Document"}]`;
107
- } else if (msg.message.extendedTextMessage) {
108
- // Handle extended text messages
109
- content = msg.message.extendedTextMessage.text;
110
- } else if (msg.message.contactMessage) {
111
- // Handle contact messages
112
- content = `[Contact: ${msg.message.contactMessage.displayName || "Unknown"}]`;
113
- } else if (msg.message.locationMessage) {
114
- // Handle location messages
115
- const { degreesLatitude, degreesLongitude } = msg.message.locationMessage;
116
- content = `[Location: ${degreesLatitude}, ${degreesLongitude}]`;
117
- } else if (msg.message.buttonsMessage) {
118
- // Handle buttons messages
119
- content = msg.message.buttonsMessage.contentText || "[Buttons Message]";
120
- } else if (msg.message.listMessage) {
121
- // Handle list messages
122
- content = msg.message.listMessage.description || "[List Message]";
123
- } else if (msg.message.pollCreationMessage) {
124
- // Handle poll messages
125
- content = msg.message.pollCreationMessage.name || "[Poll]";
126
- }
127
-
128
- // Get the chat name dynamically
129
- const chatName = await getChatName(msg.key.remoteJid);
130
-
131
- // Prepare the message data
132
- const messageData = {
133
- jid: msg.key.remoteJid,
134
- sender: msg.key.fromMe ? "You" : msg.pushName || msg.key.remoteJid,
135
- chatName,
136
- content,
137
- filePath: filePath ? `Temp/${path.basename(filePath)}` : null,
138
- timestamp: msg.messageTimestamp,
139
- };
140
-
141
- // Save the message data
142
- allMessages.push(messageData);
143
- saveMessages(allMessages);
144
-
145
- // Emit the message to the frontend
146
- io.emit("new_message", messageData);
147
- }
148
- }
149
- });
150
-
151
- // Save credentials on update
152
- socket.ev.on("connection.update", (update) => {
153
- const { connection, lastDisconnect } = update;
154
-
155
- if (connection === "open") {
156
- console.log("WhatsApp connected!");
157
- } else if (connection === "close") {
158
- console.error("Connection closed:", lastDisconnect?.error);
159
- }
160
- });
161
-
162
- // Save credentials on update
163
- socket.ev.on("creds.update", saveCreds);
164
-
165
- return socket;
166
- };
167
-
168
- // Initialize Baileys socket
169
- let whatsappSocket;
170
- initBaileys()
171
- .then((sock) => {
172
- whatsappSocket = sock;
173
- console.log("Connected to WhatsApp");
174
- })
175
- .catch((err) => console.error("Failed to initialize Baileys:", err));
176
-
177
- // Routes
178
- app.get("/", (req, res) => {
179
- res.sendFile(path.join(__dirname, "public", "index.html"));
180
- });
181
-
182
- app.get("/chat/:jid", (req, res) => {
183
- res.sendFile(path.join(__dirname, "public", "chat.html"));
184
- });
185
-
186
- app.post('/validate-key', (req, res) => {
187
- const { key } = req.body;
188
- console.log("Key Received by Server:", key); // Debugging line
189
-
190
- if (key === VALID_KEY) {
191
- res.status(200).send('Key valid');
192
- } else {
193
- res.status(403).send('Invalid key');
194
- }
195
- });
196
-
197
- app.get("/api/messages", async (req, res) => {
198
- const allMessages = loadMessages();
199
- const uniqueChatsMap = new Map(); // To track unique chats with their data
200
-
201
- for (const msg of allMessages) {
202
- // Check if the chat is already processed
203
- const existingChat = uniqueChatsMap.get(msg.jid);
204
- if (existingChat) {
205
- // Update the last message if the timestamp is newer
206
- if (msg.timestamp > existingChat.timestamp) {
207
- existingChat.lastMessage = msg.content;
208
- existingChat.timestamp = msg.timestamp;
209
- }
210
- } else {
211
- // Fetch chat name dynamically
212
- try {
213
- const chatName = await getChatName(msg.jid);
214
- uniqueChatsMap.set(msg.jid, {
215
- jid: msg.jid,
216
- chatName,
217
- lastMessage: msg.content,
218
- timestamp: msg.timestamp,
219
- });
220
- } catch (error) {
221
- console.error(`Failed to fetch chat name for ${msg.jid}:`, error);
222
- }
223
- }
224
- }
225
-
226
- // Convert Map to array and sort by timestamp
227
- const uniqueChats = Array.from(uniqueChatsMap.values());
228
- uniqueChats.sort((a, b) => b.timestamp - a.timestamp);
229
-
230
- res.json(uniqueChats);
231
- });
232
-
233
- app.post("/upload-image", upload.single("image"), async (req, res) => {
234
- const { jid, caption } = req.body;
235
-
236
- if (!req.file) {
237
- return res.status(400).send("No image uploaded.");
238
- }
239
-
240
- const imagePath = path.join(IMAGE_DIR, req.file.filename);
241
-
242
- try {
243
- if (whatsappSocket) {
244
- // Send image to WhatsApp
245
- await whatsappSocket.sendMessage(jid, {
246
- image: { url: imagePath },
247
- caption: caption || "",
248
- });
249
-
250
- // Save the sent message locally
251
- const allMessages = loadMessages();
252
- allMessages.push({
253
- jid,
254
- sender: "You",
255
- chatName: await getChatName(jid),
256
- content: caption || "[Image]",
257
- filePath: `Temp/${req.file.filename}`,
258
- timestamp: Date.now(),
259
- });
260
- saveMessages(allMessages);
261
-
262
- res.sendStatus(200);
263
- } else {
264
- res.status(500).send("WhatsApp session not initialized.");
265
- }
266
- } catch (error) {
267
- console.error("Error sending image:", error);
268
- res.status(500).send("Failed to send image.");
269
- }
270
- });
271
-
272
- app.get("/messages.json", (req, res) => {
273
- res.sendFile(path.join(__dirname, "messages.json"));
274
- });
275
-
276
- app.get("/api/messages/:jid", (req, res) => {
277
- const { jid } = req.params;
278
- const chatMessages = loadMessages().filter((msg) => msg.jid === jid);
279
- res.json(chatMessages);
280
- });
281
-
282
- // WebSocket Connection
283
- io.on("connection", (socket) => {
284
- console.log("Client connected via WebSocket");
285
- socket.on("disconnect", () => {
286
- console.log("Client disconnected");
287
- });
288
- });
289
-
290
- app.post("/send-message", async (req, res) => {
291
- const { jid, message, replyTo } = req.body;
292
-
293
- try {
294
- if (whatsappSocket) {
295
- const messages = loadMessages();
296
- const quotedMessage = messages.find((msg) => msg.jid === jid && msg.timestamp == replyTo);
297
-
298
- if (replyTo && quotedMessage) {
299
- await whatsappSocket.sendMessage(jid, {
300
- text: message,
301
- quoted: {
302
- key: { remoteJid: jid, id: replyTo },
303
- message: { conversation: quotedMessage.content },
304
- },
305
- });
306
- } else {
307
- await whatsappSocket.sendMessage(jid, { text: message });
308
- }
309
-
310
- res.sendStatus(200);
311
- } else {
312
- res.status(500).send("WhatsApp session not initialized.");
313
- }
314
- } catch (error) {
315
- console.error("Error sending message:", error);
316
- res.status(500).send("Failed to send message.");
317
- }
318
- });
319
-
320
- app.post("/send-sticker", async (req, res) => {
321
- const { jid, stickerPath } = req.body;
322
- try {
323
- if (whatsappSocket && fs.existsSync(stickerPath)) {
324
- await whatsappSocket.sendMessage(jid, { sticker: { url: stickerPath } });
325
- res.sendStatus(200);
326
- } else {
327
- res.status(400).send("Sticker file not found or session not initialized.");
328
- }
329
- } catch (error) {
330
- console.error("Error sending sticker:", error);
331
- res.sendStatus(500);
332
- }
333
- });
334
-
335
- app.post("/send-image", async (req, res) => {
336
- const { jid, imagePath, caption } = req.body;
337
- try {
338
- if (whatsappSocket && fs.existsSync(imagePath)) {
339
- await whatsappSocket.sendMessage(jid, {
340
- image: { url: imagePath },
341
- caption: caption || "",
342
- });
343
- res.sendStatus(200);
344
- } else {
345
- res.status(400).send("Image file not found or session not initialized.");
346
- }
347
- } catch (error) {
348
- console.error("Error sending image:", error);
349
- res.sendStatus(500);
350
- }
351
- });
352
-
353
- // WebSocket connection
354
- io.on('connection', (socket) => {
355
- console.log('User connected');
356
-
357
- // Example event to listen for new messages
358
- socket.on('sendMessage', (message) => {
359
- saveMessage(message); // Save the message to storage
360
-
361
- // Broadcast to all connected clients
362
- io.emit('newMessage', message);
363
- });
364
-
365
- socket.on('disconnect', () => {
366
- console.log('User disconnected');
367
- });
368
- });
369
-
370
- // Start server
371
- server.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));