diff --git a/opal.json b/opal.json index bfd38cd..a45bfb5 100644 --- a/opal.json +++ b/opal.json @@ -1,6 +1,6 @@ { "name": "mistwarp-api", - "version": "1.7.0", + "version": "2.0.0", "main": "main.osl", "scripts": { "dev": ["osl", "run", "main.osl"], diff --git a/scripts/e2e_smoke.py b/scripts/e2e_smoke.py index d7f0f0f..6d5518a 100644 --- a/scripts/e2e_smoke.py +++ b/scripts/e2e_smoke.py @@ -32,16 +32,28 @@ "monitors": [], "extensions": [], "meta": {"semver": "3.0.0", "vm": "0.2.0", "agent": "smoke"}, } -USERS = {"sam": "u_sam", "alice": "u_alice", "bob": "u_bob", "dee": "u_dee", "mist": "u_mist", "lena": "u_lena"} +USERS = {"sam": "u_sam", "alice": "u_alice", "bob": "u_bob", "dee": "u_dee", "mist": "u_mist", "lena": "u_lena", "vic": "u_vic", "wes": "u_wes"} FULL_STORAGE = {"u_dee"} +ORGS = { + "studio": { + "id": "o_studio", "username": "studio", "display_name": "Smoke Studio", "bio": "Games", "member_count": 3, + "members": [ + {"id": "u_sam", "username": "sam", "admin": True, "perms": ["admin"], "public": True}, + {"id": "u_alice", "username": "alice", "admin": False, "perms": ["billing"], "public": True}, + {"id": "u_dee", "username": "dee", "admin": False, "perms": ["apps"], "public": False}, + ], + }, +} +GHOST_ORGS = {"ghoststudio": "o_ghost"} GONE_USERS = {"gone_user"} BUSY_USERS = {"busy_user"} BANNED_USERS = {"banned_user"} SLOW_USERS = {"slow_user": "u_slow"} SLOW_LEDGER_USERS = {"u_lena"} +SLOW_ORG_LISTS = {"u_vic", "u_wes"} ROTUR_DELAY = 4 EXPECTED_ERRORS = {"patch team unknown user", "patch transfer unknown", "patch team rotur unavailable", "patch transfer rotur unavailable", "upload unsaved first save of the day", "upload extension store failure", "upload extension store failure with history", "upload json store failure", "upload metadata save failure"} -CHECK_STEPS = {"sync pull reads stay inside the pull", "sync pull hides remix commits when seeInside is off", "sync merged pull reads stay inside the pull", "sync pull already merged completes even if base branch was renamed", "sync pull follows the remix", "sync prepared heads", "sync result", "sync pull diff uses the live base", "sync pull merge result", "sync remix is dirty", "sync refusals are enforced", "sync dirty refusals are enforced"} +CHECK_STEPS = {"org studio thumbnail checks", "org challenge checks", "sync pull reads stay inside the pull", "sync pull hides remix commits when seeInside is off", "sync merged pull reads stay inside the pull", "sync pull already merged completes even if base branch was renamed", "sync pull follows the remix", "sync prepared heads", "sync result", "sync pull diff uses the live base", "sync pull merge result", "sync remix is dirty", "sync refusals are enforced", "sync dirty refusals are enforced"} SCOPED_SESSIONS = {"sam_editor": ("sam", "editor")} VOLATILE_NAMES = {"token", "viewKey", "expires", "created", "edited", "firstSeen", "historyBytes"} UNORDERED = {"largest"} @@ -89,7 +101,16 @@ def do_GET(self): if self.path.startswith("/v2/storage-ledger/"): self.answer(404, {"code": "not_found"}) return + if self.path.startswith("/v2/integrations/mistwarp/"): + self.answer_org_integration() + return name = self.path.split("?", 1)[0][len("/profile/"):] if self.path.startswith("/profile/") else "" + if name in ORGS: + self.answer(200, {"id": ORGS[name]["id"], "username": name, "account_type": "org"}) + return + if name in GHOST_ORGS: + self.answer(200, {"id": GHOST_ORGS[name], "username": name, "account_type": "org"}) + return if name in GONE_USERS: self.answer(404, {"error": "User not found"}) return @@ -108,6 +129,28 @@ def do_GET(self): return self.answer(200, {"id": USERS[name], "username": name}) + def answer_org_integration(self): + if self.headers.get("X-Commerce-Key") != "smoke": + self.answer(403, {"error": "invalid service key"}) + return + parts = self.path.split("?", 1)[0].split("/") + if parts[4] == "orgs" and len(parts) == 6: + wanted = urllib.parse.unquote(parts[5]) + org = ORGS.get(wanted) or next((value for value in ORGS.values() if value["id"] == wanted), None) + self.answer(200, org) if org else self.answer(404, {"code": "not_org", "not_org": True}) + return + if parts[4] == "users" and len(parts) == 7 and parts[6] == "orgs": + if parts[5] in SLOW_ORG_LISTS: + time.sleep(ROTUR_DELAY) + mine = [] + for org in ORGS.values(): + for member in org["members"]: + if member["id"] == parts[5]: + mine.append({"id": org["id"], "username": org["username"], "display_name": org["display_name"], "perms": member["perms"]}) + self.answer(200, {"orgs": mine}) + return + self.answer(404, {"code": "not_found"}) + def do_POST(self): if not self.path.startswith("/v2/storage-ledger/"): self.close_connection = True @@ -149,7 +192,7 @@ def __init__(self, binary, keep): os.makedirs(os.path.join(data, "sessions")) with open(os.path.join(self.dir, ".env"), "w") as env: rotur = "http://127.0.0.1:%d" % self.rotur.server_address[1] - env.write("PORT=%d\nAPP_URL=http://127.0.0.1:%d\nROTUR_BASE=%s\nROTUR_LOCAL_API_URL=%s\nROTUR_SERVICE_SECRET=smoke\n" % (self.port, self.port, rotur, rotur)) + env.write("PORT=%d\nAPP_URL=http://127.0.0.1:%d\nROTUR_BASE=%s\nROTUR_LOCAL_API_URL=%s\nROTUR_SERVICE_SECRET=smoke\nCOMMERCE_SERVICE_KEY=smoke\n" % (self.port, self.port, rotur, rotur)) with open(os.path.join(data, "agreement.json"), "w") as handle: json.dump({"version": 1, "text": "", "updatedAt": 1700000000000}, handle) with open(os.path.join(data, "agreement.md"), "w") as handle: @@ -777,10 +820,7 @@ def patch(name, body, who="sam"): patch("patch vanity without plan", {"vanitySlug": "smoke-game"}) patch("patch null vanity", {"vanitySlug": None}) patch("patch vanity cleared", {"vanitySlug": ""}) - patch("patch group tag invalid", {"groupTag": "!!!"}) - patch("patch group tag not managed", {"groupTag": "somegroup"}) - patch("patch null group tag", {"groupTag": None}) - patch("patch group tag cleared", {"groupTag": " "}) + patch("patch group tag ignored", {"groupTag": "somegroup"}) patch("patch nameless teammate", {"collaborators": [{"role": "editor"}]}) patch("patch team share too high", {"collaborators": [{"username": "alice", "role": "editor", "share": 60}]}) patch("patch team unknown user", {"collaborators": [{"username": "ghost_user", "role": "editor"}]}) @@ -802,7 +842,7 @@ def patch(name, body, who="sam"): patch("patch editor session refused", {"collaborators": []}, who="sam_editor") patch("patch transfer as maintainer", {"owner": "bob"}, who="alice") patch("patch transfer unknown", {"owner": "ghost_user"}) - patch("patch transfer", {"owner": "bob", "keepGroup": True, "title": "Given away"}) + patch("patch transfer", {"owner": "bob", "title": "Given away"}) patch("patch after transfer", {"title": "Mine again"}) step("get updated project", "GET", path, "bob") for name, body in ( @@ -990,6 +1030,119 @@ def synced_tree(server, ids, alias, who, head, merge): return zip_files(files) +def org_flow(server, step, steps, ids): + step("org page for a person", "GET", "/v1/orgs/bob") + step("my orgs", "GET", "/v1/me/orgs", "alice") + step("org create refused for billing", "POST", "/v1/projects", "alice", {"title": "Not allowed", "org": "studio"}) + step("org create for a person", "POST", "/v1/projects", "dee", {"title": "Not an org", "org": "bob"}) + status, created = step("org create", "POST", "/v1/projects", "dee", {"title": "Studio game", "org": "studio"}) + ids[str(created.get("id", "")) if isinstance(created, dict) else ""] = "" + path = "/v1/projects/" + step("org project as publisher", "GET", path, "sam") + step("org project edit as publisher", "PUT", path, "sam", {"title": "Studio game 2"}) + step("org project edit as billing", "PUT", path, "alice", {"title": "Nope"}) + status, mine = step("org own create", "POST", "/v1/projects", "bob", {"title": "Bob's game"}) + ids[str(mine.get("id", "")) if isinstance(mine, dict) else ""] = "" + step("org transfer refused for an outsider", "PUT", "/v1/projects/", "bob", {"owner": "studio"}) + step("org transfer to an org that can't own content", "PUT", "/v1/projects/", "bob", {"owner": "ghoststudio"}) + status, given = step("org transfer by member", "POST", "/v1/projects", "dee", {"title": "Dee's game"}) + ids[str(given.get("id", "")) if isinstance(given, dict) else ""] = "" + step("org transfer", "PUT", "/v1/projects/", "dee", {"owner": "studio"}) + step("org move out refused for a publisher", "PUT", "/v1/projects/", "dee", {"owner": "dee"}) + step("org transfer back", "PUT", "/v1/projects/", "sam", {"owner": "dee"}) + status, studio = step("org space create", "POST", "/v1/spaces", "dee", {"title": "Studio space", "kind": "studio", "org": "studio"}) + studio = studio.get("space", {}) if isinstance(studio, dict) else {} + ids[str(studio.get("_id", studio.get("id", "")))] = "" + time.sleep(0.01) + status, thumbed = step("org studio thumbnail by publisher", "POST", "/v1/spaces//thumbnail", "sam", form=({}, {"thumbnail": b"\x89PNG studio thumbnail"})) + status, studio_after = step("org studio after thumbnail", "GET", "/v1/spaces/", "sam") + studio_after = studio_after.get("space", {}) if isinstance(studio_after, dict) else {} + steps.append({"step": "org studio thumbnail checks", "status": 0, "body": { + "the thumbnail is saved": status == 200 and isinstance(thumbed, dict) and bool(thumbed.get("thumbnailUrl")), + "the returned url matches the saved space": isinstance(thumbed, dict) and thumbed.get("thumbnailUrl") == studio_after.get("thumbnailUrl"), + }}) + status, own_space = step("org own space create", "POST", "/v1/spaces", "sam", {"title": "Sam's space", "kind": "collection"}) + own_space = own_space.get("space", {}) if isinstance(own_space, dict) else {} + ids[str(own_space.get("_id", own_space.get("id", "")))] = "" + step("org space move refused for billing", "PUT", "/v1/spaces/", "alice", {"owner": "studio"}) + step("org space move to an org that can't own content", "PUT", "/v1/spaces/", "sam", {"owner": "ghoststudio"}) + step("org space move", "PUT", "/v1/spaces/", "sam", {"owner": "studio"}) + step("org space managed by publisher", "PUT", "/v1/spaces/", "dee", {"title": "Studio collection"}) + step("org space move out refused for a publisher", "PUT", "/v1/spaces/", "dee", {"owner": "dee"}) + step("org page", "GET", "/v1/orgs/studio") + step("org page as member", "GET", "/v1/orgs/studio", "dee") + org_challenge_flow(server, step, steps, ids, path) + step("org project delete by billing", "DELETE", path, "alice") + step("org project delete by publisher", "DELETE", path, "dee") + + +def org_challenge_flow(server, step, steps, ids, project_path): + step("accept agreement vic", "POST", "/v1/agreement/accept", "vic", {}) + step("accept agreement wes", "POST", "/v1/agreement/accept", "wes", {}) + step("profile wes", "PUT", "/v1/me/profile", "wes", {"bio": "Curator"}) + step("org challenge entry save", "POST", project_path + "/upload", "dee", form=({}, {"project": sb3_archive(project_with_costumes([]))})) + step("org challenge entry share", "POST", project_path + "/visibility", "dee", {"visibility": "public"}) + now = int(time.time() * 1000) + status, created = step("org challenge create", "POST", "/v1/spaces", "dee", {"title": "Studio jam", "kind": "challenge", "org": "studio", "visibility": "public", "openSubmissions": True, "votingMode": "audience", "startsAt": now - 3600000, "endsAt": now + 3600000}) + created = created.get("space", {}) if isinstance(created, dict) else {} + ids[str(created.get("_id", created.get("id", "")))] = "" + challenge = "/v1/spaces/" + entered, _ = step("org challenge entry by publisher", "POST", challenge + "/projects/", "sam") + invited, _ = step("org challenge curator invite", "POST", challenge + "/curators", "sam", {"username": "bob"}) + invited_again, _ = step("org challenge curator invite again", "POST", challenge + "/curators", "sam", {"username": "bob"}) + cancelled, _ = step("org challenge curator invite cancel", "DELETE", challenge + "/invitations/bob", "sam") + not_curator, _ = step("org challenge curator remove when not one", "DELETE", challenge + "/curators/bob", "sam") + reinvited, _ = step("org challenge curator invite after cancel", "POST", challenge + "/curators", "sam", {"username": "bob"}) + step("org challenge curator invite for wes", "POST", challenge + "/curators", "sam", {"username": "wes"}) + accepted, _ = step("org challenge curator accepts", "POST", challenge + "/invitations/respond", "wes", {"accepted": True}) + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + slow_edit = pool.submit(step, "org challenge edit by a curator removed meanwhile", "PUT", challenge, "wes", {"rules": "Be kind"}) + time.sleep(ROTUR_DELAY / 4) + removal = pool.submit(step, "org challenge curator removed", "DELETE", challenge + "/curators/wes", "sam") + stale_curator = [slow_edit.result()[0], removal.result()[0]] + commented, comment_body = step("org challenge comment", "POST", challenge + "/comments", "bob", {"content": "Good luck"}) + comment_id = ((comment_body or {}).get("comment") or {}).get("id", "") if isinstance(comment_body, dict) else "" + step("org challenge second comment", "POST", challenge + "/comments", "alice", {"content": "Have fun"}) + uncommented, _ = step("org challenge comment delete", "DELETE", challenge + "/comments/" + str(comment_id), "bob") + followed, follow_body = step("org challenge follow", "POST", challenge + "/follow", "bob", {}) + unfollowed, unfollow_body = step("org challenge unfollow", "DELETE", challenge + "/follow", "bob") + status, counted_space = step("org challenge counts", "GET", challenge, "bob") + counted_space = counted_space.get("space", {}) if isinstance(counted_space, dict) else {} + joined, _ = step("org challenge join", "POST", challenge + "/join", "bob", {}) + submitter_left, _ = step("org challenge leave refused for the submitter", "DELETE", challenge + "/join", "sam") + left, left_body = step("org challenge leave", "DELETE", challenge + "/join", "bob") + step("org challenge to judging", "PUT", challenge, "dee", {"endsAt": now - 1000, "judgingEndsAt": now + 3600000}) + own, _ = step("org challenge vote on own entry", "PUT", challenge + "/entries//vote", "dee", {"value": 4}) + vote = challenge + "/entries//vote" + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + slow = pool.submit(step, "org challenge vote while Rotur is slow", "PUT", vote, "vic", {"value": 3}) + time.sleep(ROTUR_DELAY / 4) + fast = pool.submit(step, "org challenge vote by an outsider", "PUT", vote, "bob", {"value": 5}) + votes = [slow.result()[0], fast.result()[0]] + status, got = step("org challenge after votes", "GET", challenge, "dee") + space = got.get("space", {}) if isinstance(got, dict) else {} + entries = [entry for entry in space.get("projects", []) if isinstance(entry, dict)] + counted = sum(int(entry.get("audienceVoteCount", 0)) for entry in entries) + removed, removed_body = step("org challenge entry removed by the submitter", "DELETE", challenge + "/projects/", "sam") + remaining = ((removed_body or {}).get("space") or {}).get("projects", []) if isinstance(removed_body, dict) else None + deleted, _ = step("org challenge delete", "DELETE", challenge, "sam") + gone, _ = step("org challenge after delete", "GET", challenge, "sam") + steps.append({"step": "org challenge checks", "status": 0, "body": { + "publisher entered the org project": entered == 200 and len(entries) == 1, + "one participant recorded": space.get("participantCount") == 1, + "an outsider joins and leaves": joined == 200 and left == 200 and isinstance(left_body, dict) and left_body.get("joined") is False, + "the submitter cannot leave": submitter_left == 400, + "the submitter removes the entry": removed == 200 and remaining == [], + "an org admin deletes the challenge": deleted == 200 and gone == 404, + "a curator removed during their edit cannot save it": accepted == 200 and stale_curator == [409, 200], + "comments and follows keep their counts": [commented, uncommented, followed, unfollowed] == [201, 200, 200, 200] and counted_space.get("commentCount") == 1 and (follow_body or {}).get("followers") == 1 and (unfollow_body or {}).get("followers") == 0, + "curator invites are kept once and can be cancelled": [invited, invited_again, cancelled, not_curator, reinvited] == [201, 400, 200, 200, 201], + "own entry vote refused": own == 403, + "outside votes saved": votes == [200, 200], + "both votes counted": counted == 2, + }}) + + def remix_sync_flow(server, step, steps, ids): plain = sb3_archive(project_with_costumes([])) status, created = step("sync original create", "POST", "/v1/projects", "sam", {"title": "Sync original"}) @@ -1289,6 +1442,7 @@ def step(name, method, path, who=None, body=None, upload=None, headers=(), form= slow_ledger_flow(server, step, steps, ids) locks_flow(server, step, steps, ids) remix_sync_flow(server, step, steps, ids) + org_flow(server, step, steps, ids) time.sleep(1.5) for real, alias in list(ids.items()): if alias in ("", "", ""): diff --git a/src/admin/errors.osl b/src/admin/errors.osl index 9c30daf..b4ad06c 100644 --- a/src/admin/errors.osl +++ b/src/admin/errors.osl @@ -8,14 +8,14 @@ array siteErrorPathWords = [ "about", "account-frame.html", "addon-settings.html", "addons", "admin", "assignments", "bounties", "changes", "claim", "classroom", "commits", "compare", "dpa", "editor", "editor.html", "embed", "embed.html", "entry", "explore", "followers", "following", "fullscreen", "fullscreen.html", "groups", "index.html", "join", - "leaderboard", "library", "manage", "mystuff", "news", "notifications", "p", "perks", "player", "player.html", + "leaderboard", "library", "manage", "mystuff", "news", "notifications", "orgs", "p", "perks", "player", "player.html", "posts", "privacy", "project", "pulls", "purchases", "random", "remixes", "roadmap", "school", "search", "settings", "simple.html", "spaces", "stats", "status", "students", "subprocessors", "support", "terms", "themes", "trust", "users", "wallet" ] array siteErrorIdParents = [ - "assignments", "bounties", "claim", "commits", "entry", "groups", "join", "news", "p", "posts", "project", + "assignments", "bounties", "claim", "commits", "entry", "groups", "join", "news", "orgs", "p", "posts", "project", "pulls", "spaces", "students", "themes", "users" ] @@ -61,7 +61,7 @@ def siteErrorText(string text, string pageUrl, string scrubbedUrl) string ( value = regex.replace(regex.escape(page) ++ "([^A-Za-z0-9._~%/-]|$)", value, scrubbedUrl ++ "$1") ) value = regex.replace("(https?://[^[:space:]?#()<>\"']+)[?#][^[:space:]()<>\"']*?((:[0-9]+){1,2})?([[:space:])<>\"']|$)", value, "$1$2$4") - value = regex.replace("(?i)(https?://([a-z0-9-]+[.])*mistwarp[.]org)/(p|project|users|spaces|groups|bounties|news|posts|themes|claim|join)/[^/?#[:space:]:()<>\"']+", value, "$1/$3/:id") + value = regex.replace("(?i)(https?://([a-z0-9-]+[.])*mistwarp[.]org)/(p|project|users|orgs|spaces|groups|bounties|news|posts|themes|claim|join)/[^/?#[:space:]:()<>\"']+", value, "$1/$3/:id") value = regex.replace("(?i)(https?://editor[.]mistwarp[.]org)/[0-9]+", value, "$1/:id") value = regex.replace("(https?://avatars[.]rotur[.]dev)/[^/?#[:space:]:()<>\"']+", value, "$1/:id") value = regex.replace("(?i)/(users|blocks|mutes|followers|following|curators|invitations|judges|profiles?|projects|classes|students|teachers|claim|join|vanity|game-saves|library)/[^/?#[:space:]:()<>\"']+", value, "/$1/:id") diff --git a/src/admin/project-moderation.osl b/src/admin/project-moderation.osl index 38a3bd0..b60077e 100644 --- a/src/admin/project-moderation.osl +++ b/src/admin/project-moderation.osl @@ -351,7 +351,7 @@ def hideProjectForModeration(object project, string reason, string actor) ( ownerProfile.featuredProject = "" saveProfile(ownerProfile) ) - addNotification(project.owner.toStr(), actor, "project_hidden", {projectId: project.id, projectTitle: project.title, reason: reason}) + notifyContentOwner(project, actor, "project_hidden", {projectId: project.id, projectTitle: project.title, reason: reason}) ) def handleRestoreHiddenProject(*serve.Context c) ( @@ -383,6 +383,6 @@ def handleRestoreHiddenProject(*serve.Context c) ( ) saveProject(project) upsertIndexEntry(project) - addNotification(project.owner.toStr(), contextString(c, "username"), "project_restored", {projectId: project.id, projectTitle: project.title, visibility: visibility}) + notifyContentOwner(project, contextString(c, "username"), "project_restored", {projectId: project.id, projectTitle: project.title, visibility: visibility}) c.json(200, {ok: true, project: projectResponse(project, c)}) ) diff --git a/src/auth/account-controls.osl b/src/auth/account-controls.osl index be48568..f68e7b5 100644 --- a/src/auth/account-controls.osl +++ b/src/auth/account-controls.osl @@ -236,7 +236,7 @@ def eraseUser(string userId, string username) ( for i ownedProjectIds.len ( deleteProjectCommunityRecords(ownedProjectIds[i].toStr()) ) - purgeUserFromSpaces(username) + purgeUserFromSpaces(username, userId) removeProjectsFromSpaces(ownedProjectIds) purgeUserCommunityRecords(username, userId) purgeUserFromNews(username) diff --git a/src/auth/user-identity.osl b/src/auth/user-identity.osl index 5210f47..ec42c87 100644 --- a/src/auth/user-identity.osl +++ b/src/auth/user-identity.osl @@ -147,7 +147,7 @@ def renameUserInProjects(string oldKey, string newKey, string newName, string us if res.ok ( object project = res.project.assert(object) boolean changed = false - if normalizeUsername(project.owner.toStr()) == oldKey ( + if normalizeUsername(project.owner.toStr()) == oldKey and !ownedByAnotherOrg(project, userId) ( project.owner = newName project.ownerId = userId changed = true @@ -212,11 +212,16 @@ def renameUserInProjects(string oldKey, string newKey, string newName, string us ) ) +def ownedByAnotherOrg(object record, string userId) boolean ( + string ownerId = (record.ownerId ?? "").toStr() + return (record.ownerType ?? "").toStr() == "org" and ownerId != "" and ownerId != userId +) + def renameIdentityFieldInCollection(*db.Collection collection, string nameField, string idField, string oldKey, string newName, string userId) ( array documents = collection.all() for i documents.len ( object document = documents[i].assert(object) - if document.contains(nameField) and document[nameField] != null and normalizeUsername(document[nameField].toStr()) == oldKey ( + if document.contains(nameField) and document[nameField] != null and normalizeUsername(document[nameField].toStr()) == oldKey and !ownedByAnotherOrg(document, userId) ( document[nameField] = newName document[idField] = userId putDocument(collection, document["_id"].toStr(), document) @@ -464,7 +469,7 @@ def backfillOwnerIdForUserProjects(string userId, string username) ( array matches = projectSearchDocs.where("ownerKey", "==", ownerKey).all() for i matches.len ( object entry = matches[i].assert(object) - if (entry.ownerId ?? "").toStr() != userId ( + if (entry.ownerType ?? "").toStr() != "org" and (entry.ownerId ?? "").toStr() != userId ( entry.ownerId = userId putDocument(projectSearchDocs, entry["_id"].toStr(), entry) auto loaded = loadProject(entry.id.toStr()) @@ -578,7 +583,7 @@ def discoverUserIdentityOutcome(string username) object ( ) ensureUserIdentity(userId, currentUsername) identityRefreshCache.set(userId, currentUsername) - return {id: userId, outcome: "found"} + return {id: userId, outcome: "found", accountType: (profile.account_type ?? "").toStr()} ) def usernameForId(string userId) string ( @@ -815,7 +820,7 @@ def purgeUser(string userId, string username) ( purgeUserFromNotifications(key) purgeGameDataForUser(userId) purgeBackpackForUser(userId) - purgeUserFromSpaces(username) + purgeUserFromSpaces(username, userId) purgeUserCommunityRecords(username, userId) purgeUserFromNews(username) removeUserFromSafetyLists(username) diff --git a/src/classroom/classroom-release.osl b/src/classroom/classroom-release.osl index 1226fde..5631369 100644 --- a/src/classroom/classroom-release.osl +++ b/src/classroom/classroom-release.osl @@ -114,7 +114,7 @@ def handleGetClaim(*serve.Context c) ( def moveProjectOwner(object project, string username, string userId) ( project.owner = username project.ownerId = userId - project.groupTag = "" + project.ownerType = "" project.edited = timestamp saveProject(project) upsertIndexEntry(project) diff --git a/src/classroom/classrooms.osl b/src/classroom/classrooms.osl index 1f82f39..5d16eb5 100644 --- a/src/classroom/classrooms.osl +++ b/src/classroom/classrooms.osl @@ -1132,7 +1132,7 @@ def createBlankStudentProject(object student, string title) object ( id: id, owner: student.username, ownerId: student["_id"], - groupTag: "", + ownerType: "", branding: {}, vanitySlug: "", title: title, diff --git a/src/community/challenges.osl b/src/community/challenges.osl index 327d73d..ce1841a 100644 --- a/src/community/challenges.osl +++ b/src/community/challenges.osl @@ -56,26 +56,66 @@ def challengeAudienceVotingEnabled(object space) boolean ( return challengeAudienceJudged(space) or (space.contains("communityVoting") and space.communityVoting == true) ) +def challengeOrgSnapshot(object space) object ( + if challengeAudienceJudged(space) or !isOrgOwned(space) ( + return {ok: false} + ) + object snapshot = ownerOrgSnapshotCached(space) + string ownerId = (space.ownerId ?? "").toStr() + if !snapshot.ok or (ownerId != "" and (snapshot.org.assertElse(object, {}).id ?? "").toStr() != ownerId) ( + return {ok: false} + ) + return snapshot +) + +def challengeOrgJudges(object space) array ( + object snapshot = challengeOrgSnapshot(space) + array listed = [] + array publishers = orgPublisherNames(snapshot) + array visible = orgPublicMemberNames(snapshot) + for i publishers.len ( + if stringArrayContainsUser(visible, publishers[i].toStr()) ( + listed.append(publishers[i]) + ) + ) + return listed +) + def challengeJudges(object space) array ( if challengeAudienceJudged(space) ( return [] ) array judges = challengeArray(space, "judges") - string tag = groupTagOf(space) - if tag != "" ( - array members = groupMemberNames(roturGroupSnapshot(tag)) - for i members.len ( - string member = members[i].toStr() - if !stringArrayContainsUser(judges, member) ( - judges.append(member) - ) + array members = challengeOrgJudges(space) + for i members.len ( + string member = members[i].toStr() + if !stringArrayContainsUser(judges, member) ( + judges.append(member) ) ) return judges ) +def challengeJudgeCount(object space) number ( + if challengeAudienceJudged(space) ( + return 0 + ) + array judges = challengeArray(space, "judges") + array publishers = orgPublisherNames(challengeOrgSnapshot(space)) + number count = judges.len + for i publishers.len ( + if !stringArrayContainsUser(judges, publishers[i].toStr()) ( + count += 1 + ) + ) + return count +) + def isChallengeJudge(object space, string username) boolean ( - return stringArrayContainsUser(challengeJudges(space), username) + if stringArrayContainsUser(challengeJudges(space), username) ( + return true + ) + return stringArrayContainsUser(orgPublisherNames(challengeOrgSnapshot(space)), username) ) def isChallengeJudgeInvitee(object space, string username) boolean ( @@ -148,6 +188,32 @@ def challengeScoreSummary(object space, string projectId, string viewer) object return {judgeScore: judgeScore, judgeScoreCount: scoreCount, audienceScore: audienceScore, audienceVoteCount: audienceCount, myScore: myScore, myVote: myVote, scores: entryScores} ) +def challengeShownJudges(object space,*serve.Context c) object ( + if !isOrgOwned(space) or contextBool(c, "isAdmin") ( + return {all: true, names: []} + ) + object snapshot = challengeOrgSnapshot(space) + if snapshot.ok and orgHasMember(snapshot, contextString(c, "userId"), contextString(c, "username")) ( + return {all: true, names: []} + ) + return {all: false, names: challengeJudges(space)} +) + +def scoresByShownJudges(array scores, object shown) array ( + if shown.all == true ( + return scores + ) + array names = shown.names.assertElse(array, []) + array kept = [] + for i scores.len ( + object score = scores[i].assertElse(object, {}) + if stringArrayContainsUser(names, (score.judge ?? "").toStr()) ( + kept.append(score) + ) + ) + return kept +) + def challengeProjects(object space,*serve.Context c) array ( array projects = [] array ids = spaceProjectIds(space) @@ -155,6 +221,7 @@ def challengeProjects(object space,*serve.Context c) array ( boolean audienceJudged = challengeAudienceJudged(space) string phase = challengePhase(space) boolean revealRatings = phase == "awaiting-results" or phase == "results" or canManageSpace(space, c) + object shownJudges = if canManageSpace(space, c) then challengeShownJudges(space, c) else {all: false, names: []} for i ids.len ( auto loaded = loadProject(ids[i].toStr()) if loaded.ok == true ( @@ -172,7 +239,7 @@ def challengeProjects(object space,*serve.Context c) array ( ) entry.myVote = summary.myVote entry.myScore = if isChallengeJudge(space, contextString(c, "username")) then summary.myScore else {} - entry.scoreBreakdown = if canManageSpace(space, c) then summary.scores else [] + entry.scoreBreakdown = if canManageSpace(space, c) then scoresByShownJudges(summary.scores, shownJudges) else [] projects.append(entry) ) ) @@ -228,18 +295,48 @@ def handleInviteChallengeJudge(*serve.Context c) ( c.notFound("user not found") return ) - if normalizeUsername(space.owner.toStr()) == usernameKey or isChallengeJudge(space, requested) or isChallengeJudgeInvitee(space, requested) ( + if normalizeUsername(space.owner.toStr()) == usernameKey or stringArrayContainsUser(challengeJudges(space), requested) or isChallengeJudgeInvitee(space, requested) ( c.badRequest("this user is already on the challenge team") return ) object invite = {username: profile.username, invitedBy: contextString(c, "username"), created: timestamp} + string invited = inviteChallengeJudgeLocked(space["_id"].toStr(), invite, spaceCuratorOnly(space, c)) + if invited == "missing" ( + c.notFound("challenge not found") + return + ) + if invited == "curator" ( + c.forbidden("you cannot manage this challenge") + return + ) + if invited == "taken" ( + c.badRequest("this user is already on the challenge team") + return + ) + addNotification(profile.username.toStr(), contextString(c, "username"), "challenge_judge_invite", {spaceId: space["_id"], spaceTitle: space.title}) + c.json(201, {ok: true, invitation: invite}) +) + +def inviteChallengeJudgeLocked(string spaceId, object invite, string curator) string ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + string username = invite.username.toStr() + if space.len == 0 ( + return "missing" + ) + if !stillSpaceCurator(space, curator) ( + return "curator" + ) + if stringArrayContainsUser(challengeArray(space, "judges"), username) or isChallengeJudgeInvitee(space, username) ( + return "taken" + ) array invites = challengeArray(space, "judgeInvites") invites.append(invite) space.judgeInvites = invites space.edited = timestamp putSpaceDocument(space) - addNotification(profile.username.toStr(), contextString(c, "username"), "challenge_judge_invite", {spaceId: space["_id"], spaceTitle: space.title}) - c.json(201, {ok: true, invitation: invite}) + return "saved" ) def handleJoinChallenge(*serve.Context c) ( @@ -253,17 +350,34 @@ def handleJoinChallenge(*serve.Context c) ( c.badRequest("this challenge is no longer open to new participants") return ) + object joined = joinChallengeLocked(space["_id"].toStr(), contextString(c, "username")) + if joined.len == 0 ( + c.badRequest("this challenge is no longer open to new participants") + return + ) + if joined.added == true and !isSpaceOwner(space, c) ( + notifyContentOwner(space, contextString(c, "username"), "challenge_join", {spaceId: space["_id"], spaceTitle: space.title}) + ) + c.json(200, {ok: true, joined: true, participantCount: joined.count}) +) + +def joinChallengeLocked(string spaceId, string username) object ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + string phase = if space.len > 0 then challengePhase(space) else "" + if phase != "upcoming" and phase != "submissions" ( + return {} + ) array participants = challengeArray(space, "participants") - if !stringArrayContainsUser(participants, contextString(c, "username")) ( - participants.append(contextString(c, "username")) - space.participants = participants - space.edited = timestamp - putSpaceDocument(space) - if !isSpaceOwner(space, c) ( - addNotification(space.owner.toStr(), contextString(c, "username"), "challenge_join", {spaceId: space["_id"], spaceTitle: space.title}) - ) + if stringArrayContainsUser(participants, username) ( + return {added: false, count: participants.len} ) - c.json(200, {ok: true, joined: true, participantCount: participants.len}) + participants.append(username) + space.participants = participants + space.edited = timestamp + putSpaceDocument(space) + return {added: true, count: participants.len} ) def handleLeaveChallenge(*serve.Context c) ( @@ -285,15 +399,56 @@ def handleLeaveChallenge(*serve.Context c) ( array ids = spaceProjectIds(space) for i ids.len ( object project = (projectSearchDocs.findById(ids[i].toStr()) ?? {}) - if project.len > 0 and searchEntryOwnedByContext(project, c) ( - c.badRequest("remove your submission before leaving the challenge") - return + if project.len > 0 and (!isOrgOwned(project) or submittedBy(space, project.id.toStr(), username)) ( + string ownership = searchEntryOwnership(project, c) + if ownership == "unavailable" ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."}) + return + ) + if ownership == "yes" ( + c.badRequest("remove your submission before leaving the challenge") + return + ) + ) + ) + object left = leaveChallengeLocked(space["_id"].toStr(), username, ids) + if left.len == 0 ( + c.json(409, {ok: false, code: "challenge_changed", error: "The challenge changed while you were leaving. Try again."}) + return + ) + c.json(200, {ok: true, joined: false, participantCount: left.count}) +) + +def leaveChallengeLocked(string spaceId, string username, array checkedIds) object ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + string phase = if space.len > 0 then challengePhase(space) else "" + if phase != "upcoming" and phase != "submissions" ( + return {} + ) + array ids = spaceProjectIds(space) + for i ids.len ( + if !checkedIds.contains(ids[i].toStr()) and submittedBy(space, ids[i].toStr(), username) ( + return {} ) ) + array participants = challengeArray(space, "participants") space.participants = removeUser(participants, username) space.edited = timestamp putSpaceDocument(space) - c.json(200, {ok: true, joined: false, participantCount: space.participants.len}) + return {count: space.participants.len} +) + +def submittedBy(object space, string projectId, string username) boolean ( + array submissions = challengeArray(space, "submissions") + for i submissions.len ( + object entry = submissions[i].assertElse(object, {}) + if (entry.projectId ?? "").toStr() == projectId and normalizeUsername((entry.submittedBy ?? "").toStr()) == normalizeUsername(username) ( + return true + ) + ) + return false ) def handleRespondChallengeJudgeInvite(*serve.Context c) ( @@ -317,7 +472,7 @@ def handleRespondChallengeJudgeInvite(*serve.Context c) ( judges.append(contextString(c, "username")) ) space.judges = judges - addNotification(space.owner.toStr(), contextString(c, "username"), "challenge_judge_accepted", {spaceId: space["_id"], spaceTitle: space.title}) + notifyContentOwner(space, contextString(c, "username"), "challenge_judge_accepted", {spaceId: space["_id"], spaceTitle: space.title}) ) space.edited = timestamp putSpaceDocument(space) @@ -330,7 +485,20 @@ def handleRemoveChallengeJudge(*serve.Context c) ( c.forbidden("you cannot manage this challenge") return ) - string username = c.param("username") + if !removeChallengeJudgeLocked(space["_id"].toStr(), c.param("username"), spaceCuratorOnly(space, c)) ( + c.forbidden("you cannot manage this challenge") + return + ) + c.json(200, {ok: true}) +) + +def removeChallengeJudgeLocked(string spaceId, string username, string curator) boolean ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + if space.len == 0 or !stillSpaceCurator(space, curator) ( + return false + ) array judges = challengeArray(space, "judges") boolean changed = stringArrayContainsUser(judges, username) space.judges = removeUser(judges, username) @@ -350,7 +518,7 @@ def handleRemoveChallengeJudge(*serve.Context c) ( space.edited = timestamp putSpaceDocument(space) ) - c.json(200, {ok: true}) + return true ) def validChallengeCriterion(object space, string criterionId) boolean ( @@ -371,7 +539,12 @@ def handleScoreChallengeEntry(*serve.Context c) ( c.notFound("challenge entry not found") return ) + object judgeSnapshot = if isOrgOwned(space) and !challengeAudienceJudged(space) then ownerOrgSnapshot(space) else {ok: true} if !isChallengeJudge(space, contextString(c, "username")) ( + if !judgeSnapshot.ok and judgeSnapshot.contains("unavailable") and judgeSnapshot.unavailable == true ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."}) + return + ) c.forbidden("only invited judges can score entries") return ) @@ -380,7 +553,12 @@ def handleScoreChallengeEntry(*serve.Context c) ( return ) object project = (projectSearchDocs.findById(projectId) ?? {}) - if project.len > 0 and searchEntryOwnedByContext(project, c) ( + string ownership = if project.len > 0 then searchEntryOwnership(project, c) else "no" + if ownership == "unavailable" ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."}) + return + ) + if ownership == "yes" ( c.forbidden("you cannot score your own entry") return ) @@ -406,21 +584,94 @@ def handleScoreChallengeEntry(*serve.Context c) ( c.badRequest("feedback is too long") return ) - string judge = contextString(c, "username") + object score = {projectId: projectId, judge: contextString(c, "username"), ratings: ratings, feedback: feedback, edited: timestamp} + if !saveChallengeScore(space["_id"].toStr(), score) ( + c.json(409, {ok: false, code: "challenge_changed", error: "The challenge changed while your score was being saved. Try again."}) + return + ) + c.json(200, {ok: true, score: score}) +) + +def spaceWriteLock(string id) string ( + return "space-write:" ++ id +) + +def stillChallengeJudge(object space, string judge) boolean ( + if challengeAudienceJudged(space) ( + return false + ) + if stringArrayContainsUser(challengeArray(space, "judges"), judge) ( + return true + ) + if !isOrgOwned(space) ( + return false + ) + object snapshot = ownerOrgSnapshotCached(space) + string ownerId = (space.ownerId ?? "").toStr() + if !snapshot.ok or (ownerId != "" and (snapshot.org.assertElse(object, {}).id ?? "").toStr() != ownerId) ( + return false + ) + return stringArrayContainsUser(orgPublisherNames(snapshot), judge) +) + +def ratingsMatchCriteria(object space, array ratings) boolean ( + if ratings.len != challengeCriteria(space).len ( + return false + ) + for i ratings.len ( + if !validChallengeCriterion(space, ratings[i].assertElse(object, {}).criterionId.toStr()) ( + return false + ) + ) + return true +) + +def saveChallengeScore(string spaceId, object score) boolean ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + string projectId = score.projectId.toStr() + if space.len == 0 or challengePhase(space) != "judging" or !spaceProjectIds(space).contains(projectId) ( + return false + ) + if !stillChallengeJudge(space, score.judge.toStr()) or !ratingsMatchCriteria(space, score.ratings.assertElse(array, [])) ( + return false + ) array scores = challengeArray(space, "scores") array nextScores = [] for i scores.len ( object existing = scores[i].assert(object) - if existing.projectId.toStr() != projectId or normalizeUsername(existing.judge.toStr()) != normalizeUsername(judge) ( + if existing.projectId.toStr() != projectId or normalizeUsername(existing.judge.toStr()) != normalizeUsername(score.judge.toStr()) ( nextScores.append(existing) ) ) - object score = {projectId: projectId, judge: judge, ratings: ratings, feedback: feedback, edited: timestamp} nextScores.append(score) space.scores = nextScores space.edited = timestamp putSpaceDocument(space) - c.json(200, {ok: true, score: score}) + return true +) + +def saveChallengeVote(string spaceId, object vote) boolean ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + string projectId = vote.projectId.toStr() + if space.len == 0 or !challengeAudienceVotingEnabled(space) or challengePhase(space) != "judging" or !spaceProjectIds(space).contains(projectId) ( + return false + ) + array votes = challengeArray(space, "audienceVotes") + array nextVotes = [] + for i votes.len ( + object existing = votes[i].assert(object) + if existing.projectId.toStr() != projectId or normalizeUsername(existing.username.toStr()) != normalizeUsername(vote.username.toStr()) ( + nextVotes.append(existing) + ) + ) + nextVotes.append(vote) + space.audienceVotes = nextVotes + putSpaceDocument(space) + return true ) def handleVoteChallengeEntry(*serve.Context c) ( @@ -435,7 +686,12 @@ def handleVoteChallengeEntry(*serve.Context c) ( return ) object project = (projectSearchDocs.findById(projectId) ?? {}) - if project.len > 0 and searchEntryOwnedByContext(project, c) ( + string ownership = if project.len > 0 then searchEntryOwnership(project, c) else "no" + if ownership == "unavailable" ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."}) + return + ) + if ownership == "yes" ( c.forbidden("you cannot vote for your own entry") return ) @@ -444,18 +700,10 @@ def handleVoteChallengeEntry(*serve.Context c) ( c.badRequest("rating must be between 1 and 5") return ) - string username = contextString(c, "username") - array votes = challengeArray(space, "audienceVotes") - array nextVotes = [] - for i votes.len ( - object vote = votes[i].assert(object) - if vote.projectId.toStr() != projectId or normalizeUsername(vote.username.toStr()) != normalizeUsername(username) ( - nextVotes.append(vote) - ) + if !saveChallengeVote(space["_id"].toStr(), {projectId: projectId, username: contextString(c, "username"), value: value, edited: timestamp}) ( + c.json(409, {ok: false, code: "challenge_changed", error: "The challenge changed while your vote was being saved. Try again."}) + return ) - nextVotes.append({projectId: projectId, username: username, value: value, edited: timestamp}) - space.audienceVotes = nextVotes - putSpaceDocument(space) c.json(200, {ok: true, value: value}) ) @@ -478,8 +726,26 @@ def handlePublishChallengeResults(*serve.Context c) ( c.badRequest("at least one entry needs a judge score") return ) + object published = publishChallengeResultsLocked(space["_id"].toStr(), spaceCuratorOnly(space, c)) + if published.len == 0 ( + c.json(409, {ok: false, code: "challenge_changed", error: "The challenge changed while results were being published. Try again."}) + return + ) + c.json(200, {ok: true, space: spaceResponse(published, c)}) +) + +def publishChallengeResultsLocked(string spaceId, string curator) object ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + if space.len == 0 or !stillSpaceCurator(space, curator) or timestamp <= space.endsAt.toNum() ( + return {} + ) + if challengeArray(space, if challengeAudienceJudged(space) then "audienceVotes" else "scores").len == 0 ( + return {} + ) space.resultsPublishedAt = timestamp space.edited = timestamp putSpaceDocument(space) - c.json(200, {ok: true, space: spaceResponse(space, c)}) + return space ) diff --git a/src/community/comments.osl b/src/community/comments.osl index 1a18f25..38b88b8 100644 --- a/src/community/comments.osl +++ b/src/community/comments.osl @@ -621,9 +621,9 @@ def handleCreateProjectComment(*serve.Context c) ( ) if normalizeUsername(project.owner.toStr()) != normalizeUsername(parentAuthor) ( if donationAmount > 0 ( - addNotification(project.owner.toStr(), commenter, "donation", {projectId: project.id, projectTitle: project.title, commentId: newCommentId, amount: donationAmount, preview: preview}) + notifyContentOwnerExcept(project, commenter, "donation", {projectId: project.id, projectTitle: project.title, commentId: newCommentId, amount: donationAmount, preview: preview}, [parentAuthor]) ) else ( - addNotification(project.owner.toStr(), commenter, "comment", {projectId: project.id, projectTitle: project.title, commentId: newCommentId, preview: preview}) + notifyContentOwnerExcept(project, commenter, "comment", {projectId: project.id, projectTitle: project.title, commentId: newCommentId, preview: preview}, [parentAuthor]) ) ) notifyMentions(created.comment.content.toStr(), commenter, [project.owner.toStr(), parentAuthor], {projectId: project.id, projectTitle: project.title, commentId: newCommentId, preview: preview}) @@ -649,7 +649,7 @@ def handleDeleteProjectComment(*serve.Context c) ( object project = res.project.assert(object) boolean requesterIsAdmin = contextBool(c, "isAdmin") - object deleted = deleteComment("project-" ++ project.id.toStr(), c.param("cid"), contextString(c, "username"), project.owner.toStr(), requesterIsAdmin) + object deleted = deleteComment("project-" ++ project.id.toStr(), c.param("cid"), contextString(c, "username"), projectModerator(project, c), requesterIsAdmin) if !deleted.ok ( c.json(deleted.status.toInt(), {ok: false, error: deleted.error}) return @@ -704,7 +704,7 @@ def handlePinProjectComment(*serve.Context c) ( if body.contains("pinned") and body.pinned != null ( pinned = body.pinned == true ) - object updated = setCommentPin("project-" ++ project.id.toStr(), c.param("cid"), contextString(c, "username"), project.owner.toStr(), contextBool(c, "isAdmin"), pinned) + object updated = setCommentPin("project-" ++ project.id.toStr(), c.param("cid"), contextString(c, "username"), projectModerator(project, c), contextBool(c, "isAdmin"), pinned) if !updated.ok ( c.json(updated.status.toInt(), {ok: false, error: updated.error}) return diff --git a/src/community/community-user-records.osl b/src/community/community-user-records.osl index 474b9d9..c1ea161 100644 --- a/src/community/community-user-records.osl +++ b/src/community/community-user-records.osl @@ -3,13 +3,14 @@ export { purgeUserFromSpaces } -def purgeUserFromSpaces(string username) boolean ( +def purgeUserFromSpaces(string username, string userId) boolean ( string key = normalizeUsername(username) array spaces = spaceDocs.all() for i spaces.len ( object space = spaces[i].assert(object) string spaceId = space["_id"].toStr() - if normalizeUsername(space.owner.toStr()) == key ( + boolean anotherOrg = isOrgOwned(space) and (space.ownerId ?? "").toStr() != userId + if normalizeUsername(space.owner.toStr()) == key and !anotherOrg ( void spaceDocs.deleteOne({_id: space["_id"]}) deleteSpaceMemberships(spaceId) void fs.remove(commentsDir ++ spaceCommentKey(spaceId) ++ ".json") @@ -206,6 +207,11 @@ def renameUserCommunityRecords(string oldKey, string newKey, string newName) boo submissions[j] = submission changed = true ) + if normalizeUsername((submission.submittedBy ?? "").toStr()) == oldKey ( + submission.submittedBy = newName + submissions[j] = submission + changed = true + ) ) space.submissions = submissions ) diff --git a/src/community/groups.osl b/src/community/groups.osl deleted file mode 100644 index e9755f0..0000000 --- a/src/community/groups.osl +++ /dev/null @@ -1,163 +0,0 @@ -export { - canManageGroupContent, - canManageGroupTag, - groupTagOf, - normalizeGroupTag -} - -*cache.Cache groupSnapshotCache = cache.new({capacity: 10000, ttl: 60000}) - -def normalizeGroupTag(string value) string ( - string tag = value.toLower().strip() - if tag.len < 1 or tag.len > 10 or !regex.match("^[a-z0-9]+$", tag) ( - return "" - ) - return tag -) - -def roturPublicGroupSnapshot(string tag) object ( - object publicResponse = requests.get(roturBase ++ "/groups/" ++ url.escape(tag)).unwrapOr({body: null, error: "request failed", headers: {}, raw: null, status: 0, success: false}) - if publicResponse.status != 200 ( - return {ok: false, error: if publicResponse.status == 404 then "group not found" else "could not load group"} - ) - auto publicParsed = json.parse(publicResponse.body, {type: "object"}) - if publicParsed.isErr() ( - return {ok: false, error: "invalid group response"} - ) - object fallback = {ok: true, degraded: true, group: publicParsed.unwrap(), members: []} - groupSnapshotCache.set(tag, fallback) - return fallback -) - -def roturGroupSnapshot(string rawTag) object ( - string tag = normalizeGroupTag(rawTag) - if tag == "" ( - return {ok: false, error: "invalid group tag"} - ) - if groupSnapshotCache.has(tag) ( - return groupSnapshotCache.get(tag).assertElse(object, {ok: false}) - ) - if commerceServiceKey == "" ( - return roturPublicGroupSnapshot(tag) - ) - object response = requests.get( - roturBase ++ "/groups/" ++ url.escape(tag) ++ "/integrations/mistwarp", - {headers: {"X-Commerce-Key": commerceServiceKey}} - ).unwrapOr({body: null, error: "request failed", headers: {}, raw: null, status: 0, success: false}) - if response.status != 200 ( - return roturPublicGroupSnapshot(tag) - ) - auto parsed = json.parse(response.body, {type: "object"}) - if parsed.isErr() ( - return {ok: false, error: "invalid group response"} - ) - object data = parsed.unwrap().assert(object) - object snapshot = {ok: true, group: data.group, members: data.members} - groupSnapshotCache.set(tag, snapshot) - return snapshot -) - -def groupMemberNames(object snapshot) array ( - array names = [] - if !snapshot.ok or !snapshot.contains("members") or snapshot.members == null ( - return names - ) - array members = snapshot.members.assertElse(array, []) - for i members.len ( - object member = members[i].assert(object) - string username = member.username.toStr().strip() - if username != "" and !stringArrayContainsUser(names, username) ( - names.append(username) - ) - ) - return names -) - -def groupHasMember(object snapshot, string userId, string username) boolean ( - if !snapshot.ok ( - return false - ) - array members = snapshot.members.assertElse(array, []) - for i members.len ( - object member = members[i].assert(object) - if identityMatches(member.user_id.toStr(), member.username.toStr(), userId, username) ( - return true - ) - ) - return false -) - -def groupMemberCanManage(object snapshot, string userId, string username) boolean ( - if !snapshot.ok ( - return false - ) - object group = snapshot.group.assert(object) - if normalizeUsername(group.owner_user_id.toStr()) == normalizeUsername(username) ( - return true - ) - array members = snapshot.members.assertElse(array, []) - for i members.len ( - object member = members[i].assert(object) - if identityMatches(member.user_id.toStr(), member.username.toStr(), userId, username) ( - array permissions = member.permissions.assertElse(array, []) - return permissions.contains("groups.manage") or permissions.contains("groups.group.edit") - ) - ) - return false -) - -def canManageGroupTag(string tag,*serve.Context c) boolean ( - if contextBool(c, "isAdmin") ( - return true - ) - return groupMemberCanManage(roturGroupSnapshot(tag), contextString(c, "userId"), contextString(c, "username")) -) - -def groupTagOf(object value) string ( - if value.contains("groupTag") and value.groupTag != null ( - return normalizeGroupTag(value.groupTag.toStr()) - ) - return "" -) - -def canManageGroupContent(object value,*serve.Context c) boolean ( - string tag = groupTagOf(value) - return tag != "" and canManageGroupTag(tag, c) -) - -def handleGetMistWarpGroup(*serve.Context c) ( - string tag = normalizeGroupTag(c.param("tag")) - object snapshot = roturGroupSnapshot(tag) - if !snapshot.ok ( - c.notFound("group not found") - return - ) - boolean canManage = contextBool(c, "authenticated") and groupMemberCanManage(snapshot, contextString(c, "userId"), contextString(c, "username")) - array projects = [] - array projectEntries = projectSearchDocs.where("groupTag", "==", tag).sort("edited", "desc").all() - for i projectEntries.len ( - object project = projectEntries[i].assert(object) - if project.shared == true or project.visibility.toStr() == "unlisted" or canManage ( - projects.append(project) - ) - ) - projects = projectsVisibleTo(projects, c) - array spaces = [] - array spaceEntries = spaceDocs.where("groupTag", "==", tag).sort("edited", "desc").all() - for i spaceEntries.len ( - object space = spaceEntries[i].assert(object) - if space.visibility.toStr() == "public" or space.visibility.toStr() == "unlisted" or canManage ( - spaces.append(spaceListResponse(space, c)) - ) - ) - c.json(200, { - ok: true, - group: snapshot.group, - members: groupMemberNames(snapshot), - projects: projects, - spaces: spaces, - canManage: canManage, - isMember: contextBool(c, "authenticated") and groupHasMember(snapshot, contextString(c, "userId"), contextString(c, "username")), - membershipLive:!snapshot.contains("degraded") or snapshot.degraded != true - }) -) diff --git a/src/community/notifications.osl b/src/community/notifications.osl index 0840619..c3a59c0 100644 --- a/src/community/notifications.osl +++ b/src/community/notifications.osl @@ -1,5 +1,7 @@ export { addNotification, + notifyContentOwner, + notifyContentOwnerExcept, loadNotifications, saveNotifications } @@ -448,3 +450,49 @@ def markNotificationsReadLocked(string username) ( ) saveNotifications(username, items) ) + +def notifyContentOwner(object content, string actor, string notifType, object extra) ( + notifyContentOwnerExcept(content, actor, notifType, extra, []) +) + +def notifyContentOwnerExcept(object content, string actor, string notifType, object extra, array skip) ( + string owner = (content.owner ?? "").toStr() + if !isOrgOwned(content) ( + addNotification(owner, actor, notifType, extra) + return + ) + string ownerId = (content.ownerId ?? "").toStr() + string fanOutKey = ownerId ++ ":" ++ owner ++ ":" ++ actor ++ ":" ++ notifType ++ ":" ++ extra.toStr() + if notifType != "purchase" ( + if recentOrgFanOuts.get(fanOutKey).assertElse(boolean, false) ( + return + ) + recentOrgFanOuts.set(fanOutKey, true) + ) + thread.new(notifyOrgPublishers, owner, ownerId, actor, notifType, extra, fanOutKey, skip) +) + +number orgNotificationLimit = 25 +*cache.Cache recentOrgFanOuts = cache.new({capacity: 10000, ttl: 600000}) + +def notifyOrgPublishers(string owner, string ownerId, string actor, string notifType, object extra, string fanOutKey, array skip) ( + object snapshot = roturOrgSnapshot(if ownerId != "" then ownerId else owner) + if !snapshot.ok and snapshot.contains("unavailable") and snapshot.unavailable == true ( + recentOrgFanOuts.delete(fanOutKey) + return + ) + if !snapshot.ok or (ownerId != "" and (snapshot.org.assertElse(object, {}).id ?? "").toStr() != ownerId) ( + return + ) + array names = orgPublisherNames(snapshot) + number sent = 0 + for i names.len ( + if sent >= orgNotificationLimit ( + return + ) + if normalizeUsername(names[i].toStr()) != normalizeUsername(actor) and !stringArrayContainsUser(skip, names[i].toStr()) ( + addNotification(names[i].toStr(), actor, notifType, extra) + sent += 1 + ) + ) +) diff --git a/src/community/notifications.test.osl b/src/community/notifications.test.osl index 59c2a55..5b77da3 100644 --- a/src/community/notifications.test.osl +++ b/src/community/notifications.test.osl @@ -4,6 +4,7 @@ import "std:json" import "std:requests" import "std:serve" import "std:thread" +import "std:cache" string notificationsDir = "notifications/" string editorOrigin = "https://mistwarp.org" @@ -85,6 +86,30 @@ def rewriteNotificationIdentityFields(object data, string oldKey, string newName return false ) +def stringArrayContainsUser(array users, string username) boolean ( + for i users.len ( + if users[i].toStr().toLower() == username.toLower() ( + return true + ) + ) + return false +) + +def isOrgOwned(object value) boolean ( + return (value.ownerType ?? "").toStr() == "org" +) + +def roturOrgSnapshot(string name) object ( + if name == "studio" or name == "o_studio" ( + return {ok: true, org: {id: "o_studio"}} + ) + return {ok: false, notOrg: true} +) + +def orgPublisherNames(object snapshot) array ( + return if snapshot.ok then ["ada", "bea"] else [] +) + import "./notifications.osl" def handleFakeNotification(*serve.Context c) ( @@ -127,3 +152,52 @@ messageRefused = ["student>owner"] addNotification("owner", "student", "comment", {projectId: "p4"}) testing.assert(askedRotur.len == 0, "a student's notification stays in MistWarp") testing.assert(loadNotifications("owner").len == 2, "and classroom rules, not Rotur's message signal, decide it") + +roturStatus = 200 +askedRotur = [] +notifyContentOwner({owner: "studio", ownerId: "o_studio", ownerType: "org"}, "bea", "love", {projectId: "p5"}) +for i 50 ( + if askedRotur.len > 0 ( + break + ) + wait 0.05 +) +testing.assert(askedRotur.len == 1 and askedRotur[1].toStr().contains("ada") and !askedRotur[1].toStr().contains("\"studio\""), "a love on an org's project goes to its other publishers, not the org account") +askedRotur = [] +notifyContentOwner({owner: "studio", ownerId: "o_taken", ownerType: "org"}, "zed", "love", {projectId: "p6"}) +wait 0.3 +testing.assert(askedRotur.len == 0, "content left by an org whose name was taken notifies nobody") +notifyContentOwner({owner: "sam", ownerType: ""}, "zed", "love", {projectId: "p7"}) +testing.assert(askedRotur.len == 1, "a person's content notifies them as before") +askedRotur = [] +notifyContentOwner({owner: "studio", ownerId: "o_studio", ownerType: "org"}, "bea", "love", {projectId: "p5"}) +wait 0.3 +testing.assert(askedRotur.len == 0, "the same love toggled again soon doesn't fan out to the publishers twice") +notifyContentOwner({owner: "studio", ownerId: "o_studio", ownerType: "org"}, "bea", "love", {projectId: "p8"}) +for i 50 ( + if askedRotur.len > 0 ( + break + ) + wait 0.05 +) +testing.assert(askedRotur.len == 1, "a love on another of the org's projects still fans out") +askedRotur = [] +notifyContentOwner({owner: "studio", ownerId: "o_studio", ownerType: "org"}, "bea", "purchase", {projectId: "p8", productId: "x", amount: 5}) +notifyContentOwner({owner: "studio", ownerId: "o_studio", ownerType: "org"}, "bea", "purchase", {projectId: "p8", productId: "x", amount: 5}) +for i 50 ( + if askedRotur.len > 1 ( + break + ) + wait 0.05 +) +testing.assert(askedRotur.len == 2, "buying the same product twice tells the publishers about both purchases") +askedRotur = [] +notifyContentOwnerExcept({owner: "studio", ownerId: "o_studio", ownerType: "org"}, "zed", "comment", {projectId: "p9", commentId: "c1"}, ["ada"]) +for i 50 ( + if askedRotur.len > 0 ( + break + ) + wait 0.05 +) +wait 0.2 +testing.assert(askedRotur.len == 1 and !askedRotur[1].toStr().contains("ada"), "a publisher who already got the reply is not sent the comment again") diff --git a/src/community/org-page.osl b/src/community/org-page.osl new file mode 100644 index 0000000..d264414 --- /dev/null +++ b/src/community/org-page.osl @@ -0,0 +1,96 @@ +export {} + +def orgMemberResponse(object member) object ( + return { + username: (member.username ?? "").toStr(), + displayName: (member.display_name ?? "").toStr(), + admin: member.admin == true + } +) + +def orgProfileResponse(object org) object ( + return { + id: (org.id ?? "").toStr(), + username: (org.username ?? "").toStr(), + displayName: (org.display_name ?? "").toStr(), + bio: (org.bio ?? "").toStr(), + location: (org.location ?? "").toStr(), + links: (org.links ?? []).assertElse(array, []), + created: (org.created ?? 0).toNum(), + memberCount: (org.member_count ?? 0).toNum() + } +) + +def orgLookupFailed(*serve.Context c, object snapshot) ( + if snapshot.contains("unavailable") and snapshot.unavailable == true ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."}) + return + ) + c.notFound("organisation not found") +) + +def handleGetMistWarpOrg(*serve.Context c) ( + object snapshot = roturOrgSnapshot(c.param("name")) + if !snapshot.ok ( + orgLookupFailed(c, snapshot) + return + ) + string userId = contextString(c, "userId") + string username = contextString(c, "username") + boolean signedIn = contextBool(c, "authenticated") + boolean isMember = signedIn and orgHasMember(snapshot, userId, username) + array members = [] + array all = snapshot.members.assertElse(array, []) + for i all.len ( + object member = all[i].assertElse(object, {}) + if member.public == true or isMember or contextBool(c, "isAdmin") ( + members.append(orgMemberResponse(member)) + ) + ) + object org = snapshot.org.assertElse(object, {}) + boolean canManage = signedIn and (contextBool(c, "isAdmin") or orgMemberCanPublish(snapshot, userId, username)) + array projects = projectsVisibleTo(orgProjectEntries(org, canManage), c) + c.json(200, { + ok: true, + org: orgProfileResponse(org), + members: members, + projects: if canManage then viewerThumbEntries(projects) else projects, + spaces: orgSpaces((org.id ?? "").toStr(), canManage, c), + isMember: isMember, + canManage: canManage + }) +) + +number orgPageLimit = 100 + +def orgProjectEntries(object org, boolean canManage) array ( + string orgId = (org.id ?? "").toStr() + array owned = [] + if orgId == "" ( + return owned + ) + array entries = projectSearchDocs.where("ownerId", "==", orgId).sort("edited", "desc").all() + for i entries.len ( + object entry = entries[i].assertElse(object, {}) + if (entry.ownerType ?? "").toStr() == "org" and (entry.shared == true or canManage) and owned.len < orgPageLimit ( + owned.append(entry) + ) + ) + return owned +) + +def orgSpaces(string orgId,boolean canManage,*serve.Context c) array ( + array spaces = [] + if orgId == "" ( + return spaces + ) + array entries = spaceDocs.where("ownerId", "==", orgId).sort("edited", "desc").all() + for i entries.len ( + object space = entries[i].assertElse(object, {}) + string visibility = (space.visibility ?? "").toStr() + if spaces.len < orgPageLimit and (space.ownerType ?? "").toStr() == "org" and (visibility == "public" or canManage) ( + spaces.append(spaceListResponse(space, c)) + ) + ) + return spaces +) diff --git a/src/community/orgs.osl b/src/community/orgs.osl new file mode 100644 index 0000000..2d162bf --- /dev/null +++ b/src/community/orgs.osl @@ -0,0 +1,347 @@ +export { + canManageOrgContent, + creationOwner, + isOrgOwned, + ownerOrgSnapshot, + ownerOrgSnapshotCached, + orgAdminAccess, + orgMoveOutAccess, + orgAccess, + orgContentAccess, + orgContentPublisherAccess, + orgHasMember, + orgMemberCanPublish, + orgPublisherNames, + orgPublicMemberNames, + roturOrgSnapshot +} + +*cache.Cache orgSnapshotCache = cache.new({capacity: 10000, ttl: 60000}) +*cache.Cache orgUnavailableCache = cache.new({capacity: 10000, ttl: 15000}) +*cache.Cache orgMissingCache = cache.new({capacity: 10000, ttl: 10000}) +*cache.Cache orgWarmingCache = cache.new({capacity: 10000, ttl: 12000}) +*cache.Cache userOrgsCache = cache.new({capacity: 10000, ttl: 60000}) +*cache.Cache userOrgsUnavailableCache = cache.new({capacity: 10000, ttl: 15000}) + +def roturServiceGet(string path) object ( + object failed = {body: null, error: "request failed", headers: {}, raw: null, status: 0, success: false} + return requests.get(roturBase ++ path, {headers: {"X-Commerce-Key": commerceServiceKey}, timeoutMs: 10000}).unwrapOr(failed) +) + +def roturOrgSnapshot(string rawName) object ( + string name = normalizeUsername(rawName) + if name == "" or !isSafePathPart(name) ( + return {ok: false, notOrg: true} + ) + object known = cachedOrgSnapshot(name) + if known.len > 0 ( + return known + ) + sync.lock("rotur-org:" ++ name) + defer sync.unlock("rotur-org:" ++ name) + return fetchOrgSnapshot(name) +) + +def cachedOrgSnapshot(string name) object ( + object cached = orgSnapshotCache.get(name).assertElse(object, {}) + if cached.contains("ok") ( + return cached + ) + if orgMissingCache.get(name).assertElse(boolean, false) ( + return {ok: false, notOrg: true} + ) + if commerceServiceKey == "" or orgUnavailableCache.get(name).assertElse(boolean, false) ( + return {ok: false, unavailable: true} + ) + return {} +) + +def fetchOrgSnapshot(string name) object ( + object known = cachedOrgSnapshot(name) + if known.len > 0 ( + return known + ) + object response = roturServiceGet("/v2/integrations/mistwarp/orgs/" ++ url.escape(name)) + if response.status == 404 ( + orgMissingCache.set(name, true) + return {ok: false, notOrg: true} + ) + auto parsed = json.parse(response.body ?? "", {type: "object"}) + object data = if response.status == 200 and parsed.isOk() then parsed.unwrap().assert(object) else {} + if (data.id ?? "").toStr() == "" or (data.username ?? "").toStr() == "" ( + orgUnavailableCache.set(name, true) + return {ok: false, unavailable: true} + ) + object snapshot = {ok: true, org: data, members: (data.members ?? []).assertElse(array, [])} + orgSnapshotCache.set(name, snapshot) + orgSnapshotCache.set(normalizeUsername((data.id ?? "").toStr()), snapshot) + orgSnapshotCache.set(normalizeUsername((data.username ?? "").toStr()), snapshot) + return snapshot +) + +def orgMemberPerms(object snapshot, string userId, string username) array ( + if !snapshot.ok ( + return [] + ) + array members = snapshot.members.assertElse(array, []) + for i members.len ( + object member = members[i].assertElse(object, {}) + if identityMatches((member.id ?? "").toStr(), (member.username ?? "").toStr(), userId, username) ( + if member.admin == true ( + return ["admin"] + ) + return (member.perms ?? []).assertElse(array, []) + ) + ) + return [] +) + +def orgHasMember(object snapshot, string userId, string username) boolean ( + if !snapshot.ok or (userId == "" and username == "") ( + return false + ) + array members = snapshot.members.assertElse(array, []) + for i members.len ( + object member = members[i].assertElse(object, {}) + if identityMatches((member.id ?? "").toStr(), (member.username ?? "").toStr(), userId, username) ( + return true + ) + ) + return false +) + +def orgPermsAllowPublishing(array perms) boolean ( + return perms.contains("admin") or perms.contains("apps") +) + +def orgMemberCanPublish(object snapshot, string userId, string username) boolean ( + return orgPermsAllowPublishing(orgMemberPerms(snapshot, userId, username)) +) + +def ownerOrgSnapshot(object value) object ( + string ownerId = (value.ownerId ?? "").toStr() + return roturOrgSnapshot(if ownerId != "" then ownerId else (value.owner ?? "").toStr()) +) + +def ownerOrgSnapshotCached(object value) object ( + string ownerId = (value.ownerId ?? "").toStr() + string key = normalizeUsername(if ownerId != "" then ownerId else (value.owner ?? "").toStr()) + if key == "" or !isSafePathPart(key) ( + return {ok: false, notOrg: true} + ) + object known = cachedOrgSnapshot(key) + if known.len > 0 ( + return known + ) + if !orgWarmingCache.get(key).assertElse(boolean, false) ( + orgWarmingCache.set(key, true) + thread.new(warmOrgSnapshot, key) + ) + return {ok: false, unavailable: true} +) + +def warmOrgSnapshot(string key) ( + void roturOrgSnapshot(key) + orgWarmingCache.delete(key) +) + +def viewerOrgListing(string name, string expectedOrgId,*serve.Context c) string ( + object mine = roturUserOrgs(contextString(c, "userId")) + if !mine.ok ( + return "unavailable" + ) + array orgs = mine.orgs.assertElse(array, []) + for i orgs.len ( + object org = orgs[i].assertElse(object, {}) + boolean idMatches = expectedOrgId != "" and (org.id ?? "").toStr() == expectedOrgId + boolean nameMatches = expectedOrgId == "" and normalizeUsername((org.username ?? "").toStr()) == normalizeUsername(name) + if idMatches or nameMatches ( + return "yes" + ) + ) + return "no" +) + +def orgAccess(string name, string expectedOrgId,*serve.Context c) string ( + if contextBool(c, "authenticated") and contextBool(c, "isAdmin") ( + return "yes" + ) + return orgPublisherAccess(name, expectedOrgId, c) +) + +def orgPublisherAccess(string name, string expectedOrgId,*serve.Context c) string ( + if !contextBool(c, "authenticated") or isStudentUserId(contextString(c, "userId")) ( + return "no" + ) + string listed = viewerOrgListing(name, expectedOrgId, c) + if listed != "yes" ( + return listed + ) + object snapshot = roturOrgSnapshot(if expectedOrgId != "" then expectedOrgId else name) + if !snapshot.ok ( + return if snapshot.contains("unavailable") and snapshot.unavailable == true then "unavailable" else "no" + ) + object org = snapshot.org.assertElse(object, {}) + if expectedOrgId != "" and (org.id ?? "").toStr() != expectedOrgId ( + return "no" + ) + return if orgMemberCanPublish(snapshot, contextString(c, "userId"), contextString(c, "username")) then "yes" else "no" +) + +def orgAdminAccess(object snapshot, string expectedOrgId,*serve.Context c) string ( + if contextBool(c, "isAdmin") ( + return "yes" + ) + if !contextBool(c, "authenticated") ( + return "no" + ) + if !snapshot.ok ( + return if snapshot.contains("unavailable") and snapshot.unavailable == true then "unavailable" else "no" + ) + if expectedOrgId != "" and (snapshot.org.assertElse(object, {}).id ?? "").toStr() != expectedOrgId ( + return "no" + ) + return if orgMemberPerms(snapshot, contextString(c, "userId"), contextString(c, "username")).contains("admin") then "yes" else "no" +) + +def orgMoveOutAccess(object value,*serve.Context c) string ( + if !isOrgOwned(value) or contextBool(c, "isAdmin") ( + return "yes" + ) + if !contextBool(c, "authenticated") or isStudentUserId(contextString(c, "userId")) ( + return "no" + ) + string listed = viewerOrgListing((value.owner ?? "").toStr(), (value.ownerId ?? "").toStr(), c) + if listed != "yes" ( + return listed + ) + return orgAdminAccess(ownerOrgSnapshot(value), (value.ownerId ?? "").toStr(), c) +) + +def isOrgOwned(object value) boolean ( + return (value.ownerType ?? "").toStr() == "org" +) + +def orgContentAccess(object value,*serve.Context c) string ( + if !isOrgOwned(value) ( + return "no" + ) + return orgAccess((value.owner ?? "").toStr(), (value.ownerId ?? "").toStr(), c) +) + +def orgContentPublisherAccess(object value,*serve.Context c) string ( + if !isOrgOwned(value) ( + return "no" + ) + return orgPublisherAccess((value.owner ?? "").toStr(), (value.ownerId ?? "").toStr(), c) +) + +def canManageOrgContent(object value,*serve.Context c) boolean ( + return orgContentAccess(value, c) == "yes" +) + +def creationOwner(*serve.Context c, object body, string noun) object ( + string requestedOrg = (body.org ?? "").toStr().strip() + if requestedOrg == "" ( + return {ok: true, owner: contextString(c, "username"), ownerId: contextString(c, "userId"), ownerType: ""} + ) + object snapshot = roturOrgSnapshot(requestedOrg) + if !snapshot.ok and snapshot.contains("unavailable") and snapshot.unavailable == true ( + return {ok: false, status: 503, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."} + ) + if !snapshot.ok ( + return {ok: false, status: 400, code: "org_not_found", error: "organisation not found"} + ) + if !contextBool(c, "isAdmin") and !orgMemberCanPublish(snapshot, contextString(c, "userId"), contextString(c, "username")) ( + return {ok: false, status: 403, code: "org_forbidden", error: "you cannot create " ++ noun ++ " for this organisation"} + ) + object org = snapshot.org.assertElse(object, {}) + string orgId = (org.id ?? "").toStr() + string orgName = (org.username ?? "").toStr() + if orgId == "" or orgName == "" ( + return {ok: false, status: 503, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."} + ) + return {ok: true, owner: orgName, ownerId: orgId, ownerType: "org"} +) + +def orgPublicMemberNames(object snapshot) array ( + array names = [] + if !snapshot.ok ( + return names + ) + array members = snapshot.members.assertElse(array, []) + for i members.len ( + object member = members[i].assertElse(object, {}) + string username = (member.username ?? "").toStr().strip() + if member.public == true and username != "" and !stringArrayContainsUser(names, username) ( + names.append(username) + ) + ) + return names +) + +def orgPublisherNames(object snapshot) array ( + array names = [] + if !snapshot.ok ( + return names + ) + array members = snapshot.members.assertElse(array, []) + for i members.len ( + object member = members[i].assertElse(object, {}) + string username = (member.username ?? "").toStr().strip() + boolean publishes = member.admin == true or orgPermsAllowPublishing((member.perms ?? []).assertElse(array, [])) + if username != "" and publishes and !stringArrayContainsUser(names, username) ( + names.append(username) + ) + ) + return names +) + +def roturUserOrgs(string userId) object ( + if userId == "" or !isSafePathPart(userId) ( + return {ok: true, orgs: []} + ) + object cached = userOrgsCache.get(userId).assertElse(object, {}) + if cached.contains("ok") ( + return cached + ) + if commerceServiceKey == "" or userOrgsUnavailableCache.get(userId).assertElse(boolean, false) ( + return {ok: false} + ) + object response = roturServiceGet("/v2/integrations/mistwarp/users/" ++ url.escape(userId) ++ "/orgs") + if response.status == 404 ( + object none = {ok: true, orgs: []} + userOrgsCache.set(userId, none) + return none + ) + auto parsed = json.parse(response.body ?? "", {type: "object"}) + if response.status != 200 or parsed.isErr() ( + userOrgsUnavailableCache.set(userId, true) + return {ok: false} + ) + object data = parsed.unwrap().assert(object) + object found = {ok: true, orgs: (data.orgs ?? []).assertElse(array, [])} + userOrgsCache.set(userId, found) + return found +) + +def handleGetMyOrgs(*serve.Context c) ( + object found = roturUserOrgs(contextString(c, "userId")) + if !found.ok ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."}) + return + ) + array orgs = [] + array entries = found.orgs.assertElse(array, []) + for i entries.len ( + object org = entries[i].assertElse(object, {}) + array perms = (org.perms ?? []).assertElse(array, []) + orgs.append({ + username: (org.username ?? "").toStr(), + displayName: (org.display_name ?? "").toStr(), + perms: perms, + canPublish: org.admin == true or orgPermsAllowPublishing(perms) + }) + ) + c.json(200, {ok: true, orgs: orgs}) +) diff --git a/src/community/orgs.test.osl b/src/community/orgs.test.osl new file mode 100644 index 0000000..b68a9b8 --- /dev/null +++ b/src/community/orgs.test.osl @@ -0,0 +1,268 @@ +import "std:testing" +import "std:sync" +import "std:json" +import "std:requests" +import "std:serve" +import "std:thread" +import "std:cache" +import "std:url" +import "std:db" +import "std:fs" + +string roturBase = "http://127.0.0.1:18351" +string commerceServiceKey = "mw-key" +array askedRotur = [] +number orgStatus = 200 + +def normalizeUsername(string name) string ( + return name.toLower().strip() +) + +def isSafePathPart(string value) boolean ( + return value != "" and !value.contains("/") +) + +def identityMatches(string storedId, string storedUsername, string userId, string username) boolean ( + if storedId != "" and userId != "" ( + return storedId == userId + ) + return normalizeUsername(storedUsername) == normalizeUsername(username) +) + +def stringArrayContainsUser(array users, string username) boolean ( + for i users.len ( + if normalizeUsername(users[i].toStr()) == normalizeUsername(username) ( + return true + ) + ) + return false +) + +def isStudentUserId(string userId) boolean ( + return userId.startsWith("stu_") +) + +def contextString(*serve.Context c, string key) string ( + if key == "username" ( + return (c.header("X-Test-User") ?? "") + ) + if key == "userId" ( + return (c.header("X-Test-Id") ?? "") + ) + return "" +) + +def contextBool(*serve.Context c, string key) boolean ( + if key == "authenticated" ( + return (c.header("X-Test-User") ?? "") != "" + ) + if key == "isAdmin" ( + return (c.header("X-Test-Admin") ?? "") == "1" + ) + return false +) + +string spaceDbPath = "/tmp/mistwarp-org-page-" ++ timestamp.toStr() ++ ".db" +*db.DB orgPageDb = db.open(spaceDbPath) +*db.Collection spaceDocs = orgPageDb.collection("spaces") +void spaceDocs.insertOne({_id: "s_pub", ownerId: "org_studio", ownerType: "org", visibility: "public", edited: 3}) +void spaceDocs.insertOne({_id: "s_unl", ownerId: "org_studio", ownerType: "org", visibility: "unlisted", edited: 2}) +void spaceDocs.insertOne({_id: "s_pri", ownerId: "org_studio", ownerType: "org", visibility: "private", edited: 1}) +void spaceDocs.insertOne({_id: "s_own", ownerId: "org_studio", ownerType: "", visibility: "public", edited: 0}) + +*db.Collection projectSearchDocs = orgPageDb.collection("projects") +void projectSearchDocs.insertOne({_id: "p_org", id: "p_org", ownerId: "org_studio", ownerKey: "studio", ownerType: "org", shared: true, edited: 4}) +void projectSearchDocs.insertOne({_id: "p_old", id: "p_old", ownerId: "org_gone", ownerKey: "studio", ownerType: "org", shared: true, edited: 3}) +void projectSearchDocs.insertOne({_id: "p_person", id: "p_person", ownerId: "u_studio", ownerKey: "studio", ownerType: "", shared: true, edited: 2}) +void projectSearchDocs.insertOne({_id: "p_draft", id: "p_draft", ownerId: "org_studio", ownerKey: "studio", ownerType: "org", shared: false, edited: 1}) + +def viewerThumbEntries(array entries) array ( + array out = [] + for i entries.len ( + object keyed = entries[i].assert(object).clone() + keyed.thumbUrl = "keyed" + out.append(keyed) + ) + return out +) + +def projectsVisibleTo(array entries,*serve.Context c) array ( + return entries +) + +def spaceListResponse(object space,*serve.Context c) object ( + return {id: space["_id"]} +) + +import "./orgs.osl" +import "./org-page.osl" + +object studio = { + id: "org_studio", + username: "Studio", + display_name: "The Studio", + bio: "We make games.", + member_count: 4, + members: [ + {id: "u_ada", username: "ada", admin: true, perms: ["admin"], public: true}, + {id: "u_bea", username: "bea", admin: false, perms: ["apps"], public: false}, + {id: "u_cal", username: "cal", admin: false, perms: ["billing"], public: true}, + {id: "u_dee", username: "dee", admin: false, perms: [], public: false} + ] +} + +def handleFakeOrg(*serve.Context c) ( + askedRotur.append(c.param("name") ++ " " ++ (c.header("X-Commerce-Key") ?? "")) + if (c.header("X-Commerce-Key") ?? "") != commerceServiceKey ( + c.json(403, {error: "invalid service key"}) + return + ) + if orgStatus != 200 ( + c.json(orgStatus, {error: "no"}) + return + ) + if c.param("name") == "broken" ( + c.json(200, {error: "half an answer"}) + return + ) + if c.param("name") != "studio" and c.param("name") != "org_studio" ( + c.json(404, {error: "Not an organisation", code: "not_org", not_org: true}) + return + ) + c.json(200, studio) +) + +def handleFakeUserOrgs(*serve.Context c) ( + askedRotur.append("orgs of " ++ c.param("id")) + c.json(200, {orgs: [{id: "org_studio", username: "Studio", display_name: "The Studio", perms: ["apps"]}, {id: "org_other", username: "other", perms: []}]}) +) + +def handleCheckPublish(*serve.Context c) ( + c.json(200, {ok: orgAccess(c.param("name"), "", c) == "yes"}) +) + +def handleCheckContent(*serve.Context c) ( + c.json(200, {ok: canManageOrgContent({owner: "studio", ownerId: (c.query("id") ?? ""), ownerType: (c.query("kind") ?? "")}, c)}) +) + +def handleCheckOwnWork(*serve.Context c) ( + object content = {owner: "studio", ownerId: "org_studio", ownerType: "org"} + c.json(200, {ok: true, manage: orgContentAccess(content, c), publisher: orgContentPublisherAccess(content, c)}) +) + +def handleCheckCreation(*serve.Context c) ( + c.json(200, creationOwner(c, {org: (c.query("org") ?? "")}, "projects")) +) + +*serve.Router fakeRotur = serve.new() +fakeRotur.GET("/v2/integrations/mistwarp/orgs/:name", handleFakeOrg) +fakeRotur.GET("/v2/integrations/mistwarp/users/:id/orgs", handleFakeUserOrgs) +fakeRotur.GET("/check/publish/:name", handleCheckPublish) +fakeRotur.GET("/check/content", handleCheckContent) +fakeRotur.GET("/check/create", handleCheckCreation) +fakeRotur.GET("/check/own", handleCheckOwnWork) +fakeRotur.GET("/ready", handleFakeUserOrgs) +fakeRotur.GET("/page/:name", handleGetMistWarpOrg) + +def runFakeRotur() ( + fakeRotur.run(":18351") +) +thread.new(runFakeRotur) +for i 50 ( + if requests.get(roturBase ++ "/ready").isOk() ( + break + ) + wait 0.1 +) + +def ask(string path, string user, string id) object ( + object response = requests.get(roturBase ++ path, {headers: {"X-Test-User": user, "X-Test-Id": id}}).unwrap() + return json.parse(response.body, {type: "object"}).unwrap().assert(object) +) + +askedRotur = [] +object snapshot = roturOrgSnapshot("Studio") +testing.assert(snapshot.ok and snapshot.org.id == "org_studio", "an org comes back from Rotur") +testing.assert(askedRotur == ["studio mw-key"], "MistWarp asks with its service key, by the lowercased name") +void roturOrgSnapshot("studio") +testing.assert(askedRotur.len == 1, "a second look within the minute is cached") +testing.assert(roturOrgSnapshot("org_studio").ok and askedRotur.len == 1, "the same org asked for by id is already known") + +testing.assert(orgMemberPerms(snapshot, "u_ada", "ada") == ["admin"], "an admin has every permission") +testing.assert(orgMemberPerms(snapshot, "", "BEA") == ["apps"], "a member is found by name too") +testing.assert(orgMemberPerms(snapshot, "u_zed", "zed") == [], "someone outside the org has none") +testing.assert(orgHasMember(snapshot, "", "dee") and !orgHasMember(snapshot, "", "zed"), "membership includes private members") +testing.assert(orgPublicMemberNames(snapshot) == ["ada", "cal"], "only public members are named") +testing.assert(orgPublisherNames(snapshot) == ["ada", "bea"], "publishers are the admins and app members, private ones included") +testing.assert(orgMemberCanPublish(snapshot, "u_bea", "bea") and orgMemberCanPublish(snapshot, "u_ada", "ada"), "apps and admin may publish") +testing.assert(!orgMemberCanPublish(snapshot, "u_cal", "cal") and !orgMemberCanPublish(snapshot, "u_dee", "dee"), "billing and plain members may not") + +object person = roturOrgSnapshot("ada") +testing.assert(!person.ok and person.notOrg == true, "a person is not an org") +testing.assert(!roturOrgSnapshot("a/b").ok and askedRotur.len == 2, "an unsafe name is never sent") + +orgStatus = 500 +object down = roturOrgSnapshot("busy") +testing.assert(!down.ok and down.unavailable == true, "a Rotur error is reported as unavailable") +void roturOrgSnapshot("busy") +testing.assert(askedRotur.len == 3, "an unavailable answer is remembered briefly, so a list of spaces doesn't ask again for each") +orgStatus = 200 + +testing.assert(isOrgOwned({ownerType: "org"}) and !isOrgOwned({ownerType: ""}) and !isOrgOwned({}), "only content marked as org-owned is") + +testing.assert(ask("/check/publish/studio", "bea", "u_bea").ok == true, "a member with apps can publish for the org") +testing.assert(ask("/check/publish/studio", "cal", "u_cal").ok == false, "a billing member cannot") +testing.assert(ask("/check/publish/studio", "", "").ok == false, "nobody signed out can") +testing.assert(ask("/check/publish/ada", "ada", "u_ada").ok == false, "nobody publishes for a person") +testing.assert(ask("/check/content?kind=org", "bea", "u_bea").ok == true, "a publisher manages the org's content") +testing.assert(ask("/check/content", "bea", "u_bea").ok == false, "but not content the org's name merely matches") + +object created = ask("/check/create?org=studio", "bea", "u_bea") +testing.assert(created.ok and created.owner == "Studio" and created.ownerId == "org_studio" and created.ownerType == "org", "content made for an org is owned by it") +object refused = ask("/check/create?org=studio", "dee", "u_dee") +testing.assert(!refused.ok and refused.status == 403, "a member without apps can't make content for the org") +object notOrg = ask("/check/create?org=ada", "ada", "u_ada") +testing.assert(!notOrg.ok and notOrg.status == 400, "content can't be made for a person through org") +object mine = ask("/check/create", "bea", "u_bea") +testing.assert(mine.ok and mine.owner == "bea" and mine.ownerType == "", "without an org, content is the creator's") + +askedRotur = [] +object orgs = roturUserOrgs("u_eve") +testing.assert(orgs.ok and orgs.orgs.len == 2 and askedRotur == ["orgs of u_eve"], "a person's orgs come from Rotur") +void roturUserOrgs("u_eve") +testing.assert(askedRotur.len == 1, "and are cached") +testing.assert(orgPermsAllowPublishing(["apps"]) and !orgPermsAllowPublishing([]), "the org list says where someone can publish") + +testing.assert(ask("/check/content?kind=org&id=org_studio", "bea", "u_bea").ok == true, "a publisher manages content the org owns by id") +testing.assert(ask("/check/content?kind=org&id=org_gone", "bea", "u_bea").ok == false, "but not content left by an earlier org with the same name") +testing.assert(ask("/check/content?kind=org&id=org_gone", "zed", "u_zed").ok == false, "nor does anyone else") +object broken = roturOrgSnapshot("broken") +testing.assert(!broken.ok and broken.unavailable == true, "a 200 without an org in it is unavailable, not an empty org") + +object adminCheck = json.parse(requests.get(roturBase ++ "/check/own", {headers: {"X-Test-User": "root", "X-Test-Id": "u_root", "X-Test-Admin": "1"}}).unwrap().body, {type: "object"}).unwrap().assert(object) +testing.assert(adminCheck.manage == "yes" and adminCheck.publisher == "no", "a site admin manages an org's content but is not one of its publishers") +askedRotur = [] +object studentCheck = ask("/check/own", "kid", "stu_kid") +testing.assert(studentCheck.manage == "no" and studentCheck.publisher == "no" and askedRotur.len == 0, "a student never publishes for an org and Rotur is not asked") +testing.assert(ask("/check/own", "bea", "u_bea").publisher == "yes", "a publisher's own org work counts as theirs") + +def page(string user, string id) object ( + return ask("/page/studio", user, id) +) + +object anonymous = page("", "") +array anonymousMembers = anonymous.members.assert(array) +testing.assert(anonymousMembers.len == 2 and anonymousMembers[1].username == "ada" and anonymousMembers[2].username == "cal", "a visitor sees only the listed members") +testing.assert(anonymous.isMember == false and anonymous.canManage == false, "a visitor is neither member nor publisher") +testing.assert(anonymous.projects.assert(array).len == 1 and anonymous.projects[1].id == "p_org" and anonymous.projects[1].thumbUrl != "keyed", "a visitor sees the org's shared projects, not an old org's or a person's") +testing.assert(anonymous.spaces.assert(array).len == 1 and anonymous.spaces[1].id == "s_pub", "a visitor sees only public spaces, not unlisted ones") + +object member = page("dee", "u_dee") +testing.assert(member.members.assert(array).len == 4 and member.isMember == true and member.canManage == false, "a member sees every member but cannot manage") +testing.assert(member.projects.assert(array).len == 1 and member.spaces.assert(array).len == 1, "a member without apps sees what visitors see") + +object publisher = page("bea", "u_bea") +testing.assert(publisher.canManage == true and publisher.projects.assert(array).len == 2 and publisher.projects[1].thumbUrl == "keyed" and publisher.spaces.assert(array).len == 3, "a publisher also sees drafts, unlisted and private spaces") + +orgPageDb.close() +void fs.remove(spaceDbPath) diff --git a/src/community/project-feedback.osl b/src/community/project-feedback.osl index f3967ae..490c6a7 100644 --- a/src/community/project-feedback.osl +++ b/src/community/project-feedback.osl @@ -23,7 +23,7 @@ def handleCreateProjectFeedback(*serve.Context c) ( string feedbackId = project.id.toStr() ++ ":" ++ randomString(16) object feedback = {_id: feedbackId, projectId: project.id, type: feedbackType, message: message, status: "open", author: contextString(c, "username"), authorId: contextString(c, "userId"), created: timestamp, edited: timestamp} void feedbackDocs.insertOne(feedback) - addNotification(project.owner.toStr(), contextString(c, "username"), "project_feedback", {projectId: project.id, projectTitle: project.title, feedbackType: feedbackType}) + notifyContentOwner(project, contextString(c, "username"), "project_feedback", {projectId: project.id, projectTitle: project.title, feedbackType: feedbackType, feedbackId: feedbackId}) c.json(201, {ok: true}) ) @@ -121,7 +121,12 @@ def handleSaveProjectReview(*serve.Context c) ( return ) object project = res.project.assert(object) - if projectRole(project, contextString(c, "username")) == "owner" ( + string orgOwnership = if projectRole(project, contextString(c, "username")) == "owner" then "yes" else orgContentPublisherAccess(project, c) + if orgOwnership == "unavailable" ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."}) + return + ) + if orgOwnership == "yes" ( c.badRequest("you cannot review your own project") return ) @@ -152,7 +157,7 @@ def handleSaveProjectReview(*serve.Context c) ( object review = {_id: reviewId, projectId: project.id, author: contextString(c, "username"), authorId: contextString(c, "userId"), authorKey: normalizeUsername(contextString(c, "username")), rating: rating, message: message, created: created, edited: timestamp} putDocument(reviewDocs, reviewId, review) if existing.len == 0 ( - addNotification(project.owner.toStr(), contextString(c, "username"), "project_review", {projectId: project.id, projectTitle: project.title, rating: rating}) + notifyContentOwner(project, contextString(c, "username"), "project_review", {projectId: project.id, projectTitle: project.title, rating: rating}) ) review.playtimeMs = authorPublicPlaytime(project.id.toStr(), review.author.toStr()) c.json(200, {ok: true, review: review}) diff --git a/src/community/routes.osl b/src/community/routes.osl index f9e5b33..23ebaa0 100644 --- a/src/community/routes.osl +++ b/src/community/routes.osl @@ -21,7 +21,8 @@ def registerCommunityRoutes(*serve.Router api) ( api.GET("/me/purchases", requireAuth, handleGetMyPurchases) - api.GET("/groups/:tag", handleGetMistWarpGroup) + api.GET("/orgs/:name", serve.rateLimit({requests: 120, window: date.minute}), handleGetMistWarpOrg) + api.GET("/me/orgs", requireAuth, serve.rateLimit({requests: 120, window: date.minute}), handleGetMyOrgs) api.GET("/development/pulls", handleDevelopmentPulls) api.GET("/roadmap", handleListIdeas) diff --git a/src/community/social.osl b/src/community/social.osl index 4b00137..495f422 100644 --- a/src/community/social.osl +++ b/src/community/social.osl @@ -51,6 +51,10 @@ def ownerIndexEntries(string owner, boolean includeUnshared) array ( for i keyMatches.len ( object entry = keyMatches[i].assert(object) string pid = entry.id.toStr() + boolean orgEntry = (entry.ownerType ?? "").toStr() == "org" + if orgEntry and (ownerId == "" or (entry.ownerId ?? "").toStr() != ownerId) ( + continue + ) if ownerId != "" and (entry.ownerId ?? "").toStr() != ownerId ( entry.ownerId = ownerId putDocument(projectSearchDocs, entry["_id"].toStr(), entry) diff --git a/src/community/space-comments.osl b/src/community/space-comments.osl index dbe4e53..dd6bb42 100644 --- a/src/community/space-comments.osl +++ b/src/community/space-comments.osl @@ -29,12 +29,7 @@ def handleCreateSpaceComment(*serve.Context c) ( c.badRequest(created.error.toStr()) return ) - if space.contains("commentCount") ( - space.commentCount = space.commentCount.toNum() + 1 - ) else ( - space.commentCount = loadComments(spaceCommentKey(space["_id"].toStr())).len - ) - putSpaceDocument(space) + adjustSpaceCommentCountLocked(space["_id"].toStr(), 1) string commenter = contextString(c, "username") string parentAuthor = created.parentAuthor.toStr() string newCommentId = created.comment.id.toStr() @@ -43,7 +38,7 @@ def handleCreateSpaceComment(*serve.Context c) ( addNotification(parentAuthor, commenter, "reply", notificationData) ) if normalizeUsername(space.owner.toStr()) != normalizeUsername(commenter) and normalizeUsername(space.owner.toStr()) != normalizeUsername(parentAuthor) ( - addNotification(space.owner.toStr(), commenter, "space_comment", notificationData) + notifyContentOwnerExcept(space, commenter, "space_comment", notificationData, [parentAuthor]) ) notifyMentions(created.comment.content.toStr(), commenter, [space.owner.toStr(), parentAuthor], notificationData) c.json(201, created) @@ -64,13 +59,37 @@ def handleDeleteSpaceComment(*serve.Context c) ( c.json(deleted.status.toInt(), {ok: false, error: deleted.error}) return ) + adjustSpaceCommentCountLocked(space["_id"].toStr(), 0 - deleted.removed.toNum()) + c.json(200, {ok: true}) +) + +def adjustSpaceCommentCountLocked(string spaceId, number delta) ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + if space.len == 0 ( + return + ) if space.contains("commentCount") ( - space.commentCount = clampNumber(space.commentCount.toNum() - deleted.removed.toNum(), 0, space.commentCount.toNum()) + space.commentCount = clampNumber(space.commentCount.toNum() + delta, 0, space.commentCount.toNum() + 1000000) ) else ( - space.commentCount = loadComments(spaceCommentKey(space["_id"].toStr())).len + space.commentCount = loadComments(spaceCommentKey(spaceId)).len ) putSpaceDocument(space) - c.json(200, {ok: true}) +) + +def ensureSpaceCommentCountLocked(string spaceId) number ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + if space.len == 0 ( + return loadComments(spaceCommentKey(spaceId)).len + ) + if !space.contains("commentCount") ( + space.commentCount = loadComments(spaceCommentKey(spaceId)).len + putSpaceDocument(space) + ) + return space.commentCount.toNum() ) def handleEditSpaceComment(*serve.Context c) ( diff --git a/src/community/space-model.osl b/src/community/space-model.osl index b0d2aa0..44764fd 100644 --- a/src/community/space-model.osl +++ b/src/community/space-model.osl @@ -94,15 +94,22 @@ def isSpaceOwner(object space,*serve.Context c) boolean ( if space.contains("ownerId") and space.ownerId != null ( ownerId = space.ownerId.toStr() ) - return contextBool(c, "isAdmin") or identityMatches(ownerId, space.owner.toStr(), contextString(c, "userId"), contextString(c, "username")) + return contextBool(c, "isAdmin") or identityMatches(ownerId, space.owner.toStr(), contextString(c, "userId"), contextString(c, "username")) or canManageOrgContent(space, c) ) -def searchEntryOwnedByContext(object project,*serve.Context c) boolean ( +def searchEntryOwnership(object project,*serve.Context c) string ( string ownerId = "" if project.contains("ownerId") and project.ownerId != null ( ownerId = project.ownerId.toStr() ) - return identityMatches(ownerId, project.owner.toStr(), contextString(c, "userId"), contextString(c, "username")) + if identityMatches(ownerId, project.owner.toStr(), contextString(c, "userId"), contextString(c, "username")) ( + return "yes" + ) + return orgContentPublisherAccess(project, c) +) + +def searchEntryOwnedByContext(object project,*serve.Context c) boolean ( + return searchEntryOwnership(project, c) == "yes" ) def isSpaceInvitee(object space,*serve.Context c) boolean ( @@ -124,12 +131,20 @@ def canManageSpace(object space,*serve.Context c) boolean ( if isSpaceOwner(space, c) ( return true ) - if canManageGroupContent(space, c) ( - return true - ) return stringArrayContainsUser(spaceManagers(space), username) ) +def spaceCuratorOnly(object space,*serve.Context c) string ( + if contextBool(c, "isAdmin") or isSpaceOwner(space, c) ( + return "" + ) + return contextString(c, "username") +) + +def stillSpaceCurator(object space, string curator) boolean ( + return curator == "" or stringArrayContainsUser(spaceManagers(space), curator) +) + def canViewSpace(object space,*serve.Context c) boolean ( if space.visibility.toStr() == "public" or space.visibility.toStr() == "unlisted" ( return true diff --git a/src/community/space-responses.osl b/src/community/space-responses.osl index d18f5c6..f9f499c 100644 --- a/src/community/space-responses.osl +++ b/src/community/space-responses.osl @@ -8,12 +8,14 @@ def spaceTotalPlaytime(array ids) number ( def spaceResponse(object space,*serve.Context c) object ( if !space.contains("commentCount") ( - space.commentCount = loadComments(spaceCommentKey(space["_id"].toStr())).len - putSpaceDocument(space) + space.commentCount = ensureSpaceCommentCountLocked(space["_id"].toStr()) ) array projects = [] array ids = spaceProjectIds(space) if space.kind.toStr() == "challenge" ( + if contextBool(c, "authenticated") and isOrgOwned(space) and !challengeAudienceJudged(space) ( + void ownerOrgSnapshot(space) + ) projects = challengeProjects(space, c) ) else ( for i ids.len ( @@ -37,6 +39,7 @@ def spaceResponse(object space,*serve.Context c) object ( response.projectIds = if canManageSpace(space, c) then ids else visibleIds response.canManage = canManageSpace(space, c) response.isOwner = isSpaceOwner(space, c) + response.canMoveOut = response.isOwner == true and orgMoveOutAccess(space, c) == "yes" response.following = stringArrayContainsUser(spaceFollowers(space), contextString(c, "username")) response.followerCount = spaceFollowers(space).len response.invited = isSpaceInvitee(space, c) @@ -80,7 +83,7 @@ def spaceResponse(object space,*serve.Context c) object ( response.phase = challengePhase(space) response.isJudge = isChallengeJudge(space, contextString(c, "username")) response.judgeInvited = isChallengeJudgeInvitee(space, contextString(c, "username")) - response.judgeCount = challengeJudges(space).len + response.judgeCount = challengeJudgeCount(space) response.participantCount = challengeArray(space, "participants").len response.joined = stringArrayContainsUser(challengeArray(space, "participants"), contextString(c, "username")) response.judges = challengeJudges(space) @@ -115,7 +118,7 @@ def spaceListResponse(object space,*serve.Context c) object ( kind: space.kind, visibility: space.visibility, owner: space.owner, - groupTag: groupTagOf(space), + ownerType: if isOrgOwned(space) then "org" else "", edited: space.edited, startsAt: space.startsAt, endsAt: space.endsAt, @@ -127,6 +130,7 @@ def spaceListResponse(object space,*serve.Context c) object ( thumbnailUrl: thumbnailURL, canManage: canManage, isOwner: isSpaceOwner(space, c), + canMoveOut: isSpaceOwner(space, c) and orgMoveOutAccess(space, c) == "yes", following: stringArrayContainsUser(followers, contextString(c, "username")), invited: isSpaceInvitee(space, c) } diff --git a/src/community/spaces.osl b/src/community/spaces.osl index 18864dd..d97dfd7 100644 --- a/src/community/spaces.osl +++ b/src/community/spaces.osl @@ -100,22 +100,15 @@ def handleGetSpace(*serve.Context c) ( def handleCreateSpace(*serve.Context c) ( object body = requestJSON(c) - number ownedSpaces = spaceDocs.where("ownerId", "==", contextString(c, "userId")).count() - if !contextBool(c, "isAdmin") and ownedSpaces >= mistwarpBenefitsForUserId(contextString(c, "userId")).maxSpaces.toNum() ( - c.json(413, {ok: false, error: "space limit reached; delete a space or upgrade your plan"}) + object owner = creationOwner(c, body, "spaces") + if !owner.ok ( + c.json(owner.status.toNum(), {ok: false, code: owner.code, error: owner.error}) return ) - string groupTag = "" - if body.contains("groupTag") and body.groupTag != null and body.groupTag.toStr().strip() != "" ( - groupTag = normalizeGroupTag(body.groupTag.toStr()) - if groupTag == "" ( - c.badRequest("invalid group tag") - return - ) - if !canManageGroupTag(groupTag, c) ( - c.forbidden("you cannot create spaces for this group") - return - ) + number ownedSpaces = spaceDocs.where("ownerId", "==", owner.ownerId.toStr()).count() + if !contextBool(c, "isAdmin") and ownedSpaces >= mistwarpBenefitsForUserId(owner.ownerId.toStr()).maxSpaces.toNum() ( + c.json(413, {ok: false, error: "space limit reached; delete a space or upgrade your plan"}) + return ) string title = body.title.toStr().strip() string kind = body.kind.toStr().toLower().strip() @@ -170,9 +163,9 @@ def handleCreateSpace(*serve.Context c) ( description: description, kind: kind, visibility: visibility, - owner: contextString(c, "username"), - ownerId: contextString(c, "userId"), - groupTag: groupTag, + owner: owner.owner, + ownerId: owner.ownerId, + ownerType: owner.ownerType, managers: [], curatorInvites: [], projects: [], @@ -209,19 +202,29 @@ def handleUpdateSpace(*serve.Context c) ( c.notFound("space not found") return ) + string readJson = json.stringify(space) if !canManageSpace(space, c) ( + if isOrgOwned(space) and orgAccess(space.owner.toStr(), (space.ownerId ?? "").toStr(), c) == "unavailable" ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."}) + return + ) c.forbidden("you cannot manage this space") return ) object body = requestJSON(c) if body.contains("owner") ( - boolean canTransfer = isSpaceOwner(space, c) or canManageGroupContent(space, c) + boolean canTransfer = isSpaceOwner(space, c) if !canTransfer ( c.forbidden("you cannot transfer this space") return ) string requestedOwner = body.owner.toStr().strip() - string nextOwnerId = discoverUserIdentity(requestedOwner) + object identity = discoverUserIdentityOutcome(requestedOwner) + if identity.outcome == "unavailable" ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now, so " ++ requestedOwner ++ " couldn't be checked. Try again soon."}) + return + ) + string nextOwnerId = identity.id.toStr() if nextOwnerId == "" ( c.badRequest("Rotur user not found") return @@ -231,29 +234,47 @@ def handleUpdateSpace(*serve.Context c) ( c.badRequest("Rotur user not found") return ) + boolean sameOwner = identityMatches((space.ownerId ?? "").toStr(), space.owner.toStr(), nextOwnerId, nextOwner) number nextOwnerLimit = mistwarpBenefitsForUserId(nextOwnerId).maxSpaces.toNum() - if !identityMatches((space.ownerId ?? "").toStr(), space.owner.toStr(), nextOwnerId, nextOwner) and spaceDocs.where("ownerId", "==", nextOwnerId).count() >= nextOwnerLimit ( + if !sameOwner and spaceDocs.where("ownerId", "==", nextOwnerId).count() >= nextOwnerLimit ( c.badRequest("the new owner has reached their space limit") return ) - space.owner = nextOwner - space.ownerId = nextOwnerId - if !body.contains("keepGroup") or body.keepGroup != true ( - space.groupTag = "" + if isOrgOwned(space) and !sameOwner ( + string moveOut = orgMoveOutAccess(space, c) + if moveOut == "unavailable" ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."}) + return + ) + if moveOut != "yes" ( + c.forbidden("only an admin of the organisation can move this space out of it") + return + ) ) - ) - if body.contains("groupTag") ( - string nextGroupTag = normalizeGroupTag(body.groupTag.toStr()) - if body.groupTag.toStr().strip() == "" ( - nextGroupTag = "" - ) else if nextGroupTag == "" ( - c.badRequest("invalid group tag") + object nextOrg = roturOrgSnapshot(nextOwner) + boolean nextOwnerIsOrg = nextOrg.ok + if !nextOrg.ok and (identity.accountType ?? "").toStr() == "org" and nextOrg.contains("notOrg") and nextOrg.notOrg == true ( + c.json(403, {ok: false, code: "org_unavailable", error: "that organisation can't own spaces right now"}) return - ) else if !canManageGroupTag(nextGroupTag, c) ( - c.forbidden("you cannot move this space into that group") + ) + if (!nextOrg.ok and (identity.accountType ?? "").toStr() == "org") or (nextOwnerIsOrg and (nextOrg.org.assertElse(object, {}).id ?? "").toStr() != nextOwnerId) ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now, so " ++ requestedOwner ++ " couldn't be checked. Try again soon."}) return ) - space.groupTag = nextGroupTag + if nextOwnerIsOrg and !sameOwner ( + string access = orgAccess(nextOwner, nextOwnerId, c) + if access == "unavailable" ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now, so " ++ requestedOwner ++ " couldn't be checked. Try again soon."}) + return + ) + if access != "yes" ( + c.forbidden("you cannot move this space into that organisation") + return + ) + ) + space.owner = nextOwner + space.ownerId = nextOwnerId + space.ownerType = if nextOwnerIsOrg then "org" else "" ) if body.contains("title") ( string title = body.title.toStr().strip() @@ -347,8 +368,71 @@ def handleUpdateSpace(*serve.Context c) ( return ) space.edited = timestamp - putSpaceDocument(space) - c.json(200, {ok: true, space: spaceResponse(space, c)}) + object read = json.parse(readJson, {type: "object"}).unwrap().assert(object) + object saved = saveEditedSpace(read, space, spaceCuratorOnly(read, c)) + if saved.len == 0 ( + c.notFound("space not found") + return + ) + if saved.contains("refused") ( + string refusal = saved.refused.toStr() + if refusal == "criteria" ( + c.badRequest("judging criteria cannot change after scoring begins") + ) else if refusal == "dates" ( + c.badRequest("challenge dates must be in order") + ) else if refusal == "votingMode" ( + c.badRequest("the voting mode cannot change after results are published") + ) else ( + c.json(409, {ok: false, code: "space_changed", error: "This space changed while your edit was being saved. Reload it and try again."}) + ) + return + ) + c.json(200, {ok: true, space: spaceResponse(saved, c)}) +) + +def saveEditedSpace(object read, object edited, string curator) object ( + string spaceId = read["_id"].toStr() + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object fresh = (spaceDocs.findById(spaceId) ?? {}) + if fresh.len == 0 ( + return {} + ) + if !stillSpaceCurator(fresh, curator) ( + return {refused: "owner"} + ) + array ownerFields = ["owner", "ownerId", "ownerType"] + for i ownerFields.len ( + string field = ownerFields[i].toStr() + if json.stringify(fresh[field] ?? "") != json.stringify(read[field] ?? "") ( + return {refused: "owner"} + ) + ) + array changed = [] + array keys = edited.getKeys() + for i keys.len ( + string key = keys[i].toStr() + if key != "edited" and (!read.contains(key) or json.stringify(read[key]) != json.stringify(edited[key])) ( + changed.append(key) + ) + ) + boolean isChallenge = fresh.kind.toStr() == "challenge" + if isChallenge and changed.contains("criteria") and challengeArray(fresh, "scores").len > 0 ( + return {refused: "criteria"} + ) + if isChallenge and changed.contains("votingMode") and challengeVotingMode(edited) != challengeVotingMode(fresh) and challengePhase(fresh) == "results" ( + return {refused: "votingMode"} + ) + for i changed.len ( + string key = changed[i].toStr() + fresh[key] = edited[key] + ) + if isChallenge and (fresh.startsAt.toNum() <= 0 or fresh.endsAt.toNum() <= fresh.startsAt.toNum() or (fresh.judgingEndsAt ?? 0).toNum() <= fresh.endsAt.toNum()) ( + return {refused: "dates"} + ) + fresh.edited = edited.edited + putSpaceDocument(fresh) + return fresh ) def handleDeleteSpace(*serve.Context c) ( @@ -361,8 +445,7 @@ def handleDeleteSpace(*serve.Context c) ( c.forbidden("only the owner can delete this space") return ) - void spaceDocs.deleteOne({_id: space["_id"]}) - deleteSpaceMemberships(space["_id"].toStr()) + deleteSpaceLocked(space["_id"].toStr()) void fs.remove(commentsDir ++ spaceCommentKey(space["_id"].toStr()) ++ ".json") void fs.remove(commentsDir ++ spaceCommentKey(space["_id"].toStr()) ++ ".jsonl") if fs.exists(spaceThumbnailPath(space["_id"].toStr())) ( @@ -371,6 +454,13 @@ def handleDeleteSpace(*serve.Context c) ( c.json(200, {ok: true}) ) +def deleteSpaceLocked(string spaceId) ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + void spaceDocs.deleteOne({_id: spaceId}) + deleteSpaceMemberships(spaceId) +) + def handleSetSpaceThumbnail(*serve.Context c) ( object space = (spaceDocs.findById(c.param("id")) ?? {}) if space.len == 0 ( @@ -381,6 +471,7 @@ def handleSetSpaceThumbnail(*serve.Context c) ( c.forbidden("you cannot change this studio thumbnail") return ) + string curator = spaceCuratorOnly(space, c) auto fileResult = c.formFile("thumbnail") if fileResult.isErr() ( c.badRequest("missing thumbnail file") @@ -391,13 +482,39 @@ def handleSetSpaceThumbnail(*serve.Context c) ( c.badRequest("thumbnail too large") return ) - if !fs.writeFileBytes(spaceThumbnailPath(space["_id"].toStr()), thumbnail.data) ( + object saved = saveSpaceThumbnailLocked(space["_id"].toStr(), curator, thumbnail.data) + string outcome = saved.outcome.toStr() + if outcome == "missing" ( + c.notFound("space not found") + return + ) + if outcome == "curator" ( + c.forbidden("you cannot change this studio thumbnail") + return + ) + if outcome == "failed" ( c.internalError("thumbnail save failed") return ) + c.json(200, {ok: true, thumbnailUrl: spaceThumbnailUrl(saved.space.assert(object))}) +) + +def saveSpaceThumbnailLocked(string spaceId, string curator, byte[] data) object ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + if space.len == 0 ( + return {outcome: "missing"} + ) + if !stillSpaceCurator(space, curator) ( + return {outcome: "curator"} + ) + if !fs.writeFileBytes(spaceThumbnailPath(spaceId), data) ( + return {outcome: "failed"} + ) space.edited = timestamp putSpaceDocument(space) - c.json(200, {ok: true, thumbnailUrl: spaceThumbnailUrl(space)}) + return {outcome: "saved", space: space} ) def handleAddSpaceProject(*serve.Context c) ( @@ -412,7 +529,8 @@ def handleAddSpaceProject(*serve.Context c) ( c.forbidden("only shared or unlisted projects can be added") return ) - boolean allowed = canManageSpace(space, c) + boolean manages = canManageSpace(space, c) + boolean allowed = manages boolean ownsProject = searchEntryOwnedByContext(project, c) boolean participantCanSubmit = space.openSubmissions == true and ownsProject if space.kind.toStr() == "challenge" ( @@ -423,25 +541,52 @@ def handleAddSpaceProject(*serve.Context c) ( c.forbidden("submissions are closed") return ) + string participant = project.owner.toStr() + if isOrgOwned(project) ( + participant = if ownsProject then contextString(c, "username") else "" + ) + object added = addProjectToSpace(space["_id"].toStr(), project, contextString(c, "username"), participant, manages, if manages then spaceCuratorOnly(space, c) else "", ownsProject) + if added.len == 0 ( + c.json(409, {ok: false, code: "space_changed", error: "The space changed while this project was being added. Try again."}) + return + ) + object fresh = added.space.assert(object) + if added.added == true ( + notifyContentOwner(fresh, contextString(c, "username"), "space_project", {spaceId: fresh["_id"], spaceTitle: fresh.title, projectId: project.id, projectTitle: project.title}) + ) + c.json(200, {ok: true, space: spaceResponse(fresh, c)}) +) + +def addProjectToSpace(string spaceId, object project, string submitter, string participant, boolean manages, string curator, boolean ownsProject) object ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + if space.len == 0 ( + return {} + ) + boolean asManager = manages and stillSpaceCurator(space, curator) + if !asManager and (!ownsProject or space.openSubmissions != true or (space.kind.toStr() == "challenge" and challengePhase(space) != "submissions")) ( + return {} + ) array ids = spaceProjectIds(space) - if !ids.contains(project.id.toStr()) ( - ids.append(project.id.toStr()) - space.projects = ids - if space.kind.toStr() == "challenge" ( - array submissions = challengeArray(space, "submissions") - submissions.append({projectId: project.id, owner: project.owner, submittedAt: timestamp}) - space.submissions = submissions - array participants = challengeArray(space, "participants") - if !stringArrayContainsUser(participants, project.owner.toStr()) ( - participants.append(project.owner) - ) - space.participants = participants + if ids.contains(project.id.toStr()) ( + return {space: space, added: false} + ) + ids.append(project.id.toStr()) + space.projects = ids + if space.kind.toStr() == "challenge" ( + array submissions = challengeArray(space, "submissions") + submissions.append({projectId: project.id, owner: project.owner, submittedBy: submitter, submittedAt: timestamp}) + space.submissions = submissions + array participants = challengeArray(space, "participants") + if participant != "" and !stringArrayContainsUser(participants, participant) ( + participants.append(participant) ) - space.edited = timestamp - putSpaceDocument(space) - addNotification(space.owner.toStr(), contextString(c, "username"), "space_project", {spaceId: space["_id"], spaceTitle: space.title, projectId: project.id, projectTitle: project.title}) + space.participants = participants ) - c.json(200, {ok: true, space: spaceResponse(space, c)}) + space.edited = timestamp + putSpaceDocument(space) + return {space: space, added: true} ) def handleRemoveSpaceProject(*serve.Context c) ( @@ -452,20 +597,51 @@ def handleRemoveSpaceProject(*serve.Context c) ( ) object project = (projectSearchDocs.findById(c.param("project")) ?? {}) boolean allowed = canManageSpace(space, c) - if project.len > 0 ( - allowed = allowed or searchEntryOwnedByContext(project, c) + string curator = if allowed then spaceCuratorOnly(space, c) else "" + if curator != "" and project.len > 0 and searchEntryOwnership(project, c) == "yes" ( + curator = "" + ) + if !allowed and project.len > 0 ( + string ownership = searchEntryOwnership(project, c) + if ownership == "unavailable" ( + c.json(503, {ok: false, code: "rotur_unavailable", error: "Rotur can't be reached right now. Try again soon."}) + return + ) + allowed = ownership == "yes" ) if !allowed ( c.forbidden("you cannot remove this project") return ) - space.projects = removeString(spaceProjectIds(space), c.param("project")) + object saved = removeProjectFromSpaceLocked(space["_id"].toStr(), c.param("project"), curator) + if saved.len == 0 ( + c.notFound("space not found") + return + ) + if saved.contains("refused") ( + c.forbidden("you cannot remove this project") + return + ) + c.json(200, {ok: true, space: spaceResponse(saved, c)}) +) + +def removeProjectFromSpaceLocked(string spaceId, string projectId, string curator) object ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + if space.len == 0 ( + return {} + ) + if !stillSpaceCurator(space, curator) ( + return {refused: "curator"} + ) + space.projects = removeString(spaceProjectIds(space), projectId) if space.kind.toStr() == "challenge" ( array submissions = challengeArray(space, "submissions") array nextSubmissions = [] for i submissions.len ( object submission = submissions[i].assert(object) - if submission.projectId.toStr() != c.param("project") ( + if submission.projectId.toStr() != projectId ( nextSubmissions.append(submission) ) ) @@ -473,7 +649,7 @@ def handleRemoveSpaceProject(*serve.Context c) ( ) space.edited = timestamp putSpaceDocument(space) - c.json(200, {ok: true, space: spaceResponse(space, c)}) + return space ) def handleFollowSpace(*serve.Context c) ( @@ -482,13 +658,33 @@ def handleFollowSpace(*serve.Context c) ( c.notFound("space not found") return ) + number count = followSpaceLocked(space["_id"].toStr(), contextString(c, "username"), true) + if count < 0 ( + c.notFound("space not found") + return + ) + c.json(200, {ok: true, following: true, followers: count}) +) + +def followSpaceLocked(string spaceId, string username, boolean follow) number ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + if space.len == 0 ( + return -1 + ) array followers = spaceFollowers(space) - if !stringArrayContainsUser(followers, contextString(c, "username")) ( - followers.append(contextString(c, "username")) + boolean present = stringArrayContainsUser(followers, username) + if follow and !present ( + followers.append(username) + space.followers = followers + putSpaceDocument(space) + ) else if !follow and present ( + followers = removeUser(followers, username) space.followers = followers putSpaceDocument(space) ) - c.json(200, {ok: true, following: true, followers: followers.len}) + return followers.len ) def handleUnfollowSpace(*serve.Context c) ( @@ -497,13 +693,12 @@ def handleUnfollowSpace(*serve.Context c) ( c.notFound("space not found") return ) - array followers = spaceFollowers(space) - if stringArrayContainsUser(followers, contextString(c, "username")) ( - followers = removeUser(followers, contextString(c, "username")) - space.followers = followers - putSpaceDocument(space) + number count = followSpaceLocked(space["_id"].toStr(), contextString(c, "username"), false) + if count < 0 ( + c.notFound("space not found") + return ) - c.json(200, {ok: true, following: false, followers: followers.len}) + c.json(200, {ok: true, following: false, followers: count}) ) def handleMySpaces(*serve.Context c) ( @@ -524,11 +719,7 @@ def handleMySpaces(*serve.Context c) ( object space = allSpaces[i].assert(object) string spaceId = space["_id"].toStr() if !seen.contains(spaceId) ( - boolean include = isSpaceOwner(space, c) - if !include and groupTagOf(space) != "" ( - include = canManageGroupContent(space, c) - ) - if include ( + if isSpaceOwner(space, c) ( seen[spaceId] = true stored.append(space) ) @@ -577,25 +768,86 @@ def handleInviteSpaceCurator(*serve.Context c) ( c.notFound("user not found") return ) - if stringArrayContainsUser(spaceManagers(space), username) ( + object invite = {username: profile.username, invitedBy: contextString(c, "username"), created: timestamp} + string outcome = inviteCuratorLocked(space["_id"].toStr(), invite) + if outcome == "missing" ( + c.notFound("space not found") + return + ) + if outcome == "curator" ( c.badRequest("this user is already a curator") return ) + if outcome == "invited" ( + c.badRequest("this user already has an invitation") + return + ) + addNotification(profile.username.toStr(), contextString(c, "username"), "space_curator_invite", {spaceId: space["_id"], spaceTitle: space.title}) + c.json(201, {ok: true, invitation: invite}) +) + +def inviteCuratorLocked(string spaceId, object invite) string ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + if space.len == 0 ( + return "missing" + ) + string username = invite.username.toStr() + if stringArrayContainsUser(spaceManagers(space), username) ( + return "curator" + ) array invites = spaceCuratorInvites(space) for i invites.len ( object existing = invites[i].assert(object) - if normalizeUsername(existing.username.toStr()) == usernameKey ( - c.badRequest("this user already has an invitation") - return + if normalizeUsername(existing.username.toStr()) == normalizeUsername(username) ( + return "invited" ) ) - object invite = {username: profile.username, invitedBy: contextString(c, "username"), created: timestamp} invites.append(invite) space.curatorInvites = invites space.edited = timestamp putSpaceDocument(space) - addNotification(profile.username.toStr(), contextString(c, "username"), "space_curator_invite", {spaceId: space["_id"], spaceTitle: space.title}) - c.json(201, {ok: true, invitation: invite}) + return "saved" +) + +def removeCuratorLocked(string spaceId, string username) boolean ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + array managers = if space.len > 0 then spaceManagers(space) else [] + if !stringArrayContainsUser(managers, username) ( + return false + ) + space.managers = removeUser(managers, username) + space.edited = timestamp + putSpaceDocument(space) + return true +) + +def cancelCuratorInviteLocked(string spaceId, string username) ( + sync.lock(spaceWriteLock(spaceId)) + defer sync.unlock(spaceWriteLock(spaceId)) + object space = (spaceDocs.findById(spaceId) ?? {}) + if space.len == 0 ( + return + ) + array remaining = [] + array invites = spaceCuratorInvites(space) + boolean found = false + for i invites.len ( + object invite = invites[i].assert(object) + if normalizeUsername(invite.username.toStr()) != normalizeUsername(username) ( + remaining.append(invite) + ) else ( + found = true + ) + ) + if found ( + space.curatorInvites = remaining + space.edited = timestamp + putSpaceDocument(space) + ) ) def handleRespondSpaceCuratorInvite(*serve.Context c) ( @@ -635,7 +887,7 @@ def handleRespondSpaceCuratorInvite(*serve.Context c) ( if accepted ( notificationType = "space_curator_accepted" ) - addNotification(space.owner.toStr(), username, notificationType, {spaceId: space["_id"], spaceTitle: space.title}) + notifyContentOwner(space, username, notificationType, {spaceId: space["_id"], spaceTitle: space.title}) c.json(200, {ok: true, accepted: accepted}) ) @@ -650,11 +902,7 @@ def handleRemoveSpaceCurator(*serve.Context c) ( return ) string username = c.param("username") - array managers = spaceManagers(space) - if stringArrayContainsUser(managers, username) ( - space.managers = removeUser(managers, username) - space.edited = timestamp - putSpaceDocument(space) + if removeCuratorLocked(space["_id"].toStr(), username) ( addNotification(username, contextString(c, "username"), "space_curator_removed", {spaceId: space["_id"], spaceTitle: space.title}) ) c.json(200, {ok: true}) @@ -670,27 +918,16 @@ def handleCancelSpaceCuratorInvite(*serve.Context c) ( c.forbidden("only the owner can cancel invitations") return ) - string username = c.param("username") - array remaining = [] - array invites = spaceCuratorInvites(space) - boolean found = false - for i invites.len ( - object invite = invites[i].assert(object) - if normalizeUsername(invite.username.toStr()) != normalizeUsername(username) ( - remaining.append(invite) - ) else ( - found = true - ) - ) - if found ( - space.curatorInvites = remaining - space.edited = timestamp - putSpaceDocument(space) - ) + cancelCuratorInviteLocked(space["_id"].toStr(), c.param("username")) c.json(200, {ok: true}) ) def handleReactSpace(*serve.Context c) ( + object visible = (spaceDocs.findById(c.param("id")) ?? {}) + if visible.len == 0 or !canViewSpace(visible, c) ( + c.notFound("space not found") + return + ) string lockName = "space-reactions:" ++ c.param("id") sync.lock(lockName) defer sync.unlock(lockName) @@ -732,6 +969,8 @@ def handleReactSpaceLocked(*serve.Context c) ( c.internalError("could not save reaction") return ) - notifyLikeMilestones(space.owner.toStr(), space.kind.toStr(), space["_id"].toStr(), previousLikes, likes.len, "/spaces/" ++ space["_id"].toStr(), {}) + if !isOrgOwned(space) ( + notifyLikeMilestones(space.owner.toStr(), space.kind.toStr(), space["_id"].toStr(), previousLikes, likes.len, "/spaces/" ++ space["_id"].toStr(), {}) + ) c.json(200, {ok: true, likeCount: likes.len, brokenHeartCount: brokenHearts.len, myReaction: if hadReaction then "" else reactionType}) ) diff --git a/src/games/game-marketplace.osl b/src/games/game-marketplace.osl index 2efd032..af785aa 100644 --- a/src/games/game-marketplace.osl +++ b/src/games/game-marketplace.osl @@ -210,7 +210,7 @@ def completeGameProductPurchase(string key) object ( ) number paid = (entry.price ?? product.price).toNum() addPurchaseRecord(buyer, {projectId: project.id.toStr(), productId: product.id, title: product.name, seller: project.owner, amount: paid, at: timestamp, type: "game_product"}) - addNotification(project.owner.toStr(), buyer, "purchase", {projectId: project.id, projectTitle: project.title, productId: product.id, productName: product.name, amount: paid}) + notifyContentOwner(project, buyer, "purchase", {projectId: project.id, projectTitle: project.title, productId: product.id, productName: product.name, amount: paid}) ) forgetPurchase(key) return {ok: true, project: project, product: product} diff --git a/src/git/pulls.osl b/src/git/pulls.osl index 505e796..be4ad87 100644 --- a/src/git/pulls.osl +++ b/src/git/pulls.osl @@ -147,7 +147,7 @@ def isPullSourceOwnerWithSource(object pull, object source,*serve.Context c) boo if !contextBool(c, "authenticated") ( return false ) - if source.len > 0 and projectRole(source, contextString(c, "username")) == "owner" ( + if source.len > 0 and projectRoleFor(source, c) == "owner" ( return true ) return identityMatches( @@ -201,7 +201,7 @@ def createNativePull(*serve.Context c, object target, object source, string titl if !projectHasWorkspace(target) or !projectHasWorkspace(source) ( return {ok: false, status: 400, error: "both projects need MistWarp history before changes can be sent"} ) - if projectRole(source, contextString(c, "username")) != "owner" ( + if projectRoleFor(source, c) != "owner" ( return {ok: false, status: 403, error: "use a remix you own"} ) if source.remixParent.toStr() != target.id.toStr() ( @@ -227,7 +227,7 @@ def createNativePull(*serve.Context c, object target, object source, string titl ) object pull = inserted.pull.assert(object) sequence = pull.index.toNum() - addNotification(target.owner.toStr(), contextString(c, "username"), "contribution", {projectId: target.id, projectTitle: target.title, pull: sequence}) + notifyContentOwner(target, contextString(c, "username"), "contribution", {projectId: target.id, projectTitle: target.title, pull: sequence}) return {ok: true, pull: pullResponse(pull)} ) @@ -370,6 +370,7 @@ def handleProjectBranchMutation(*serve.Context c, string action) ( ) def mutateProjectBranchesLocked(*serve.Context c, string action) object ( + warmProjectOrgAccess(c.param("id"), c) string lockName = "project-history-" ++ c.param("id") sync.lock(lockName) defer sync.unlock(lockName) @@ -643,7 +644,7 @@ def handleCreatePullComment(*serve.Context c) ( addNotification(pull.author.toStr(), commenter, "comment", notificationData) ) if normalizeUsername(project.owner.toStr()) != normalizeUsername(commenter) and normalizeUsername(project.owner.toStr()) != normalizeUsername(pull.author.toStr()) ( - addNotification(project.owner.toStr(), commenter, "comment", notificationData) + notifyContentOwnerExcept(project, commenter, "comment", notificationData, [pull.author.toStr()]) ) notifyMentions(created.comment.content.toStr(), commenter, [project.owner.toStr(), pull.author.toStr()], notificationData) created.comment = commentResponse(created.comment.assert(object), commenter) @@ -662,7 +663,7 @@ def handleDeletePullComment(*serve.Context c) ( return ) object project = res.project.assert(object) - object deleted = deleteComment(pullCommentKey(pull), c.param("cid"), contextString(c, "username"), project.owner.toStr(), contextBool(c, "isAdmin")) + object deleted = deleteComment(pullCommentKey(pull), c.param("cid"), contextString(c, "username"), projectModerator(project, c), contextBool(c, "isAdmin")) if !deleted.ok ( c.json(deleted.status.toInt(), {ok: false, error: deleted.error}) return @@ -1253,7 +1254,13 @@ def completeNativePull(object project, string pullIndex, string expectedHead, st project.mergedContributors = mergedContributors saveProject(project) upsertIndexEntry(project) - addNotification(pull.sourceOwner.toStr(), project.owner.toStr(), "contribution_merged", {projectId: project.id, projectTitle: project.title, pull: pull.index}) + object mergedNotice = {projectId: project.id, projectTitle: project.title, pull: pull.index} + object sourceLoad = loadProject((pull.sourceProjectId ?? "").toStr()) + if sourceLoad.ok and identityMatches((pull.sourceOwnerId ?? "").toStr(), pull.sourceOwner.toStr(), (sourceLoad.project.ownerId ?? "").toStr(), (sourceLoad.project.owner ?? "").toStr()) ( + notifyContentOwner(sourceLoad.project.assert(object), project.owner.toStr(), "contribution_merged", mergedNotice) + ) else ( + addNotification(pull.sourceOwner.toStr(), project.owner.toStr(), "contribution_merged", mergedNotice) + ) if pull.contains("bountyId") and pull.bountyId != null and pull.bountyId.toStr() != "" ( boolean bountyPaid = awardContributionBounty(pull.bountyId.toStr(), project.id.toStr(), pull.sourceOwner.toStr()) if !bountyPaid ( diff --git a/src/git/pulls.test.osl b/src/git/pulls.test.osl index c365856..f7b61f1 100644 --- a/src/git/pulls.test.osl +++ b/src/git/pulls.test.osl @@ -85,6 +85,18 @@ def contextString(*serve.Context c, string key) string ( def addNotification(string target, string actor, string kind, object payload) ( return ) +def notifyContentOwner(object content, string actor, string kind, object payload) ( + return +) +def notifyContentOwnerExcept(object content, string actor, string kind, object payload, array skip) ( + return +) +def projectModerator(object project,*serve.Context c) string ( + return project.owner.toStr() +) +def projectRoleFor(object project,*serve.Context c) string ( + return projectRole(project, contextString(c, "username")) +) def canEditProject(object project,*serve.Context c) boolean ( return false @@ -92,6 +104,9 @@ def canEditProject(object project,*serve.Context c) boolean ( def canSeeInsideProject(object project,*serve.Context c) boolean ( return false ) +def warmProjectOrgAccess(string id,*serve.Context c) ( + return +) def canViewProject(object project,*serve.Context c) boolean ( return false ) diff --git a/src/history/commit-management.osl b/src/history/commit-management.osl index d0e37e7..d2b6600 100644 --- a/src/history/commit-management.osl +++ b/src/history/commit-management.osl @@ -42,13 +42,13 @@ def normalizedCommitCoAuthors(array incoming) object ( return {ok: true, coAuthors: coAuthors} ) -def applyCommitPatch(string id, string sha, object body, string username, boolean isAdmin) object ( +def applyCommitPatch(string id, string sha, object body,*serve.Context c, boolean isAdmin) object ( auto loaded = loadProject(id) if !loaded.ok ( return {status: 404, error: "project not found"} ) object project = loaded.project.assert(object) - string role = projectRole(project, username) + string role = projectRoleFor(project, c) if !projectSourcePolicyAllows(project, role == "owner") ( return {status: 403, error: "only the owner can edit commits for this project"} ) @@ -107,10 +107,11 @@ def handlePatchCommit(*serve.Context c) ( ) def applyCommitPatchLocked(*serve.Context c) object ( + warmProjectOrgAccess(c.param("id"), c) string lockName = "project-history-" ++ c.param("id") sync.lock(lockName) defer sync.unlock(lockName) - return applyCommitPatch(c.param("id"), c.param("sha"), requestJSON(c), contextString(c, "username"), contextBool(c, "isAdmin")) + return applyCommitPatch(c.param("id"), c.param("sha"), requestJSON(c), c, contextBool(c, "isAdmin")) ) def handleGetCommitCollaborators(*serve.Context c) ( diff --git a/src/projects/extensions.osl b/src/projects/extensions.osl index 4545d17..b74152e 100644 --- a/src/projects/extensions.osl +++ b/src/projects/extensions.osl @@ -498,7 +498,7 @@ def unshareProjectForBlockedExtension(object project) boolean ( profile.featuredProject = "" saveProfile(profile) ) - addNotification(project.owner.toStr(), "MistWarp", "moderation", {message: "Your project \"" ++ project.title.toStr() ++ "\" uses an extension that has been blocked. Remove the extension before sharing the project again."}) + notifyContentOwner(project, "MistWarp", "moderation", {message: "Your project \"" ++ project.title.toStr() ++ "\" uses an extension that has been blocked. Remove the extension before sharing the project again."}) return true ) diff --git a/src/projects/extensions.test.osl b/src/projects/extensions.test.osl index 0424d01..2abd385 100644 --- a/src/projects/extensions.test.osl +++ b/src/projects/extensions.test.osl @@ -58,6 +58,9 @@ def saveProfile(object profile) boolean ( def addNotification(string target, string actor, string kind, object payload) ( return ) +def notifyContentOwner(object content, string actor, string kind, object payload) ( + addNotification((content.owner ?? "").toStr(), actor, kind, payload) +) def saveProject(object project) boolean ( return true ) diff --git a/src/projects/fork-visibility.test.osl b/src/projects/fork-visibility.test.osl index fe8bff6..a6e1592 100644 --- a/src/projects/fork-visibility.test.osl +++ b/src/projects/fork-visibility.test.osl @@ -28,7 +28,7 @@ def isBannedUser(string username) boolean ( return false ) -def canManageGroupContent(object project, object ctx) boolean ( +def canManageOrgContent(object project, object ctx) boolean ( return false ) @@ -102,7 +102,7 @@ def canEditProjectTest(object project, object ctx) boolean ( if ctx.isAdmin ( return true ) - if canManageGroupContent(project, ctx) ( + if canManageOrgContent(project, ctx) ( return true ) string role = projectRole(project, ctx.username.toStr()) diff --git a/src/projects/live-collaboration.osl b/src/projects/live-collaboration.osl index eefdf86..a9de787 100644 --- a/src/projects/live-collaboration.osl +++ b/src/projects/live-collaboration.osl @@ -39,7 +39,8 @@ def liveSession(object project, string branch) object ( if session.getKeys().len == 0 or session.expires.toNum() <= timestamp ( return {} ) - string role = projectRole(project, session.host.toStr()) + string hostRole = projectRole(project, session.host.toStr()) + string role = if isSharedEditorRole(hostRole) then hostRole else projectRoleForName(project, session.host.toStr()) if !isSharedEditorRole(role) ( return {} ) @@ -73,7 +74,7 @@ def handleLiveCollaboration(*serve.Context c) ( ) object project = res.project.assert(object) string username = normalizeUsername(contextString(c, "username")) - string role = projectRole(project, username) + string role = projectRoleFor(project, c) if role == "" ( c.forbidden("only project team members can discover editing sessions") return @@ -92,7 +93,7 @@ def handleLiveCollaboration(*serve.Context c) ( object session = liveSession(project, branch) object editors = projectEditorPresence.get(project.id.toStr()).assertElse(object, {}) for key in editors.getKeys() ( - if editors[key].expires.toNum() <= timestamp or projectRole(project, editors[key].username.toStr()) == "" ( + if editors[key].expires.toNum() <= timestamp or projectRoleForName(project, editors[key].username.toStr()) == "" ( editors.delete(key) ) ) @@ -108,7 +109,7 @@ def handleLiveCollaboration(*serve.Context c) ( if session.getKeys().len != 0 ( object activeMembers = session.members.assert(object) for key in activeMembers.getKeys() ( - string memberRole = projectRole(project, key) + string memberRole = projectRoleForName(project, key) if activeMembers[key].expires.toNum() <= timestamp or memberRole == "" ( activeMembers.delete(key) ) diff --git a/src/projects/monetize.osl b/src/projects/monetize.osl index ea6bc44..b3371a5 100644 --- a/src/projects/monetize.osl +++ b/src/projects/monetize.osl @@ -82,7 +82,7 @@ def projectSeeInside(object project) boolean ( ) def sourcePolicyAllowsViewer(object project,*serve.Context c) boolean ( - boolean owner = contextBool(c, "authenticated") and projectRole(project, contextString(c, "username")) == "owner" + boolean owner = contextBool(c, "authenticated") and projectRoleFor(project, c) == "owner" return projectSourcePolicyAllows(project, owner) ) @@ -476,7 +476,7 @@ def completeProjectPurchase(string key) object ( upsertIndexEntry(project) siteBroadcastStats(project.id.toStr(), buyer, {saved: true}) addPurchaseRecord(buyer, {projectId: project.id.toStr(), title: project.title, seller: seller, amount: owed, at: timestamp}) - addNotification(seller, buyer, "purchase", {projectId: project.id, projectTitle: project.title, amount: owed}) + notifyContentOwner(project, buyer, "purchase", {projectId: project.id, projectTitle: project.title, amount: owed}) ) forgetPurchase(key) return {ok: true, project: project} diff --git a/src/projects/project-access.osl b/src/projects/project-access.osl index a532294..aba095e 100644 --- a/src/projects/project-access.osl +++ b/src/projects/project-access.osl @@ -5,9 +5,14 @@ export { canViewProjectJson, ensureViewKey, projectJsonAccess, + projectModerator, projectMustStayPrivate, projectRole, - removeString + projectRoleFor, + projectRoleForName, + projectRoleForUser, + removeString, + warmProjectOrgAccess } def removeString(array items, string value) array ( @@ -56,13 +61,90 @@ def canEditProject(object project,*serve.Context c) boolean ( if contextBool(c, "isAdmin") ( return true ) - if canManageGroupContent(project, c) ( + if canManageOrgContent(project, c) ( return true ) string role = projectRole(project, contextString(c, "username")) return role == "owner" or role == "maintainer" ) +def projectRoleFor(object project,*serve.Context c) string ( + string role = projectRole(project, contextString(c, "username")) + if role != "owner" and canManageOrgContent(project, c) ( + return "owner" + ) + return role +) + +def warmProjectOrgAccess(string id,*serve.Context c) ( + auto loaded = loadProject(id) + if !loaded.ok ( + return + ) + object project = loaded.project.assert(object) + warmOneProjectOrg(project, c) + string parentId = remixLinkId(project, "remixParent") + string rootId = remixLinkId(project, "remixRoot") + if parentId != "" and parentId != id ( + auto parent = loadProject(parentId) + if parent.ok ( + object parentProject = parent.project.assert(object) + warmOneProjectOrg(parentProject, c) + string grandparentId = remixLinkId(parentProject, "remixParent") + if grandparentId != "" and grandparentId != parentId and grandparentId != rootId ( + auto grandparent = loadProject(grandparentId) + if grandparent.ok ( + warmOneProjectOrg(grandparent.project.assert(object), c) + ) + ) + ) + ) + if rootId != "" and rootId != id and rootId != parentId ( + auto root = loadProject(rootId) + if root.ok ( + warmOneProjectOrg(root.project.assert(object), c) + ) + ) +) + +def remixLinkId(object project, string field) string ( + if !project.contains(field) or project[field] == null ( + return "" + ) + return project[field].toStr() +) + +def warmOneProjectOrg(object project,*serve.Context c) ( + if isOrgOwned(project) ( + void ownerOrgSnapshot(project) + void canManageOrgContent(project, c) + ) +) + +def projectModerator(object project,*serve.Context c) string ( + if canManageOrgContent(project, c) ( + return contextString(c, "username") + ) + return project.owner.toStr() +) + +def projectRoleForName(object project, string username) string ( + return projectRoleForUser(project, "", username, true) +) + +def projectRoleForUser(object project, string userId, string username, boolean waitForRotur) string ( + string role = projectRole(project, username) + if role == "owner" or username == "" or !isOrgOwned(project) ( + return role + ) + object snapshot = if waitForRotur then ownerOrgSnapshot(project) else ownerOrgSnapshotCached(project) + string ownerId = (project.ownerId ?? "").toStr() + if !snapshot.ok or (ownerId != "" and (snapshot.org.assertElse(object, {}).id ?? "").toStr() != ownerId) ( + return role + ) + return if orgMemberCanPublish(snapshot, userId, username) then "owner" else role +) + def canViewForkProject(object project,*serve.Context c) boolean ( if !contextBool(c, "authenticated") ( return false diff --git a/src/projects/project-create.osl b/src/projects/project-create.osl index e8463e0..abef012 100644 --- a/src/projects/project-create.osl +++ b/src/projects/project-create.osl @@ -1,22 +1,14 @@ def handleCreateProject(*serve.Context c) ( object body = requestJSON(c) - string username = contextString(c, "username") - number projectLimit = mistwarpBenefitsForUserId(contextString(c, "userId")).maxProjects.toNum() - if !contextBool(c, "isAdmin") and ownedProjectSlotCount(contextString(c, "userId"), username) >= projectLimit ( - c.json(413, {ok: false, error: "project limit reached; delete a trashed project permanently or upgrade your plan"}) + object owner = creationOwner(c, body, "projects") + if !owner.ok ( + c.json(owner.status.toNum(), {ok: false, code: owner.code, error: owner.error}) return ) - string groupTag = "" - if body.contains("groupTag") and body.groupTag != null and body.groupTag.toStr().strip() != "" ( - groupTag = normalizeGroupTag(body.groupTag.toStr()) - if groupTag == "" ( - c.badRequest("invalid group tag") - return - ) - if !canManageGroupTag(groupTag, c) ( - c.forbidden("you cannot create projects for this group") - return - ) + number projectLimit = mistwarpBenefitsForUserId(owner.ownerId.toStr()).maxProjects.toNum() + if !contextBool(c, "isAdmin") and ownedProjectSlotCount(owner.ownerId.toStr(), owner.owner.toStr()) >= projectLimit ( + c.json(413, {ok: false, error: "project limit reached; delete a trashed project permanently or upgrade your plan"}) + return ) string title = body.title.toStr().strip() @@ -51,9 +43,9 @@ def handleCreateProject(*serve.Context c) ( string id = generateId() object project = { id: id, - owner: username, - ownerId: contextString(c, "userId"), - groupTag: groupTag, + owner: owner.owner, + ownerId: owner.ownerId, + ownerType: owner.ownerType, branding: {}, vanitySlug: "", title: title, @@ -94,13 +86,20 @@ def handleCreateProject(*serve.Context c) ( ) def ownedProjectSlotCount(string userId, string username) number ( - return ownerIndexCount(username, true) + trashedProjectsOwnedBy(userId, username).len + number byName = ownerIndexCount(username, true) + number byId = 0 + if userId != "" ( + byId = projectSearchDocs.where("ownerId", "==", userId).count() + ) + return (if byId > byName then byId else byName) + trashedProjectsOwnedBy(userId, username).len ) def projectFirstShared(object project) ( - addActivity(project.owner.toStr(), "share", {projectId: project.id, projectTitle: project.title}) + if !isOrgOwned(project) ( + addActivity(project.owner.toStr(), "share", {projectId: project.id, projectTitle: project.title}) + roturBadgeEvent(project.owner.toStr(), "project_shared", 0) + ) notifyPublishedRemix(project) - roturBadgeEvent(project.owner.toStr(), "project_shared", 0) ) def notifyPublishedRemix(object project) ( @@ -112,11 +111,13 @@ def notifyPublishedRemix(object project) ( return ) object parent = parentResult.project.assert(object) - addNotification(parent.owner.toStr(), project.owner.toStr(), "remix", {projectId: project.id, projectTitle: parent.title}) - if normalizeUsername(parent.owner.toStr()) != normalizeUsername(project.owner.toStr()) ( + notifyContentOwner(parent, project.owner.toStr(), "remix", {projectId: project.id, projectTitle: parent.title}) + if normalizeUsername(parent.owner.toStr()) != normalizeUsername(project.owner.toStr()) and !isOrgOwned(parent) ( roturBadgeEvent(parent.owner.toStr(), "remixed", 0) ) - addActivity(project.owner.toStr(), "remix", {projectId: project.id, projectTitle: project.title, parentId: parent.id, parentTitle: parent.title}) + if !isOrgOwned(project) ( + addActivity(project.owner.toStr(), "remix", {projectId: project.id, projectTitle: project.title, parentId: parent.id, parentTitle: parent.title}) + ) project.remixNotified = true saveProject(project) ) diff --git a/src/projects/project-discovery.osl b/src/projects/project-discovery.osl index 8a0566e..3d4b0ec 100644 --- a/src/projects/project-discovery.osl +++ b/src/projects/project-discovery.osl @@ -190,7 +190,7 @@ def sitemapUrl(string path) string ( def handleSitemap(*serve.Context c) ( array entries = projectsVisibleToEveryone(sharedIndexEntries()) entries.sortBy("views", "descending") - array staticPaths = ["/", "/explore", "/spaces", "/themes", "/groups", "/news", "/leaderboard", "/roadmap", "/compare"] + array staticPaths = ["/", "/explore", "/spaces", "/themes", "/news", "/leaderboard", "/roadmap", "/compare"] string sitemapXml = "" for i staticPaths.len ( sitemapXml ++= sitemapUrl(staticPaths[i].toStr()) diff --git a/src/projects/project-publishing.osl b/src/projects/project-publishing.osl index 3c38ab9..ecf7ccd 100644 --- a/src/projects/project-publishing.osl +++ b/src/projects/project-publishing.osl @@ -194,10 +194,12 @@ def handleReactProjectLocked(*serve.Context c) ( ) upsertIndexEntry(project) - notifyLikeMilestones(project.owner.toStr(), "project", project.id.toStr(), previousLikes, loves.len, "/project/" ++ project.id.toStr(), {projectId: project.id, projectTitle: project.title}) + if !isOrgOwned(project) ( + notifyLikeMilestones(project.owner.toStr(), "project", project.id.toStr(), previousLikes, loves.len, "/project/" ++ project.id.toStr(), {projectId: project.id, projectTitle: project.title}) + ) if addedHeart ( - addNotification(project.owner.toStr(), viewer, "love", {projectId: project.id, projectTitle: project.title}) - if firstLove and normalizeUsername(viewer) != normalizeUsername(project.owner.toStr()) ( + notifyContentOwner(project, viewer, "love", {projectId: project.id, projectTitle: project.title}) + if firstLove and normalizeUsername(viewer) != normalizeUsername(project.owner.toStr()) and !isOrgOwned(project) ( roturBadgeEvent(project.owner.toStr(), "love_received", 0) ) addActivity(viewer, "love", {projectId: project.id, projectTitle: project.title, projectOwner: project.owner}) diff --git a/src/projects/project-remix.osl b/src/projects/project-remix.osl index 9f88900..e02c4a5 100644 --- a/src/projects/project-remix.osl +++ b/src/projects/project-remix.osl @@ -144,6 +144,7 @@ class ForkOutcome ( ) def handleRemixProject(*serve.Context c) ( + warmProjectOrgAccess(c.param("id"), c) object benefits = mistwarpBenefitsForUserId(contextString(c, "userId")) object body = requestJSON(c) string forkId = generateId() diff --git a/src/projects/project-remix.test.osl b/src/projects/project-remix.test.osl index 5580c2c..86426e9 100644 --- a/src/projects/project-remix.test.osl +++ b/src/projects/project-remix.test.osl @@ -133,11 +133,18 @@ def userIdForUsername(string username) string ( def vanityEligibility(object project) string ( return "unknown" ) -def canManageGroupTag(string tag,*serve.Context c) boolean ( - return false +def orgAccess(string name, string expectedOrgId, *serve.Context c) string ( + return "no" ) -def groupTagOf(object value) string ( - return "" +def roturOrgSnapshot(string name) object ( + return {ok: false, notOrg: true} +) +def warmProjectOrgAccess(string id,*serve.Context c) ( + return +) + +def isOrgOwned(object value) boolean ( + return false ) def generateId() string ( ids += 1 diff --git a/src/projects/project-response.osl b/src/projects/project-response.osl index 7f8d7df..4533342 100644 --- a/src/projects/project-response.osl +++ b/src/projects/project-response.osl @@ -193,7 +193,7 @@ def projectResponse(object project,*serve.Context c) object ( object response = { id: project.id, owner: project.owner, - groupTag: groupTagOf(project), + ownerType: if isOrgOwned(project) then "org" else "", branding: if project.contains("branding") then project.branding else {}, vanitySlug: activeVanity.slug.toStr(), title: project.title, @@ -282,7 +282,8 @@ def projectResponse(object project,*serve.Context c) object ( contributors: searchEntry.contributors, acceptedChanges: searchEntry.acceptedChanges } - response.myRole = projectRole(project, viewer) + response.myRole = projectRoleFor(project, c) + response.canMoveOut = response.myRole == "owner" and orgMoveOutAccess(project, c) == "yes" response.canSaveDirectly = canSaveLiveProject(project, c) if isOwner ( response.collaborators = collaborators diff --git a/src/projects/project-team.test.osl b/src/projects/project-team.test.osl index 9a70cfa..71a10b4 100644 --- a/src/projects/project-team.test.osl +++ b/src/projects/project-team.test.osl @@ -33,11 +33,14 @@ def userIdForUsername(string username) string ( def vanityEligibility(object project) string ( return "unknown" ) -def canManageGroupTag(string tag, *serve.Context c) boolean ( - return false +def orgAccess(string name, string expectedOrgId, *serve.Context c) string ( + return "no" ) -def groupTagOf(object value) string ( - return "" +def roturOrgSnapshot(string name) object ( + return {ok: false, notOrg: true} +) +def isOrgOwned(object value) boolean ( + return false ) def noStorageHold() object ( return {ok: true, reservations: []} diff --git a/src/projects/project-trash.osl b/src/projects/project-trash.osl index 01ac472..68cfbfc 100644 --- a/src/projects/project-trash.osl +++ b/src/projects/project-trash.osl @@ -116,7 +116,7 @@ def handleDeleteProject(*serve.Context c) ( return ) object project = res.project.assert(object) - if projectRole(project, contextString(c, "username")) != "owner" and !contextBool(c, "isAdmin") ( + if projectRoleFor(project, c) != "owner" and !contextBool(c, "isAdmin") ( c.forbidden("not your project") return ) @@ -177,6 +177,13 @@ def purgeExpiredTrash() ( ) ) +def canManageTrashedProject(object project,*serve.Context c) boolean ( + if contextBool(c, "isAdmin") or canManageOrgContent(project, c) ( + return true + ) + return identityMatches((project.ownerId ?? "").toStr(), project.owner.toStr(), contextString(c, "userId"), contextString(c, "username")) +) + def handleGetMyTrash(*serve.Context c) ( purgeExpiredTrash() array projects = [] @@ -190,7 +197,7 @@ def handleGetMyTrash(*serve.Context c) ( if res.ok ( object project = res.data.assert(object) string ownerId = (project.ownerId ?? "").toStr() - if identityMatches(ownerId, project.owner.toStr(), userId, username) ( + if identityMatches(ownerId, project.owner.toStr(), userId, username) or orgContentPublisherAccess(project, c) == "yes" ( projects.append({ id: project.id, title: project.title, @@ -214,7 +221,7 @@ def handleRestoreProject(*serve.Context c) ( return ) object project = res.project.assert(object) - if !identityMatches((project.ownerId ?? "").toStr(), project.owner.toStr(), contextString(c, "userId"), contextString(c, "username")) and !contextBool(c, "isAdmin") ( + if !canManageTrashedProject(project, c) ( c.forbidden("not your project") return ) @@ -246,7 +253,7 @@ def handlePurgeTrashedProject(*serve.Context c) ( return ) object project = res.project.assert(object) - if !identityMatches((project.ownerId ?? "").toStr(), project.owner.toStr(), contextString(c, "userId"), contextString(c, "username")) and !contextBool(c, "isAdmin") ( + if !canManageTrashedProject(project, c) ( c.forbidden("not your project") return ) diff --git a/src/projects/project-update-lookups.osl b/src/projects/project-update-lookups.osl index 6d5e0b8..f54d913 100644 --- a/src/projects/project-update-lookups.osl +++ b/src/projects/project-update-lookups.osl @@ -65,20 +65,33 @@ def lookupVanityEligibility(UpdateLookups lookups, object holder) string ( return lookups.answers[key].toStr() ) -def lookupGroupManager(UpdateLookups lookups, *serve.Context c, string tag) boolean ( - string key = "group:" ++ tag +def lookupOrgAccess(UpdateLookups lookups, *serve.Context c, string name, string expectedOrgId) string ( + string key = "org-access:" ++ name.toLower().strip() ++ ":" ++ expectedOrgId if !lookupKnown(lookups, key) ( if lookups.replay ( - return false + return "unavailable" ) - lookups.answers[key] = canManageGroupTag(tag, c) + lookups.answers[key] = orgAccess(name, expectedOrgId, c) ) - return lookups.answers[key] == true + return lookups.answers[key].toStr() +) + +def lookupOrgContentAccess(UpdateLookups lookups, *serve.Context c, object project) string ( + if !isOrgOwned(project) ( + return "no" + ) + return lookupOrgAccess(lookups, c, (project.owner ?? "").toStr(), (project.ownerId ?? "").toStr()) ) -def lookupGroupContentManager(UpdateLookups lookups, *serve.Context c, object project) boolean ( - string tag = groupTagOf(project) - return tag != "" and lookupGroupManager(lookups, c, tag) +def lookupOrgSnapshot(UpdateLookups lookups, string name) object ( + string key = "org-snapshot:" ++ name.toLower().strip() + if !lookupKnown(lookups, key) ( + if lookups.replay ( + return {ok: false, unavailable: true} + ) + lookups.answers[key] = roturOrgSnapshot(name) + ) + return lookups.answers[key].assertElse(object, {ok: false, unavailable: true}) ) def storageHoldKey(string userId, object changes, boolean enforce) string ( diff --git a/src/projects/project-update-lookups.test.osl b/src/projects/project-update-lookups.test.osl index ad55b48..3605234 100644 --- a/src/projects/project-update-lookups.test.osl +++ b/src/projects/project-update-lookups.test.osl @@ -1,6 +1,8 @@ import "std:testing" import "std:json" import "std:serve" +import "std:requests" +import "std:thread" import "./project-refusal.osl" import "./project-update-lookups.osl" @@ -26,11 +28,16 @@ def vanityEligibility(object project) string ( asked.append("vanity " ++ project.id.toStr()) return "yes" ) -def canManageGroupTag(string tag, *serve.Context c) boolean ( - return true +def orgAccess(string name, string expectedOrgId, *serve.Context c) string ( + asked.append("org " ++ name ++ " " ++ expectedOrgId) + return if name == "busy" then "unavailable" else "yes" ) -def groupTagOf(object value) string ( - return (value.groupTag ?? "").toStr() +def roturOrgSnapshot(string name) object ( + asked.append("snapshot " ++ name) + return {ok: true, org: {id: "o_" ++ name}} +) +def isOrgOwned(object value) boolean ( + return (value.ownerType ?? "").toStr() == "org" ) def noStorageHold() object ( return {ok: true, reservations: []} @@ -77,6 +84,48 @@ released = [] releaseStorageHolds(holds, "") testing.assert(released == ["u_a", "u_b"], "an unsaved update releases every hold") +def handleOrgLookups(*serve.Context c) ( + UpdateLookups orgs = UpdateLookups() + number before = asked.len + object answers = { + publisher: lookupOrgContentAccess(orgs, c, {owner: "Studio", ownerId: "o_studio", ownerType: "org"}), + person: lookupOrgContentAccess(orgs, c, {owner: "sam", ownerType: ""}), + busy: lookupOrgAccess(orgs, c, "busy", ""), + snapshot: lookupOrgSnapshot(orgs, "Studio").org.id, + livePassAsked: asked.len - before + } + orgs.replay = true + number replayBefore = asked.len + answers.replayed = lookupOrgAccess(orgs, c, "studio", "o_studio") + answers.replayedSnapshot = lookupOrgSnapshot(orgs, "studio").ok + answers.replayAsked = asked.len - replayBefore + answers.missedBefore = orgs.missed + answers.unknown = lookupOrgAccess(orgs, c, "other", "") + answers.missedAfter = orgs.missed + c.json(200, answers) +) + +*serve.Router lookupServer = serve.new() +lookupServer.GET("/orgs", handleOrgLookups) +def runLookupServer() ( + lookupServer.run(":18364") +) +thread.new(runLookupServer) +object orgResult = {} +for i 50 ( + auto attempt = requests.get("http://127.0.0.1:18364/orgs") + if attempt.isOk() ( + orgResult = json.parse(attempt.unwrap().body, {type: "object"}).unwrap().assert(object) + break + ) + wait 0.1 +) +testing.assert(orgResult.publisher == "yes" and orgResult.snapshot == "o_studio", "a publisher manages org content and an org is looked up") +testing.assert(orgResult.person == "no" and orgResult.livePassAsked == 3, "a person's content never asks Rotur about orgs") +testing.assert(orgResult.busy == "unavailable", "an unreachable Rotur is unavailable, not a refusal") +testing.assert(orgResult.replayed == "yes" and orgResult.replayedSnapshot == true and orgResult.replayAsked == 0 and orgResult.missedBefore == false, "org answers replay by name, whatever its case") +testing.assert(orgResult.unknown == "unavailable" and orgResult.missedAfter == true, "an org the live pass never asked about is a miss") + testing.assert(roturUnavailableRefusal("alice").status == 503 and roturUnavailableRefusal("alice").body.code == "rotur_unavailable", "an unreachable Rotur is a 503") object knownIdentities = {} diff --git a/src/projects/project-update.osl b/src/projects/project-update.osl index 1bbe5c5..a2ab36e 100644 --- a/src/projects/project-update.osl +++ b/src/projects/project-update.osl @@ -77,6 +77,9 @@ def finishProjectUpdate(*serve.Context c, object body, UpdateOutcome outcome) ( def applyProjectUpdate(*serve.Context c, object project, object body, UpdateLookups lookups, OwnerTransfer transfer) Refusal ( if !canEditProjectWith(c, project, lookups) ( + if contextBool(c, "authenticated") and lookupOrgContentAccess(lookups, c, project) == "unavailable" ( + return roturUnavailableRefusal(project.owner.toStr()) + ) return refuse(403, "not your project") ) Refusal refusal = applyAccessChanges(c, project, body, lookups, transfer) @@ -91,8 +94,6 @@ def applyAccessChanges(*serve.Context c, object project, object body, UpdateLook if isRefused(refusal) return refusal refusal = applyOwnerTransfer(c, project, body, transfer, lookups) if isRefused(refusal) return refusal - refusal = applyGroupTag(c, project, body, lookups) - if isRefused(refusal) return refusal object creatorBenefits = lookupProjectBenefits(lookups, project) refusal = applyBranding(project, body, creatorBenefits) if isRefused(refusal) return refusal @@ -107,7 +108,7 @@ def applyContentChanges(*serve.Context c, object project, object body, UpdateLoo applyProjectFlags(project, body) refusal = projectSaleRefusal(body) if isRefused(refusal) return refusal - refusal = applyRemixShareUpdate(c, project, body) + refusal = applyRemixShareUpdate(c, project, body, lookups) if isRefused(refusal) return refusal refusal = applyTags(project, body) if isRefused(refusal) return refusal @@ -128,7 +129,7 @@ def canEditProjectWith(*serve.Context c, object project, UpdateLookups lookups) if !contextBool(c, "authenticated") ( return false ) - if contextBool(c, "isAdmin") or lookupGroupContentManager(lookups, c, project) ( + if contextBool(c, "isAdmin") or lookupOrgContentAccess(lookups, c, project) == "yes" ( return true ) string role = projectRole(project, contextString(c, "username")) @@ -145,15 +146,22 @@ def updateScopeRefusal(*serve.Context c, object project, object body) Refusal ( return noRefusal() ) -def isOwnerOrAdmin(*serve.Context c, object project) boolean ( - return projectRole(project, contextString(c, "username")) == "owner" or contextBool(c, "isAdmin") +def ownerOrAdminRefusal(*serve.Context c, object project, UpdateLookups lookups, string message) Refusal ( + if contextBool(c, "isAdmin") or projectRole(project, contextString(c, "username")) == "owner" ( + return noRefusal() + ) + string access = lookupOrgContentAccess(lookups, c, project) + if access == "unavailable" ( + return roturUnavailableRefusal(project.owner.toStr()) + ) + return if access == "yes" then noRefusal() else refuse(403, message) ) def applyOwnerTransfer(*serve.Context c, object project, object body, OwnerTransfer transfer, UpdateLookups lookups) Refusal ( if !body.contains("owner") ( return noRefusal() ) - boolean canTransfer = contextBool(c, "isAdmin") or projectRole(project, contextString(c, "username")) == "owner" or lookupGroupContentManager(lookups, c, project) + boolean canTransfer = contextBool(c, "isAdmin") or projectRole(project, contextString(c, "username")) == "owner" or lookupOrgContentAccess(lookups, c, project) == "yes" if !canTransfer ( return refuse(403, "you cannot transfer this project") ) @@ -175,33 +183,45 @@ def applyOwnerTransfer(*serve.Context c, object project, object body, OwnerTrans if !sameOwner and ownedProjectSlotCount(nextOwnerId, nextOwner) >= nextOwnerLimit ( return refuse(400, "the new owner has reached their project limit") ) + if isOrgOwned(project) and !sameOwner ( + string ownerKey = if (project.ownerId ?? "").toStr() != "" then project.ownerId.toStr() else project.owner.toStr() + string moveOut = orgAdminAccess(lookupOrgSnapshot(lookups, ownerKey), (project.ownerId ?? "").toStr(), c) + if moveOut == "unavailable" ( + return roturUnavailableRefusal(project.owner.toStr()) + ) + if moveOut != "yes" ( + return refuse(403, "only an admin of the organisation can move this project out of it") + ) + ) + object nextOrg = lookupOrgSnapshot(lookups, nextOwner) + if !nextOrg.ok and (identity.accountType ?? "").toStr() == "org" ( + if nextOrg.contains("notOrg") and nextOrg.notOrg == true ( + return refuseWithBody(403, {ok: false, code: "org_unavailable", error: "that organisation can't own projects right now"}) + ) + return roturUnavailableRefusal(requestedOwner) + ) + boolean nextOwnerIsOrg = nextOrg.ok + if nextOwnerIsOrg and (nextOrg.org.assertElse(object, {}).id ?? "").toStr() != nextOwnerId ( + return roturUnavailableRefusal(requestedOwner) + ) + if nextOwnerIsOrg and !sameOwner ( + string access = lookupOrgAccess(lookups, c, nextOwner, nextOwnerId) + if access == "unavailable" ( + return roturUnavailableRefusal(requestedOwner) + ) + if access != "yes" ( + return refuse(403, "you cannot move this project into that organisation") + ) + ) if !sameOwner ( transfer.fromId = projectOwnerId(project) ) project.owner = nextOwner project.ownerId = nextOwnerId - if !body.contains("keepGroup") or body.keepGroup != true ( - project.groupTag = "" - ) + project.ownerType = if nextOwnerIsOrg then "org" else "" return noRefusal() ) -def applyGroupTag(*serve.Context c, object project, object body, UpdateLookups lookups) Refusal ( - if !body.contains("groupTag") ( - return noRefusal() - ) - string requestedGroupTag = (body.groupTag ?? "").toStr() - string nextGroupTag = normalizeGroupTag(requestedGroupTag) - if requestedGroupTag.strip() == "" ( - nextGroupTag = "" - ) else if nextGroupTag == "" ( - return refuse(400, "invalid group tag") - ) else if !lookupGroupManager(lookups, c, nextGroupTag) ( - return refuse(403, "you cannot move this project into that group") - ) - project.groupTag = nextGroupTag - return noRefusal() -) def vanitySlugHeldElsewhere(object project, string slug, UpdateLookups lookups) boolean ( array matches = vanityClaimEntries(slug) @@ -244,13 +264,12 @@ def applyVanitySlug(object project, object body, object creatorBenefits, UpdateL return noRefusal() ) -def applyRemixShareUpdate(*serve.Context c, object project, object body) Refusal ( +def applyRemixShareUpdate(*serve.Context c, object project, object body, UpdateLookups lookups) Refusal ( if !body.contains("remixShare") ( return noRefusal() ) - if !isOwnerOrAdmin(c, project) ( - return refuse(403, "only the owner can change the remix share") - ) + Refusal ownerRefusal = ownerOrAdminRefusal(c, project, lookups, "only the owner can change the remix share") + if isRefused(ownerRefusal) return ownerRefusal return applyRemixShare(project, body.remixShare.toNum()) ) @@ -258,9 +277,8 @@ def applyTeamUpdate(*serve.Context c, object project, object body, UpdateLookups if !body.contains("collaborators") ( return noRefusal() ) - if !isOwnerOrAdmin(c, project) ( - return refuse(403, "only the owner can manage the project team") - ) + Refusal teamRefusal = ownerOrAdminRefusal(c, project, lookups, "only the owner can manage the project team") + if isRefused(teamRefusal) return teamRefusal if typeof(body.collaborators) != "array" ( return refuse(400, "collaborators must be a list") ) diff --git a/src/projects/project-upload.osl b/src/projects/project-upload.osl index 1fff723..354c3b9 100644 --- a/src/projects/project-upload.osl +++ b/src/projects/project-upload.osl @@ -55,6 +55,7 @@ def remixSyncAccessRefusal(*serve.Context c, object project, UploadRequest reque ) def handleUploadProject(*serve.Context c) ( + warmProjectOrgAccess(c.param("id"), c) runLocked(projectSaveLock(c.param("id")), def() -> ( handleUploadProjectLocked(c) )) diff --git a/src/realtime/site-realtime.osl b/src/realtime/site-realtime.osl index 3bafc5b..b1bc6ff 100644 --- a/src/realtime/site-realtime.osl +++ b/src/realtime/site-realtime.osl @@ -28,14 +28,15 @@ def siteAllows(*ws.Connection conn, string field, number maximum, number windowM return true ) -def siteCanView(object project,*ws.Connection conn, string accessKey) boolean ( +def siteCanView(object project,*ws.Connection conn, string accessKey, boolean waitForRotur) boolean ( + string viewerId = (conn.Get("userId") ?? "").toStr() if conn.Get("isAdmin") == true ( return true ) if projectOwnerBanned(project) ( return false ) - if isStudentUserId((conn.Get("userId") ?? "").toStr()) ( + if isStudentUserId(viewerId) ( return projectRole(project, conn.Get("username").toStr()) != "" ) if projectIsViewable(project) ( @@ -45,7 +46,7 @@ def siteCanView(object project,*ws.Connection conn, string accessKey) boolean ( return true ) if conn.Get("authenticated") == true ( - return projectRole(project, conn.Get("username").toStr()) != "" + return projectRoleForUser(project, viewerId, conn.Get("username").toStr(), waitForRotur) != "" ) return false ) @@ -91,7 +92,7 @@ def siteBroadcastProject(string projectId, object message) ( for conn in siteRealtimeSocket.Connections() ( if !siteSubscribed(conn, projectId) continue string accessKey = siteProjectKey(conn, projectId) - if siteCanView(project, conn, accessKey) ( + if siteCanView(project, conn, accessKey, false) ( conn.Send(encoded) ) ) @@ -120,7 +121,7 @@ def siteBroadcastStats(string projectId, string actor, object viewerState) ( string actorKey = normalizeUsername(actor) for conn in siteRealtimeSocket.Connections() ( if !siteSubscribed(conn, projectId) continue - if !siteCanView(project, conn, siteProjectKey(conn, projectId)) continue + if !siteCanView(project, conn, siteProjectKey(conn, projectId), false) continue if conn.Get("authenticated") == true and normalizeUsername(conn.Get("username").toStr()) == actorKey ( conn.Send(actorMessage) ) else ( @@ -175,7 +176,7 @@ def siteSubscribe(*ws.Connection conn, object message) ( string projectId = message.projectId.assertElse(string, "").strip() string accessKey = message.accessKey.assertElse(string, "").strip() auto res = loadProject(projectId) - if !res.ok or !siteCanView(res.project.assert(object), conn, accessKey) ( + if !res.ok or !siteCanView(res.project.assert(object), conn, accessKey, true) ( siteError(conn, "project not found") return ) diff --git a/src/storage/storage.osl b/src/storage/storage.osl index c48db16..167e39d 100644 --- a/src/storage/storage.osl +++ b/src/storage/storage.osl @@ -179,10 +179,6 @@ def indexEntryFromProject(object project) object ( if project.contains("remixRoot") and project.remixRoot != null ( remixRoot = project.remixRoot.toStr() ) - string groupTag = "" - if project.contains("groupTag") and project.groupTag != null ( - groupTag = normalizeGroupTag(project.groupTag.toStr()) - ) number lastUploadAt = 0 if project.contains("lastUploadAt") and project.lastUploadAt != null ( lastUploadAt = project.lastUploadAt.toNum() @@ -196,7 +192,7 @@ def indexEntryFromProject(object project) object ( owner: project.owner, ownerId: ownerId, ownerKey: normalizeUsername(project.owner.toStr()), - groupTag: groupTag, + ownerType: if isOrgOwned(project) then "org" else "", vanityClaim: vanitySlug, vanitySlug: if (project.vanityLapsedAt ?? 0).toNum() > 0 then "" else vanitySlug, title: project.title,