import { bytesToBase64Url } from './crypto-utils.js'; import { computeTorrentV2PieceRoot, TorrentV2PieceAccumulator, TORRENT_V2_PIECE_BYTES } from './torrent-v2-service.js'; export const R2_MAX_FILE_BYTES = 500 * 1024 * 1024; const mimeByExtension = { mp4: 'video/mp4', webm: 'video/webm', jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', webp: 'image/webp', gif: 'image/gif', pdf: 'application/pdf', mp3: 'audio/mpeg', zip: 'application/zip', txt: 'text/plain' }; export function fileMime(file) { const extension = String(file?.name || '').toLowerCase().split('.').pop(); const value = String(file?.type || mimeByExtension[extension] || 'application/octet-stream').trim(); return /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i.test(value) && value.length <= 127 ? value : 'application/octet-stream'; } export async function preparePublicFile(file, { onProgress = null } = {}) { if (!(file instanceof Blob) || !file.size) throw new Error('Выберите непустой файл'); const accumulator = new TorrentV2PieceAccumulator(); for (let offset = 0; offset < file.size; offset += TORRENT_V2_PIECE_BYTES) { const bytes = new Uint8Array(await file.slice(offset, offset + TORRENT_V2_PIECE_BYTES).arrayBuffer()); const piece = await computeTorrentV2PieceRoot(bytes, { padToPieceLength: file.size > TORRENT_V2_PIECE_BYTES }); await accumulator.addPieceRoot(piece); onProgress?.(Math.min(file.size, offset + bytes.byteLength), file.size); } const root = await accumulator.finalize(); return { file, name: String(file.name || 'file'), size: file.size, mm: fileMime(file), pr: bytesToBase64Url(root) }; }