120 lines
2.8 KiB
Python
120 lines
2.8 KiB
Python
import re
|
|
from typing import Iterator
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from markdown import markdown
|
|
from webdav3.exceptions import RemoteResourceNotFound
|
|
|
|
from .. import CLIENT
|
|
from ..config import SETTINGS
|
|
from ..dav_file import DavFile
|
|
|
|
router = APIRouter(prefix="/text", tags=["text"])
|
|
|
|
|
|
async def get_ticker_lines() -> Iterator[str]:
|
|
ticker = await DavFile("text/ticker.txt").string
|
|
|
|
return (
|
|
line.strip()
|
|
for line in ticker.split("\n")
|
|
if line.strip()
|
|
)
|
|
|
|
|
|
async def get_ticker_content_lines(
|
|
ticker_lines: Iterator[str] = Depends(get_ticker_lines),
|
|
) -> Iterator[str]:
|
|
return (
|
|
line
|
|
for line in ticker_lines
|
|
if not line.startswith("#")
|
|
)
|
|
|
|
|
|
@router.get("/get/ticker")
|
|
async def get_ticker_content(
|
|
ticker_content_lines: Iterator[str] = Depends(get_ticker_content_lines),
|
|
) -> str:
|
|
return markdown(
|
|
SETTINGS.ticker_separator.join(ticker_content_lines)
|
|
)
|
|
|
|
|
|
_re_text_file = re.compile(
|
|
r"\.(txt|md)$",
|
|
flags=re.IGNORECASE,
|
|
)
|
|
|
|
|
|
async def get_text_file_names() -> Iterator[str]:
|
|
try:
|
|
file_names = CLIENT.list("text")
|
|
|
|
return (
|
|
name
|
|
for name in file_names
|
|
if _re_text_file.search(name)
|
|
)
|
|
|
|
except RemoteResourceNotFound:
|
|
return iter(())
|
|
|
|
|
|
@router.get("/list", response_model=list[str])
|
|
async def list_texts(
|
|
text_file_names: Iterator[str] = Depends(get_text_file_names),
|
|
) -> list[str]:
|
|
return list(text_file_names)
|
|
|
|
|
|
async def find_file_names(
|
|
prefix: str = "",
|
|
text_file_names: Iterator[str] = Depends(get_text_file_names),
|
|
) -> Iterator[str]:
|
|
return (
|
|
file_name
|
|
for file_name in text_file_names
|
|
if file_name.lower().startswith(prefix.lower())
|
|
)
|
|
|
|
|
|
@router.get("/find/{prefix}", response_model=list[str])
|
|
async def find_texts(
|
|
file_names: Iterator[str] = Depends(find_file_names),
|
|
) -> list[str]:
|
|
return list(file_names)
|
|
|
|
|
|
@router.get(
|
|
"/get/{prefix}",
|
|
responses={
|
|
status.HTTP_200_OK: {
|
|
"description": "Operation successful",
|
|
},
|
|
status.HTTP_404_NOT_FOUND: {
|
|
"description": "text file not found",
|
|
"content": None,
|
|
},
|
|
status.HTTP_409_CONFLICT: {
|
|
"description": "ambiguous text file name",
|
|
"content": None,
|
|
},
|
|
},
|
|
)
|
|
async def get_text(
|
|
file_names: Iterator[str] = Depends(find_file_names),
|
|
) -> str:
|
|
file_names = list(file_names)
|
|
|
|
if not (file_names := list(file_names)):
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
|
|
|
|
elif len(file_names) > 1:
|
|
raise HTTPException(status_code=status.HTTP_409_CONFLICT)
|
|
|
|
text = await DavFile(f"text/{file_names[0]}").string
|
|
|
|
return markdown(
|
|
text
|
|
)
|