/* Copyright (C) 2025 QuantumNous This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ // 「WeyAi → 内容管理」的浏览器直传(M21):本地检查 → 申请上传地址 → 直传 COS → // 让后台核对。文件不经过 monkey-ai 服务器,不受 nginx 上传大小的限制。 import { API } from '../../../helpers'; /** Whether the server records and verifies the file's sha256 (mirrors ContentMediaRole.NeedsSha256). */ export const roleNeedsSha256 = (role) => Boolean(role?.cacheable) || role?.kind === 'zip'; /** Human readable size, e.g. 3 MB. */ export const formatBytes = (n) => { if (n >= 1 << 20) return `${Math.round((n / (1 << 20)) * 10) / 10} MB`; if (n >= 1 << 10) return `${Math.round(n / (1 << 10))} KB`; return `${n} B`; }; /** Content type the server expects; browsers report zip files inconsistently. */ export const contentTypeOf = (file, role) => { if (role?.kind === 'zip') return 'application/zip'; return file.type || ''; }; const sha256Hex = async (file) => { const digest = await crypto.subtle.digest( 'SHA-256', await file.arrayBuffer(), ); return Array.from(new Uint8Array(digest)) .map((b) => b.toString(16).padStart(2, '0')) .join(''); }; const readMediaMeta = (file, kind) => new Promise((resolve) => { const url = URL.createObjectURL(file); const done = (meta) => { URL.revokeObjectURL(url); resolve(meta); }; if (kind === 'video') { const video = document.createElement('video'); video.preload = 'metadata'; video.onloadedmetadata = () => done({ width: video.videoWidth, height: video.videoHeight, duration: Number.isFinite(video.duration) ? video.duration : 0, }); video.onerror = () => done({}); video.src = url; } else if (kind === 'image') { const img = new Image(); img.onload = () => done({ width: img.naturalWidth, height: img.naturalHeight }); img.onerror = () => done({}); img.src = url; } else { done({}); } }); const putWithProgress = (ticket, file, onProgress) => new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open(ticket.method || 'PUT', ticket.url); Object.entries(ticket.headers || {}).forEach(([k, v]) => xhr.setRequestHeader(k, v), ); xhr.upload.onprogress = (e) => { if (e.lengthComputable && onProgress) { onProgress(Math.round((e.loaded / e.total) * 100)); } }; xhr.onload = () => xhr.status >= 200 && xhr.status < 300 ? resolve() : reject(new Error(`HTTP ${xhr.status}`)); xhr.onerror = () => reject(new Error('network')); xhr.send(file); }); /** * Uploads one file for a slot role and returns the confirmed object. * Throws an Error whose message is meant for the administrator; `code` is * 'cors' when the browser could not reach the bucket at all. */ export const uploadContentFile = async ({ slot, role, file, onProgress }) => { const contentType = contentTypeOf(file, role); const [meta, sha256] = await Promise.all([ readMediaMeta(file, role.kind), roleNeedsSha256(role) ? sha256Hex(file) : Promise.resolve(''), ]); const signed = await API.post( '/api/admin/weyai/content/uploads', { slot, role: role.key, content_type: contentType, size: file.size }, { skipErrorHandler: true }, ); if (!signed?.data?.success) { throw new Error(signed?.data?.message || 'sign failed'); } try { await putWithProgress(signed.data.data, file, onProgress); } catch (e) { const err = new Error(e.message); err.code = e.message === 'network' ? 'cors' : 'upload'; throw err; } const confirmed = await API.post( '/api/admin/weyai/content/uploads/confirm', { key: signed.data.data.key, sha256, width: Math.round(meta.width || 0), height: Math.round(meta.height || 0), duration: meta.duration || 0, }, { skipErrorHandler: true }, ); if (!confirmed?.data?.success) { throw new Error(confirmed?.data?.message || 'confirm failed'); } return confirmed.data.data; };