Spaces:
Sleeping
Sleeping
Soumik Bose commited on
Commit ·
3012e93
1
Parent(s): cdee413
ok
Browse filesFiles changed (4)
1234583 unmodified lines89909192939495969798999394100101102import shutilimport mimetypesfrom contextlib import asynccontextmanagerfrom fastapi import FastAPI, Depends, Query, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddleware83 unmodified lines file_path = file_service.get_file_path(fileid) logger.info(f"Serving file: {db_record.filename} ({fileid})") mime_type = file_service.get_mime_type(db_record.filename) headers = { "Content-Disposition": f'inline; filename="{db_record.filename}"' } return FileResponse( path=file_path, filename=db_record.filename, media_type="application/octet-stream" media_type=mime_type or "application/octet-stream", headers=headers )11 unmodified lines121314151617181919202021222324222325262711 unmodified lines response.headers["X-XSS-Protection"] = "1; mode=block" response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin" response.headers["Permissions-Policy"] = "geolocation=(), microphone=(), camera=()" # Relax CSP for file rendering (e.g., PDFs and images) response.headers["Content-Security-Policy"] = ( "default-src 'self'; " "script-src 'self'; " "style-src 'self'; " "img-src 'self' data:; " "object-src 'none';" "img-src 'self' data: *; " "object-src 'self' *;" ) # For file serving, we might want to allow caching, but for now we just ensure it doesn't force download if not request.url.path.startswith("/v1/getfile"): response.headers["Cache-Control"] = "no-store" response.headers["Pragma"] = "no-cache" response.headers["Cache-Control"] = "no-store" response.headers["Pragma"] = "no-cache" return response53 unmodified lines5455565757585960616263646566676869706263717253 unmodified lines
file_path = file_service.get_file_path(fileid)
mime_type, _ = mimetypes.guess_type(db_record.filename) mime_type = file_service.get_mime_type(db_record.filename)
# If we want the browser to render the file (inline), we should set the media_type # and use content_disposition_type="inline". # Note: Some browsers might still download if 'filename' is provided in the header. # To maximize compatibility with "render in browser", we ensure the media_type is correct. headers = { "Content-Disposition": f'inline; filename="{db_record.filename}"' } return FileResponse( path=file_path, media_type=mime_type or "application/octet-stream", filename=db_record.filename, content_disposition_type="inline" headers=headers )1 unmodified line23456784 unmodified lines1314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374104 unmodified lines1791801811821831841851861871881891901911921931941951961 unmodified lineimport uuidimport shutilfrom pathlib import Pathimport mimetypesfrom sqlalchemy.orm import Sessionfrom fastapi import UploadFile, HTTPExceptionfrom app.core.config import settings4 unmodified lineslogger = get_logger(__name__)
class FileService: # Custom MIME type mapping for common browser-renderable files # This helps ensure that files are rendered inline when possible, even if mimetypes.guess_type is generic. RENDERABLE_MIME_TYPES = { # Images '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.svg': 'image/svg+xml', '.apng': 'image/apng', '.avif': 'image/avif', '.bmp': 'image/bmp', '.ico': 'image/vnd.microsoft.icon', '.tif': 'image/tiff', '.tiff': 'image/tiff',
# Audio '.aac': 'audio/aac', '.mp3': 'audio/mpeg', '.oga': 'audio/ogg', '.ogg': 'audio/ogg', '.wav': 'audio/wav', '.weba': 'audio/webm', '.midi': 'audio/midi', '.mid': 'audio/midi',
# Video '.mp4': 'video/mp4', '.mpeg': 'video/mpeg', '.ogv': 'video/ogg', '.webm': 'video/webm', '.ts': 'video/mp2t',
# Documents & Text '.pdf': 'application/pdf', '.txt': 'text/plain', '.html': 'text/html', '.htm': 'text/html', '.css': 'text/css', '.js': 'text/javascript', '.json': 'application/json', '.jsonld': 'application/ld+json', '.md': 'text/markdown', '.xml': 'application/xml', '.xhtml': 'application/xhtml+xml', '.csv': 'text/csv', '.ics': 'text/calendar',
# Fonts (browsers can render these if linked, but serving them inline might just show binary or trigger download) '.otf': 'font/otf', '.ttf': 'font/ttf', '.woff': 'font/woff', '.woff2': 'font/woff2', }
def __init__(self): self.files_dir = Path(settings.FILES_DIR) self.files_dir.mkdir(parents=True, exist_ok=True)104 unmodified lines raise HTTPException(status_code=404, detail="File not found on disk") return file_path
def get_mime_type(self, filename: str) -> str: # First, try to get MIME type from our custom mapping file_extension = Path(filename).suffix.lower() if file_extension in self.RENDERABLE_MIME_TYPES: return self.RENDERABLE_MIME_TYPES[file_extension] # If not in custom mapping, try mimetypes.guess_type mime_type, _ = mimetypes.guess_type(filename) if mime_type: return mime_type # Fallback to a generic binary stream if type is still unknown return "application/octet-stream"
file_service = FileService()app/main.py+9-2
app/middleware/security_headers.py+7-4
app/routers/files.py+11-3
app/services/file_service.py+71