Add composable social profiles, conversations, posts, notes and comments
This commit is contained in:
+7
-1
@@ -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")
|
||||
|
||||
@@ -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]
|
||||
@@ -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"))}),))
|
||||
@@ -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")}),))
|
||||
@@ -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
|
||||
@@ -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",)),))
|
||||
@@ -0,0 +1,3 @@
|
||||
from .publication import publication
|
||||
|
||||
plugin = publication("note", text_limit=10000, min_images=1, max_images=18)
|
||||
@@ -0,0 +1,3 @@
|
||||
from .publication import publication
|
||||
|
||||
plugin = publication("post", text_limit=280, min_images=0, max_images=4)
|
||||
@@ -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",)),))
|
||||
@@ -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}),))
|
||||
@@ -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")})),))
|
||||
Reference in New Issue
Block a user