96 lines
2 KiB
Python
96 lines
2 KiB
Python
"""
|
|
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 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 filter_prefix, filter_prefix_unique, get_remote_path, list_files
|
|
|
|
_logger = getLogger(__name__)
|
|
_PATH_NAME = "text_dir"
|
|
|
|
router = APIRouter(prefix="/text", tags=["text"])
|
|
|
|
_ls = list_files(
|
|
path_name=_PATH_NAME,
|
|
re=re.compile(
|
|
r"\.(txt|md)$",
|
|
flags=re.IGNORECASE,
|
|
),
|
|
)
|
|
|
|
_rp = get_remote_path(path_name=_PATH_NAME)
|
|
_fp = filter_prefix(_ls)
|
|
_fpu = filter_prefix_unique(_fp)
|
|
|
|
|
|
@router.on_event("startup")
|
|
async def start_router() -> None:
|
|
_logger.debug(f"{router.prefix} router starting.")
|
|
|
|
remote_path = await _rp()
|
|
if not webdav_ensure_path(remote_path):
|
|
webdav_ensure_files(
|
|
remote_path,
|
|
"message.txt",
|
|
"title.txt",
|
|
"ticker.txt",
|
|
)
|
|
|
|
|
|
@router.get(
|
|
"/list",
|
|
responses=_ls.responses,
|
|
)
|
|
async def list_all_texts(
|
|
names: list[str] = Depends(_ls.func),
|
|
) -> list[str]:
|
|
return names
|
|
|
|
|
|
@router.get(
|
|
"/find/{prefix}",
|
|
responses=_fp.responses,
|
|
)
|
|
async def find_texts_by_prefix(
|
|
names: list[str] = Depends(_fp.func),
|
|
) -> list[str]:
|
|
return names
|
|
|
|
|
|
async def _get_raw_text_by_prefix(
|
|
remote_path: str = Depends(_rp.func),
|
|
name: str = Depends(_fpu.func),
|
|
) -> str:
|
|
return await WebDAV.read_str(f"{remote_path}/{name}")
|
|
|
|
|
|
@router.get(
|
|
"/get/raw/{prefix}",
|
|
responses=_fpu.responses,
|
|
)
|
|
async def get_raw_text_by_prefix(
|
|
text: str = Depends(_get_raw_text_by_prefix),
|
|
) -> str:
|
|
return text
|
|
|
|
|
|
@router.get(
|
|
"/get/html/{prefix}",
|
|
responses=_fpu.responses,
|
|
)
|
|
async def get_html_by_prefix(
|
|
text: str = Depends(_get_raw_text_by_prefix),
|
|
) -> str:
|
|
return markdown(text)
|