Spaces:
Running
Running
Update utils/file.js
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748const fs = require('fs');const path = require('path');const { ALLOWED_EXTENSIONS } = require('../constants/allowed');const extractCloudinaryId = (url) => {if (!url) return null;const match = url.match(/\/v\d+\/(4send_cloud\/[^\.]+)/) || url.match(/(4send_cloud\/[^\.]+)/);return match ? match[1] : null;};const detectFileSignature = (buf) => {if (!buf || buf.length < 16) return null;const hex = buf.slice(0, 16).toString('hex').toLowerCase();const ascii = buf.slice(0, 16).toString('latin1');if (hex.startsWith('ffd8ff')) return 'image';if (hex.startsWith('89504e47')) return 'image';if (ascii.startsWith('GIF87a') || ascii.startsWith('GIF89a')) return 'image';if (ascii.startsWith('RIFF') && buf.slice(8, 12).toString('latin1') === 'WEBP') return 'image';if (ascii.startsWith('RIFF') && buf.slice(8, 12).toString('latin1') === 'WAVE') return 'media';if (hex.startsWith('494433') || hex.startsWith('fffb') || hex.startsWith('fff3') || hex.startsWith('fff2')) return 'media';if (ascii.startsWith('OggS')) return 'media';if (buf.slice(4, 8).toString('latin1') === 'ftyp') return 'media';if (hex.startsWith('1a45dfa3')) return 'media';return null;};const verifyUploadedFile = async (filePath, ext) => {if (!ALLOWED_EXTENSIONS.includes(ext)) return false;const fsPromises = require('fs').promises;const fd = await fsPromises.open(filePath, 'r');try {const buf = Buffer.alloc(16);await fd.read(buf, 0, 16, 0);const detectedType = detectFileSignature(buf);if (!detectedType) return false;const imageExts = ['.jpg', '.jpeg', '.png', '.webp', '.gif'];const mediaExts = ['.mp3', '.wav', '.ogg', '.m4a', '.mp4', '.webm', '.mov'];if (imageExts.includes(ext)) return detectedType === 'image';if (mediaExts.includes(ext)) return detectedType === 'media';return false;} finally {await fd.close();}};module.exports = { extractCloudinaryId, detectFileSignature, verifyUploadedFile };1234567const extractCloudinaryId = (url) => {if (!url) return null;const match = url.match(/\/v\d+\/(4send_cloud\/[^\.]+)/) || url.match(/(4send_cloud\/[^\.]+)/);return match ? match[1] : null;};module.exports = { extractCloudinaryId };
utils/file.js+1-42