66 lines
1.8 KiB
Python
66 lines
1.8 KiB
Python
import re
|
|
from typing import Annotated
|
|
from uuid import UUID
|
|
|
|
from pydantic import (
|
|
BaseModel,
|
|
BeforeValidator,
|
|
ConfigDict,
|
|
Field,
|
|
StrictStr,
|
|
ValidationInfo,
|
|
field_validator,
|
|
model_validator,
|
|
)
|
|
|
|
from src.cursor import parse_uuid
|
|
|
|
UuidIn = Annotated[UUID, BeforeValidator(parse_uuid)]
|
|
|
|
|
|
class Input(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
@field_validator("*", mode="after")
|
|
@classmethod
|
|
def nonblank(cls, value: object, info: ValidationInfo) -> object:
|
|
if isinstance(value, str) and (
|
|
(not value.strip() and info.field_name != "text")
|
|
or any(0xD800 <= ord(c) <= 0xDFFF for c in value)
|
|
):
|
|
raise ValueError("Invalid text")
|
|
return value
|
|
|
|
|
|
class CreateUser(Input):
|
|
username: StrictStr
|
|
display_name: StrictStr = Field(min_length=1, max_length=100)
|
|
password: StrictStr = Field(min_length=12, max_length=128)
|
|
|
|
@field_validator("username")
|
|
@classmethod
|
|
def username_format(cls, value: str) -> str:
|
|
if not re.fullmatch(r"[a-z0-9_]{3,32}", value):
|
|
raise ValueError("Invalid username")
|
|
return value
|
|
|
|
|
|
class CreateChat(Input):
|
|
title: StrictStr = Field(min_length=1, max_length=100)
|
|
member_ids: list[UuidIn] = Field(min_length=1, max_length=100, strict=True)
|
|
|
|
|
|
class CreateMessage(Input):
|
|
text: StrictStr = Field(max_length=4000)
|
|
attachment_ids: list[UuidIn] = Field(
|
|
default_factory=list, max_length=10, strict=True
|
|
)
|
|
|
|
@model_validator(mode="after")
|
|
def content(self):
|
|
if len(set(self.attachment_ids)) != len(self.attachment_ids):
|
|
raise ValueError("Duplicate attachment")
|
|
if not self.text.strip() and not self.attachment_ids:
|
|
raise ValueError("Empty message")
|
|
return self
|