Reaperxxxx commited on
Commit
5f12e6f
·
verified ·
1 Parent(s): 151213d

Delete snoencserver.js

Browse files
Files changed (1) hide show
  1. snoencserver.js +0 -381
snoencserver.js DELETED
@@ -1,381 +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
- // Attempt to reconnect if connection was closed
160
- setTimeout(() => {
161
- console.log("Reconnecting...");
162
- initBaileys()
163
- .then((sock) => {
164
- whatsappSocket = sock;
165
- console.log("Reconnected to WhatsApp");
166
- })
167
- .catch((err) => console.error("Failed to reconnect:", err));
168
- }, 5000); // Retry after 5 seconds
169
- }
170
- });
171
-
172
- // Save credentials on update
173
- socket.ev.on("creds.update", saveCreds);
174
-
175
- return socket;
176
- };
177
-
178
- // Initialize Baileys socket
179
- let whatsappSocket;
180
- initBaileys()
181
- .then((sock) => {
182
- whatsappSocket = sock;
183
- console.log("Connected to WhatsApp");
184
- })
185
- .catch((err) => console.error("Failed to initialize Baileys:", err));
186
-
187
- // Routes
188
- app.get("/", (req, res) => {
189
- res.sendFile(path.join(__dirname, "public", "index.html"));
190
- });
191
-
192
- app.get("/chat/:jid", (req, res) => {
193
- res.sendFile(path.join(__dirname, "public", "chat.html"));
194
- });
195
-
196
- app.post('/validate-key', (req, res) => {
197
- const { key } = req.body;
198
- console.log("Key Received by Server:", key); // Debugging line
199
-
200
- if (key === VALID_KEY) {
201
- res.status(200).send('Key valid');
202
- } else {
203
- res.status(403).send('Invalid key');
204
- }
205
- });
206
-
207
- app.get("/api/messages", async (req, res) => {
208
- const allMessages = loadMessages();
209
- const uniqueChatsMap = new Map(); // To track unique chats with their data
210
-
211
- for (const msg of allMessages) {
212
- // Check if the chat is already processed
213
- const existingChat = uniqueChatsMap.get(msg.jid);
214
- if (existingChat) {
215
- // Update the last message if the timestamp is newer
216
- if (msg.timestamp > existingChat.timestamp) {
217
- existingChat.lastMessage = msg.content;
218
- existingChat.timestamp = msg.timestamp;
219
- }
220
- } else {
221
- // Fetch chat name dynamically
222
- try {
223
- const chatName = await getChatName(msg.jid);
224
- uniqueChatsMap.set(msg.jid, {
225
- jid: msg.jid,
226
- chatName,
227
- lastMessage: msg.content,
228
- timestamp: msg.timestamp,
229
- });
230
- } catch (error) {
231
- console.error(`Failed to fetch chat name for ${msg.jid}:`, error);
232
- }
233
- }
234
- }
235
-
236
- // Convert Map to array and sort by timestamp
237
- const uniqueChats = Array.from(uniqueChatsMap.values());
238
- uniqueChats.sort((a, b) => b.timestamp - a.timestamp);
239
-
240
- res.json(uniqueChats);
241
- });
242
-
243
- app.post("/upload-image", upload.single("image"), async (req, res) => {
244
- const { jid, caption } = req.body;
245
-
246
- if (!req.file) {
247
- return res.status(400).send("No image uploaded.");
248
- }
249
-
250
- const imagePath = path.join(IMAGE_DIR, req.file.filename);
251
-
252
- try {
253
- if (whatsappSocket) {
254
- // Send image to WhatsApp
255
- await whatsappSocket.sendMessage(jid, {
256
- image: { url: imagePath },
257
- caption: caption || "",
258
- });
259
-
260
- // Save the sent message locally
261
- const allMessages = loadMessages();
262
- allMessages.push({
263
- jid,
264
- sender: "You",
265
- chatName: await getChatName(jid),
266
- content: caption || "[Image]",
267
- filePath: `Temp/${req.file.filename}`,
268
- timestamp: Date.now(),
269
- });
270
- saveMessages(allMessages);
271
-
272
- res.sendStatus(200);
273
- } else {
274
- res.status(500).send("WhatsApp session not initialized.");
275
- }
276
- } catch (error) {
277
- console.error("Error sending image:", error);
278
- res.status(500).send("Failed to send image.");
279
- }
280
- });
281
-
282
- app.get("/messages.json", (req, res) => {
283
- res.sendFile(path.join(__dirname, "messages.json"));
284
- });
285
-
286
- app.get("/api/messages/:jid", (req, res) => {
287
- const { jid } = req.params;
288
- const chatMessages = loadMessages().filter((msg) => msg.jid === jid);
289
- res.json(chatMessages);
290
- });
291
-
292
- // WebSocket Connection
293
- io.on("connection", (socket) => {
294
- console.log("Client connected via WebSocket");
295
- socket.on("disconnect", () => {
296
- console.log("Client disconnected");
297
- });
298
- });
299
-
300
- app.post("/send-message", async (req, res) => {
301
- const { jid, message, replyTo } = req.body;
302
-
303
- try {
304
- if (whatsappSocket) {
305
- const messages = loadMessages();
306
- const quotedMessage = messages.find((msg) => msg.jid === jid && msg.timestamp == replyTo);
307
-
308
- if (replyTo && quotedMessage) {
309
- await whatsappSocket.sendMessage(jid, {
310
- text: message,
311
- quoted: {
312
- key: { remoteJid: jid, id: replyTo },
313
- message: { conversation: quotedMessage.content },
314
- },
315
- });
316
- } else {
317
- await whatsappSocket.sendMessage(jid, { text: message });
318
- }
319
-
320
- res.sendStatus(200);
321
- } else {
322
- res.status(500).send("WhatsApp session not initialized.");
323
- }
324
- } catch (error) {
325
- console.error("Error sending message:", error);
326
- res.status(500).send("Failed to send message.");
327
- }
328
- });
329
-
330
- app.post("/send-sticker", async (req, res) => {
331
- const { jid, stickerPath } = req.body;
332
- try {
333
- if (whatsappSocket && fs.existsSync(stickerPath)) {
334
- await whatsappSocket.sendMessage(jid, { sticker: { url: stickerPath } });
335
- res.sendStatus(200);
336
- } else {
337
- res.status(400).send("Sticker file not found or session not initialized.");
338
- }
339
- } catch (error) {
340
- console.error("Error sending sticker:", error);
341
- res.sendStatus(500);
342
- }
343
- });
344
-
345
- app.post("/send-image", async (req, res) => {
346
- const { jid, imagePath, caption } = req.body;
347
- try {
348
- if (whatsappSocket && fs.existsSync(imagePath)) {
349
- await whatsappSocket.sendMessage(jid, {
350
- image: { url: imagePath },
351
- caption: caption || "",
352
- });
353
- res.sendStatus(200);
354
- } else {
355
- res.status(400).send("Image file not found or session not initialized.");
356
- }
357
- } catch (error) {
358
- console.error("Error sending image:", error);
359
- res.sendStatus(500);
360
- }
361
- });
362
-
363
- // WebSocket connection
364
- io.on('connection', (socket) => {
365
- console.log('User connected');
366
-
367
- // Example event to listen for new messages
368
- socket.on('sendMessage', (message) => {
369
- saveMessage(message); // Save the message to storage
370
-
371
- // Broadcast to all connected clients
372
- io.emit('newMessage', message);
373
- });
374
-
375
- socket.on('disconnect', () => {
376
- console.log('User disconnected');
377
- });
378
- });
379
-
380
- // Start server
381
- server.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));