import type { Agent } from "@atproto/api"; import { and, eq, inArray, ne, or, isNull } from "drizzle-orm"; import { db } from "../db/index.js"; import { slugify } from "../db/helpers.js"; import { spools, tangledRepoDeclined, tangledRepoPending } from "../db/schema.js"; // Repo records are sh.tangled.repo, written to the owner's own PDS — // Tangled (tangled.sh/tangled.org) has no separate API for this, it's the // generic AT Proto record-listing method. Fields we care about; the schema // allows more (knot, spindle, topics, labels...) that we don't use here. type TangledRepo = { name?: string; description?: string; }; const TANGLED_REPO_COLLECTION = "sh.tangled.repo"; const MAX_REPOS = 200; // sane cap — a few pages, not an unbounded loop type FetchedRepo = { uri: string; name: string; description: string | null; repoUrl: string; }; // Fetches the repos an account owns on Tangled directly from their PDS. async function fetchTangledRepos(agent: Agent, did: string, handle: string): Promise { const repos: FetchedRepo[] = []; let cursor: string | undefined; let seen = 0; while (seen < MAX_REPOS) { const response = await agent.com.atproto.repo.listRecords({ repo: did, collection: TANGLED_REPO_COLLECTION, cursor, }); for (const record of response.data.records) { const repo = record.value as TangledRepo; // Tangled's UI doesn't actually populate the record's optional "name" // field — the repo's real short name is the AT-URI's record key // instead (at://did/sh.tangled.repo/{rkey}), which is also what // tangled.sh uses in the repo's real URL. Prefer the cosmetic name if // present, but the rkey is what a repo is actually addressed by. const rkey = record.uri.split("/").pop(); if (!rkey) continue; const name = repo.name || rkey; repos.push({ uri: record.uri, name, description: repo.description ?? null, repoUrl: `https://tangled.sh/${handle}/${rkey}`, }); } seen += response.data.records.length; cursor = response.data.cursor; if (!cursor || response.data.records.length === 0) break; } return repos; } // Reads the repos a user actually owns on Tangled and stages the ones that // haven't already been synced or declined, so the user can be asked which // to sync. Called on every login; replaces this owner's staged set so a // repo removed upstream also drops out of the pending list. export async function refreshPendingTangledRepos( agent: Agent, did: string, handle: string, ownerId: number ): Promise { const repos = await fetchTangledRepos(agent, did, handle); const alreadySynced = await db .select({ tangledUri: spools.tangledUri }) .from(spools) .where(eq(spools.ownerId, ownerId)); const alreadyDeclined = await db .select({ tangledUri: tangledRepoDeclined.tangledUri }) .from(tangledRepoDeclined) .where(eq(tangledRepoDeclined.ownerId, ownerId)); const decided = new Set([ ...alreadySynced.map((r) => r.tangledUri), ...alreadyDeclined.map((r) => r.tangledUri), ]); const pending = repos.filter((r) => !decided.has(r.uri)); await db.delete(tangledRepoPending).where(eq(tangledRepoPending.ownerId, ownerId)); if (pending.length > 0) { await db.insert(tangledRepoPending).values( pending.map((r) => ({ ownerId, tangledUri: r.uri, name: r.name, description: r.description, repoUrl: r.repoUrl, })) ); } } export type PendingTangledRepo = { uri: string; name: string; description: string | null; repoUrl: string; }; // Reads the repos still awaiting a sync decision, for the picker UI. export async function listPendingTangledRepos(ownerId: number): Promise { const rows = await db .select({ uri: tangledRepoPending.tangledUri, name: tangledRepoPending.name, description: tangledRepoPending.description, repoUrl: tangledRepoPending.repoUrl, }) .from(tangledRepoPending) .where(eq(tangledRepoPending.ownerId, ownerId)); return rows; } // Applies the user's sync choices: accepted repos become Spools, declined // repos are remembered so they aren't asked about again. Either way, the // decided repos are cleared from the pending list. export async function applyTangledRepoDecisions( ownerId: number, accepted: string[], declined: string[] ): Promise { if (accepted.length > 0) { const pendingRows = await db .select() .from(tangledRepoPending) .where(and(eq(tangledRepoPending.ownerId, ownerId), inArray(tangledRepoPending.tangledUri, accepted))); for (const row of pendingRows) { await syncOneRepo(row.tangledUri, row.name, row.description, row.repoUrl, ownerId); } } if (declined.length > 0) { await db .insert(tangledRepoDeclined) .values(declined.map((tangledUri) => ({ ownerId, tangledUri }))) .onConflictDoNothing(); } const decided = [...accepted, ...declined]; if (decided.length > 0) { await db .delete(tangledRepoPending) .where(and(eq(tangledRepoPending.ownerId, ownerId), inArray(tangledRepoPending.tangledUri, decided))); } } async function syncOneRepo( uri: string, name: string, description: string | null, repoUrl: string, ownerId: number ) { const slug = await freeSlug(slugify(name), uri); if (!slug) return; await db .insert(spools) .values({ slug, name, description, repoUrl, tangledUri: uri, ownerId }) .onConflictDoUpdate({ target: spools.tangledUri, set: { slug, name, description, repoUrl, ownerId }, }); } // Finds a slug for this repo, appending "-2", "-3", ... if another spool // (not this same synced repo, on a re-sync) already holds the base slug. async function freeSlug(base: string, uri: string): Promise { if (!base) return null; for (let n = 1; n < 50; n++) { const candidate = n === 1 ? base : `${base}-${n}`; const [taken] = await db .select({ id: spools.id }) .from(spools) .where( and(eq(spools.slug, candidate), or(isNull(spools.tangledUri), ne(spools.tangledUri, uri))) ); if (!taken) return candidate; } return null; }