Bulletin client.

This commit is contained in:
Michael Woods
2025-02-15 20:38:25 -05:00
parent e7cd7188b0
commit d541b399bd
2 changed files with 56 additions and 3 deletions

View File

@@ -0,0 +1,52 @@
from packetserver.client import Client
from packetserver.common import Request, Response, PacketServerConnection
from typing import Union, Optional
import datetime
import time
class BulletinWrapper:
def __init__(self, data: dict):
for i in ['author', 'id', 'subject', 'body', 'created_at', 'updated_at']:
if i not in data:
raise ValueError("Was not given a bulletin dictionary.")
self.data = data
@property
def created(self) -> datetime.datetime:
return datetime.datetime.fromisoformat(self.data['created_at'])
@property
def updated(self) -> datetime.datetime:
return datetime.datetime.fromisoformat(self.data['updated_at'])
@property
def author(self) -> str:
return self.data['author']
@property
def subject(self) -> str:
return self.data['subject']
@property
def body(self) -> str:
return self.data['body']
def post_bulletin(client: Client, bbs_callsign: str, subject: str, body: str) -> int:
req = Request.blank()
req.path = "bulletin"
req.payload = {'subject': subject, 'body': body}
req.method = Request.Method.POST
response = client.send_receive_callsign(req, bbs_callsign)
if response.status_code != 201:
raise RuntimeError(f"Posting bulletin failed: {response.status_code}: {response.payload}")
return response.payload['bulletin_id']
def get_bulletin_by_id(client: Client, bbs_callsign: str, bid: int) -> BulletinWrapper:
req = Request.blank()
req.path = "bulletin"
req.set_var('id', bid)
req.method = Request.Method.GET
response = client.send_receive_callsign(req, bbs_callsign)
if response.status_code != 200:
raise RuntimeError(f"Sending job failed: {response.status_code}: {response.payload}")
return BulletinWrapper(response.payload)

View File

@@ -49,12 +49,13 @@ class Bulletin(persistent.Persistent):
def from_dict(cls, bulletin_dict: dict) -> Self:
return Bulletin(bulletin_dict['author'], bulletin_dict['subject'], bulletin_dict['body'])
def write_new(self, db_root: PersistentMapping):
def write_new(self, db_root: PersistentMapping) -> int:
if self.id is None:
self.id = get_new_bulletin_id(db_root)
self.created_at = datetime.datetime.now(datetime.UTC)
self.updated_at = datetime.datetime.now(datetime.UTC)
db_root['bulletins'].append(self)
return self.id
def update_subject(self, new_text: str):
self.subject = new_text
@@ -128,8 +129,8 @@ def handle_bulletin_post(req: Request, conn: PacketServerConnection, db: ZODB.DB
b = Bulletin(author, str(req.payload['subject']), str(req.payload['body']))
response = Response.blank()
with db.transaction() as db:
b.write_new(db.root())
send_blank_response(conn, req, status_code=201)
bid = b.write_new(db.root())
send_blank_response(conn, req, status_code=201, payload={'bulletin_id': bid})
def handle_bulletin_update(req: Request, conn: PacketServerConnection, db: ZODB.DB): # TODO
response = Response.blank()