Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion server/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ FROM python:3.15-slim-trixie
LABEL io.modelcontextprotocol.server.name="io.github.BukeLy/peerbox"
WORKDIR /app
COPY --from=build /app/.venv /app/.venv
COPY server.py instance.py accounts.py mailbox.py bucket.py panel.py icon.png schema.sql ./
COPY server.py instance.py accounts.py messages.py bucket.py panel.py icon.png schema.sql ./
COPY panel ./panel
ENV PATH="/app/.venv/bin:$PATH"
CMD exec granian --interface asgi --loop uvloop --http 1 --no-ws --host 0.0.0.0 --port "${PORT:-8000}" server:app
2 changes: 1 addition & 1 deletion server/accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from asyncpg import Connection, UniqueViolationError

from mailbox import Address, Refused, wake_known_by
from messages import Address, Refused, wake_known_by

# Letters, digits and single hyphens, as in GitHub's logins; matched in any case.
USERNAME = r"[A-Za-z0-9]+(-[A-Za-z0-9]+)*"
Expand Down
12 changes: 6 additions & 6 deletions server/instance.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from fastmcp.utilities.logging import get_logger

import accounts
import mailbox
import messages

HERE = Path(__file__).parent
logger = get_logger("peerbox")
Expand Down Expand Up @@ -83,7 +83,7 @@ async def _expire_hourly() -> None:
while True:
try:
async with get_db() as db:
await mailbox.expire(db)
await messages.expire(db)
except Exception:
logger.exception("Deleting old messages failed")
await asyncio.sleep(3600)
Expand All @@ -108,7 +108,7 @@ async def database(server):
listener = await connect(DATABASE_URL)
expiry = asyncio.create_task(_expire_hourly())
try:
await listener.add_listener(mailbox.CHANNEL, waiters.wake)
await listener.add_listener(messages.CHANNEL, waiters.wake)
yield {}
finally:
expiry.cancel()
Expand Down Expand Up @@ -136,11 +136,11 @@ async def admit(token: str, claims: dict) -> bool:
},
timeout=10,
) as github:
if mailbox.GITHUB_ORG is None:
if messages.GITHUB_ORG is None:
await _record_organisations(github, claims)
admitted = True
else:
admitted = await _member_or_guest(github, mailbox.GITHUB_ORG)
admitted = await _member_or_guest(github, messages.GITHUB_ORG)
if admitted:
now = time.monotonic()
for stale in [held for held, until in _admitted_until.items() if until <= now]:
Expand Down Expand Up @@ -179,4 +179,4 @@ async def _record_organisations(github: httpx2.AsyncClient, claims: dict) -> Non
page = installed.links.get("next", {}).get("url")
async with get_db() as db:
you = await accounts.sign_in(db, claims)
await mailbox.record_memberships(db, you.person, orgs)
await messages.record_memberships(db, you.person, orgs)
File renamed without changes.
8 changes: 4 additions & 4 deletions server/panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

import accounts
import instance
import mailbox
import messages

HERE = Path(__file__).parent
CALLBACK_URL = f"{instance.BASE_URL}/login/callback"
Expand Down Expand Up @@ -152,14 +152,14 @@ async def route(request: Request) -> Response:

async def me(db, person: int, request: Request) -> dict | None:
shown = await accounts.profile(db, person)
return shown and shown | await mailbox.contacts_and_groups(db, person)
return shown and shown | await messages.contacts_and_groups(db, person)

async def conversations(db, person: int, request: Request) -> dict:
return await mailbox.conversations(db, person)
return await messages.conversations(db, person)

async def history(db, person: int, request: Request) -> dict:
before = request.query_params.get("before", "")
return await mailbox.history(
return await messages.history(
db,
person,
request.path_params["key"],
Expand Down
3 changes: 0 additions & 3 deletions server/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,3 @@ extend-immutable-calls = [
"fastmcp.dependencies.CurrentContext",
"fastmcp.dependencies.Depends",
]

[tool.ruff.lint.isort]
known-first-party = ["mailbox"] # ours, not the standard library's mailbox
52 changes: 26 additions & 26 deletions server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@

import accounts
import instance
import mailbox
import messages
import panel
from instance import BASE_URL, DATABASE_URL, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET

Expand Down Expand Up @@ -235,10 +235,10 @@ def limit_key(ctx) -> str:

async def me(
db: Connection, token: AccessToken, agent: str | None = None
) -> mailbox.Address:
) -> messages.Address:
"""The caller's address: them, or one of their agents, which must have read its
inbox once."""
return await mailbox.as_agent(db, await accounts.sign_in(db, token.claims), agent)
return await messages.as_agent(db, await accounts.sign_in(db, token.claims), agent)


@mcp.tool(annotations=READ)
Expand Down Expand Up @@ -293,7 +293,7 @@ async def set_remark(
"""
you = await me(db, token)
other = await accounts.resolve(db, username)
kept = await mailbox.set_remark(db, you.person, other, remark)
kept = await messages.set_remark(db, you.person, other, remark)
return {"username": str(other), "remark": kept}


Expand All @@ -312,7 +312,7 @@ async def contacts(
name fits, or more than one does, ask your user who they mean. To reach
someone who is not a contact, ask with add_contact.
"""
return await mailbox.contacts_and_groups(db, (await me(db, token)).person)
return await messages.contacts_and_groups(db, (await me(db, token)).person)


@mcp.tool(annotations=WRITE)
Expand Down Expand Up @@ -348,7 +348,7 @@ async def send(
group, with `reply_to` set to its id.
"""
you = await me(db, token, from_agent)
return await mailbox.send(
return await messages.send(
db, you, await accounts.resolve(db, to), text, reply_to, attachments
)

Expand Down Expand Up @@ -377,7 +377,7 @@ async def inbox(
their ids, and the same agent you read as, once you have handled them.
"""
you = replace(await me(db, token), agent=agent)
return {"notice": NOTICE} | await mailbox.inbox(db, you, limit)
return {"notice": NOTICE} | await messages.inbox(db, you, limit)


@mcp.tool(annotations=IDEMPOTENT_WRITE)
Expand All @@ -399,7 +399,7 @@ async def mark_read(
address you read them as are marked.
"""
you = await me(db, token, agent)
return {"marked_read": await mailbox.mark_read(db, you, ids)}
return {"marked_read": await messages.mark_read(db, you, ids)}


@mcp.tool(annotations=WRITE)
Expand All @@ -418,7 +418,7 @@ async def create_group(
agents with invite.
"""
you = await me(db, token, from_agent)
return {"group": str(await mailbox.create_group(db, you, name))}
return {"group": str(await messages.create_group(db, you, name))}


@mcp.tool(annotations=IDEMPOTENT_WRITE)
Expand All @@ -432,7 +432,7 @@ async def invite(
"""Add an address to a group you are in: one of your own joins at once; a
contact's is invited and joins when they accept."""
you = await me(db, token, from_agent)
status = await mailbox.invite(
status = await messages.invite(
db, you, await accounts.resolve(db, group), await accounts.resolve(db, address)
)
return {"group": group, "address": address, "status": status}
Expand Down Expand Up @@ -462,7 +462,7 @@ async def leave(
"""
you = await me(db, token, from_agent)
member = await accounts.resolve(db, address) if address else you
await mailbox.leave(db, you, await accounts.resolve(db, group), member)
await messages.leave(db, you, await accounts.resolve(db, group), member)
return {"group": group, "removed": str(member)}


Expand All @@ -486,7 +486,7 @@ async def add_contact(
"""
you = await me(db, token, from_agent)
other = await accounts.resolve(db, username)
status = await mailbox.add_contact(db, you, other, greeting)
status = await messages.add_contact(db, you, other, greeting)
return await accounts.profile(db, other.person) | {"status": status}


Expand All @@ -511,7 +511,7 @@ async def answer(
from any of them settles it.
"""
you = await me(db, token, from_agent)
status = await mailbox.answer(db, you, request_id, accept)
status = await messages.answer(db, you, request_id, accept)
return {"request": request_id, "status": status}


Expand All @@ -526,7 +526,7 @@ async def remove_contact(
"""Remove a contact and block them, so neither of you can write to the other.
Ask your user first. add_contact undoes it."""
other = await accounts.resolve(db, username)
await mailbox.remove_contact(db, (await me(db, token)).person, other.person)
await messages.remove_contact(db, (await me(db, token)).person, other.person)
return {"removed": str(other)}


Expand Down Expand Up @@ -560,7 +560,7 @@ async def delete_account(
you = await me(db, token)
# Before the bucket's deletes, so one of them failing can't skip it.
signed_out = await revoke_grant(token.token)
await mailbox.delete_account(db, you.person)
await messages.delete_account(db, you.person)
return {"deleted": you.username, "signed_out": signed_out}


Expand Down Expand Up @@ -617,7 +617,7 @@ async def content() -> tuple[str, str, bytes | None]:
try:
data, content_type = await fetch_public(source)
except httpx2.HTTPError as error:
raise mailbox.Refused(f"Could not fetch the file: {error}") from error
raise messages.Refused(f"Could not fetch the file: {error}") from error
named = (
name
or (file and file.file_name)
Expand All @@ -633,7 +633,7 @@ async def content() -> tuple[str, str, bytes | None]:
)
return named, typed, data

return await mailbox.attach(db, you, content)
return await messages.attach(db, you, content)


SHOWN_AS_IMAGES = {"image/png", "image/jpeg", "image/gif", "image/webp"}
Expand All @@ -650,7 +650,7 @@ async def open_attachment(
) -> Image | EmbeddedResource:
"""Open an attachment of a message you sent or received, to see what it holds."""
person = (await me(db, token)).person
name, mime, data = await mailbox.open_attachment(db, person, id)
name, mime, data = await messages.open_attachment(db, person, id)
if mime in SHOWN_AS_IMAGES:
return Image(data=data, format=mime.removeprefix("image/"))
uri = f"attachment://{id}/{name}"
Expand Down Expand Up @@ -823,7 +823,7 @@ class Challenge(BaseModel):
async def save(subscription: Subscription) -> None:
"""Store the subscription so a restarted server resumes its deliveries."""
async with instance.get_db() as db:
await mailbox.save_subscription(
await messages.save_subscription(
db,
subscription.id,
subscription.expires_at,
Expand Down Expand Up @@ -930,11 +930,11 @@ async def fetch_public(url: str) -> tuple[bytes, str | None]:
data = bytearray()
async for chunk in response.aiter_bytes():
data += chunk
if len(data) > mailbox.MAX_ATTACHMENT:
raise mailbox.Refused(mailbox.TOO_LARGE)
if len(data) > messages.MAX_ATTACHMENT:
raise messages.Refused(messages.TOO_LARGE)
content_type = response.headers.get("content-type", "")
return bytes(data), content_type.split(";")[0] or None
raise mailbox.Refused(f"{url} redirects too many times.")
raise messages.Refused(f"{url} redirects too many times.")


async def verify(subscription: Subscription) -> None:
Expand Down Expand Up @@ -1022,7 +1022,7 @@ def methods(self) -> tuple[MethodBinding, ...]:
@asynccontextmanager
async def lifespan(self):
async with instance.get_db() as db:
states = await mailbox.subscriptions(db)
states = await messages.subscriptions(db)
for state in states:
# A rotated GITHUB_CLIENT_SECRET drops the row; the client resubscribes.
with suppress(InvalidToken):
Expand Down Expand Up @@ -1102,7 +1102,7 @@ async def subscribe(
truncated=False,
)
async with instance.get_db() as db:
position, truncated = await mailbox.start_position(
position, truncated = await messages.start_position(
db,
None if params.cursor is None else int(params.cursor),
params.max_age_ms,
Expand Down Expand Up @@ -1154,14 +1154,14 @@ async def unsubscribe(

async def pump(self, subscription: Subscription) -> None:
"""Deliver the subscription's new deliveries in order until it expires."""
reader = mailbox.Address(subscription.person, subscription.agent)
reader = messages.Address(subscription.person, subscription.agent)
try:
with instance.waiters.watch(subscription.person) as woken:
while datetime.now(UTC) < subscription.expires_at:
woken.clear()
try:
async with instance.get_db() as db:
events = await mailbox.waiting(
events = await messages.waiting(
db, reader, subscription.position
)
for event in events:
Expand Down
Loading