~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
feat: add encrypted database storage for PDFs
LearningCircuit8d7bb38d1a2c
diff --git a/src/local_deep_research/database/models/library.py b/src/local_deep_research/database/models/library.pyindex 82893f9bc4..469e28bfcf 100644--- a/src/local_deep_research/database/models/library.py+++ b/src/local_deep_research/database/models/library.py@@ -15,6 +15,7 @@ from sqlalchemy import (ForeignKey,Index,Integer,+ LargeBinary,String,Text,UniqueConstraint,@@ -101,6 +102,14 @@ class SplitterType(str, enum.Enum):SENTENCE = "sentence"+class PDFStorageMode(str, enum.Enum):+ """Storage modes for PDF files."""++ NONE = "none" # Don't store PDFs, text-only+ FILESYSTEM = "filesystem" # Store PDFs unencrypted on filesystem+ DATABASE = "database" # Store PDFs encrypted in database++class SourceType(Base):"""Document source types (research_download, user_upload, manual_entry, etc.).@@ -215,6 +224,11 @@ class Document(Base):Text, nullable=True) # Extracted/uploaded text content+ # PDF storage mode (none, filesystem, database)+ storage_mode = Column(+ String(20), nullable=True, default="none"+ ) # PDFStorageMode value+# Metadatatitle = Column(Text) # Document titledescription = Column(Text) # User description@@ -292,6 +306,41 @@ class Document(Base):return f"<Document(title='{title_str}', type={self.file_type}, size={self.file_size})>"+class DocumentBlob(Base):+ """+ Separate table for storing PDF binary content.+ SQLite best practices: keep BLOBs in separate table for better query performance.+ Stored in encrypted SQLCipher database for security.+ """++ __tablename__ = "document_blobs"++ # Primary key references Document.id+ document_id = Column(+ String(36),+ ForeignKey("documents.id", ondelete="CASCADE"),+ primary_key=True,+ nullable=False,+ )++ # Binary PDF content+ pdf_binary = Column(LargeBinary, nullable=False)++ # Hash for integrity verification+ blob_hash = Column(String(64), nullable=True, index=True) # SHA256++ # Timestamps+ stored_at = Column(UtcDateTime, default=utcnow(), nullable=False)+ last_accessed = Column(UtcDateTime, nullable=True)++ # Relationship+ document = relationship("Document", backref="blob")++ def __repr__(self):+ size = len(self.pdf_binary) if self.pdf_binary else 0+ return f"<DocumentBlob(document_id='{self.document_id[:8]}...', size={size})>"++class Collection(Base):"""Collections for organizing documents.diff --git a/src/local_deep_research/defaults/research_library/library_settings.json b/src/local_deep_research/defaults/research_library/library_settings.jsonindex a35624d834..a4f4edea4f 100644--- a/src/local_deep_research/defaults/research_library/library_settings.json+++ b/src/local_deep_research/defaults/research_library/library_settings.json@@ -29,19 +29,47 @@"visible": true,"env_var": "RESEARCH_LIBRARY_SHARED_LIBRARY"},- "research_library.enable_pdf_storage": {+ "research_library.pdf_storage_mode": {"category": "research_library",- "description": "⚠️ PRIVACY WARNING: PDFs will be stored unencrypted on disk, exposing your research interests to anyone with filesystem access. Only enable if you need PDF files for external tools.",+ "description": "Choose how PDFs are stored. Database mode encrypts PDFs in your personal database (secure, portable). Filesystem mode stores unencrypted files on disk (faster, compatible with external tools). None stores only text content (most private).","editable": true,"max_value": null,"min_value": null,- "name": "Enable PDF Storage",+ "name": "PDF Storage Mode",+ "options": [+ {+ "value": "database",+ "label": "Database (Encrypted, Portable)"+ },+ {+ "value": "filesystem",+ "label": "Filesystem (Unencrypted, Faster)"+ },+ {+ "value": "none",+ "label": "None (Text Only)"+ }+ ],+ "step": null,+ "type": "APP",+ "ui_element": "select",+ "value": "database",+ "visible": true,+ "env_var": "RESEARCH_LIBRARY_PDF_STORAGE_MODE"+ },+ "research_library.enable_pdf_storage": {+ "category": "research_library",+ "description": "DEPRECATED: Use pdf_storage_mode instead. Kept for backward compatibility.",+ "editable": false,+ "max_value": null,+ "min_value": null,+ "name": "Enable PDF Storage (Legacy)","options": null,"step": null,"type": "APP","ui_element": "checkbox","value": false,- "visible": true,+ "visible": false,"env_var": "RESEARCH_LIBRARY_ENABLE_PDF_STORAGE"},"rag.indexing_batch_size": {diff --git a/src/local_deep_research/research_library/routes/library_routes.py b/src/local_deep_research/research_library/routes/library_routes.pyindex f2236da527..7592c70d9a 100644--- a/src/local_deep_research/research_library/routes/library_routes.py+++ b/src/local_deep_research/research_library/routes/library_routes.py@@ -8,6 +8,7 @@ Provides web endpoints for:"""import json+from io import BytesIOfrom pathlib import Pathfrom urllib.parse import urlparsefrom flask import (@@ -28,6 +29,7 @@ from ...database.session_context import get_user_db_sessionfrom ...database.models.research import ResearchResourcefrom ...database.models.library import (Document as Document,+ DocumentBlob,DocumentStatus,DownloadQueue as LibraryDownloadQueue,Collection,@@ -200,9 +202,11 @@ def library_page():from ...utilities.db_utils import get_settings_managersettings = get_settings_manager()- enable_pdf_storage = settings.get_setting(- "research_library.enable_pdf_storage", False+ pdf_storage_mode = settings.get_setting(+ "research_library.pdf_storage_mode", "database")+ # Enable PDF storage button if mode is not "none"+ enable_pdf_storage = pdf_storage_mode != "none"shared_library = settings.get_setting("research_library.shared_library", False)@@ -241,6 +245,7 @@ def library_page():selected_collection=collection_filter,storage_path=stats.get("storage_path", ""),enable_pdf_storage=enable_pdf_storage,+ pdf_storage_mode=pdf_storage_mode,shared_library=shared_library,)@@ -274,9 +279,11 @@ def download_manager_page():from ...utilities.db_utils import get_settings_managersettings = get_settings_manager()- enable_pdf_storage = settings.get_setting(- "research_library.enable_pdf_storage", False+ pdf_storage_mode = settings.get_setting(+ "research_library.pdf_storage_mode", "database")+ # Enable PDF storage button if mode is not "none"+ enable_pdf_storage = pdf_storage_mode != "none"shared_library = settings.get_setting("research_library.shared_library", False)@@ -322,6 +329,7 @@ def download_manager_page():already_downloaded=already_downloaded,available_to_download=available_to_download,enable_pdf_storage=enable_pdf_storage,+ pdf_storage_mode=pdf_storage_mode,shared_library=shared_library,)@@ -432,44 +440,67 @@ def get_pdf_url(document_id):@library_bp.route("/document/<string:document_id>/pdf")@login_requireddef view_pdf_page(document_id):- """Page for viewing PDF file."""+ """Page for viewing PDF file - database first, filesystem fallback."""username = session.get("username")- service = LibraryService(username)- # Get the specific document by ID- document = service.get_document_by_id(document_id)- if not document:- logger.warning(- f"Document ID {document_id} not found in database for user {username}"- )- return "Document not found", 404+ with get_user_db_session(username) as db_session:+ # Get document from database+ document = db_session.query(Document).filter_by(id=document_id).first()- file_path = document.get("file_absolute_path")- logger.info(- f"Document {document_id}: title='{document.get('document_title')}', file_exists={document.get('file_exists')}, downloaded_successfully={document.get('downloaded_successfully')}, file_path={file_path}"- )+ if not document:+ logger.warning(+ f"Document ID {document_id} not found in database for user {username}"+ )+ return "Document not found", 404- # Check if PDF storage is enabled- if file_path is None:- logger.warning(- f"Document {document_id} has no file path - PDF may not have been downloaded (privacy mode or download failed)"- )- return (- "PDF not downloaded. Enable PDF storage in settings and use Download Manager to download this file.",- 404,+ logger.info(+ f"Document {document_id}: title='{document.title}', "+ f"file_path={document.file_path}")- if file_path and Path(file_path).exists():- logger.info(f"Serving PDF: {file_path}")- return send_file(- file_path,- mimetype="application/pdf",- as_attachment=False,- download_name=document.get("file_name", "document.pdf"),+ # 1. First check database for blob (regardless of storage_mode)+ blob = (+ db_session.query(DocumentBlob)+ .filter_by(document_id=document_id)+ .first())- logger.error(f"PDF file not found on disk: {file_path}")- return "PDF file not found", 404+ if blob and blob.pdf_binary:+ logger.info(+ f"Serving PDF from database: {document_id} "+ f"({len(blob.pdf_binary)} bytes)"+ )+ return send_file(+ BytesIO(blob.pdf_binary),+ mimetype="application/pdf",+ as_attachment=False,+ download_name=document.filename or "document.pdf",+ )++ # 2. Fallback to filesystem+ if document.file_path and document.file_path != "metadata_only":+ # Get library root from settings+ settings = get_settings_manager(username)+ library_root = settings.get_setting(+ "research_library.storage_path",+ str(Path.home() / ".local-deep-research" / "library"),+ )+ file_path = Path(library_root) / document.file_path++ if file_path.exists():+ logger.info(f"Serving PDF from filesystem: {file_path}")+ return send_file(+ str(file_path),+ mimetype="application/pdf",+ as_attachment=False,+ download_name=document.filename or "document.pdf",+ )++ logger.warning(f"PDF file not found on disk: {file_path}")++ # 3. No PDF found anywhere+ logger.warning(f"No PDF available for document {document_id}")+ return "PDF not available", 404@library_bp.route("/api/document/<string:document_id>/pdf")diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.pyindex 67cca93fa2..c717c7651c 100644--- a/src/local_deep_research/research_library/services/download_service.py+++ b/src/local_deep_research/research_library/services/download_service.py@@ -35,11 +35,11 @@ from ...database.models.library import (DownloadQueue as LibraryDownloadQueue,DocumentCollection,)+from .pdf_storage_manager import PDFStorageManagerfrom ...database.models.research import ResearchResourcefrom ...database.library_init import get_source_type_id, get_default_library_idfrom ...database.session_context import get_user_db_sessionfrom ...utilities.db_utils import get_settings_manager-from ...security.path_validator import PathValidatorfrom ...library.download_management import RetryManagerfrom ..utils import (get_url_hash,@@ -523,12 +523,12 @@ class DownloadService:logger.info(f"Download failed with reason: {error_msg}")return False, error_msg- # Check if PDF storage is enabled- enable_pdf_storage = self.settings.get_setting(- "research_library.enable_pdf_storage", False+ # Get PDF storage mode setting+ pdf_storage_mode = self.settings.get_setting(+ "research_library.pdf_storage_mode", "none")logger.info(- f"[DOWNLOAD_SERVICE] PDF storage setting retrieved: {enable_pdf_storage} (type: {type(enable_pdf_storage)})"+ f"[DOWNLOAD_SERVICE] PDF storage mode: {pdf_storage_mode}")# Update tracker@@ -539,22 +539,11 @@ class DownloadService:tracker.is_downloaded = Truetracker.downloaded_at = datetime.now(UTC)- # Only save PDF file if storage is enabled- if enable_pdf_storage:- # Save file- file_path = self._save_pdf(resource, pdf_content)- # Store only relative path- tracker.file_path = str(- Path(file_path).relative_to(self.library_root)- )- tracker.file_name = Path(file_path).name- else:- # PDF storage disabled - only store metadata- tracker.file_path = None- tracker.file_name = None- logger.info(- "PDF storage disabled - only storing metadata and text"- )+ # Initialize PDF storage manager+ pdf_storage_manager = PDFStorageManager(+ library_root=self.library_root,+ storage_mode=pdf_storage_mode,+ )# Update attempt with success infoattempt.succeeded = True@@ -569,12 +558,29 @@ class DownloadService:if existing_doc:# Update existing documentexisting_doc.document_hash = tracker.file_hash- existing_doc.file_path = (- tracker.file_path if tracker.file_path else "metadata_only"- )existing_doc.file_size = len(pdf_content)existing_doc.status = DocumentStatus.COMPLETEDexisting_doc.processed_at = datetime.now(UTC)++ # Save PDF using storage manager (updates storage_mode and file_path)+ file_path_result, _ = pdf_storage_manager.save_pdf(+ pdf_content=pdf_content,+ document=existing_doc,+ session=session,+ filename=f"{resource.id}.pdf",+ url=url,+ resource_id=resource.id,+ )++ # Update tracker+ tracker.file_path = (+ file_path_result if file_path_result else None+ )+ tracker.file_name = (+ Path(file_path_result).name+ if file_path_result and file_path_result != "database"+ else None+ )else:# Get source type ID for research downloadstry:@@ -600,17 +606,36 @@ class DownloadService:research_id=resource.research_id,document_hash=tracker.file_hash,original_url=url,- file_path=tracker.file_path- if tracker.file_path- else "metadata_only",file_size=len(pdf_content),file_type="pdf",mime_type="application/pdf",title=resource.title,status=DocumentStatus.COMPLETED,processed_at=datetime.now(UTC),+ storage_mode=pdf_storage_mode,)session.add(doc)+ session.flush() # Ensure doc.id is available for blob storage++ # Save PDF using storage manager (updates storage_mode and file_path)+ file_path_result, _ = pdf_storage_manager.save_pdf(+ pdf_content=pdf_content,+ document=doc,+ session=session,+ filename=f"{resource.id}.pdf",+ url=url,+ resource_id=resource.id,+ )++ # Update tracker+ tracker.file_path = (+ file_path_result if file_path_result else None+ )+ tracker.file_name = (+ Path(file_path_result).name+ if file_path_result and file_path_result != "database"+ else None+ )# Link document to default Library collectiondoc_collection = DocumentCollection(@@ -624,7 +649,11 @@ class DownloadService:attempt.succeeded = Trueattempt.bytes_downloaded = len(pdf_content)- if enable_pdf_storage:+ if pdf_storage_mode == "database":+ logger.info(+ f"Successfully stored PDF in database: {resource.url}"+ )+ elif pdf_storage_mode == "filesystem":logger.info(f"Successfully downloaded: {tracker.file_path}")else:logger.info(f"Successfully extracted text from: {resource.url}")@@ -679,70 +708,6 @@ class DownloadService:safe_error = redact_data(str(e))return False, safe_error- def _save_pdf(self, resource: ResearchResource, content: bytes) -> str:- """- Save PDF content to disk with organized structure.-- Returns:- Absolute path to saved file- """- # Generate filename- domain = urlparse(resource.url).netloc.replace(".", "_")- timestamp = datetime.now(UTC).strftime("%Y%m%d")-- # Try to extract identifier from URL- parsed_url = urlparse(resource.url)- hostname = parsed_url.hostname or ""-- if hostname == "arxiv.org" or hostname.endswith(".arxiv.org"):- # Extract arXiv ID- match = re.search(r"(\d{4}\.\d{4,5})", resource.url)- if match:- filename = f"arxiv_{match.group(1)}.pdf"- else:- filename = f"arxiv_{timestamp}_{resource.id}.pdf"- elif hostname == "ncbi.nlm.nih.gov" and "/pmc" in parsed_url.path:- # Extract PMC ID- match = re.search(r"(PMC\d+)", resource.url)- if match:- filename = f"pmc_{match.group(1)}.pdf"- else:- filename = f"pubmed_{timestamp}_{resource.id}.pdf"- else:- # Generic filename- safe_title = re.sub(r"[^\w\s-]", "", resource.title or "")[:50]- filename = f"{domain}_{safe_title}_{resource.id}.pdf"-- # Create simple flat directory structure - all PDFs in one folder- pdf_path = Path(self.library_root) / "pdfs"- pdf_path.mkdir(parents=True, exist_ok=True)-- # Use PathValidator with relative path from library_root- # Pass the relative path "pdfs/filename" for validation- relative_path = f"pdfs/{filename}"- validated_path = PathValidator.validate_safe_path(- relative_path,- base_dir=str(self.library_root),- required_extensions=(".pdf",),- )-- if not validated_path:- raise ValueError("Invalid file path")-- # Write the PDF file with security verification- from ...security.file_write_verifier import write_file_verified-- write_file_verified(- validated_path,- content,- "research_library.enable_pdf_storage",- True,- "library PDF storage",- mode="wb",- )-- return str(validated_path)-def _extract_text_from_pdf(self, pdf_content: bytes) -> Optional[str]:"""Extract text from PDF content using multiple methods for best results.diff --git a/src/local_deep_research/research_library/services/library_service.py b/src/local_deep_research/research_library/services/library_service.pyindex 85ce002250..6e4b788f77 100644--- a/src/local_deep_research/research_library/services/library_service.py+++ b/src/local_deep_research/research_library/services/library_service.py@@ -277,7 +277,10 @@ class LibraryService:get_absolute_path_from_settings(doc.file_path))- has_pdf = bool(file_absolute_path)+ # Check if PDF is available (filesystem OR database)+ has_pdf = (+ bool(file_absolute_path) or doc.storage_mode == "database"+ )has_text_db = bool(doc.text_content) # Text now in Document# Use DocumentCollection from query results@@ -566,8 +569,8 @@ class LibraryService:len(doc.text_content.split()) if doc.text_content else 0)- # Check if actual PDF file exists (not just text_only_not_stored)- has_pdf = bool(+ # Check if PDF is available (database OR filesystem)+ has_pdf = doc.storage_mode == "database" or bool(doc.file_pathand doc.file_path != "metadata_only"and doc.file_path != "text_only_not_stored"@@ -585,10 +588,14 @@ class LibraryService:"file_absolute_path": str(get_absolute_path_from_settings(doc.file_path))- if has_pdf+ if doc.file_path+ and doc.file_path+ not in ("metadata_only", "text_only_not_stored")else None,"file_name": Path(doc.file_path).name- if has_pdf+ if doc.file_path+ and doc.file_path+ not in ("metadata_only", "text_only_not_stored")else doc.filename,"file_size": doc.file_size,"file_type": doc.file_type,diff --git a/src/local_deep_research/research_library/services/pdf_storage_manager.py b/src/local_deep_research/research_library/services/pdf_storage_manager.pynew file mode 100644index 0000000000..8fa26df7ca--- /dev/null+++ b/src/local_deep_research/research_library/services/pdf_storage_manager.py@@ -0,0 +1,312 @@+"""+PDF Storage Manager for Research Library++Handles PDF storage across three modes:+- none: Don't store PDFs (text-only)+- filesystem: Store PDFs unencrypted on disk (fast, external tool compatible)+- database: Store PDFs encrypted in SQLCipher database (secure, portable)+"""++import hashlib+import re+from datetime import datetime, UTC+from pathlib import Path+from typing import Optional, Tuple+from urllib.parse import urlparse++from loguru import logger++from ...database.models.library import DocumentBlob+from ...security.path_validator import PathValidator+++class PDFStorageManager:+ """Unified interface for PDF storage across all modes."""++ def __init__(self, library_root: Path, storage_mode: str):+ """+ Initialize PDF storage manager.++ Args:+ library_root: Base directory for filesystem storage+ storage_mode: One of 'none', 'filesystem', 'database'+ """+ self.library_root = Path(library_root)+ self.storage_mode = storage_mode++ if storage_mode not in ("none", "filesystem", "database"):+ logger.warning(+ f"Unknown storage mode '{storage_mode}', defaulting to 'none'"+ )+ self.storage_mode = "none"++ def save_pdf(+ self,+ pdf_content: bytes,+ document,+ session,+ filename: str,+ url: Optional[str] = None,+ resource_id: Optional[int] = None,+ ) -> Tuple[Optional[str], int]:+ """+ Save PDF based on configured storage mode.++ Args:+ pdf_content: Raw PDF bytes+ document: Document model instance+ session: Database session+ filename: Filename to use for saving+ url: Source URL (for generating better filenames)+ resource_id: Resource ID (for generating better filenames)++ Returns:+ Tuple of (file_path or storage indicator, file_size)+ - For filesystem: relative path string+ - For database: "database"+ - For none: None+ """+ file_size = len(pdf_content)++ if self.storage_mode == "none":+ logger.debug("PDF storage mode is 'none' - skipping PDF save")+ return None, file_size++ elif self.storage_mode == "filesystem":+ file_path = self._save_to_filesystem(+ pdf_content, filename, url, resource_id+ )+ relative_path = str(file_path.relative_to(self.library_root))+ document.storage_mode = "filesystem"+ document.file_path = relative_path+ logger.info(f"PDF saved to filesystem: {relative_path}")+ return relative_path, file_size++ elif self.storage_mode == "database":+ self._save_to_database(pdf_content, document, session)+ document.storage_mode = "database"+ document.file_path = None # No filesystem path+ logger.info(f"PDF saved to database for document {document.id}")+ return "database", file_size++ return None, file_size++ def load_pdf(self, document, session) -> Optional[bytes]:+ """+ Load PDF - check database first, then filesystem.++ Smart retrieval: doesn't rely on storage_mode column, actually checks+ where the PDF exists.++ Args:+ document: Document model instance+ session: Database session++ Returns:+ PDF bytes or None if not available+ """+ # 1. Check database first+ pdf_bytes = self._load_from_database(document, session)+ if pdf_bytes:+ logger.debug(f"Loaded PDF from database for document {document.id}")+ return pdf_bytes++ # 2. Fallback to filesystem+ pdf_bytes = self._load_from_filesystem(document)+ if pdf_bytes:+ logger.debug(+ f"Loaded PDF from filesystem for document {document.id}"+ )+ return pdf_bytes++ logger.debug(f"No PDF available for document {document.id}")+ return None++ def _infer_storage_mode(self, document) -> str:+ """+ Infer storage mode for documents without explicit mode set.+ Used for backward compatibility with existing documents.+ """+ # If there's a blob, it's database storage+ if hasattr(document, "blob") and document.blob:+ return "database"+ # If there's a file_path (and not 'metadata_only'), it's filesystem+ if document.file_path and document.file_path != "metadata_only":+ return "filesystem"+ # Otherwise no storage+ return "none"++ def _save_to_filesystem(+ self,+ pdf_content: bytes,+ filename: str,+ url: Optional[str] = None,+ resource_id: Optional[int] = None,+ ) -> Path:+ """+ Save PDF to filesystem with organized structure.++ Returns:+ Absolute path to saved file+ """+ # Generate better filename if URL is provided+ if url:+ filename = self._generate_filename(url, resource_id, filename)++ # Create simple flat directory structure - all PDFs in one folder+ pdf_path = self.library_root / "pdfs"+ pdf_path.mkdir(parents=True, exist_ok=True)++ # Use PathValidator with relative path from library_root+ relative_path = f"pdfs/{filename}"+ validated_path = PathValidator.validate_safe_path(+ relative_path,+ base_dir=str(self.library_root),+ required_extensions=(".pdf",),+ )++ if not validated_path:+ raise ValueError("Invalid file path")++ # Write the PDF file with security verification+ from ...security.file_write_verifier import write_file_verified++ write_file_verified(+ validated_path,+ pdf_content,+ "research_library.pdf_storage_mode",+ "filesystem",+ "library PDF storage",+ mode="wb",+ )++ return Path(validated_path)++ def _save_to_database(self, pdf_content: bytes, document, session) -> None:+ """Store PDF in document_blobs table."""+ # Check if blob already exists+ existing_blob = (+ session.query(DocumentBlob)+ .filter_by(document_id=document.id)+ .first()+ )++ if existing_blob:+ # Update existing blob+ existing_blob.pdf_binary = pdf_content+ existing_blob.blob_hash = hashlib.sha256(pdf_content).hexdigest()+ existing_blob.stored_at = datetime.now(UTC)+ logger.debug(f"Updated existing blob for document {document.id}")+ else:+ # Create new blob+ blob = DocumentBlob(+ document_id=document.id,+ pdf_binary=pdf_content,+ blob_hash=hashlib.sha256(pdf_content).hexdigest(),+ stored_at=datetime.now(UTC),+ )+ session.add(blob)+ logger.debug(f"Created new blob for document {document.id}")++ def _load_from_filesystem(self, document) -> Optional[bytes]:+ """Load PDF from filesystem."""+ if not document.file_path or document.file_path == "metadata_only":+ return None++ file_path = self.library_root / document.file_path++ if not file_path.exists():+ logger.warning(f"PDF file not found: {file_path}")+ return None++ try:+ return file_path.read_bytes()+ except Exception:+ logger.exception(f"Failed to read PDF from {file_path}")+ return None++ def _load_from_database(self, document, session) -> Optional[bytes]:+ """Load PDF from document_blobs table."""+ blob = (+ session.query(DocumentBlob)+ .filter_by(document_id=document.id)+ .first()+ )++ if not blob:+ logger.debug(f"No blob found for document {document.id}")+ return None++ # Update last accessed timestamp+ blob.last_accessed = datetime.now(UTC)++ return blob.pdf_binary++ def _generate_filename(+ self, url: str, resource_id: Optional[int], fallback_filename: str+ ) -> str:+ """Generate a meaningful filename from URL."""+ parsed_url = urlparse(url)+ hostname = parsed_url.hostname or ""+ timestamp = datetime.now(UTC).strftime("%Y%m%d")++ if hostname == "arxiv.org" or hostname.endswith(".arxiv.org"):+ # Extract arXiv ID+ match = re.search(r"(\d{4}\.\d{4,5})", url)+ if match:+ return f"arxiv_{match.group(1)}.pdf"+ return f"arxiv_{timestamp}_{resource_id or 'unknown'}.pdf"++ elif hostname == "ncbi.nlm.nih.gov" and "/pmc" in parsed_url.path:+ # Extract PMC ID+ match = re.search(r"(PMC\d+)", url)+ if match:+ return f"pmc_{match.group(1)}.pdf"+ return f"pubmed_{timestamp}_{resource_id or 'unknown'}.pdf"++ # Use fallback filename+ return fallback_filename++ def delete_pdf(self, document, session) -> bool:+ """+ Delete PDF for a document.++ Args:+ document: Document model instance+ session: Database session++ Returns:+ True if deletion succeeded+ """+ storage_mode = document.storage_mode or self._infer_storage_mode(+ document+ )++ try:+ if storage_mode == "filesystem":+ if document.file_path and document.file_path != "metadata_only":+ file_path = self.library_root / document.file_path+ if file_path.exists():+ file_path.unlink()+ logger.info(f"Deleted PDF file: {file_path}")+ document.file_path = None+ document.storage_mode = "none"+ return True++ elif storage_mode == "database":+ blob = (+ session.query(DocumentBlob)+ .filter_by(document_id=document.id)+ .first()+ )+ if blob:+ session.delete(blob)+ logger.info(f"Deleted PDF blob for document {document.id}")+ document.storage_mode = "none"+ return True++ return True # Nothing to delete for 'none' mode++ except Exception:+ logger.exception(f"Failed to delete PDF for document {document.id}")+ return Falsediff --git a/src/local_deep_research/web/services/settings_manager.py b/src/local_deep_research/web/services/settings_manager.pyindex 144d2d6368..7b9d8b98c2 100644--- a/src/local_deep_research/web/services/settings_manager.py+++ b/src/local_deep_research/web/services/settings_manager.py@@ -285,9 +285,45 @@ class SettingsManager:f"Error retrieving setting {key} from database: {e}")+ # Backward compatibility: migrate enable_pdf_storage to pdf_storage_mode+ if key == "research_library.pdf_storage_mode":+ legacy_value = self._get_legacy_pdf_storage_setting()+ if legacy_value is not None:+ return legacy_value+# Return default if not foundreturn default+ def _get_legacy_pdf_storage_setting(self) -> Any:+ """+ Check for legacy enable_pdf_storage setting and migrate to new format.++ Only migrates true -> "filesystem". If false, returns None to use+ the new default ("database") instead of "none".++ Returns:+ Migrated storage mode value or None if no legacy setting exists+ """+ try:+ legacy_settings = self.__query_settings(+ "research_library.enable_pdf_storage"+ )+ if len(legacy_settings) == 1:+ legacy_value = self.__get_typed_setting_value(+ legacy_settings[0], False, True+ )+ # Only migrate true -> "filesystem"+ # For false, return None to use new default "database"+ if legacy_value is True:+ logger.info(+ "Migrating legacy enable_pdf_storage=true to "+ "pdf_storage_mode='filesystem'"+ )+ return "filesystem"+ except SQLAlchemyError:+ pass+ return None+def set_setting(self, key: str, value: Any, commit: bool = True) -> bool:"""Set a setting valuediff --git a/src/local_deep_research/web/templates/components/storage_mode_modal.html b/src/local_deep_research/web/templates/components/storage_mode_modal.htmlnew file mode 100644index 0000000000..089aea07dc--- /dev/null+++ b/src/local_deep_research/web/templates/components/storage_mode_modal.html@@ -0,0 +1,253 @@+<!-- PDF Storage Mode Selection Modal -->+<div id="storage-mode-modal" class="modal" style="display: none;">+ <div class="modal-content" style="max-width: 650px;">+ <div class="modal-header">+ <h2><i class="fas fa-database"></i> PDF Storage Mode</h2>+ <button class="ldr-close" onclick="closeStorageModeModal()">×</button>+ </div>+ <div class="modal-body">+ <p style="margin-bottom: 20px;">Choose where to store downloaded PDFs:</p>++ <div class="ldr-storage-mode-options">+ <label class="ldr-storage-mode-option" data-mode="database">+ <input type="radio" name="storage_mode" value="database" {% if pdf_storage_mode == 'database' %}checked{% endif %}>+ <div class="ldr-option-content">+ <div class="ldr-option-header">+ <i class="fas fa-database" style="color: #28a745;"></i>+ <strong>Database (Encrypted)</strong>+ <span class="badge badge-success">Recommended</span>+ </div>+ <p class="ldr-option-description">PDFs stored encrypted in your personal database. Maximum security and portability.</p>+ </div>+ </label>++ <label class="ldr-storage-mode-option" data-mode="filesystem">+ <input type="radio" name="storage_mode" value="filesystem" {% if pdf_storage_mode == 'filesystem' %}checked{% endif %}>+ <div class="ldr-option-content">+ <div class="ldr-option-header">+ <i class="fas fa-hdd" style="color: #ffc107;"></i>+ <strong>Filesystem (Unencrypted)</strong>+ </div>+ <p class="ldr-option-description">PDFs saved to disk unencrypted. Compatible with external tools like ChromaDB.</p>+ <div class="ldr-option-warning">+ <i class="fas fa-exclamation-triangle"></i> Files visible to anyone with disk access+ </div>+ </div>+ </label>++ <label class="ldr-storage-mode-option" data-mode="none">+ <input type="radio" name="storage_mode" value="none" {% if pdf_storage_mode == 'none' %}checked{% endif %}>+ <div class="ldr-option-content">+ <div class="ldr-option-header">+ <i class="fas fa-file-alt" style="color: #6c757d;"></i>+ <strong>Text Only</strong>+ </div>+ <p class="ldr-option-description">Only text content stored. PDFs not saved. Most private option.</p>+ </div>+ </label>+ </div>+ </div>+ <div class="modal-footer">+ <button id="storage-mode-confirm-btn" class="btn btn-primary" onclick="confirmStorageModeChange()">+ <i class="fas fa-check"></i> Save+ </button>+ <button class="btn btn-secondary" onclick="closeStorageModeModal()">Cancel</button>+ </div>+ </div>+</div>++<style>+/* Storage Mode Modal */+#storage-mode-modal .modal-content {+ color: var(--text-primary, #e4e4e4);+}++#storage-mode-modal .modal-body p {+ color: var(--text-primary, #e4e4e4);+}++#storage-mode-modal .ldr-close {+ background: none;+ border: none;+ font-size: 24px;+ cursor: pointer;+ color: var(--text-secondary, #aaa);+ padding: 0;+ line-height: 1;+}++#storage-mode-modal .ldr-close:hover {+ color: var(--text-primary, #fff);+}++/* Storage Mode Modal Options */+.ldr-storage-mode-options {+ display: flex;+ flex-direction: column;+ gap: 12px;+}++.ldr-storage-mode-option {+ display: flex;+ align-items: flex-start;+ padding: 15px;+ border: 2px solid var(--border-color, #3a3a3a);+ border-radius: 8px;+ cursor: pointer;+ transition: all 0.2s ease;+ color: var(--text-primary, #e4e4e4);+ background: var(--card-bg, #2a2a2a);+}++.ldr-storage-mode-option:hover {+ border-color: var(--primary-color, #4a9eff);+ background: rgba(74, 158, 255, 0.05);+}++.ldr-storage-mode-option:has(input:checked) {+ border-color: var(--primary-color, #4a9eff);+ background: rgba(74, 158, 255, 0.1);+}++.ldr-storage-mode-option input[type="radio"] {+ margin-right: 12px;+ margin-top: 4px;+}++.ldr-storage-mode-option .ldr-option-content {+ flex: 1;+}++.ldr-storage-mode-option .ldr-option-header {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-bottom: 6px;+}++.ldr-storage-mode-option .ldr-option-header strong {+ color: var(--text-primary, #e4e4e4);+}++.ldr-storage-mode-option .ldr-option-header i {+ font-size: 1.2em;+}++.ldr-storage-mode-option .ldr-option-description {+ color: var(--text-secondary, #aaa);+ font-size: 0.9em;+ margin: 0;+}++.ldr-storage-mode-option .ldr-option-warning {+ margin-top: 8px;+ padding: 6px 10px;+ background: rgba(255, 193, 7, 0.15);+ border-radius: 4px;+ color: #ffc107;+ font-size: 0.85em;+}++.ldr-storage-mode-option .ldr-option-warning i {+ margin-right: 6px;+}++/* Storage Mode Button styling */+.ldr-storage-mode-btn {+ cursor: pointer;+ border: none;+ width: 100%;+ text-align: left;+ font-size: inherit;+ font-family: inherit;+ transition: all 0.2s;+ color: inherit;+ background: inherit;+}++button.ldr-storage-mode-btn.ldr-info-message {+ color: #0dcaf0 !important;+ background: rgba(13, 202, 240, 0.15) !important;+ padding: 8px 12px;+ border-radius: 4px;+ border-left: 3px solid #0dcaf0;+}++button.ldr-storage-mode-btn.ldr-warning-message {+ color: #ff9800 !important;+ background: rgba(255, 152, 0, 0.15) !important;+ padding: 8px 12px;+ border-radius: 4px;+ border-left: 3px solid #ff9800;+}++.ldr-storage-mode-btn:hover {+ filter: brightness(1.1);+ transform: translateX(2px);+}+</style>++<script>+// Storage Mode Modal Functions+function showStorageModeModal() {+ document.getElementById('storage-mode-modal').style.display = 'flex';+}++function closeStorageModeModal() {+ document.getElementById('storage-mode-modal').style.display = 'none';+}++async function confirmStorageModeChange() {+ const selectedMode = document.querySelector('input[name="storage_mode"]:checked')?.value;+ if (!selectedMode) {+ alert('Please select a storage mode');+ return;+ }++ const btn = document.getElementById('storage-mode-confirm-btn');+ const originalContent = btn.innerHTML;+ btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...';+ btn.disabled = true;++ try {+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';++ const response = await fetch('/settings/save_all_settings', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': csrfToken+ },+ body: JSON.stringify({+ 'research_library.pdf_storage_mode': selectedMode+ })+ });++ if (!response.ok) {+ throw new Error(`HTTP error! status: ${response.status}`);+ }++ const result = await response.json();++ if (result.status === 'success') {+ closeStorageModeModal();+ location.reload();+ } else {+ throw new Error(result.message || 'Failed to update setting');+ }++ } catch (error) {+ console.error('Failed to update storage mode:', error);+ alert('Failed to update PDF storage mode. Please try again or use the Settings page.');+ btn.innerHTML = originalContent;+ btn.disabled = false;+ }+}++// Close modal when clicking outside+document.getElementById('storage-mode-modal')?.addEventListener('click', function(e) {+ if (e.target === this) {+ closeStorageModeModal();+ }+});+</script>diff --git a/src/local_deep_research/web/templates/pages/download_manager.html b/src/local_deep_research/web/templates/pages/download_manager.htmlindex cc182473c7..7774ee87fd 100644--- a/src/local_deep_research/web/templates/pages/download_manager.html+++ b/src/local_deep_research/web/templates/pages/download_manager.html@@ -11,15 +11,15 @@<button class="btn btn-success" onclick="downloadAllNew()"{% if not enable_pdf_storage %}disabled- title="PDF downloads are disabled. Enable PDF storage in Settings → Research Library"+ title="PDF storage is disabled. Click the storage mode button to enable."{% else %}- title="Download ALL available PDF files to disk"+ title="Download PDF files from all your research sources and save to library"{% endif %}>- <i class="fas fa-file-pdf"></i> Download ALL PDFs+ <i class="fas fa-file-pdf"></i> Get All Research PDFs</button><button class="btn btn-info" onclick="downloadAllAsText()"- title="Extract ALL text to encrypted database">- <i class="fas fa-database"></i> Extract ALL Text+ title="Extract text from all research sources without saving PDF files">+ <i class="fas fa-file-alt"></i> Text Only (from PDFs)</button></div><button class="btn btn-secondary" onclick="window.location.href='/library'">@@ -36,15 +36,15 @@<div class="ldr-btn-group ldr-download-buttons"><button class="btn btn-success" id="download-pdfs" disabled{% if not enable_pdf_storage %}- title="PDF downloads are disabled. Enable PDF storage in Settings → Research Library"+ title="PDF storage is disabled. Click the storage mode button to enable."{% else %}- title="Download PDF files to disk and store metadata in encrypted database"+ title="Download PDF files and save to library"{% endif %}>- <i class="fas fa-file-pdf"></i> Download PDFs (<span class="ldr-selected-count-pdf">0</span>)+ <i class="fas fa-file-pdf"></i> Get PDFs (<span class="ldr-selected-count-pdf">0</span>)</button><button class="btn btn-info" id="download-text-db" disabled- title="Extract text to encrypted database">- <i class="fas fa-database"></i> Extract Text (<span class="ldr-selected-count-text-db">0</span>)+ title="Extract text without saving PDF files">+ <i class="fas fa-file-alt"></i> Text Only (<span class="ldr-selected-count-text-db">0</span>)</button></div></div>@@ -58,22 +58,29 @@</div><div class="ldr-info-content"><h4>Library Storage Settings</h4>- {% if not enable_pdf_storage %}- <p class="ldr-warning-message">- <i class="fas fa-exclamation-triangle"></i>- <strong>PDF downloads are currently disabled.</strong>- Only text extraction to the encrypted database is available for maximum privacy protection.- </p>+ {% if pdf_storage_mode == 'database' %}+ <button class="ldr-storage-mode-btn ldr-info-message" onclick="showStorageModeModal()" title="Click to change storage mode">+ <i class="fas fa-database"></i>+ <strong>PDF Storage: Encrypted Database</strong> - PDFs will be stored securely in your personal encrypted database.+ <i class="fas fa-pen" style="margin-left: 8px; opacity: 0.6; font-size: 0.85em;"></i>+ </button>+ {% elif pdf_storage_mode == 'filesystem' %}+ <button class="ldr-storage-mode-btn ldr-warning-message" onclick="showStorageModeModal()" title="Click to change storage mode">+ <i class="fas fa-hdd"></i>+ <strong>PDF Storage: Filesystem</strong> - PDFs will be saved unencrypted to your library folder.+ <i class="fas fa-pen" style="margin-left: 8px; opacity: 0.6; font-size: 0.85em;"></i>+ </button>{% else %}- <p class="ldr-info-message">- <i class="fas fa-check-circle"></i>- PDF downloads are enabled. Files will be saved unencrypted to your library folder.- </p>+ <button class="ldr-storage-mode-btn ldr-warning-message" onclick="showStorageModeModal()" title="Click to change storage mode">+ <i class="fas fa-file-alt"></i>+ <strong>PDF Storage: Disabled</strong> - Only text extraction is available (text-only mode).+ <i class="fas fa-pen" style="margin-left: 8px; opacity: 0.6; font-size: 0.85em;"></i>+ </button>{% endif %}<p class="ldr-info-message">- <i class="fas fa-database"></i>- Text extraction saves to the encrypted database.+ <i class="fas fa-lock"></i>+ Text content is always stored in the encrypted database.</p>{% if shared_library %}@@ -294,8 +301,8 @@</button><button class="btn btn-sm btn-info"onclick="downloadResearch('{{ research.id }}', 'text_only')"- title="Extract text to encrypted database from this research">- <i class="fas fa-database"></i> Extract Text+ title="Extract text from this research without saving PDF files">+ <i class="fas fa-file-alt"></i> Text Only</button>{% if research.downloaded_count > 0 %}<button class="btn btn-sm" onclick="viewDownloaded('{{ research.id }}')">@@ -331,6 +338,8 @@</div></div></div>++ {% include 'components/storage_mode_modal.html' %}</div><style>diff --git a/src/local_deep_research/web/templates/pages/library.html b/src/local_deep_research/web/templates/pages/library.htmlindex 903c0d0f98..418236fb8c 100644--- a/src/local_deep_research/web/templates/pages/library.html+++ b/src/local_deep_research/web/templates/pages/library.html@@ -14,18 +14,18 @@<button class="btn btn-success"{% if not enable_pdf_storage %}disabled- title="PDF downloads are disabled. Enable PDF storage in Settings → Research Library"+ title="PDF storage is disabled. Click the storage mode button above to enable."data-toggle="tooltip"{% else %}onclick="downloadAllNew()"- title="Download ALL available PDF files to disk and store metadata in encrypted database"+ title="Download PDF files from all your research sources and save to library"{% endif %}>- <i class="fas fa-file-pdf"></i> Download ALL PDFs+ <i class="fas fa-file-pdf"></i> Get All Research PDFs</button><button class="btn btn-info"onclick="downloadAllAsText()"- title="Extract ALL text to encrypted database">- <i class="fas fa-database"></i> Extract ALL Text+ title="Extract text from all research sources without saving PDF files">+ <i class="fas fa-file-alt"></i> Text Only (from PDFs)</button></div><button class="btn btn-primary" onclick="window.location.href='/library/download-manager'">@@ -68,15 +68,19 @@<div class="status-item"><span class="status-label">PDF Storage:</span>- <button class="badge badge-button {% if enable_pdf_storage %}badge-success{% else %}badge-warning{% endif %}"- onclick="togglePDFStorage({{ 'true' if enable_pdf_storage else 'false' }})"- title="Click to {% if enable_pdf_storage %}disable{% else %}enable{% endif %} PDF storage">- {% if enable_pdf_storage %}- <i class="fas fa-check-circle"></i> Enabled - Click to Disable- {% else %}- <i class="fas fa-exclamation-circle"></i> Disabled - Click to Enable- {% endif %}- </button>+ {% if pdf_storage_mode == 'database' %}+ <button class="btn btn-sm btn-success" onclick="showStorageModeModal()" title="Click to change storage mode">+ <i class="fas fa-database"></i> Database (Encrypted)+ </button>+ {% elif pdf_storage_mode == 'filesystem' %}+ <button class="btn btn-sm btn-warning" onclick="showStorageModeModal()" title="Click to change storage mode">+ <i class="fas fa-hdd"></i> Filesystem (Unencrypted)+ </button>+ {% else %}+ <button class="btn btn-sm btn-secondary" onclick="showStorageModeModal()" title="Click to change storage mode">+ <i class="fas fa-file-alt"></i> Text Only+ </button>+ {% endif %}</div><div class="status-item">@@ -365,46 +369,7 @@</div></div>-<!-- PDF Storage Toggle Confirmation Modal -->-<div id="pdf-storage-modal" class="modal" style="display: none;">- <div class="modal-content" style="max-width: 600px;">- <div class="modal-header">- <h2><i class="fas fa-exclamation-triangle" style="color: #ff9800;"></i> <span id="pdf-modal-title">Enable PDF Storage?</span></h2>- <button class="close" onclick="closePDFStorageModal()">×</button>- </div>- <div class="modal-body">- <div id="pdf-enable-warning" class="pdf-storage-warning">- <div class="ldr-security-warning" style="background: var(--warning-bg, #3d3313); padding: 15px; border-radius: 8px; border-left: 4px solid #ff9800; margin-bottom: 15px;">- <i class="fas fa-exclamation-triangle" style="color: #ff9800; font-size: 1.5em; margin-right: 10px;"></i>- <strong style="color: #ff9800;">PRIVACY WARNING</strong>- <p style="margin-top: 10px;">Enabling PDF storage will save research PDFs <strong>unencrypted to the server's hard drive</strong>. This means:</p>- <ul style="margin: 10px 0; padding-left: 30px;">- <li>Anyone with filesystem access can see your downloaded PDFs</li>- <li>Your research interests will be exposed</li>- <li>Files are stored wherever LDR is running (not encrypted)</li>- </ul>- <p style="margin-top: 10px;">Currently, only encrypted metadata is stored in your database. Enable PDF storage only if you need PDF files for external tools or offline reading.</p>- </div>- <p><strong>Are you sure you want to enable PDF storage?</strong></p>- </div>- <div id="pdf-disable-warning" class="pdf-storage-warning" style="display: none;">- <p>Disabling PDF storage will:</p>- <ul style="margin: 10px 0; padding-left: 30px;">- <li>Prevent new PDFs from being downloaded to disk</li>- <li>Keep existing PDFs on disk (not deleted)</li>- <li>Maintain encrypted metadata in your database</li>- </ul>- <p style="margin-top: 10px;"><strong>Are you sure you want to disable PDF storage?</strong></p>- </div>- </div>- <div class="modal-footer">- <button id="pdf-storage-confirm-btn" class="btn btn-primary" onclick="confirmPDFStorageToggle()">- <i class="fas fa-check"></i> <span id="pdf-confirm-text">Yes, Enable</span>- </button>- <button class="btn btn-secondary" onclick="closePDFStorageModal()">Cancel</button>- </div>- </div>-</div>+{% include 'components/storage_mode_modal.html' %}<!-- Sync Library Modal --><div id="sync-library-modal" class="modal" style="display: none;">@@ -1810,80 +1775,5 @@ document.querySelectorAll('.view-toggle button').forEach(btn => {}});});--// PDF Storage Toggle Functions-let pendingPDFStorageState = false;--function togglePDFStorage(currentState) {- pendingPDFStorageState = !currentState;-- // Update modal content based on what we're doing- if (pendingPDFStorageState) {- // Enabling PDF storage- document.getElementById('pdf-modal-title').textContent = 'Enable PDF Storage?';- document.getElementById('pdf-enable-warning').style.display = 'block';- document.getElementById('pdf-disable-warning').style.display = 'none';- document.getElementById('pdf-confirm-text').textContent = 'Yes, Enable';- document.getElementById('pdf-storage-confirm-btn').className = 'btn btn-primary';- } else {- // Disabling PDF storage- document.getElementById('pdf-modal-title').textContent = 'Disable PDF Storage?';- document.getElementById('pdf-enable-warning').style.display = 'none';- document.getElementById('pdf-disable-warning').style.display = 'block';- document.getElementById('pdf-confirm-text').textContent = 'Yes, Disable';- document.getElementById('pdf-storage-confirm-btn').className = 'btn btn-danger';- }-- // Show modal- document.getElementById('pdf-storage-modal').style.display = 'block';-}--function closePDFStorageModal() {- document.getElementById('pdf-storage-modal').style.display = 'none';-}--async function confirmPDFStorageToggle() {- const btn = document.getElementById('pdf-storage-confirm-btn');- const originalContent = btn.innerHTML;- btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Updating...';- btn.disabled = true;-- try {- // Get CSRF token- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';-- // Update the setting via settings manager endpoint- const response = await fetch('/settings/save_all_settings', {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- 'X-CSRFToken': csrfToken- },- body: JSON.stringify({- 'research_library.enable_pdf_storage': pendingPDFStorageState- })- });-- if (!response.ok) {- throw new Error(`HTTP error! status: ${response.status}`);- }-- const result = await response.json();-- if (result.status === 'success') {- // Close modal and reload page to reflect changes- closePDFStorageModal();- location.reload();- } else {- throw new Error(result.message || 'Failed to update setting');- }-- } catch (error) {- console.error('Failed to toggle PDF storage:', error);- alert('Failed to update PDF storage setting. Please try again or use the Settings page.');- btn.innerHTML = originalContent;- btn.disabled = false;- }-}</script>{% endblock %}