ovdashboard/api/ovdashboard_api/routers/text.py

100 lines
2.3 KiB
Python
Raw Normal View History

2022-08-31 01:55:17 +00:00
import re
from typing import Iterator
2022-08-29 11:27:18 +00:00
from fastapi import APIRouter, Depends, HTTPException, status
from markdown import markdown
2022-08-29 11:27:18 +00:00
2022-08-31 01:29:44 +00:00
from ..config import SETTINGS
2022-08-29 11:27:18 +00:00
from ..dav_file import DavFile
2022-09-02 13:22:35 +00:00
from ._common import FileNameLister, FilePrefixFinder
2022-08-29 11:27:18 +00:00
router = APIRouter(prefix="/text", tags=["text"])
2022-09-02 13:22:35 +00:00
_lister = FileNameLister(
remote_path="text",
re=re.compile(
r"\.(txt|md)$",
flags=re.IGNORECASE,
),
)
_finder = FilePrefixFinder(_lister)
2022-08-29 11:27:18 +00:00
2022-08-31 01:55:17 +00:00
async def get_ticker_lines() -> Iterator[str]:
ticker = await DavFile("text/ticker.txt").string
2022-08-31 01:55:17 +00:00
return (
2022-08-29 19:20:03 +00:00
line.strip()
for line in ticker.split("\n")
2022-08-31 01:55:17 +00:00
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("#")
2022-08-29 19:20:03 +00:00
)
2022-08-31 01:55:17 +00:00
@router.get("/get/ticker")
2022-08-31 01:55:17 +00:00
async def get_ticker_content(
ticker_content_lines: Iterator[str] = Depends(get_ticker_content_lines),
) -> str:
return markdown(
2022-08-31 01:55:17 +00:00
SETTINGS.ticker_separator.join(ticker_content_lines)
)
@router.get("/list", response_model=list[str])
async def list_texts(
2022-09-02 13:22:35 +00:00
text_file_names: Iterator[str] = Depends(_lister),
) -> list[str]:
return list(text_file_names)
@router.get("/find/{prefix}", response_model=list[str])
async def find_texts(
2022-09-02 13:22:35 +00:00
file_names: Iterator[str] = Depends(_finder),
) -> list[str]:
return list(file_names)
@router.get(
"/get/{prefix}",
2022-09-02 13:22:35 +00:00
response_model=str,
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(
2022-09-02 13:22:35 +00:00
file_names: Iterator[str] = Depends(_finder),
) -> str:
file_names = list(file_names)
if not (file_names := list(file_names)):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
2022-08-31 01:55:17 +00:00
elif len(file_names) > 1:
raise HTTPException(status_code=status.HTTP_409_CONFLICT)
2022-08-31 01:55:17 +00:00
text = await DavFile(f"text/{file_names[0]}").string
return markdown(
text
2022-08-29 19:20:03 +00:00
)