File size: 11,278 Bytes
183a3de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import FormData from "form-data";
import axios from "axios";
import fs from "fs";
import path from "path";
import { tempDir } from "./io-json.js";
import { exec } from "child_process";
import { promisify } from "util";
import sharp from "sharp";
import { analyzeLinks } from "../api-zalo/utils.js";
import { getRecentMessage } from "../commands/bot-manager/recent-message.js";
import { getBotId } from "../index.js";

export async function checkUrlStatus(url) {
	try {
		const response = await axios.head(url, {
			timeout: 5000,
		});
		return response.status === 200;
	} catch (error) {
		console.log(`Link đã gãy hoặc timeout: ${url}`);
		return false;
	}
}

export function checkLinkIsValid(content) {
  try {
    if (!content || typeof content !== 'string') return false;
    content = content.trim();
    if (!content.match(/^https?:\/\//i)) {
      content = 'https://' + content;
    }
    new URL(content);
    return true;
  } catch {
    return false;
  }
}

export const execAsync = promisify(exec);

export async function uploadTempFile(pathLocal, serviceType = 1) {
  // const startTime = performance.now();
  let result = null;

  try {
    if (serviceType === 2) result = await uploadToTmpFile(pathLocal);
  } catch (error) {
    result = await uploadToUguu(pathLocal);
  }
  try {
    if (serviceType === 1) result = await uploadToUguu(pathLocal);
  } catch (error) {
    result = await uploadToTmpFile(pathLocal);
  }

  // const endTime = performance.now();
  // const duration = (endTime - startTime) / 1000;

  // if (duration.toFixed(2) > 1) {
  //   console.log(`⏱️ Thời gian upload file bằng service ${serviceType}: ${duration.toFixed(2)} giây`);
  // }
  return result;
}

/**

 * Upload file lên tmpfiles.org

 */

export async function uploadToTmpFile(pathLocal) {
  try {
    const fileName = path.basename(pathLocal);
    const buffer = fs.createReadStream(pathLocal);
    const formData = new FormData();
    formData.append("file", buffer, {
      filename: fileName,
    });

    const response = await axios.post("https://tmpfiles.org/api/v1/upload", formData, {
      headers: formData.getHeaders(),
    });

    if (response.status === 200 && response.data.data.url) {
      const downloadUrl = response.data.data.url.replace("https://tmpfiles.org/", "https://tmpfiles.org/dl/");
      return downloadUrl;
    } else {
      console.error("Lỗi khi upload:", response.data);
      return null;
    }
  } catch (error) {
    console.error("Lỗi khi upload lên dịch vụ tempfile:", error);
    return null;
  }
}


 /* 

 Upload file lên uguu.se

 */
export async function uploadToUguu(pathLocal) {
  try {
    const fileName = path.basename(pathLocal);
    const buffer = fs.createReadStream(pathLocal);

    const formData = new FormData();
    formData.append("files[]", buffer, fileName);
    formData.append("randomname", "true");

    const response = await axios.post("https://uguu.se/upload.php", formData, {
      headers: {
        ...formData.getHeaders(),
        accept: "application/json",
      },
    });

    if (response.status === 200 && response.data) {
      return response.data.files[0].url;
    } else {
      console.error("Lỗi upload:", response.data);
      return null;
    }
  } catch (error) {
    console.error("Lỗi khi upload lên Uguu:", error.message);
    return null;
  }
}  

/**

 * Download file từ URL và lưu vào file với các options phù hợp theo loại file

 */
export async function downloadFile(url, filepath) {
  const response = await axios({
    url,
    method: "GET",
    responseType: "stream",
  });
  const tempFilePath = filepath || path.join(tempDir, `fileDownload_${Date.now()}.${checkExstentionFileRemote(url)}`);
  return new Promise((resolve, reject) => {
    const writer = fs.createWriteStream(tempFilePath);
    response.data.pipe(writer);
    writer.on("finish", () => {
      resolve(tempFilePath);
    });
    writer.on("error", reject);
  });
}

/**

 * Download video từ URL và lưu vào file

 */
export async function downloadAndSaveVideo(videoUrl) {
  const videoResponse = await axios({
    method: "GET",
    url: videoUrl,
    responseType: "arraybuffer",
  });

  if (!fs.existsSync(tempDir)) {
    fs.mkdirSync(tempDir);
  }

  const tempFilePath = path.join(tempDir, `video_${Date.now()}.mp4`);
  fs.writeFileSync(tempFilePath, videoResponse.data);

  return tempFilePath;
}

/**

 * Xóa file theo đường dẫn

 */
export async function deleteFile(pathFile) {
  if (!pathFile) return;
  let attempts = 0;
  const maxAttempts = 3;

  while (attempts < maxAttempts) {
    try {
      if (fs.existsSync(pathFile)) {
        fs.unlinkSync(pathFile);
        if (!fs.existsSync(pathFile)) {
          return;
        }
      } else {
        return;
      }
    } catch (error) {
    }
    attempts++;

    if (attempts < maxAttempts) {
      await new Promise(resolve => setTimeout(resolve, 100));
    }
  }
}

/**

 * Kiểm tra định dạng file từ URL remote

 */
export async function checkExstentionFileRemote(url) {
  let attempts = 0;
  const maxAttempts = 3;
  const mimeToExt = {
    'image/jpeg': 'jpg',
    'image/jpg': 'jpg',
    'image/png': 'png',
    'image/gif': 'gif',
    'image/webp': 'webp',
    'video/mp4': 'mp4',
    'video/webm': 'webm',
    'video/quicktime': 'mov',
    'audio/mpeg': 'mp3',
    'audio/mp4': 'm4a',
    'audio/wav': 'wav',
    'audio/webm': 'weba',
    'audio/aac': 'aac',
    'application/pdf': 'pdf',
    'application/zip': 'zip',
    'application/x-rar-compressed': 'rar',
    'application/x-7z-compressed': '7z',
    'application/x-tar': 'tar',
    'application/x-gzip': 'gz',
    'application/x-bzip2': 'bz2',
    'application/x-xz': 'xz',
  };

  while (attempts < maxAttempts) {
    try {
      const response = await axios.head(url);
      const contentType = response.headers['content-type'];

      if (!contentType) return null;

      let ext = mimeToExt[contentType] || null;
      if (ext) return ext;

      let extension = url.split('.').pop().toLowerCase();
      if (extension && extension.length <= 4) {
        return extension;
      }

      if (contentType.includes("octet-stream") && response.headers['content-disposition']) {
        const contentDisposition = response.headers['content-disposition'];
        const filenameMatch = contentDisposition.match(/filename=["']?([^"']+)["']?/);
        if (filenameMatch && filenameMatch[1]) {
          const extension = filenameMatch[1].split('.').pop().toLowerCase();
          return extension;
        }
      }

      return null;

    } catch (error) {
      if (error.response && error.response.headers && error.response.headers['content-type']) {
        const contentType = error.response.headers['content-type'];

        let ext = mimeToExt[contentType] || null;
        if (ext) return ext;
      }

      attempts++;
      if (attempts === maxAttempts) {
        console.error('Lỗi khi kiểm tra định dạng file sau 3 lần thử:', error.message);
        return null;
      }
      await new Promise(resolve => setTimeout(resolve, 500));
    }
  }
}

/**

 * Tải và chuyển đổi ảnh sang PNG buffer từ đường dẫn hoặc URL

 * @param {string} source - Đường dẫn file hoặc URL của ảnh

 * @returns {Promise<Buffer>} Buffer dạng PNG của ảnh

 */
export async function loadImageBuffer(source) {
  try {
    let buffer;

    if (source.startsWith("http://") || source.startsWith("https://")) {
      const response = await axios({
        url: source,
        method: 'GET',
        responseType: 'arraybuffer',
        timeout: 3000
      });
      buffer = Buffer.from(response.data);
    } else {
      buffer = await fs.promises.readFile(source);
    }

    const pngBuffer = await sharp(buffer)
      .png()
      .toBuffer();

    return pngBuffer;
  } catch (error) {
    console.error("Lỗi khi xử lý ảnh:", error.message);
    return null;
  }
}

/**

 * Lấy thông tin kích thước và dung lượng của ảnh thông qua ffmpeg

 * @param {string} imageUrl - URL hoặc đường dẫn của ảnh

 * @returns {Promise<{width: number, height: number, totalSize: number}>} Thông tin kích thước và dung lượng của ảnh

 */
export async function getImageInfo(imageUrl) {
  try {
    const response = await axios.head(imageUrl);
    const totalSize = parseInt(response.headers['content-length'] || 0);

    const imageResponse = await axios.get(imageUrl, {
      responseType: 'arraybuffer'
    });

    const metadata = await sharp(Buffer.from(imageResponse.data)).metadata();

    return {
      width: metadata.width || 500,
      height: metadata.height || 500,
      totalSize: totalSize || 0
    };
  } catch (error) {
    console.error("Lỗi khi lấy thông tin ảnh:", error.message);
    return null;
  }
}
export async function deleteRepliedMessage(api, message) {
  try {
    if (message?.data?.quote?.globalMsgId) {
      const idBot = getBotId();
      const quotedMsgId = message.data.quote.globalMsgId;

      const recentMessages = await getRecentMessage(api, message, 50);

      const messageToDelete = recentMessages.find(msg => msg.msgId.toString() === quotedMsgId.toString());
      if (messageToDelete) {
        const msgDel = {
          type: messageToDelete.type || message.type,
          threadId: message.threadId,
          data: {
            cliMsgId: messageToDelete.cliMsgId,
            msgId: messageToDelete.msgId,
            uidFrom: messageToDelete.uidFrom === "0" ? idBot : messageToDelete.uidFrom,
          },
        };

        await api.deleteMessage(msgDel, false).catch(err => {
          console.error("Lỗi khi xóa tin nhắn reply:", err);
        });
      }
    }
  } catch (error) {
    console.error("Lỗi khi xóa tin nhắn reply:", error);
  }
}
export async function uploadFileOnly(api, filePath, threadId, messageType) {
  if (!fs.existsSync(filePath)) {
    const msg = `❌ File không tồn tại: ${filePath}`;
    console.error("[uploadFileOnly]", msg);
    throw new Error(msg);
  }

 // console.log(`[uploadFileOnly] 📤 Bắt đầu upload file: ${filePath}`);

  try {
    const uploaded = await api.uploadAttachment([filePath], threadId, messageType);

    if (uploaded && uploaded.length > 0 && uploaded[0].fileUrl) {
      const fileInfo = uploaded[0];
      console.log(`[uploadFileOnly] Upload thành công:`, 
        {
        fileUrl: fileInfo.fileUrl,
        fileName: fileInfo.fileName,
        totalSize: fileInfo.totalSize,
        checksum: fileInfo.checksum
      });
      return fileInfo;
    } else {
      const msg = "❌ Upload thất bại: Không có fileUrl trả về.";
      console.error("[uploadFileOnly]", msg);
      throw new Error(msg);
    }
  } catch (err) {
    console.error("[uploadFileOnly] ❌ Lỗi upload:", err.message);
    throw err;
  }
}