mirror of
https://github.com/AstrBotDevs/AstrBot
synced 2026-07-15 17:30:13 +08:00
* refactor: migrate to fastapi * structure refactor * fix: pyright fix * refactor: improve error handling and public messages in plugin services * feat(api): refactor API client integration and enhance request handling - Updated API client configuration to use a dedicated HTTP client. - Introduced utility functions for generating options, queries, and form data for API requests. - Refactored multiple API methods to utilize the new utility functions for improved consistency and readability. - Renamed types for clarity and updated import statements accordingly. feat(docs): add script to update OpenAPI JSON from YAML spec - Created a Python script to convert OpenAPI YAML specification to JSON format. - The script supports customizable input and output paths. - Ensured the script handles directory creation for output paths and validates the YAML structure. * fix * feat(auth): implement rate limiting for v1 login endpoint and enhance request handling * Refactor dashboard API routers to use legacy_router for backward compatibility - Changed all instances of dashboard_router to legacy_router across multiple API modules including platform, plugins, providers, sessions, skills, stats, subagents, t2i, tools, updates, and asgi_runtime. - Updated route definitions to ensure existing endpoints remain functional under the new router structure. - Introduced support for Quart request context in asgi_runtime to enhance compatibility with existing Quart-based plugins. - Added a test case to validate the functionality of the new Quart request context handling in plugin extensions. * chore: remove cli test * fix: update dashboard tests for fastapi migration * chore: satisfy ruff checks * fix: update openapi api key scopes * fix: sync config scope chip selection * fix: restore quart dependency * docs: clarify quart plugin api compatibility * docs: update openapi scope documentation * fix: use singular skill openapi scope * fix: hide update service exception details * fix: address fastapi review comments * fix: address dashboard review findings * docs: revert unrelated package deployment changes * docs: update agent api generation guidance * feat: add plugin page web api helpers * docs: add plugin page bridge demo * fix: type plugin upload files * fix: stabilize plugin page uploads * fix: type plugin web request proxy * docs: remove plugin page docs example * fix: authenticate plugin page SSE bridge
108 lines
3.3 KiB
Python
108 lines
3.3 KiB
Python
from __future__ import annotations
|
|
|
|
from collections.abc import Callable
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from fastapi import Request
|
|
from starlette.datastructures import UploadFile as StarletteUploadFile
|
|
|
|
|
|
class UploadFileAdapter:
|
|
def __init__(self, upload_file: StarletteUploadFile) -> None:
|
|
self._upload_file = upload_file
|
|
self.filename = upload_file.filename
|
|
self.content_type = upload_file.content_type
|
|
self.headers = upload_file.headers
|
|
self.content_length = self._resolve_content_length()
|
|
|
|
def _resolve_content_length(self) -> int | None:
|
|
try:
|
|
raw = self.headers.get("content-length")
|
|
return int(raw) if raw else None
|
|
except (TypeError, ValueError):
|
|
return None
|
|
|
|
async def save(self, destination: str | Path) -> None:
|
|
path = Path(destination)
|
|
try:
|
|
await self._upload_file.seek(0)
|
|
except Exception:
|
|
pass
|
|
with path.open("wb") as output:
|
|
while True:
|
|
chunk = await self._upload_file.read(1024 * 1024)
|
|
if not chunk:
|
|
break
|
|
output.write(chunk)
|
|
|
|
|
|
class MultiDict:
|
|
def __init__(self, pairs: list[tuple[str, Any]]) -> None:
|
|
self._pairs = pairs
|
|
|
|
def get(self, key: str, default: Any = None, type: Callable | None = None):
|
|
for item_key, item_value in reversed(self._pairs):
|
|
if item_key != key:
|
|
continue
|
|
if type is None:
|
|
return item_value
|
|
try:
|
|
return type(item_value)
|
|
except (TypeError, ValueError):
|
|
return default
|
|
return default
|
|
|
|
def getlist(self, key: str) -> list[Any]:
|
|
return [item_value for item_key, item_value in self._pairs if item_key == key]
|
|
|
|
def keys(self):
|
|
return dict.fromkeys(item_key for item_key, _ in self._pairs).keys()
|
|
|
|
def values(self):
|
|
return [self[key] for key in self.keys()]
|
|
|
|
def __contains__(self, key: str) -> bool:
|
|
return any(item_key == key for item_key, _ in self._pairs)
|
|
|
|
def __getitem__(self, key: str):
|
|
value = self.get(key)
|
|
if value is None and key not in self:
|
|
raise KeyError(key)
|
|
return value
|
|
|
|
def __bool__(self) -> bool:
|
|
return bool(self._pairs)
|
|
|
|
|
|
async def multipart_parts(
|
|
request: Request,
|
|
*,
|
|
extra_form: dict[str, Any] | None = None,
|
|
) -> tuple[MultiDict, MultiDict]:
|
|
form = await request.form()
|
|
form_pairs: list[tuple[str, Any]] = []
|
|
file_pairs: list[tuple[str, Any]] = []
|
|
for key, value in form.multi_items():
|
|
if isinstance(value, StarletteUploadFile):
|
|
file_pairs.append((key, UploadFileAdapter(value)))
|
|
else:
|
|
form_pairs.append((key, value))
|
|
form_data = MultiDict(form_pairs)
|
|
for key, value in (extra_form or {}).items():
|
|
if value is not None and key not in form_data:
|
|
form_pairs.append((key, value))
|
|
return MultiDict(form_pairs), MultiDict(file_pairs)
|
|
|
|
|
|
async def single_upload(
|
|
request: Request,
|
|
*,
|
|
field_name: str = "file",
|
|
) -> UploadFileAdapter | None:
|
|
_, files = await multipart_parts(request)
|
|
upload = files.get(field_name)
|
|
if isinstance(upload, UploadFileAdapter):
|
|
return upload
|
|
return None
|