From a36cc5b117ce57728421940ab138048cb15a0641 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Thu, 3 Dec 2026 05:17:36 +0800 Subject: [PATCH] Add composable social profiles, conversations, posts, notes and comments --- README.md | 8 ++- docs/social-plugins.md | 81 +++++++++++++++++++++++++ mica/gateway.py | 8 ++- mica/social/__init__.py | 9 +++ mica/social/chat.py | 96 ++++++++++++++++++++++++++++++ mica/social/comment.py | 53 +++++++++++++++++ mica/social/common.py | 35 +++++++++++ mica/social/message.py | 27 +++++++++ mica/social/note.py | 3 + mica/social/post.py | 3 + mica/social/publication.py | 44 ++++++++++++++ mica/social/richtext.py | 34 +++++++++++ mica/social/user.py | 46 +++++++++++++++ tests/test_social.py | 118 +++++++++++++++++++++++++++++++++++++ 14 files changed, 562 insertions(+), 3 deletions(-) create mode 100644 docs/social-plugins.md create mode 100644 mica/social/__init__.py create mode 100644 mica/social/chat.py create mode 100644 mica/social/comment.py create mode 100644 mica/social/common.py create mode 100644 mica/social/message.py create mode 100644 mica/social/note.py create mode 100644 mica/social/post.py create mode 100644 mica/social/publication.py create mode 100644 mica/social/richtext.py create mode 100644 mica/social/user.py create mode 100644 tests/test_social.py diff --git a/README.md b/README.md index 9a14c09..a4242bf 100644 --- a/README.md +++ b/README.md @@ -99,9 +99,13 @@ python3 -B -m unittest discover -s tests -v 数据库契约测试可使用 `MICA_TEST_POSTGRESQL` 和 `MICA_TEST_MYSQL` 指定两个专用、可丢弃的测试库。测试会创建表、写入数据并核对再次启动、跨插件事务、并发初始化和兼容性;未设置的服务端用例显示为 skipped。 +## 首批社交插件 + +站点可分别启用用户、聊天、消息、短帖、图文笔记、评论和共享富文本能力。依赖表、授权、按用户 ID 展开帖子和聊天的完整请求见[社交插件指南](docs/social-plugins.md)。 + ## 多站点 Graph 协议 v1 -同一个进程、监听端口和 `POST /v1/graph` 路径服务多个站点。Graph 模式通过 `MICA_SITES_FILE` 选择,启动后只提供这个协议。上面的 `/content` 仍可通过原来的单站模式运行。Graph 模式使用 `mica.plugins` 入口点加载插件;新的业务插件由站点自行安装并启用。 +同一个进程、监听端口和 `POST /v1/graph` 路径服务多个站点。Graph 模式通过 `MICA_SITES_FILE` 选择,启动后只提供这个协议。上面的 `/content` 仍可通过原来的单站模式运行。Graph 模式使用 `mica.plugins` 入口点加载插件;内置社交插件可在站点配置中按名启用;外部插件可作为独立包安装。 站点配置是一个 JSON 数组。为每个站点预建独立数据库,配置稳定的名称、公开站点 key、调用者和已启用插件。下面的空插件列表可用于启动空宿主并查询 schema。将占位摘要替换成高熵随机 Bearer 凭据的 SHA-256 小写十六进制摘要。`origins` 填写允许直接调用 API 的浏览器来源;服务间调用可省略此项。 @@ -149,6 +153,6 @@ curl -sS https://api.example/v1/graph \ ### 插件声明与升级 - `Snippet.node` 可选,取值为 `mica.protocol.Node`。声明单列主键、可读字段、读权限、每字段允许的筛选符、可选的 `visibility(call)` SQL 条件。用 `Edge(target, local, remote)` 声明等值关联;`target` 指向已注册的 snippet。 -- 通过 `Action(handler, grant, arguments)` 将操作显式暴露给图端点。参数类型支持必填的 str、int、float、bool,返回 JSON 可表示的数据。已有普通 Python 操作仍可供插件内部调用。`call.principal` 包含站点、主体和授权;对象级写入权限由处理函数校验,可抛出 `ProtocolError(403, "forbidden")`。插件间调用公共操作同样检查权限。 +- 通过 `Action(handler, grant, arguments)` 将操作显式暴露给图端点。参数类型支持必填的 str、int、float、bool、list、dict,返回 JSON 可表示的数据。已有普通 Python 操作仍可供插件内部调用。`call.principal` 包含站点、主体和授权;对象级写入权限由处理函数校验,可抛出 `ProtocolError(403, "forbidden")`。插件间调用公共操作同样检查权限。 - `Plugin.version` 为从 1 开始的整型修订号。`Plugin.migrations={2: upgrade_to_2}` 声明 1 到 2 的回调,接收同一站点的 SQLAlchemy Connection。每个站点独立登记基线和逐次升级记录。新库直接创建当前模型,旧版目录按 v1 接续。升级在启动锁内执行,缺少中间步骤或尝试降级会拒绝启动。迁移应明确处理重命名、回填及其跨版本依赖。MySQL 的 DDL 隐式提交,涉及 DDL 的升级回调须可安全重试。 - 测试夹具 `tests/test_graph.py` 展示了插件声明、组合筛选、关系、调用者权限和批量更新。环境变量 `MICA_GRAPH_TEST_ONE`、`MICA_GRAPH_TEST_TWO` 可以指向两个独立的可丢弃服务端数据库;缺省用临时 SQLite 文件。 diff --git a/docs/social-plugins.md b/docs/social-plugins.md new file mode 100644 index 0000000..cd8c6e5 --- /dev/null +++ b/docs/social-plugins.md @@ -0,0 +1,81 @@ +# 按站点组合社交插件 + +在 `MICA_SITES_FILE` 对应站点的 `plugins` 数组中列出所需插件和依赖。站点启动时,Core 组装该站点的图,创建插件声明的表。用户 ID 等于此站点配置中调用者的 `subject`。用户资料、聊天和内容均保存在该站点自己的数据库中。 + +| 插件 | 必需插件 | 提供的能力 | +| --- | --- | --- | +| `user` | 无 | 创建、更新自己的公开资料,按 ID 或 handle 读取 | +| `chat` | user | 建立双人或群聊,维护成员关系和动作历史,向 User 增加 chats | +| `message` | chat(间接依赖 user) | 发送文本消息,将聊天动作和消息作为同一条时间线读取,向 Chat 增加 messages | +| `richtext` | 无 | 校验和保存格式、引用标记;与 message、post 或 note 同时启用时,给这些节点增加富文本写操作 | +| `comment` | user | 共享评论和评论线程,向 User 增加 comments | +| `post` | user、comment | 发布以文字为主的短帖,向 User 增加 posts,向 Comment 增加 post | +| `note` | user、comment | 发布多图长文,向 User 增加 notes,向 Comment 增加 note | + +例如聊天站点可以选择 `["user","chat","message","richtext"]`;图文站点可以选择 `["user","comment","note","richtext"]`。全部启用时使用 `["user","chat","message","richtext","comment","post","note"]`。数组顺序不影响图结构。关闭扩展会隐藏相应节点、边或操作,保留已有记录。富文本的校验操作只在进程内调用;其余插件各自使用 `<插件名>.read` 和 `<插件名>.write` 授权。 + +## 从用户出发 + +向同一个 `POST /v1/graph` 发送请求,附上站点 key 和调用者凭据。例如用 Alice 的凭据建立资料: + +```json +{"mutate":[{"action":"user.create","args":{ + "handle":"@alice","name":"Alice","avatar":"https://cdn.example/alice.jpg", + "bio":"写摄影笔记。","profile":{"城市":"上海"} +}}]} +``` + +handle 在站点内唯一,使用 `@` 加 1–30 个小写字母、数字或下划线,创建后不可更改。`user.update` 接收 name、avatar、bio、profile 四项,只能更新当前调用者的资料。avatar 可留空;profile 是至多 16 对公开的文本键值。真实姓名和用户自定义资料均由调用者主动提供。 + +给定 ID,一次读取这个人的短帖、图文笔记以及当前调用者有权查看的聊天: + +```json +{"query":{"node":"user","id":"alice","fields":["id","handle","name"], + "expand":{"posts":{"fields":["id","text"],"limit":10}, + "notes":{"fields":["id","images"],"limit":10}, + "chats":{"fields":["id","kind","title"],"limit":10}}}} +``` + +每个集合可独立使用 limit、offset。要继续读某个群聊里的发言,按返回的 chat ID 发下一次请求: + +```json +{"query":{"node":"chat","id":"","fields":["title"], + "expand":{"members":{"fields":["id","handle"]}, + "messages":{"fields":["id","kind","author","text","marks","detail","created_at"]}}}} +``` + +## 聊天与消息 + +`chat.create` 接收 kind、title、participants。participants 是已有用户 ID 数组,创建者自动加入。direct 要求两名不同成员,同一对用户再次创建会取得原会话;并发首次创建由唯一约束保护,发生冲突后可重试。group 至少三人,创建者可用 `chat.add_member`、`chat.remove_member` 管理成员。 + +Chat 持久记录 `chat.created`、`member.added` 和 `member.removed`。Message 将这些记录连同 `message.text` 和 `message.rich` 暴露为节点;即使后续才启用 Message,之前的群组动作仍可读取。当前成员可以读完整历史,新加入成员也可读取加入前的记录;被移除后即失去读取和发送能力。授权作用于根查询和关系展开。拥有共同聊天的两个人可以在彼此的 chats 边看到该聊天。 + +## 帖子、图像与评论 + +| 操作 | 入参 | 首版限制 | +| --- | --- | --- | +| `post.create` | text、images | 非空正文,最多 280 个 Unicode 码点,0–4 张图 | +| `note.create` | text、images | 正文最多 10,000 个 Unicode 码点,1–18 张图 | +| `comment.create` | target、target_id、text | 对可读的 post 或 note 写评论,非空正文,最多 2,000 个 Unicode 码点 | + +images 为有序 HTTPS 图片 URL 数组,顺序按原样保存。图片存储或上传由站点提供。一条帖子或笔记可以沿 comments 读取评论;评论可沿 post 或 note 返回所属目标。站点关闭某类目标、或调用者没有目标的读取权限时,对应评论也不可见。 + +## 共享富文本和引用 + +启用 richtext 后,调用 `message.send_rich`、`post.create_rich`、`note.create_rich`,在原入参之外提供 marks。普通文本操作无需传 marks。以下笔记中的“你”引用一个 User: + +```json +{"mutate":[{"action":"note.create_rich","args":{ + "text":"🙂你拍的桥","images":["https://cdn.example/bridge.jpg"], + "marks":[{"type":"ref","start":1,"end":2,"node":"user","id":"alice"}, + {"type":"bold","start":2,"end":5}] +}}]} +``` + +范围是 Unicode 码点的半开区间 `[start,end)`,最多 128 个标记。支持 bold、italic 和 ref,ref 可以指向本项目中已启用且调用者可读的 user、post、note。数据库保存目标类型和 ID,前端自行决定如何渲染及是否再次读取引用。历史内容保留原标记;读取引用目标时仍须通过当前站点的授权。 + +## 给既有插件增加关系 + +`Plugin.extensions` 允许依赖方贡献边和操作。例如 Chat 给 User 增加 chats,借助 `Edge.through` 将 user.id 经成员表的 user_id、chat_id 连接到 chat.id;成员表的复合主键保证每人每群只有一条成员记录。反方向的 chat.members 使用同一张表。目标节点仍执行自己的可见性条件。 + +条件扩展 `Extension.when` 列出所需的 snippet。例如 Message 仅在 richtext 存在时贡献 send_rich。扩展只写入当前站点的注册表,原始 User、Chat 等声明可以在其他站点以不同的组合复用。可通过 `{"schema":true}` 查看实际可用的边、读字段和写操作。 diff --git a/mica/gateway.py b/mica/gateway.py index 1c54d8b..705b454 100644 --- a/mica/gateway.py +++ b/mica/gateway.py @@ -14,6 +14,7 @@ from .core import Runtime from .database import receipts from .graph import node_for, read, schema from .plugins import check_name +from .social import selected from .protocol import Principal, ProtocolError, validate_arguments @@ -59,6 +60,9 @@ def mutate(runtime, principal, body, key): match = (receipts.c.subject == principal.subject) & (receipts.c.key_hash == key_hash) try: with runtime.transaction(principal) as call: + # SQLite ignores SELECT FOR UPDATE; serialize the membership check with the write. + if call.db.dialect.name == "sqlite": + call.db.exec_driver_sql("BEGIN IMMEDIATE") if key is not None: try: call.db.execute(receipts.insert().values(subject=principal.subject, @@ -100,7 +104,9 @@ class GraphApp: raise ValueError("configure explicit HTTP(S) origins") self.origins[key] = frozenset(origins) identities = callers(name, site["callers"]) - runtime = Runtime(site["database"], plugins, enabled=site.get("plugins"), site=name) + enabled = site.get("plugins") + builtins = selected(enabled or ()) + runtime = Runtime(site["database"], (*plugins, *builtins), enabled=enabled, site=name) self.sites[key] = (runtime, identities) if not names: raise ValueError("configure at least one site") diff --git a/mica/social/__init__.py b/mica/social/__init__.py new file mode 100644 index 0000000..cc17902 --- /dev/null +++ b/mica/social/__init__.py @@ -0,0 +1,9 @@ +"""Site-selectable social graph plugins distributed with MICA.""" + +from importlib import import_module + +NAMES = ("user", "chat", "message", "richtext", "comment", "post", "note") + + +def selected(names): + return [import_module(f"{__name__}.{name}").plugin for name in NAMES if name in names] diff --git a/mica/social/chat.py b/mica/social/chat.py new file mode 100644 index 0000000..3bd14a7 --- /dev/null +++ b/mica/social/chat.py @@ -0,0 +1,96 @@ +from hashlib import sha256 + +from sqlalchemy import JSON, Column, ForeignKey, String, Table, Text, select + +from ..plugins import Extension, Plugin, Snippet +from ..protocol import Action, Edge, Node, ProtocolError, Through +from .common import metadata, new_id, now, require, text_value +from .user import current, users + +chats = Table("social_chats", metadata, Column("id", String(52), primary_key=True), + Column("kind", String(8), nullable=False), Column("title", String(160), nullable=False), + Column("owner", ForeignKey(users.c.id), nullable=False), Column("pair", String(64), unique=True)) +members = Table("social_members", metadata, Column("chat_id", ForeignKey(chats.c.id), primary_key=True), + Column("user_id", ForeignKey(users.c.id), primary_key=True, index=True)) +# Keep the journal even on sites that enable Message after chats already exist. +events = Table("social_messages", metadata, Column("id", String(52), primary_key=True), + Column("chat_id", ForeignKey(chats.c.id), nullable=False, index=True), + Column("author", ForeignKey(users.c.id), nullable=False), Column("kind", String(32), nullable=False), + Column("text", Text, nullable=False), Column("marks", JSON, nullable=False), + Column("detail", JSON, nullable=False), Column("created_at", String(40), nullable=False)) + + +def memberships(call): + return select(members.c.chat_id).where(members.c.user_id == call.principal.subject) + + +def append(call, chat_id, kind, body="", marks=(), **detail): + identifier = new_id() + call.db.execute(events.insert().values(id=identifier, chat_id=chat_id, author=call.principal.subject, + kind=kind, text=body, marks=list(marks), detail=detail, created_at=now())) + return identifier + + +def member_chat(call, chat_id): + # Serialize membership changes and sends so a removal cannot race a send. + row = call.db.execute(select(chats).where(chats.c.id == chat_id).with_for_update()).mappings().first() + member = call.db.scalar(select(members.c.user_id).where( + members.c.chat_id == chat_id, members.c.user_id == call.principal.subject).with_for_update()) + if row is None or member is None: + raise ProtocolError(404, "unknown_chat") + return row + + +def create(call, kind, title, participants): + owner = current(call) + require(all(isinstance(p, str) for p in participants) and len(participants) <= 99, "invalid_members") + ids = sorted(set([owner, *participants])) + require((kind == "direct" and len(ids) == 2) or (kind == "group" and len(ids) >= 3), "invalid_chat") + text_value(title, 160, empty=True) + if set(call.db.scalars(select(users.c.id).where(users.c.id.in_(ids)))) != set(ids): + raise ProtocolError(404, "unknown_user") + pair = None + if kind == "direct": + pair = sha256("|".join(ids).encode()).hexdigest() + existing = call.db.scalar(select(chats.c.id).where(chats.c.pair == pair)) + if existing: + return existing + identifier = new_id() + call.db.execute(chats.insert().values(id=identifier, kind=kind, title=title, owner=owner, pair=pair)) + call.db.execute(members.insert(), [{"chat_id": identifier, "user_id": p} for p in ids]) + append(call, identifier, "chat.created", members=ids) + return identifier + + +def change_membership(call, chat_id, user_id, *, add): + chat = member_chat(call, chat_id) + if chat["kind"] != "group" or chat["owner"] != call.principal.subject: + raise ProtocolError(403, "group_owner_required") + require(user_id != chat["owner"], "owner_membership_required") + if add: + call.db.execute(members.insert().values(chat_id=chat_id, user_id=user_id)) + else: + removed = call.db.execute(members.delete().where(members.c.chat_id == chat_id, members.c.user_id == user_id)) + if not removed.rowcount: + raise ProtocolError(404, "unknown_member") + return append(call, chat_id, "member.added" if add else "member.removed", user_id=user_id) + + +def add_member(call, chat_id, user_id): + return change_membership(call, chat_id, user_id, add=True) + + +def remove_member(call, chat_id, user_id): + return change_membership(call, chat_id, user_id, add=False) + + +member_args = {"chat_id": str, "user_id": str} +node = Node(chats, "id", ("id", "kind", "title", "owner"), "chat.read", {"kind": ("eq",)}, + {"members": Edge("user", "id", "id", Through(members, "chat_id", "user_id"))}, + visibility=lambda call: chats.c.id.in_(memberships(call))) +plugin = Plugin("chat", (Snippet("chat", { + "create": Action(create, "chat.write", {"kind": str, "title": str, "participants": list}), + "add_member": Action(add_member, "chat.write", member_args), + "remove_member": Action(remove_member, "chat.write", member_args), +}, (chats, members, events), node),), requires=("user",), extensions=( + Extension("user", {"chats": Edge("chat", "id", "id", Through(members, "user_id", "chat_id"))}),)) diff --git a/mica/social/comment.py b/mica/social/comment.py new file mode 100644 index 0000000..1e0e8bb --- /dev/null +++ b/mica/social/comment.py @@ -0,0 +1,53 @@ +from sqlalchemy import Column, ForeignKey, String, Table, Text, false, or_, select + +from ..plugins import Extension, Plugin, Snippet +from ..protocol import Action, Edge, Node, ProtocolError +from .common import metadata, new_id, now, text_value +from .user import current, users + +threads = Table("social_threads", metadata, Column("id", String(52), primary_key=True), + Column("kind", String(63), nullable=False)) +comments = Table("social_comments", metadata, Column("id", String(52), primary_key=True), + Column("thread_id", ForeignKey(threads.c.id), nullable=False, index=True), + Column("author", ForeignKey(users.c.id), nullable=False), + Column("text", Text, nullable=False), Column("created_at", String(40), nullable=False)) + + +def open_thread(call, kind): + identifier = new_id() + call.db.execute(threads.insert().values(id=identifier, kind=kind)) + return identifier + + +def visible_threads(call): + conditions = [] + for name, node in call.registry.nodes.items(): + edge = node.edges.get("comments") + if edge is None or edge.target != "comment" or node.grant not in call.principal.grants: + continue + condition = threads.c.kind == name + if node.visibility is not None: + visible = select(node.table.c[node.key]).where(node.visibility(call)) + condition &= threads.c.id.in_(visible) + conditions.append(condition) + return select(threads.c.id).where(or_(false(), *conditions)) + + +def create(call, target, target_id, text): + author = current(call) + lookup = visible_threads(call).where(threads.c.id == target_id, threads.c.kind == target) + if call.db.scalar(lookup) is None: + raise ProtocolError(404, "unknown_comment_target") + identifier = new_id() + call.db.execute(comments.insert().values(id=identifier, thread_id=target_id, author=author, + text=text_value(text, 2000), created_at=now())) + return identifier + + +node = Node(comments, "id", tuple(comments.c.keys()), "comment.read", {"thread_id": ("eq",)}, + {"author_user": Edge("user", "author", "id")}, + visibility=lambda call: comments.c.thread_id.in_(visible_threads(call))) +plugin = Plugin("comment", (Snippet("comment", {"open_thread": open_thread, + "create": Action(create, "comment.write", {"target": str, "target_id": str, "text": str})}, + (threads, comments), node),), requires=("user",), + extensions=(Extension("user", {"comments": Edge("comment", "id", "author")}),)) diff --git a/mica/social/common.py b/mica/social/common.py new file mode 100644 index 0000000..42852bd --- /dev/null +++ b/mica/social/common.py @@ -0,0 +1,35 @@ +from datetime import datetime, timezone +from urllib.parse import urlsplit +from uuid import uuid4 + +from sqlalchemy import MetaData + +from ..protocol import ProtocolError + +metadata = MetaData() + + +def now(): + return datetime.now(timezone.utc).isoformat(timespec="microseconds") + + +def new_id(): + # The graph orders by primary key. Keep messages and posts in creation order. + return datetime.now(timezone.utc).strftime("%Y%m%d%H%M%S%f") + uuid4().hex + + +def require(condition, code): + if not condition: + raise ProtocolError(400, code) + + +def text_value(value, limit, *, empty=False): + require(isinstance(value, str) and len(value) <= limit and (empty or value.strip()), "invalid_text") + return value + + +def media_url(value): + require(isinstance(value, str) and len(value) <= 2048 and not any(c.isspace() for c in value), "invalid_url") + url = urlsplit(value) + require(url.scheme == "https" and url.hostname and not url.username and not url.password, "invalid_url") + return value diff --git a/mica/social/message.py b/mica/social/message.py new file mode 100644 index 0000000..ac95216 --- /dev/null +++ b/mica/social/message.py @@ -0,0 +1,27 @@ +from ..plugins import Extension, Plugin, Snippet +from ..protocol import Action, Edge, Node +from .chat import append, events, member_chat, memberships +from .common import text_value + + +def send(call, chat_id, text): + member_chat(call, chat_id) + return append(call, chat_id, "message.text", text_value(text, 10000)) + + +def send_rich(call, chat_id, text, marks): + member_chat(call, chat_id) + text_value(text, 10000) + return append(call, chat_id, "message.rich", text, call.call("richtext.validate", text=text, marks=marks)) + + +args = {"chat_id": str, "text": str} +node = Node(events, "id", tuple(events.c.keys()), "message.read", + {"kind": ("eq",), "chat_id": ("eq",), "id": ("gt", "lt")}, + {"author_user": Edge("user", "author", "id"), "chat": Edge("chat", "chat_id", "id")}, + visibility=lambda call: events.c.chat_id.in_(memberships(call))) +plugin = Plugin("message", (Snippet("message", {"send": Action(send, "message.write", args)}, node=node),), + requires=("chat",), extensions=( + Extension("chat", {"messages": Edge("message", "id", "chat_id")}), + Extension("message", operations={"send_rich": Action(send_rich, "message.write", {**args, "marks": list})}, + when=("richtext",)),)) diff --git a/mica/social/note.py b/mica/social/note.py new file mode 100644 index 0000000..d85899a --- /dev/null +++ b/mica/social/note.py @@ -0,0 +1,3 @@ +from .publication import publication + +plugin = publication("note", text_limit=10000, min_images=1, max_images=18) diff --git a/mica/social/post.py b/mica/social/post.py new file mode 100644 index 0000000..6c8a9e9 --- /dev/null +++ b/mica/social/post.py @@ -0,0 +1,3 @@ +from .publication import publication + +plugin = publication("post", text_limit=280, min_images=0, max_images=4) diff --git a/mica/social/publication.py b/mica/social/publication.py new file mode 100644 index 0000000..9f1f635 --- /dev/null +++ b/mica/social/publication.py @@ -0,0 +1,44 @@ +"""Shared publication actions; each content plugin owns its table and limits.""" + +from sqlalchemy import JSON, Column, ForeignKey, String, Table, Text + +from ..plugins import Extension, Plugin, Snippet +from ..protocol import Action, Edge, Node +from .comment import threads +from .common import media_url, metadata, now, require, text_value +from .user import current, users + + +def publication(kind, *, text_limit, min_images, max_images): + table = Table("social_" + kind + "s", metadata, Column("id", ForeignKey(threads.c.id), primary_key=True), + Column("author", ForeignKey(users.c.id), nullable=False, index=True), + Column("text", Text, nullable=False), Column("images", JSON, nullable=False), + Column("marks", JSON, nullable=False), Column("created_at", String(40), nullable=False)) + + def save(call, text, images, marks): + author = current(call) + text_value(text, text_limit, empty=min_images > 0) + require(min_images <= len(images) <= max_images, "invalid_image_count") + urls = [media_url(url) for url in images] + identifier = call.call("comment.open_thread", kind=kind) + call.db.execute(table.insert().values(id=identifier, author=author, text=text, images=urls, + marks=marks, created_at=now())) + return identifier + + def create(call, text, images): + return save(call, text, images, []) + + def create_rich(call, text, images, marks): + validated = call.call("richtext.validate", text=text, marks=marks) + return save(call, text, images, validated) + + args = {"text": str, "images": list} + write = kind + ".write" + node = Node(table, "id", tuple(table.c.keys()), kind + ".read", {"author": ("eq",), "id": ("lt", "gt")}, + {"author_user": Edge("user", "author", "id"), "comments": Edge("comment", "id", "thread_id")}) + return Plugin(kind, (Snippet(kind, {"create": Action(create, write, args)}, (table,), node),), + requires=("user", "comment"), extensions=( + Extension("user", {kind + "s": Edge(kind, "id", "author")}), + Extension("comment", {kind: Edge(kind, "thread_id", "id")}), + Extension(kind, operations={"create_rich": Action(create_rich, write, {**args, "marks": list})}, + when=("richtext",)),)) diff --git a/mica/social/richtext.py b/mica/social/richtext.py new file mode 100644 index 0000000..c2d46f1 --- /dev/null +++ b/mica/social/richtext.py @@ -0,0 +1,34 @@ +from sqlalchemy import select + +from ..plugins import Plugin, Snippet +from ..protocol import ProtocolError +from .common import require + + +def validate(call, text, marks): + require(len(marks) <= 128, "too_many_marks") + for mark in marks: + require(isinstance(mark, dict), "invalid_mark") + kind = mark.get("type") + require(kind in ("bold", "italic", "ref"), "invalid_mark") + keys = {"start", "end", "type"} + require(mark.keys() == (keys | {"node", "id"} if kind == "ref" else keys), "invalid_mark") + start, end = mark["start"], mark["end"] + require(type(start) is int and type(end) is int and 0 <= start < end <= len(text), "invalid_range") + if kind == "ref": + # These references are suitable for public posts as well as private chats. + name, identifier = mark["node"], mark["id"] + require(name in ("user", "post", "note") and isinstance(identifier, str), "invalid_ref") + node = call.registry.nodes.get(name) + if node is None: + raise ProtocolError(404, "unknown_reference") + call.principal.require(node.grant) + stmt = select(node.table.c[node.key]).where(node.table.c[node.key] == identifier) + if node.visibility: + stmt = stmt.where(node.visibility(call)) + if call.db.scalar(stmt) is None: + raise ProtocolError(404, "unknown_reference") + return marks + + +plugin = Plugin("richtext", (Snippet("richtext", {"validate": validate}),)) diff --git a/mica/social/user.py b/mica/social/user.py new file mode 100644 index 0000000..646fbd3 --- /dev/null +++ b/mica/social/user.py @@ -0,0 +1,46 @@ +import re + +from sqlalchemy import JSON, Column, String, Table, Text, select + +from ..plugins import Plugin, Snippet +from ..protocol import Action, Node, ProtocolError +from .common import media_url, metadata, require, text_value + +users = Table("social_users", metadata, Column("id", String(63), primary_key=True), + Column("handle", String(32), nullable=False, unique=True), + Column("name", String(100), nullable=False), Column("avatar", Text, nullable=False), + Column("bio", Text, nullable=False), Column("profile", JSON, nullable=False)) + + +def current(call): + subject = call.principal.subject + if call.db.scalar(select(users.c.id).where(users.c.id == subject)) is None: + raise ProtocolError(404, "profile_required") + return subject + + +def details(name, avatar, bio, profile): + require(len(profile) <= 16 and all(isinstance(v, str) and len(v) <= 256 and 0 < len(k) <= 40 + for k, v in profile.items()), "invalid_profile") + return dict(name=text_value(name, 100), avatar=media_url(avatar) if avatar else "", + bio=text_value(bio, 2000, empty=True), profile=profile) + + +def create(call, handle, **fields): + require(re.fullmatch(r"@[a-z0-9_]{1,30}", handle), "invalid_handle") + subject = call.principal.subject + call.db.execute(users.insert().values(id=subject, handle=handle, **details(**fields))) + return subject + + +def update(call, **fields): + subject = current(call) + call.db.execute(users.update().where(users.c.id == subject).values(**details(**fields))) + return subject + + +fields = {"name": str, "avatar": str, "bio": str, "profile": dict} +plugin = Plugin("user", (Snippet("user", { + "create": Action(create, "user.write", {"handle": str, **fields}), + "update": Action(update, "user.write", fields), +}, (users,), Node(users, "id", tuple(users.c.keys()), "user.read", {"handle": ("eq", "prefix")})),)) diff --git a/tests/test_social.py b/tests/test_social.py new file mode 100644 index 0000000..8cb96df --- /dev/null +++ b/tests/test_social.py @@ -0,0 +1,118 @@ +from hashlib import sha256 +from io import BytesIO +import json +import os +from pathlib import Path +from tempfile import TemporaryDirectory +from unittest import TestCase +from uuid import uuid4 + +from mica.gateway import GraphApp +from mica.social import NAMES + + +class SocialGraph(TestCase): + def setUp(self): + temp = TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.ids = [prefix + uuid4().hex[:12] for prefix in ("a", "b", "c", "d")] + grants = [f"{p}.{mode}" for p in NAMES for mode in ("read", "write")] + self.config = {"name": "one", "key": "one", "database": os.environ.get( + "MICA_SOCIAL_TEST_DB", str(Path(temp.name) / "social.db")), + "callers": [{"subject": i, "sha256": sha256(i.encode()).hexdigest(), "grants": grants} + for i in self.ids]} + self.app = None + self.addCleanup(lambda: self.app and self.app.close()) + self.enable(NAMES) + for uid in self.ids: + self.action("user.create", actor=uid, handle="@"+uid, name=uid, avatar="", bio="", profile={}) + + def enable(self, plugins): + if self.app: + self.app.close() + self.app = GraphApp([{**self.config, "plugins": list(plugins)}]) + + def request(self, body, actor=None, expected=200): + raw = json.dumps(body).encode() + status = [] + env = {"REQUEST_METHOD": "POST", "PATH_INFO": "/v1/graph", "CONTENT_TYPE": "application/json", + "CONTENT_LENGTH": str(len(raw)), "HTTP_X_MICA_SITE_KEY": "one", "wsgi.input": BytesIO(raw), + "HTTP_AUTHORIZATION": "Bearer "+(actor or self.ids[0])} + data = json.loads(b"".join(self.app(env, lambda line, headers: status.append(int(line[:3]))))) + self.assertEqual(status, [expected], data) + return data.get("data", data.get("error")) + + def action(self, action, actor=None, expected=200, **args): + data = self.request({"mutate": [{"action": action, "args": args}]}, actor, expected) + return data[0] if expected == 200 else data + + def query(self, node, id, fields, actor=None, **edges): + return self.request({"query": {"node": node, "id": id, "fields": fields, + "expand": {k: {"fields": v} for k, v in edges.items()}}}, actor) + + def test_conversation_graph_and_history(self): + a, b, c, d = self.ids + self.enable(["user", "chat"]) + direct = self.action("chat.create", kind="direct", title="", participants=[b]) + self.assertEqual(self.action("chat.create", actor=b, kind="direct", title="", participants=[a]), direct) + group = self.action("chat.create", kind="group", title="读书会", participants=[b, c]) + self.enable(["user", "chat", "message"]) + self.assertNotIn("message.send_rich", self.request({"schema": True})["actions"]) + self.assertEqual({r["id"] for r in self.query("user", a, ["id"], chats=["id"])[0]["chats"]}, {direct, group}) + self.assertEqual({r["id"] for r in self.query("chat", group, ["id"], members=["id"])[0]["members"]}, {a,b,c}) + self.assertEqual(self.query("user", a, ["id"], actor=d, chats=["id"])[0]["chats"], []) + self.action("message.send", actor=d, expected=404, chat_id=group, text="私聊") + self.action("chat.add_member", actor=b, expected=403, chat_id=group, user_id=d) + self.action("chat.add_member", chat_id=group, user_id=d) + msg = self.action("message.send", actor=d, chat_id=group, text="你好") + self.action("chat.remove_member", chat_id=group, user_id=d) + self.assertEqual(self.query("message", msg, ["text"], actor=d), []) + history = self.query("chat", group, ["id"], messages=["kind"])[0]["messages"] + self.assertEqual([r["kind"] for r in history], ["chat.created", "member.added", "message.text", "member.removed"]) + self.enable(NAMES) + mark = {"type":"ref","node":"user","id":b,"start":1,"end":2} + msg = self.action("message.send_rich", chat_id=group, text="🙂你", marks=[mark]) + self.assertEqual(self.query("message", msg, ["marks"])[0]["marks"], [mark]) + + def test_publication_graph_and_shared_marks(self): + a,b,_,_ = self.ids + marks = [{"type":"ref","node":"user","id":b,"start":0,"end":1},{"type":"bold","start":0,"end":1}] + post = self.action("post.create_rich", text="你", images=[], marks=marks) + images = [f"https://img.example/{i}.png" for i in range(18)] + note = self.action("note.create_rich", text="你"+"文"*9999, images=images, marks=marks) + self.assertEqual(self.query("note", note, ["images","marks"]), [{"images":images,"marks":marks}]) + profile = self.query("user", a, ["handle"], posts=["id"], notes=["id"])[0] + self.assertEqual(profile, {"handle":"@"+a, "posts":[{"id":post}], "notes":[{"id":note}]}) + for kind, target in [("post",post),("note",note)]: + reply = self.action("comment.create", actor=b, target=kind, target_id=target, text="好") + self.assertEqual(self.query(kind, target, ["id"], comments=["id"])[0]["comments"], [{"id":reply}]) + self.assertEqual(self.query("comment", reply, ["text"], **{kind:["id"]})[0][kind], [{"id":target}]) + self.action("comment.create", expected=404, target="note", target_id=post, text="错") + self.action("note.create", expected=400, text="少图", images=[]) + self.action("note.create", expected=400, text="多图", images=images+[images[0]]) + self.action("post.create", expected=400, text="字"*281, images=[]) + self.action("post.create", expected=400, text="图", images=images[:5]) + self.action("note.create_rich", expected=404, text="?", images=images[:1], marks=[{**marks[0],"id":"missing"}]) + # A caller with comment.read still needs read access to each kind of target. + self.config["callers"][1]["grants"].remove("note.read") + self.enable(NAMES) + visible = self.query("user", b, ["id"], actor=b, comments=["id"])[0]["comments"] + self.assertEqual(len(visible), 1) + self.assertNotEqual(visible[0]["id"], reply) + self.enable(["user","comment","post"]) + site = self.request({"schema":True}) + self.assertEqual(set(site["nodes"]["user"]["edges"]), {"posts","comments"}) + self.assertNotIn("post.create_rich", site["actions"]) + self.assertEqual(self.query("user", b, ["id"], comments=["text"])[0]["comments"], [{"text":"好"}]) + self.enable(["user"]) + self.assertEqual(self.request({"schema":True})["nodes"]["user"]["edges"], {}) + + def test_profile_and_handle(self): + a,b,_,_ = self.ids + fields = {"name":"甲","avatar":"https://img.example/a.jpg","bio":"介绍","profile":{"city":"上海"}} + self.action("user.update", **fields) + self.assertEqual(self.query("user",a,["handle",*fields]), [{"handle":"@"+a,**fields}]) + self.action("user.update", expected=400, handle="@changed", **fields) + self.action("user.update", expected=400, id=b, **fields) + self.action("user.create", expected=409, handle="@another", **fields) + self.assertEqual(self.query("user",a,["handle"]), [{"handle":"@"+a}])