"""Bundled publishing plugin shared by the article and post snippets.""" from datetime import datetime, timezone import json from uuid import uuid4 from sqlalchemy import Column, Index, MetaData, String, Table, Text, select from .content_types import discover from .plugins import Plugin, Snippet def key_type(length): # The original SQLite database stored these fields as TEXT. return String(length).with_variant(Text(), "sqlite") content = Table( "content", MetaData(), Column("id", key_type(32), primary_key=True, info={"sqlite_legacy_nullable_pk": True}), Column("type", key_type(63), nullable=False), Column("fields", Text, nullable=False), Column("published_at", key_type(32)), ) public = content.c.published_at.is_not(None) Index("public_content", content.c.published_at.desc(), content.c.id.desc(), sqlite_where=public, postgresql_where=public) def record(row): if row is None: return None return {**row, "fields": json.loads(row["fields"])} def draft(call, kind, fields): operation = f"{kind}.validate" if not isinstance(kind, str) or operation not in call.registry.operations: raise ValueError("unknown content type") call.call(operation, fields=fields) row = dict(id=uuid4().hex, type=kind, fields=json.dumps(fields), published_at=None) call.db.execute(content.insert().values(**row)) return record(row) def get_public(call, identifier): stmt = select(content).where(content.c.id == identifier, public) return record(call.db.execute(stmt).mappings().one_or_none()) def publish(call, identifier): timestamp = datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z") call.db.execute(content.update().where(content.c.id == identifier, content.c.published_at.is_(None)) .values(published_at=timestamp)) return get_public(call, identifier) def list_public(call, kind, limit, offset): stmt = select(content).where(public) if kind is not None: stmt = stmt.where(content.c.type == kind) stmt = stmt.order_by(content.c.published_at.desc(), content.c.id.desc()).limit(limit).offset(offset) return [record(row) for row in call.db.execute(stmt).mappings()] publishing = Plugin("publishing", (Snippet("content", { "draft": draft, "get": get_public, "publish": publish, "list": list_public, }, (content,)),)) def validation_operation(definition): def validate(call, fields): definition.validate(fields) return validate def bundled_plugins(): yield publishing for name, definition in discover().items(): yield Plugin(name, (Snippet(name, {"validate": validation_operation(definition)}),))