discordbot/api_service/terminal_images_endpoint.py
2025-06-05 21:31:06 -06:00

68 lines
1.9 KiB
Python

"""
Terminal Images Endpoint
This module provides an endpoint for serving terminal images generated by the terminal_cog.py.
"""
import os
from fastapi import APIRouter, HTTPException
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from typing import Optional
# Create a router for the terminal images endpoint
router = APIRouter(tags=["Terminal Images"])
# Path to the terminal_images directory
TERMINAL_IMAGES_DIR = os.path.abspath(
os.path.join(os.path.dirname(__file__), "..", "terminal_images")
)
# Ensure the terminal_images directory exists
os.makedirs(TERMINAL_IMAGES_DIR, exist_ok=True)
@router.get("/{filename}")
async def get_terminal_image(filename: str):
"""
Get a terminal image by filename.
Args:
filename: The filename of the terminal image
Returns:
The terminal image file
Raises:
HTTPException: If the file is not found
"""
file_path = os.path.join(TERMINAL_IMAGES_DIR, filename)
if not os.path.exists(file_path):
raise HTTPException(status_code=404, detail="Terminal image not found")
return FileResponse(file_path)
# Function to mount the terminal images directory as static files
def mount_terminal_images(app):
"""
Mount the terminal_images directory as static files.
Args:
app: The FastAPI app to mount the static files on
"""
# Check if the directory exists
if os.path.exists(TERMINAL_IMAGES_DIR) and os.path.isdir(TERMINAL_IMAGES_DIR):
# Mount the terminal_images directory as static files
app.mount(
"/terminal_images",
StaticFiles(directory=TERMINAL_IMAGES_DIR),
name="terminal_images",
)
print(f"Mounted terminal images directory: {TERMINAL_IMAGES_DIR}")
else:
print(
f"Warning: Terminal images directory '{TERMINAL_IMAGES_DIR}' not found. Terminal images will not be available."
)