OmegaBaSMS/uploader.js
2026-06-02 14:56:50 +03:00

53 lines
1.4 KiB
JavaScript

const config = require('./config');
function pad(n) {
return String(n).padStart(2, '0');
}
function buildFileName(originalName, ext) {
if (originalName) return originalName;
const now = new Date();
const base = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}_` +
`${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
return ext ? `${base}.${ext}` : base;
}
async function uploadMedia(base64Data, mimeType, ext, originalName) {
const url = config.appsScriptUrl;
if (!url) throw new Error('Missing Apps Script URL');
const fileName = buildFileName(originalName, ext);
const payload = JSON.stringify({
fileBase64: base64Data,
mimeType,
fileName,
});
try {
// Native fetch handles Google's 302 redirects cleanly
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: payload,
});
// Google Apps Script text output comes back as text first
const body = await response.text();
console.log('[GDRIVE] Raw response:', body);
const result = JSON.parse(body);
if (!result.success) {
throw new Error(result.error || 'Upload failed');
}
return result.url;
} catch (error) {
throw new Error('Apps Script communication failed: ' + error.message);
}
}
module.exports = { uploadMedia };