Files
t5de-hub/apps/web/app/console/catalogs/actions.ts
T
dhkatz 7ece681eef
Release / release (push) Successful in 4s
CI / test (push) Successful in 1m25s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 7s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 15s
feat: IMVU imports on the hub: grants, requests and the importer's job queue (#13)
Phase 4a (docs/imports.md): the hub's side of IMVU imports.

**Grants**
- A creator picks one of their linked IMVU accounts and a catalog with imports on. They choose the whole shop (with exclusions) or listed products, listed or unlisted, and agree to a versioned consent text (`imports.ts` `consent`).
- The catalog's team (`import:accept`) accepts or declines, and the creator is notified. Accepting queues what people already asked for, plus a grant's listed products.
- The creator can change what's covered or withdraw it; the team (`import:withdraw`, which moderators also have) can end it.
- Withdrawn products are removed the way moderation removes products: their hosting is dropped and their files go in the catalogs' changes feed. If another catalog's active grant still covers a product, it's only delisted from this catalog.
- Unlinking an IMVU account, or someone else linking it, suspends its grants.

**Requests**
- Anyone signed in can ask for an IMVU product (an ID or a shop link). The answer is one of:
  - `added`: already imported, and now in their library
  - `queued`: delivered to their library once imported
  - `suggested`: the creator grants by listed products, and will see the request
  - `counted`: no grant covers it yet
- Creators see request counts for their accounts, and moderators see the most-requested creators.
- At most 50 requests a day per person.

**Importer**
- Importers sign in with `Authorization: Importer <catalog>:<key>`; turning imports on returns the key once. The catalog's importer can be paused (`import:pause`).
- Importers claim jobs, get `t5de-import` tokens for a revision, and report outcomes.
- Claims time out after 30 minutes. Failures retry after 1 min, 10 min, 1 h, then daily, and fail for good after 5 attempts.
- `POST /catalog/revisions` takes `importToken` instead of `uploadToken`. The result is a published product owned by the creator (`product.imvu_product`, `product_revision.imvu_revision`). If another catalog already imported the same IMVU revision, this catalog hosts it too.
- Every hour, the API rechecks a batch of imported products with IMVU (each at most once a day). A product gone from IMVU, or now another creator's, is withdrawn. One rated AP becomes adult. If it's still covered, a recheck job looks for new revisions.

**Website**
- `/imports`: ask for a product; bring your products; change or withdraw a grant; what people asked for. It's linked from the account page.
- The console's catalog page has an Imports card leading to `/console/catalogs/:id/imports`:
  - importer on, off, pause and resume, and a new key
  - pending grants to accept or decline
  - grants to end
  - the queue, filtered by status, with retry
- Notification text for the two new notification types.

**Checks**
- **Tests:** `test/imports.test.ts` covers the whole flow, from grant to withdrawal. All 58 API tests pass, and type checks pass.
- **Scratch hub:** through the console forms, I turned imports on (the key was shown once), paused and resumed. I checked that importer claims accept the key and refuse a wrong one, that `/imports` renders, and that a request while IMVU is unreachable says "IMVU didn't answer."
- **IMVU fields not checked live:** `api.imvu.com` times out from the dev machine. The product fields (`product_name`, `creator_cid`, `creator_name`, `rating`, `is_purchasable`) are what the design recorded; the spike will check them.

**Formatting**
- `two-factor-card.tsx`, `signin-form.tsx` and `console-nav.tsx` are only reformatted. I'd run Prettier on them at its default 80 columns in #12, but the repo is wrapped at about 120.

**Still to do (4b and later)**
- admin-recorded grants, proofs and unclaimed creators (and claiming them)
- `GET /imports/available` for the proxy's shop button
- t5de-catalog accepting `t5de-import` tokens on uploads
- the spike, then `t5de-importer`

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Phase 4a (docs/imports.md): the hub's side of IMVU imports.

**Grants**
- A creator picks one of their linked IMVU accounts and a catalog with imports on. They choose the whole shop (with exclusions) or listed products, listed or unlisted, and agree to a versioned consent text (`imports.ts` `consent`).
- The catalog's team (`import:accept`) accepts or declines, and the creator is notified. Accepting queues what people already asked for, plus a grant's listed products.
- The creator can change what's covered or withdraw it; the team (`import:withdraw`, which moderators also have) can end it.
- Withdrawn products are removed the way moderation removes products: their hosting is dropped and their files go in the catalogs' changes feed. If another catalog's active grant still covers a product, it's only delisted from this catalog.
- Unlinking an IMVU account, or someone else linking it, suspends its grants.

**Requests**
- Anyone signed in can ask for an IMVU product (an ID or a shop link). The answer is one of:
  - `added`: already imported, and now in their library
  - `queued`: delivered to their library once imported
  - `suggested`: the creator grants by listed products, and will see the request
  - `counted`: no grant covers it yet
- Creators see request counts for their accounts, and moderators see the most-requested creators.
- At most 50 requests a day per person.

**Importer**
- Importers sign in with `Authorization: Importer <catalog>:<key>`; turning imports on returns the key once. The catalog's importer can be paused (`import:pause`).
- Importers claim jobs, get `t5de-import` tokens for a revision, and report outcomes.
- Claims time out after 30 minutes. Failures retry after 1 min, 10 min, 1 h, then daily, and fail for good after 5 attempts.
- `POST /catalog/revisions` takes `importToken` instead of `uploadToken`. The result is a published product owned by the creator (`product.imvu_product`, `product_revision.imvu_revision`). If another catalog already imported the same IMVU revision, this catalog hosts it too.
- Every hour, the API rechecks a batch of imported products with IMVU (each at most once a day). A product gone from IMVU, or now another creator's, is withdrawn. One rated AP becomes adult. If it's still covered, a recheck job looks for new revisions.

**Website**
- `/imports`: ask for a product; bring your products; change or withdraw a grant; what people asked for. It's linked from the account page.
- The console's catalog page has an Imports card leading to `/console/catalogs/:id/imports`:
  - importer on, off, pause and resume, and a new key
  - pending grants to accept or decline
  - grants to end
  - the queue, filtered by status, with retry
- Notification text for the two new notification types.

**Checks**
- **Tests:** `test/imports.test.ts` covers the whole flow, from grant to withdrawal. All 58 API tests pass, and type checks pass.
- **Scratch hub:** through the console forms, I turned imports on (the key was shown once), paused and resumed. I checked that importer claims accept the key and refuse a wrong one, that `/imports` renders, and that a request while IMVU is unreachable says "IMVU didn't answer."
- **IMVU fields not checked live:** `api.imvu.com` times out from the dev machine. The product fields (`product_name`, `creator_cid`, `creator_name`, `rating`, `is_purchasable`) are what the design recorded; the spike will check them.

**Formatting**
- `two-factor-card.tsx`, `signin-form.tsx` and `console-nav.tsx` are only reformatted. I'd run Prettier on them at its default 80 columns in #12, but the repo is wrapped at about 120.

**Still to do (4b and later)**
- admin-recorded grants, proofs and unclaimed creators (and claiming them)
- `GET /imports/available` for the proxy's shop button
- t5de-catalog accepting `t5de-import` tokens on uploads
- the spike, then `t5de-importer`

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: dhkatz <[email protected]>
2026-11-07 16:29:03 +00:00

176 lines
7.2 KiB
TypeScript

"use server";
// Managing a catalog from the console: settings, key, team, members, invitations, what it hosts, suspension.
import { revalidatePath } from "next/cache";
import { api, unwrap } from "@/lib/api";
import { attempt, field, type ActionState } from "@/lib/actions";
/** Runs a change to a catalog, then shows its pages again. */
async function onCatalog(form: FormData, change: (id: string) => Promise<string | void>): Promise<ActionState> {
const id = field(form, "id");
return attempt(async () => {
const notice = await change(id);
revalidatePath(`/console/catalogs/${id}`);
revalidatePath(`/catalogs/${id}`);
revalidatePath("/console/catalogs");
revalidatePath("/catalogs");
return notice;
});
}
const pick = <T extends string>(v: string, options: readonly T[]): T | undefined => options.find((o) => o === v);
export async function saveCatalog(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
unwrap(
await api.catalogs({ id }).patch({
name: field(form, "name"),
url: field(form, "url"),
contact: field(form, "contact"),
visibility: pick(field(form, "visibility"), ["public", "private"] as const),
membership: pick(field(form, "membership"), ["open", "approval", "invite"] as const),
maxRating: pick(field(form, "maxRating"), ["general", "adult"] as const),
uploads: pick(field(form, "uploads"), ["anyone", "members", "team"] as const),
mirrors: pick(field(form, "mirrors"), ["auto", "approve", "off"] as const),
}),
);
return "Saved.";
});
}
export async function rotateKey(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
const { key } = unwrap(await api.catalogs({ id }).key.post());
return `New key (shown once; put it in the catalog's CATALOG_KEY and restart it): ${key}`;
});
}
export async function setSuspended(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
if (field(form, "intent") === "reinstate") unwrap(await api.catalogs({ id }).reinstate.post());
else unwrap(await api.catalogs({ id }).suspend.post({ reason: field(form, "reason") }));
});
}
export async function addOperator(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
const username = field(form, "username");
unwrap(await api.catalogs({ id }).team({ username }).put({ role: "catalog-operator" }));
return `${username} is an operator now.`;
});
}
export async function removeFromTeam(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
unwrap(await api.catalogs({ id }).team({ username: field(form, "username") }).delete({}, { query: { role: "catalog-operator" } }));
});
}
/** A member or request: approve, decline, add, ban, unban or remove. */
export async function decideMember(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
const member = api.catalogs({ id }).members({ username: field(form, "username") });
switch (field(form, "decision")) {
case "approve":
case "add":
unwrap(await member.put({ status: "member" }));
break;
case "ban":
unwrap(await member.put({ status: "banned" }));
break;
default: // decline, unban, remove
unwrap(await member.delete());
}
});
}
export async function createInvite(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
const maxUses = Number(field(form, "maxUses")) || undefined;
const expiresInDays = Number(field(form, "expiresInDays")) || undefined;
const { invite } = unwrap(await api.catalogs({ id }).invites.post({ maxUses, expiresInDays }));
return `Invitation link: ${invite.url}`;
});
}
export async function revokeInvite(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
unwrap(await api.catalogs({ id }).invites({ code: field(form, "code") }).delete());
});
}
export async function delist(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
const product = field(form, "product");
unwrap(await api.catalogs({ id }).products({ product }).delete({}, { query: { reason: field(form, "reason") } }));
revalidatePath(`/products/${product}`);
});
}
/** Someone joins a catalog (or asks to), with an invitation code if they have one; or leaves it. */
export async function membership(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
if (field(form, "intent") === "leave") {
unwrap(await api.catalogs({ id }).join.delete());
revalidatePath("/library");
return "You left.";
}
const invite = field(form, "invite");
const { membership } = unwrap(await api.catalogs({ id }).join.post(invite ? { invite } : {}));
revalidatePath("/library");
return membership === "member" ? "You're a member." : "Asked. The catalog's team will decide.";
});
}
// ---- imports (docs/imports.md) ----
/** Turns the importer on (its key, shown once) or off, pauses or resumes it, or makes a new key. */
export async function setImporter(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
revalidatePath(`/console/catalogs/${id}/imports`);
const intent = field(form, "intent");
if (intent === "key") {
const { key } = unwrap(await api.catalogs({ id }).importer.key.post());
return `New importer key (shown once; put it in the importer's IMPORTER_KEY and restart it): ${key}`;
}
const body =
intent === "on" ? { enabled: true } : intent === "off" ? { enabled: false } : { paused: intent === "pause" };
const r = unwrap(await api.catalogs({ id }).importer.post(body));
if (r.key) return `Imports are on. The importer's key (shown once; put it in IMPORTER_KEY): ${r.key}`;
});
}
/** The catalog's team accepts, declines or ends a creator's grant. */
export async function decideGrant(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
revalidatePath(`/console/catalogs/${id}/imports`);
const grant = field(form, "grant");
const intent = field(form, "intent");
const reason = field(form, "reason");
if (intent === "end") {
unwrap(await api.imports.grants({ id: grant }).delete(reason ? { reason } : {}));
return "Ended. Its imported products were taken away.";
}
const decision = intent === "accept" ? "accept" : "decline";
const r = unwrap(
await api.imports
.grants({ id: grant })({ decision })
.post(reason ? { reason } : {}),
);
return decision === "accept" ? `Accepted. ${r.queued} queued for the importer.` : "Declined.";
});
}
/** Retries a failed import job (or imports a product again). */
export async function retryJob(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
revalidatePath(`/console/catalogs/${id}/imports`);
unwrap(
await api
.catalogs({ id })
.importer.jobs({ job: field(form, "job") })
.retry.post(),
);
return "Queued.";
});
}