openswx-collab-server 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- openswx_collab_server/__init__.py +2 -0
- openswx_collab_server/__main__.py +107 -0
- openswx_collab_server/access.py +98 -0
- openswx_collab_server/app.py +108 -0
- openswx_collab_server/assemblies.py +181 -0
- openswx_collab_server/auth.py +474 -0
- openswx_collab_server/config.py +66 -0
- openswx_collab_server/db.py +241 -0
- openswx_collab_server/documents.py +402 -0
- openswx_collab_server/hooks.py +46 -0
- openswx_collab_server/hub.py +870 -0
- openswx_collab_server/lifecycle.py +204 -0
- openswx_collab_server/mail.py +73 -0
- openswx_collab_server/migrate.py +77 -0
- openswx_collab_server/migrations/__init__.py +0 -0
- openswx_collab_server/migrations/env.py +22 -0
- openswx_collab_server/migrations/script.py.mako +24 -0
- openswx_collab_server/migrations/versions/0001_baseline.py +265 -0
- openswx_collab_server/migrations/versions/0002_users_deleted_at.py +28 -0
- openswx_collab_server/migrations/versions/0003_password_resets.py +36 -0
- openswx_collab_server/migrations/versions/__init__.py +0 -0
- openswx_collab_server/orgs.py +339 -0
- openswx_collab_server/security.py +85 -0
- openswx_collab_server/storage.py +123 -0
- openswx_collab_server-0.1.0.dist-info/METADATA +57 -0
- openswx_collab_server-0.1.0.dist-info/RECORD +30 -0
- openswx_collab_server-0.1.0.dist-info/WHEEL +5 -0
- openswx_collab_server-0.1.0.dist-info/entry_points.txt +2 -0
- openswx_collab_server-0.1.0.dist-info/licenses/LICENSE +202 -0
- openswx_collab_server-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Command line: `openswx-collab-server serve`, and account tools for the operator.
|
|
2
|
+
|
|
3
|
+
serve [--host 0.0.0.0] [--port 8787]
|
|
4
|
+
migrate upgrade the database schema (take a backup first)
|
|
5
|
+
db-status which schema the database is at, and which this server needs
|
|
6
|
+
create-admin <email> [name] make (or promote) a server admin; asks for a password
|
|
7
|
+
reset-password <email> set a new password and end the account's sessions
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import asyncio
|
|
13
|
+
import getpass
|
|
14
|
+
import os
|
|
15
|
+
import sys
|
|
16
|
+
|
|
17
|
+
from sqlalchemy import delete, select
|
|
18
|
+
from sqlalchemy.ext.asyncio import async_sessionmaker
|
|
19
|
+
|
|
20
|
+
from .config import Settings
|
|
21
|
+
from .db import Session, User, init_db, make_engine
|
|
22
|
+
from .hooks import load_hooks
|
|
23
|
+
from .migrate import SchemaError, current, upgrade
|
|
24
|
+
from .security import clean_email, hash_password
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _ask_password() -> str:
|
|
28
|
+
pw = os.environ.get("OSWX_COLLAB_PASSWORD") or getpass.getpass("New password: ")
|
|
29
|
+
if len(pw) < 8:
|
|
30
|
+
sys.exit("the password needs at least 8 characters")
|
|
31
|
+
return pw
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
async def _account(settings: Settings, email: str, name: str | None, admin: bool) -> str:
|
|
35
|
+
email = clean_email(email) or sys.exit("not an email address")
|
|
36
|
+
engine = make_engine(settings.database_url)
|
|
37
|
+
await init_db(engine, settings.auto_migrate, load_hooks())
|
|
38
|
+
async with async_sessionmaker(engine, expire_on_commit=False)() as s:
|
|
39
|
+
user = (await s.execute(select(User).where(User.email == email))).scalar_one_or_none()
|
|
40
|
+
if user is None and not admin:
|
|
41
|
+
sys.exit(f"no account {email}")
|
|
42
|
+
pw = hash_password(_ask_password())
|
|
43
|
+
if user is None:
|
|
44
|
+
user = User(email=email, name=name or email.split("@")[0], password_hash=pw, is_server_admin=True,
|
|
45
|
+
email_verified=True)
|
|
46
|
+
s.add(user)
|
|
47
|
+
done = f"created server admin {email}"
|
|
48
|
+
else:
|
|
49
|
+
user.password_hash = pw
|
|
50
|
+
user.is_server_admin = user.is_server_admin or admin
|
|
51
|
+
await s.execute(delete(Session).where(Session.user_id == user.id))
|
|
52
|
+
done = f"password set for {email}" + (" (server admin)" if user.is_server_admin else "")
|
|
53
|
+
await s.commit()
|
|
54
|
+
await engine.dispose()
|
|
55
|
+
return done
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
async def _schema(settings: Settings, do_upgrade: bool) -> str:
|
|
59
|
+
engine = make_engine(settings.database_url)
|
|
60
|
+
try:
|
|
61
|
+
if do_upgrade:
|
|
62
|
+
before, _ = await current(engine)
|
|
63
|
+
after = await upgrade(engine, allow=True)
|
|
64
|
+
async with engine.begin() as conn:
|
|
65
|
+
await conn.run_sync(load_hooks().prepare_db)
|
|
66
|
+
return f"schema {before or 'none'} -> {after}" if before != after else f"schema {after}: up to date"
|
|
67
|
+
at, head = await current(engine)
|
|
68
|
+
return f"database at {at or 'none (or made before migrations)'}; this server needs {head}"
|
|
69
|
+
except SchemaError as exc:
|
|
70
|
+
sys.exit(str(exc))
|
|
71
|
+
finally:
|
|
72
|
+
await engine.dispose()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def main(argv: list[str] | None = None) -> None:
|
|
76
|
+
p = argparse.ArgumentParser(prog="openswx-collab-server", description=__doc__,
|
|
77
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
78
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
79
|
+
s = sub.add_parser("serve")
|
|
80
|
+
s.add_argument("--host", default="127.0.0.1")
|
|
81
|
+
s.add_argument("--port", type=int, default=8787)
|
|
82
|
+
a = sub.add_parser("create-admin")
|
|
83
|
+
a.add_argument("email")
|
|
84
|
+
a.add_argument("name", nargs="?")
|
|
85
|
+
r = sub.add_parser("reset-password")
|
|
86
|
+
r.add_argument("email")
|
|
87
|
+
sub.add_parser("migrate")
|
|
88
|
+
sub.add_parser("db-status")
|
|
89
|
+
args = p.parse_args(argv)
|
|
90
|
+
settings = Settings.from_env()
|
|
91
|
+
if args.cmd in ("migrate", "db-status"):
|
|
92
|
+
print(asyncio.run(_schema(settings, args.cmd == "migrate")))
|
|
93
|
+
return
|
|
94
|
+
if args.cmd == "serve":
|
|
95
|
+
import uvicorn
|
|
96
|
+
|
|
97
|
+
from .app import create_app
|
|
98
|
+
# one process: open documents live in this process's memory
|
|
99
|
+
uvicorn.run(create_app(settings), host=args.host, port=args.port, workers=1, ws_max_size=settings.max_change_bytes + 65536)
|
|
100
|
+
elif args.cmd == "create-admin":
|
|
101
|
+
print(asyncio.run(_account(settings, args.email, args.name, True)))
|
|
102
|
+
else:
|
|
103
|
+
print(asyncio.run(_account(settings, args.email, None, False)))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
if __name__ == "__main__":
|
|
107
|
+
main()
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Who is asking, and what they may do.
|
|
2
|
+
|
|
3
|
+
Organisation roles: owner > admin > member. Project roles: owner > editor > viewer.
|
|
4
|
+
Organisation owners and admins are owners of every project; everyone else has the role they were given
|
|
5
|
+
in a project, or cannot see it at all. Files inherit from their project.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import AsyncIterator
|
|
10
|
+
|
|
11
|
+
from fastapi import Depends, HTTPException, Request
|
|
12
|
+
from sqlalchemy import select
|
|
13
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
14
|
+
|
|
15
|
+
from .db import Document, OrgMember, Project, ProjectMember, Session, User, now
|
|
16
|
+
from .security import ORG_ROLES, PROJECT_ROLES, token_hash
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
async def get_db(request: Request) -> AsyncIterator[AsyncSession]:
|
|
20
|
+
async with request.app.state.db() as s:
|
|
21
|
+
yield s
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
async def user_for_token(db: AsyncSession, token: str) -> User | None:
|
|
25
|
+
if not token:
|
|
26
|
+
return None
|
|
27
|
+
sess = await db.get(Session, token_hash(token))
|
|
28
|
+
if sess is None or sess.expires_at < now():
|
|
29
|
+
return None
|
|
30
|
+
user = await db.get(User, sess.user_id)
|
|
31
|
+
return None if user is None or user.disabled else user
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def bearer(request: Request) -> str:
|
|
35
|
+
auth = request.headers.get("authorization", "")
|
|
36
|
+
return auth[7:].strip() if auth.lower().startswith("bearer ") else ""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
async def current_user(request: Request, db: AsyncSession = Depends(get_db)) -> User:
|
|
40
|
+
user = await user_for_token(db, bearer(request))
|
|
41
|
+
if user is None:
|
|
42
|
+
raise HTTPException(401, "sign in first")
|
|
43
|
+
return user
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
async def org_role(db: AsyncSession, user: User, org_id: str) -> str | None:
|
|
47
|
+
m = await db.get(OrgMember, (org_id, user.id))
|
|
48
|
+
return m.role if m else None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
async def need_org(db: AsyncSession, user: User, org_id: str, minimum: str = "member") -> str:
|
|
52
|
+
role = await org_role(db, user, org_id)
|
|
53
|
+
if role is None:
|
|
54
|
+
raise HTTPException(404, "no such organisation")
|
|
55
|
+
if ORG_ROLES[role] < ORG_ROLES[minimum]:
|
|
56
|
+
raise HTTPException(403, f"needs the organisation role {minimum}")
|
|
57
|
+
return role
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
async def project_role(db: AsyncSession, user: User, project: Project) -> str | None:
|
|
61
|
+
role = await org_role(db, user, project.org_id)
|
|
62
|
+
if role is None:
|
|
63
|
+
return None
|
|
64
|
+
if ORG_ROLES[role] >= ORG_ROLES["admin"]:
|
|
65
|
+
return "owner"
|
|
66
|
+
pm = await db.get(ProjectMember, (project.id, user.id))
|
|
67
|
+
return pm.role if pm else None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
async def need_project(db: AsyncSession, user: User, project_id: str, minimum: str = "viewer") -> tuple[Project, str]:
|
|
71
|
+
project = await db.get(Project, project_id)
|
|
72
|
+
role = await project_role(db, user, project) if project else None
|
|
73
|
+
if role is None:
|
|
74
|
+
raise HTTPException(404, "no such project") # (not 403: a project you cannot see does not exist for you)
|
|
75
|
+
if PROJECT_ROLES[role] < PROJECT_ROLES[minimum]:
|
|
76
|
+
raise HTTPException(403, f"needs the project role {minimum}")
|
|
77
|
+
return project, role
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
async def need_document(db: AsyncSession, user: User, document_id: str,
|
|
81
|
+
minimum: str = "viewer") -> tuple[Document, Project, str]:
|
|
82
|
+
doc = await db.get(Document, document_id)
|
|
83
|
+
if doc is None or doc.deleted_at is not None:
|
|
84
|
+
raise HTTPException(404, "no such document")
|
|
85
|
+
try:
|
|
86
|
+
project, role = await need_project(db, user, doc.project_id, minimum)
|
|
87
|
+
except HTTPException as exc:
|
|
88
|
+
raise HTTPException(exc.status_code, "no such document" if exc.status_code == 404 else exc.detail) from exc
|
|
89
|
+
return doc, project, role
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
async def visible_projects(db: AsyncSession, user: User, org_id: str, role: str) -> list[tuple[Project, str]]:
|
|
93
|
+
projects = (await db.execute(select(Project).where(Project.org_id == org_id).order_by(Project.name))).scalars().all()
|
|
94
|
+
if ORG_ROLES[role] >= ORG_ROLES["admin"]:
|
|
95
|
+
return [(p, "owner") for p in projects]
|
|
96
|
+
mine = {pm.project_id: pm.role for pm in (await db.execute(
|
|
97
|
+
select(ProjectMember).where(ProjectMember.user_id == user.id))).scalars()}
|
|
98
|
+
return [(p, mine[p.id]) for p in projects if p.id in mine]
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""The collaboration server application."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
from contextlib import asynccontextmanager
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
from fastapi import Depends, FastAPI
|
|
9
|
+
from fastapi.responses import HTMLResponse
|
|
10
|
+
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
|
11
|
+
|
|
12
|
+
from openswx_collab_protocol import PROTOCOL_VERSION
|
|
13
|
+
|
|
14
|
+
from . import __version__, assemblies, auth, documents, lifecycle, orgs
|
|
15
|
+
from .access import get_db
|
|
16
|
+
from .config import Settings
|
|
17
|
+
from .db import init_db, make_engine
|
|
18
|
+
from .hooks import Hooks, load_hooks
|
|
19
|
+
from .hub import Hub
|
|
20
|
+
from .mail import Mailer
|
|
21
|
+
from .security import Limiter
|
|
22
|
+
from .storage import make_storage
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
_RESET_PAGE = """<!doctype html><meta charset=utf-8><meta name=viewport content="width=device-width">
|
|
26
|
+
<meta name=referrer content=no-referrer><title>Choose a new password</title>
|
|
27
|
+
<body style="font:16px system-ui;max-width:28em;margin:4em auto;padding:0 1em">
|
|
28
|
+
<h1>Choose a new password</h1>
|
|
29
|
+
<form id=f><p><label>New password<br><input id=p type=password minlength=8 required autocomplete=new-password
|
|
30
|
+
style="width:100%;font:inherit;padding:.4em"></label></p>
|
|
31
|
+
<p><label>Again<br><input id=q type=password minlength=8 required autocomplete=new-password
|
|
32
|
+
style="width:100%;font:inherit;padding:.4em"></label></p>
|
|
33
|
+
<p><button style="font:inherit;padding:.4em 1em">Set password</button></p></form><p id=m role=status></p>
|
|
34
|
+
<script>
|
|
35
|
+
const token = __TOKEN__;
|
|
36
|
+
document.getElementById("f").onsubmit = async (e) => {
|
|
37
|
+
e.preventDefault();
|
|
38
|
+
const m = document.getElementById("m"), p = document.getElementById("p").value;
|
|
39
|
+
if (p !== document.getElementById("q").value) { m.textContent = "The two passwords differ."; return; }
|
|
40
|
+
const r = await fetch("/api/auth/password-reset/confirm", {method: "POST",
|
|
41
|
+
headers: {"content-type": "application/json"}, body: JSON.stringify({token, password: p})});
|
|
42
|
+
const d = await r.json().catch(() => ({}));
|
|
43
|
+
m.textContent = r.ok ? d.message : (typeof d.detail === "string" ? d.detail : "That did not work.");
|
|
44
|
+
if (r.ok) document.getElementById("f").remove();
|
|
45
|
+
};
|
|
46
|
+
</script></body>"""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def create_app(settings: Settings | None = None, hooks: Hooks | None = None, http_client=None) -> FastAPI:
|
|
50
|
+
settings = settings or Settings.from_env()
|
|
51
|
+
|
|
52
|
+
@asynccontextmanager
|
|
53
|
+
async def lifespan(app: FastAPI):
|
|
54
|
+
engine = make_engine(settings.database_url)
|
|
55
|
+
await init_db(engine, settings.auto_migrate, app.state.hooks)
|
|
56
|
+
app.state.db = async_sessionmaker(engine, expire_on_commit=False)
|
|
57
|
+
app.state.hub = Hub(settings, app.state.db, app.state.storage)
|
|
58
|
+
await app.state.hub.start()
|
|
59
|
+
try:
|
|
60
|
+
yield
|
|
61
|
+
finally:
|
|
62
|
+
await app.state.hub.stop()
|
|
63
|
+
await engine.dispose()
|
|
64
|
+
|
|
65
|
+
app = FastAPI(title="openswx collaboration server", version=__version__, lifespan=lifespan)
|
|
66
|
+
app.state.settings = settings
|
|
67
|
+
app.state.hooks = hooks or load_hooks()
|
|
68
|
+
app.state.storage = make_storage(settings.storage_url, settings.s3_endpoint)
|
|
69
|
+
app.state.login_limiter = Limiter()
|
|
70
|
+
app.state.reset_limiter = Limiter(limit=5, window=3600)
|
|
71
|
+
app.state.mailer = Mailer(settings)
|
|
72
|
+
app.state.http_client = http_client or (lambda: httpx.AsyncClient(timeout=15))
|
|
73
|
+
|
|
74
|
+
@app.get("/api/health")
|
|
75
|
+
async def health():
|
|
76
|
+
return {"ok": True}
|
|
77
|
+
|
|
78
|
+
@app.get("/api/server")
|
|
79
|
+
async def server_info(db: AsyncSession = Depends(get_db)):
|
|
80
|
+
"""What a client needs to draw its sign-in dialog."""
|
|
81
|
+
return {"name": "openswx-collab", "version": __version__, "protocol": PROTOCOL_VERSION,
|
|
82
|
+
"registration": await auth.registration_mode(db, settings),
|
|
83
|
+
"oauth": settings.oauth_providers(), "email": app.state.mailer.enabled,
|
|
84
|
+
"edition": app.state.hooks.name,
|
|
85
|
+
**app.state.hooks.server_info()}
|
|
86
|
+
|
|
87
|
+
@app.get("/invite/{token}", response_class=HTMLResponse)
|
|
88
|
+
async def invite_page(token: str):
|
|
89
|
+
"""Where an invite link lands in a browser: the invite is used from inside openswx."""
|
|
90
|
+
return ("<!doctype html><meta charset=utf-8><title>openswx invite</title>"
|
|
91
|
+
"<body style='font:16px system-ui;max-width:34em;margin:4em auto;padding:0 1em'>"
|
|
92
|
+
"<h1>You have been invited to collaborate in openswx</h1>"
|
|
93
|
+
"<p>Open openswx, choose <b>Collaborate › Join with invite</b>, and paste this page's "
|
|
94
|
+
"address. You can create your account there.</p></body>")
|
|
95
|
+
|
|
96
|
+
@app.get("/reset-password/{token}", response_class=HTMLResponse)
|
|
97
|
+
async def reset_page(token: str):
|
|
98
|
+
"""Where a reset link lands: a small form that posts to /api/auth/password-reset/confirm."""
|
|
99
|
+
return _RESET_PAGE.replace("__TOKEN__", json.dumps(token))
|
|
100
|
+
|
|
101
|
+
app.include_router(auth.router)
|
|
102
|
+
app.include_router(orgs.router)
|
|
103
|
+
app.include_router(documents.router)
|
|
104
|
+
app.include_router(assemblies.router)
|
|
105
|
+
app.include_router(lifecycle.router)
|
|
106
|
+
for r in app.state.hooks.routers():
|
|
107
|
+
app.include_router(r)
|
|
108
|
+
return app
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""Assemblies: components that use parts by reference.
|
|
2
|
+
|
|
3
|
+
A cloud assembly does not carry copies of its parts. Each component says which part document it uses
|
|
4
|
+
and at which point of that part's history:
|
|
5
|
+
|
|
6
|
+
{"id": "c1", ..., "ref": {"document": "<part document id>", "seq": 42, "version": "Rev A"}}
|
|
7
|
+
|
|
8
|
+
`seq` is what counts (a state of a document never changes); `version` is the label the person picked,
|
|
9
|
+
kept for display. Someone editing the part therefore never changes an assembly. The assembly's users see
|
|
10
|
+
that something newer exists (GET .../references, and a `reference.update` message when a part gets a new
|
|
11
|
+
named version) and move a component to it by changing its `ref` like any other edit. Checking which mates
|
|
12
|
+
would break is the client's job, since it needs geometry; the server says what changed in between
|
|
13
|
+
(GET /documents/{part}/history?after=<pinned>&before=<newer + 1>).
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from fastapi import APIRouter, Depends, HTTPException
|
|
18
|
+
from sqlalchemy import func, select
|
|
19
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
20
|
+
|
|
21
|
+
from openswx_collab_protocol.ops import OpError
|
|
22
|
+
|
|
23
|
+
from .access import current_user, get_db, need_document, project_role
|
|
24
|
+
from .db import AssemblyRef, Document, Op, Project, User, Version
|
|
25
|
+
|
|
26
|
+
router = APIRouter(prefix="/api")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _ref(component: dict) -> tuple[str, int]:
|
|
30
|
+
"""(part document id, seq) of a component, or OpError."""
|
|
31
|
+
cid = component.get("id")
|
|
32
|
+
if "part" in component:
|
|
33
|
+
raise OpError(f"component {cid}: a cloud assembly refers to its parts ('ref'); it does not carry copies")
|
|
34
|
+
ref = component.get("ref")
|
|
35
|
+
if not isinstance(ref, dict) or not isinstance(ref.get("document"), str) or not ref["document"] \
|
|
36
|
+
or isinstance(ref.get("seq"), bool) or not isinstance(ref.get("seq"), int) or ref["seq"] < 0:
|
|
37
|
+
raise OpError(f"component {cid} needs ref: {{document: <part document id>, seq: <number>}}")
|
|
38
|
+
if ref.get("version") is not None and not isinstance(ref["version"], str):
|
|
39
|
+
raise OpError(f"component {cid}: ref.version is a version name")
|
|
40
|
+
return ref["document"], ref["seq"]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def ref_rows(content: dict) -> dict[str, tuple[str, int]]:
|
|
44
|
+
"""component id -> (part document id, seq) for a whole assembly."""
|
|
45
|
+
return {c["id"]: _ref(c) for c in content.get("components") or []}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
async def check_refs(db: AsyncSession, org_id: str, user: User, components: list[dict],
|
|
49
|
+
access_for: set[str] | None = None, allow_deleted: bool | set[str] = False) -> None:
|
|
50
|
+
"""Each of these components must use a part of the same organisation, at a state that part has.
|
|
51
|
+
For the components in `access_for` (all of them when None) `user` must also be able to open the part:
|
|
52
|
+
that is asked when someone chooses a part or a state of it, not every time a component that already
|
|
53
|
+
uses it is moved, removed or put back. `allow_deleted` (all components, or the ids in it): a part that has
|
|
54
|
+
been deleted is fine - for undo and restore, which may bring back a component whose part has gone since,
|
|
55
|
+
and for moving such a component afterwards without changing what it points at. Raises OpError; its text
|
|
56
|
+
names a part only to someone who can open it."""
|
|
57
|
+
seen: dict[tuple[str, bool, bool], Document | None] = {}
|
|
58
|
+
for c in components:
|
|
59
|
+
part_id, seq = _ref(c)
|
|
60
|
+
need = access_for is None or c["id"] in access_for
|
|
61
|
+
gone_ok = allow_deleted is True or (isinstance(allow_deleted, set) and c["id"] in allow_deleted)
|
|
62
|
+
if (part_id, need, gone_ok) not in seen:
|
|
63
|
+
doc = await db.get(Document, part_id)
|
|
64
|
+
live = doc is not None and (doc.deleted_at is None or gone_ok)
|
|
65
|
+
project = await db.get(Project, doc.project_id) if live else None
|
|
66
|
+
ok = project is not None and project.org_id == org_id
|
|
67
|
+
if ok and need:
|
|
68
|
+
ok = await project_role(db, user, project) is not None
|
|
69
|
+
seen[(part_id, need, gone_ok)] = doc if ok else None # (one answer for "missing" and "not yours")
|
|
70
|
+
doc = seen[(part_id, need, gone_ok)]
|
|
71
|
+
if doc is None:
|
|
72
|
+
raise OpError(f"component {c['id']}: there is no part {part_id} you can use")
|
|
73
|
+
label = doc.name if need else "that document"
|
|
74
|
+
if doc.kind != "part":
|
|
75
|
+
raise OpError(f"component {c['id']}: {label} is not a part")
|
|
76
|
+
if seq > doc.head_seq:
|
|
77
|
+
raise OpError(f"component {c['id']}: {label} has no state {seq}" if need else
|
|
78
|
+
f"component {c['id']}: that state does not exist")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
async def used_outside(db: AsyncSession, project_id: str) -> list[Document]:
|
|
82
|
+
"""Assemblies in other projects that use a part of this project."""
|
|
83
|
+
parts = select(Document.id).where(Document.project_id == project_id)
|
|
84
|
+
ids = select(AssemblyRef.assembly_id).where(AssemblyRef.part_id.in_(parts)).distinct()
|
|
85
|
+
return list((await db.execute(select(Document).where(
|
|
86
|
+
Document.id.in_(ids), Document.deleted_at.is_(None), Document.project_id != project_id)
|
|
87
|
+
.order_by(Document.name))).scalars())
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
async def visible(db: AsyncSession, user: User, docs: list[Document]) -> tuple[list[dict], int]:
|
|
91
|
+
"""(the documents `user` can open as {id, name}, how many they cannot)."""
|
|
92
|
+
shown, hidden = [], 0
|
|
93
|
+
for d in docs:
|
|
94
|
+
project = await db.get(Project, d.project_id)
|
|
95
|
+
if project is not None and await project_role(db, user, project) is not None:
|
|
96
|
+
shown.append({"id": d.id, "name": d.name})
|
|
97
|
+
else:
|
|
98
|
+
hidden += 1
|
|
99
|
+
return shown, hidden
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
async def used_in(db: AsyncSession, part_id: str) -> list[Document]:
|
|
103
|
+
"""The (not deleted) assemblies that use a part."""
|
|
104
|
+
ids = select(AssemblyRef.assembly_id).where(AssemblyRef.part_id == part_id).distinct()
|
|
105
|
+
return list((await db.execute(select(Document).where(Document.id.in_(ids), Document.deleted_at.is_(None))
|
|
106
|
+
.order_by(Document.name))).scalars())
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
async def where_pinned_older(db: AsyncSession, part_id: str, seq: int) -> dict[str, list[str]]:
|
|
110
|
+
"""assembly id -> components that use `part_id` at a state before `seq`."""
|
|
111
|
+
out: dict[str, list[str]] = {}
|
|
112
|
+
for assembly_id, component_id in (await db.execute(
|
|
113
|
+
select(AssemblyRef.assembly_id, AssemblyRef.component_id)
|
|
114
|
+
.where(AssemblyRef.part_id == part_id, AssemblyRef.seq < seq).order_by(AssemblyRef.component_id))).all():
|
|
115
|
+
out.setdefault(assembly_id, []).append(component_id)
|
|
116
|
+
return out
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@router.get("/documents/{document_id}/references")
|
|
120
|
+
async def references(document_id: str, user: User = Depends(current_user), db: AsyncSession = Depends(get_db)):
|
|
121
|
+
"""What each component of an assembly is pinned to, and whether its part has moved on.
|
|
122
|
+
|
|
123
|
+
`update_available`: the part has a named version newer than the pinned state (`latest_version`).
|
|
124
|
+
`newer_edits`: the part has been edited since (possibly without anyone naming a version).
|
|
125
|
+
"""
|
|
126
|
+
doc, _, _ = await need_document(db, user, document_id)
|
|
127
|
+
if doc.kind != "assembly":
|
|
128
|
+
raise HTTPException(422, "only assemblies have references")
|
|
129
|
+
rows = (await db.execute(select(AssemblyRef).where(AssemblyRef.assembly_id == document_id)
|
|
130
|
+
.order_by(AssemblyRef.component_id))).scalars().all()
|
|
131
|
+
parts: dict[str, dict] = {}
|
|
132
|
+
for part_id in {r.part_id for r in rows}:
|
|
133
|
+
part = await db.get(Document, part_id)
|
|
134
|
+
project = await db.get(Project, part.project_id) if part is not None else None
|
|
135
|
+
versions = (await db.execute(select(Version).where(Version.document_id == part_id)
|
|
136
|
+
.order_by(Version.seq.desc(), Version.created_at.desc()))).scalars().all() \
|
|
137
|
+
if part is not None else []
|
|
138
|
+
parts[part_id] = {"part": part, "versions": versions,
|
|
139
|
+
"accessible": project is not None and await project_role(db, user, project) is not None}
|
|
140
|
+
out = []
|
|
141
|
+
for r in rows:
|
|
142
|
+
info = parts[r.part_id]
|
|
143
|
+
part, versions = info["part"], info["versions"]
|
|
144
|
+
if part is None or not info["accessible"]:
|
|
145
|
+
# in a project this person cannot open: they learn that it exists and nothing about it
|
|
146
|
+
out.append({"component": r.component_id, "document": {"id": r.part_id, "accessible": False},
|
|
147
|
+
"pinned": {"seq": r.seq}})
|
|
148
|
+
continue
|
|
149
|
+
latest = versions[0] if versions else None
|
|
150
|
+
target = latest.seq if latest is not None and latest.seq > r.seq else part.head_seq
|
|
151
|
+
changes = (await db.execute(select(func.count()).select_from(Op).where(
|
|
152
|
+
Op.document_id == part.id, Op.seq > r.seq, Op.seq <= target))).scalar_one()
|
|
153
|
+
out.append({
|
|
154
|
+
"component": r.component_id,
|
|
155
|
+
"document": {"id": part.id, "name": part.name, "project_id": part.project_id, "accessible": True,
|
|
156
|
+
"deleted": part.deleted_at is not None},
|
|
157
|
+
"pinned": {"seq": r.seq, "versions": [v.name for v in versions if v.seq == r.seq]},
|
|
158
|
+
"head_seq": part.head_seq,
|
|
159
|
+
"latest_version": {"id": latest.id, "name": latest.name, "seq": latest.seq} if latest else None,
|
|
160
|
+
"update_available": latest is not None and latest.seq > r.seq,
|
|
161
|
+
"newer_edits": part.head_seq > r.seq,
|
|
162
|
+
"changes_since_pinned": changes,
|
|
163
|
+
})
|
|
164
|
+
return out
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@router.get("/documents/{document_id}/used-in")
|
|
168
|
+
async def where_used(document_id: str, user: User = Depends(current_user), db: AsyncSession = Depends(get_db)):
|
|
169
|
+
"""The assemblies that use this part and what each is pinned to (only assemblies the asker can open)."""
|
|
170
|
+
await need_document(db, user, document_id)
|
|
171
|
+
out = []
|
|
172
|
+
for asm in await used_in(db, document_id):
|
|
173
|
+
project = await db.get(Project, asm.project_id)
|
|
174
|
+
if project is None or await project_role(db, user, project) is None:
|
|
175
|
+
continue
|
|
176
|
+
comps = (await db.execute(select(AssemblyRef.component_id, AssemblyRef.seq).where(
|
|
177
|
+
AssemblyRef.assembly_id == asm.id, AssemblyRef.part_id == document_id)
|
|
178
|
+
.order_by(AssemblyRef.component_id))).all()
|
|
179
|
+
out.append({"document": {"id": asm.id, "name": asm.name, "project_id": asm.project_id},
|
|
180
|
+
"components": [{"component": c, "seq": s} for c, s in comps]})
|
|
181
|
+
return out
|