""" Router "text" provides: - listing text files - finding text files by name prefix - getting text file raw content by name prefix - getting text file HTML content by name prefix (using Markdown) """ import re from logging import getLogger from typing import Iterator from fastapi import APIRouter, Depends from markdown import markdown from ...core.dav_common import webdav_ensure_files, webdav_ensure_path from ...core.webdav import WebDAV from ._common import FileNameLister, PrefixFinder, PrefixUnique _logger = getLogger(__name__) router = APIRouter(prefix="/text", tags=["text"]) text_lister = FileNameLister( path_name="text_dir", re=re.compile( r"\.(txt|md)$", flags=re.IGNORECASE, ), ) text_finder = PrefixFinder(text_lister) text_unique = PrefixUnique(text_finder) @router.on_event("startup") async def start_router() -> None: _logger.debug(f"{router.prefix} router starting.") webdav_ensure_path(await text_lister.remote_path) webdav_ensure_files( await text_lister.remote_path, "message.txt", "title.txt", "ticker.txt", ) @router.get( "/list", response_model=list[str], responses=text_lister.responses, ) async def list_texts( names: Iterator[str] = Depends(text_lister), ) -> list[str]: return list(names) @router.get( "/find/{prefix}", response_model=list[str], responses=text_finder.responses, ) async def find_texts( names: Iterator[str] = Depends(text_finder), ) -> list[str]: return list(names) async def get_text_content( name: str = Depends(text_unique), ) -> str: return await WebDAV.read_str(f"{await text_lister.remote_path}/{name}") @router.get( "/get/html/{prefix}", response_model=str, responses=text_unique.responses, ) async def get_text( text: str = Depends(get_text_content), ) -> str: return markdown(text) @router.get( "/get/raw/{prefix}", response_model=str, responses=text_unique.responses, ) async def get_raw_text( text: str = Depends(get_text_content), ) -> str: return text