import { BadRequestException, HttpException, HttpStatus, Inject, Injectable, NotFoundException, } from '@nestjs/common'; import fs from 'node:fs'; import path from 'node:path'; import { DocumentRow } from '../domain/models'; import { DocumentConverterPort, DocumentRepository, DocumentSummary, type BlobStore, OcrPort, PdfTextExtractorPort, } from '../domain/ports'; import { DOCUMENT_CONVERTER, DOCUMENT_REPOSITORY, BLOB_STORE, OCR_SERVICE, PDF_TEXT_EXTRACTOR, } from '../domain/ports'; import { ForbiddenException } from '@nestjs/common'; import { BlobsService } from './blobs.service'; import { AiSettingsService } from './ai-settings.service'; // Below this number of extracted characters, a PDF is probably scanned. const OCR_TEXT_THRESHOLD = 100; export const PPTX_MIME = 'application/vnd.openxmlformats-officedocument.presentationml.presentation'; // Dedicated 422s: the upload/OCR produced nothing usable. class UnprocessableOcrException extends HttpException { constructor(message: string) { super({ error: message }, HttpStatus.UNPROCESSABLE_ENTITY); } } class UnprocessableConversionException extends HttpException { constructor(message: string) { super({ error: message }, HttpStatus.UNPROCESSABLE_ENTITY); } } export interface UploadedFile { originalname: string; filename: string; path: string; } @Injectable() export class DocumentsService { constructor( @Inject(DOCUMENT_REPOSITORY) private readonly documents: DocumentRepository, @Inject(PDF_TEXT_EXTRACTOR) private readonly pdfText: PdfTextExtractorPort, @Inject(OCR_SERVICE) private readonly ocr: OcrPort, @Inject(DOCUMENT_CONVERTER) private readonly converter: DocumentConverterPort, @Inject(BLOB_STORE) private readonly cas: BlobStore, private readonly blobs: BlobsService, private readonly aiSettings: AiSettingsService, ) {} // Documents are scoped to their uploader. A null owner (auth disabled) may // touch the ownerless rows; a real user may touch only their own. An // ownerless row is not readable by an authenticated user, so data created // while auth was off does not leak once accounts exist. async assertOwner(id: string, ownerId: string | null): Promise { const doc = await this.documents.findById(id); if (!doc) return; if ((doc.user_id ?? null) !== ownerId) { throw new ForbiddenException('You do not have access to this document'); } } async upload(file: UploadedFile | undefined, ownerId: string | null): Promise { if (!file) throw new BadRequestException('No file received'); const ext = path.extname(file.originalname).toLowerCase(); let text: string; let pageCount: number | null; let renderPath: string | null = null; if (ext === '.pdf') { const extracted = await this.pdfText.extract(file.path); text = extracted.text; pageCount = extracted.pageCount; // Scanned PDF: automatically fall back to OCR. if (!text || text.trim().length < OCR_TEXT_THRESHOLD) { try { const ocr = await this.ocr.ocrPdf(file.path, await this.aiSettings.get()); if (ocr.text && ocr.text.trim().length >= OCR_TEXT_THRESHOLD) text = ocr.text; } catch (e) { console.error('OCR failed on upload:', e); } } } else { // Any other accepted format: the converter (LibreOffice for office // files, pandoc for markup) renders the viewer's PDF preview; plain // text comes from pandoc or, failing that, from the render's text // layer. Without a preview the document would be unusable, so a // conversion failure rejects the upload (422) with the converter's // reason (e.g. the needed tool is not installed). const outPath = file.path.slice(0, -ext.length) + '.render.pdf'; try { await this.converter.convertToPdf(file.path, outPath); } catch (e) { if (fs.existsSync(file.path)) fs.unlinkSync(file.path); throw new UnprocessableConversionException((e as Error).message); } renderPath = outPath; try { text = (await this.converter.extractText(file.path)).trim(); } catch { text = ''; } // Page count (and fallback text) from the rendered PDF. try { const rendered = await this.pdfText.extract(outPath); pageCount = rendered.pageCount; if (!text) text = rendered.text; } catch { pageCount = null; } } // Everything byte-shaped also lands in the content-addressed store, so // local-first clients can fetch and cache by hash. const hashes = await this.storeInCas(file.path, renderPath, text, ownerId); return this.documents.create({ user_id: ownerId, original_name: file.originalname, filename: file.filename, filepath: file.path, extracted_text: text, page_count: pageCount, render_path: renderPath, ...hashes, }); } private async storeInCas( filepath: string, renderPath: string | null, text: string, ownerId: string | null, ): Promise<{ content_hash: string; render_hash: string | null; text_hash: string | null }> { const original = await this.cas.storeFile(filepath); this.cas.record(original.hash, mimeOf(filepath), original.size, ownerId); await this.blobs.claim(original.hash, ownerId); let render: { hash: string; size: number } | null = null; if (renderPath) { render = await this.cas.storeFile(renderPath); this.cas.record(render.hash, 'application/pdf', render.size, ownerId); await this.blobs.claim(render.hash, ownerId); } let textHash: string | null = null; if (text && text.trim()) { const stored = this.cas.storeBytes(Buffer.from(text, 'utf8')); this.cas.record(stored.hash, 'text/plain; charset=utf-8', stored.size, ownerId); await this.blobs.claim(stored.hash, ownerId); await this.blobs.claim(stored.hash, ownerId); textHash = stored.hash; } return { content_hash: original.hash, render_hash: render?.hash ?? null, text_hash: textHash }; } async getSummary(id: string, ownerId: string | null): Promise { await this.assertOwner(id, ownerId); const doc = await this.documents.summaryById(id); if (!doc) throw new NotFoundException('Document not found'); return doc; } async resolveFile( id: string, ownerId: string | null, ): Promise<{ filepath: string; contentType: string }> { await this.assertOwner(id, ownerId); const doc = await this.documents.findById(id); if (!doc) throw new NotFoundException('Document not found'); if (doc.render_path && fs.existsSync(doc.render_path)) { return { filepath: doc.render_path, contentType: 'application/pdf' }; } const ext = path.extname(doc.original_name || doc.filename || '').toLowerCase(); return { filepath: doc.filepath, contentType: ext === '.pptx' ? PPTX_MIME : 'application/pdf' }; } async reocr(id: string, ownerId: string | null): Promise<{ id: string; chars: number }> { await this.assertOwner(id, ownerId); const doc = await this.documents.findById(id); if (!doc) throw new NotFoundException('Document not found'); const ext = path.extname(doc.original_name || doc.filename || '').toLowerCase(); if (ext !== '.pdf') throw new BadRequestException('OCR is only available for PDFs'); if (!fs.existsSync(doc.filepath)) throw new NotFoundException('File not found on disk'); const ocr = await this.ocr.ocrPdf(doc.filepath, await this.aiSettings.get()); if (!ocr.text || ocr.text.trim().length < OCR_TEXT_THRESHOLD) { throw new UnprocessableOcrException('OCR did not produce any usable text'); } await this.documents.setExtractedText(id, ocr.text); const stored = this.cas.storeBytes(Buffer.from(ocr.text, 'utf8')); this.cas.record(stored.hash, 'text/plain; charset=utf-8', stored.size, ownerId); await this.blobs.claim(stored.hash, ownerId); await this.documents.setHashes(id, { content_hash: doc.content_hash ?? null, render_hash: doc.render_hash ?? null, text_hash: stored.hash, }); return { id, chars: ocr.text.length }; } async delete(id: string, ownerId: string | null): Promise { await this.assertOwner(id, ownerId); const doc = await this.documents.findById(id); if (doc) { this.unlinkFiles(doc); // Drop this owner's claim on the document's CAS blobs; the bytes are // deleted once no document (across any owner) still references them. await this.blobs.release( [doc.content_hash, doc.render_hash, doc.text_hash], doc.user_id ?? null, ); } await this.documents.delete(id); } private unlinkFiles(doc: DocumentRow): void { if (doc.filepath && fs.existsSync(doc.filepath)) fs.unlinkSync(doc.filepath); if (doc.render_path && fs.existsSync(doc.render_path)) fs.unlinkSync(doc.render_path); } } const MIME_BY_EXT: Record = { '.pdf': 'application/pdf', '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', '.md': 'text/markdown', '.txt': 'text/plain', '.html': 'text/html', '.htm': 'text/html', }; function mimeOf(filepath: string): string { return MIME_BY_EXT[path.extname(filepath).toLowerCase()] ?? 'application/octet-stream'; }