#!/usr/bin/env python3 """Helper script to populate synthetic demo data (including image attachment) for Lab 4 Swagger UI.""" import base64 import json from pathlib import Path import sys import urllib.request import uuid BASE_URL = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080" FIXTURE = Path(__file__).resolve().parents[1] / "tests" / "fixtures" / "sample.png" def req(method, path, body=None, raw=None, headers=None): h = {"Accept": "application/json"} data = raw if body is not None: data = json.dumps(body).encode("utf-8") h["Content-Type"] = "application/json" if headers: h.update(headers) r = urllib.request.Request(BASE_URL + path, data=data, headers=h, method=method) with urllib.request.urlopen(r, timeout=15) as resp: payload = resp.read() inst = resp.headers.get("X-Instance-Id", "") return (json.loads(payload.decode("utf-8")) if payload else None), inst def main(): suffix = uuid.uuid4().hex[:6] alice_username = f"alice_{suffix}" bob_username = f"bob_{suffix}" password = "DemoPassword-2026!" alice, inst1 = req("POST", "/api/v1/users", { "username": alice_username, "display_name": "Alice Zamorskaya", "password": password, }) bob, inst2 = req("POST", "/api/v1/users", { "username": bob_username, "display_name": "Bob Bobrov", "password": password, }) alice_basic = base64.b64encode(f"{alice_username}:{password}".encode("utf-8")).decode("ascii") bob_basic = base64.b64encode(f"{bob_username}:{password}".encode("utf-8")).decode("ascii") alice_sess, _ = req("POST", "/api/v1/auth/sessions", headers={"Authorization": f"Basic {alice_basic}"}) bob_sess, _ = req("POST", "/api/v1/auth/sessions", headers={"Authorization": f"Basic {bob_basic}"}) alice_bearer = {"Authorization": f"Bearer {alice_sess['token']}"} bob_bearer = {"Authorization": f"Bearer {bob_sess['token']}"} chat, _ = req("POST", "/api/v1/chats", { "title": "Lab 4 Attachments Chat", "member_ids": [alice["id"], bob["id"]], }, headers=alice_bearer) img_bytes = FIXTURE.read_bytes() att, inst3 = req( "POST", f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png", raw=img_bytes, headers={**alice_bearer, "Content-Type": "image/png"}, ) _, inst4 = req("POST", f"/api/v1/chats/{chat['id']}/messages", { "text": "Photo stored in private MinIO S3!", "attachment_ids": [att["id"]], }, headers={**alice_bearer, "Idempotency-Key": f"seed-att-{suffix}"}) _, inst5 = req("POST", f"/api/v1/chats/{chat['id']}/messages", { "text": "Got it via another API replica!", }, headers={**bob_bearer, "Idempotency-Key": f"seed-reply-{suffix}"}) print("=== LAB 4 DEMO DATA CREATED ===") print(f"Swagger UI: {BASE_URL}/docs") print(f"Observed IDs: {sorted({x for x in [inst1, inst2, inst3, inst4, inst5] if x})}") print(f"Password: {password}") print(f"Alice Username: {alice_username}") print(f"Alice Token: {alice_sess['token']}") print(f"Bob Username: {bob_username}") print(f"Bob Token: {bob_sess['token']}") print(f"Chat ID: {chat['id']}") print(f"Attachment ID: {att['id']}") if __name__ == "__main__": main()