import crypto from 'crypto'; import { GitError } from '../git/errors.js'; import { AssetError, formatBytes } from './errors.js'; import { sniffImageType, typeFromMime } from './sniff.js'; import { buildRepoPath, mimeFor, altText, assetUrl } from './paths.js'; // Upload von Bildern in das verbundene Repo (ADR 0004 §2). Nutzt die Git-Schicht aus ADR 0003. export const createAssetService = ({ cfg, gitSvc, getStorage, logger = console })=>{ const storage = ()=>getStorage(); const result = (brew, asset)=>({ url : assetUrl(brew.shareId, asset.sha256, typeFromMime(asset.contentType)), path : asset.repoPath, sha256 : asset.sha256, size : asset.size, contentType : asset.contentType, markdown : `![${altText(asset.filename)}](${assetUrl(brew.shareId, asset.sha256, typeFromMime(asset.contentType))})` }); const svc = { enabled : cfg.enabled && gitSvc.enabled, cfg, // Öffentliche Einstellungen für den Client (keine Geheimnisse) clientConfig() { return { enabled: svc.enabled, maxBytes: cfg.maxBytes, maxBytesPerBrew: cfg.maxBytesPerBrew, types: cfg.types }; }, /** * @param {object} account req.account * @param {string} editId * @param {{ body: Buffer, contentType?: string, filename?: string }} input * @returns {Promise<{ created: boolean, asset: object }>} */ async upload(account, editId, { body, contentType, filename }) { if(!svc.enabled) throw new AssetError('A07'); const brew = await gitSvc.loadEditableBrew(editId, account); if(brew.lock) throw new AssetError('A04'); const link = await storage().brewGitLinks.findByBrewId(brew.id); if(!link) throw new AssetError('A05'); const conn = await storage().gitConnections.findById(link.connectionId); if(!conn) throw new GitError('G08', 'Die Git-Verbindung dieses Brews existiert nicht mehr.'); if(!Buffer.isBuffer(body) || body.length === 0) throw new AssetError('A06'); if(body.length > cfg.maxBytes) throw new AssetError('A01', `Das Bild ist zu groß (${formatBytes(body.length)}). Erlaubt sind höchstens ${formatBytes(cfg.maxBytes)}.`); const type = sniffImageType(body); const declared = typeFromMime(contentType); if(!type || !cfg.types.includes(type)) throw new AssetError('A02', `Dieser Dateityp ist nicht erlaubt. Erlaubt sind: ${cfg.types.join(', ').toUpperCase()}.`); if(declared !== type) throw new AssetError('A02', `Der Dateityp stimmt nicht mit dem Inhalt überein (erkannt: ${type.toUpperCase()}).`); const sha256 = crypto.createHash('sha256').update(body).digest('hex'); const author = await gitSvc.authorOf(account); // Dedupe, Limitprüfung, Commit und Snapshot unter einem Lock pro Brew, sonst Race beim Brew-Limit return gitSvc.locks.withKey(brew.id, async ()=>{ const existing = await storage().brewAssets.findByBrewAndHash(brew.id, sha256); if(existing) return { created: false, asset: { ...existing, filename }, brew }; const used = await storage().brewAssets.sumSizeByBrew(brew.id); if(used + body.length > cfg.maxBytesPerBrew) throw new AssetError('A03', `Das Speicherlimit für Bilder dieses Brews (${formatBytes(cfg.maxBytesPerBrew)}) wäre überschritten. Belegt: ${formatBytes(used)}.`); const repoPath = buildRepoPath({ assetsDir: conn.assetsDir, filename, sha256, type }); const { commit } = await gitSvc.commitContent(conn, { branch : link.branch, filePath : repoPath, content : body, author, message : `Add asset ${repoPath} via Homebrewery`, maxBytes : cfg.maxBytes, ignoreConflict : true // inhaltsadressierter Pfad: ein vorhandener Blob ist derselbe Inhalt }); // Snapshot erst nach erfolgreichem Push (ADR 0004 §2) const asset = await storage().brewAssets.create({ brewId: brew.id, sha256, repoPath, commitSha: commit, contentType: mimeFor(type), size: body.length, data: body }); return { created: true, asset: { ...asset, filename }, brew }; }); }, toResponse : result }; return svc; };