// Sharing a project: Peppa membership plus collaborator access to its Gitea repo. import { addMember, getUser, giteaForBot, giteaForUser, PeppaError, removeMember, type GiteaClient, type Project, type User, } from "@peppa/core"; import type { Db } from "@peppa/db"; /** Gitea clients that may administer the project's repo: its owner, then peppa-bot. */ async function repoAdmins(db: Db, project: Project): Promise { const out: GiteaClient[] = []; const owner = project.ownerId ? await getUser(db, project.ownerId) : null; if (owner) { try { out.push(await giteaForUser(db, owner)); } catch {} } try { out.push(giteaForBot()); } catch {} return out; } export interface ShareResult { login: string; status: "added" | "invited"; /** False when Peppa could not add the person as a repo collaborator in Gitea. */ repoAccess: boolean; } /** Owner adds a person (by Gitea login) to the project and to its repo (write). */ export async function shareProject(db: Db, actor: User, project: Project, loginInput: string): Promise { if (project.ownerId !== actor.id) throw new PeppaError("Участниками управляет только владелец проекта"); const login = loginInput.trim().replace(/^@/, ""); if (!login) throw new PeppaError("Укажите логин Gitea"); const clients = await repoAdmins(db, project); if (!clients.length) throw new PeppaError("Нет доступа к Gitea — войдите заново"); const account = await clients[0]!.getUserByLogin(login); if (!account) throw new PeppaError(`Пользователь «${login}» не найден в Gitea`); const status = await addMember(db, project, account.login, actor.id); let repoAccess = false; for (const c of clients) { try { await c.addCollaborator(project.giteaOwner, project.giteaRepo, account.login, "write"); repoAccess = true; break; } catch {} } return { login: account.login, status, repoAccess }; } /** Owner removes a member/invitation, or a member leaves. */ export async function unshareProject(db: Db, actor: User, project: Project, loginInput: string): Promise { const login = loginInput.trim().replace(/^@/, ""); const self = actor.login.toLowerCase() === login.toLowerCase(); if (project.ownerId !== actor.id && !self) throw new PeppaError("Участниками управляет только владелец проекта"); if (!(await removeMember(db, project.id, login))) throw new PeppaError(`«${login}» не участник проекта`); for (const c of await repoAdmins(db, project)) { try { await c.removeCollaborator(project.giteaOwner, project.giteaRepo, login); break; } catch {} } }