feat: IMVU imports on the hub: grants, requests and the importer's job queue (#13)
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

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]>
This commit was merged in pull request #13.
This commit is contained in:
dhkatz authored and dhkatz committed 2026-11-07 16:29:03 +00:00
1 parent eca1884918
commit 7ece681eef
24 files changed
+6565 -158

No files matched your search

+90
View File
@@ -0,0 +1,90 @@
"use server";
// Imports from the website: asking for an IMVU product, and creators' grants (bring, change, withdraw).
import { revalidatePath } from "next/cache";
import { api, ApiError, unwrap } from "@/lib/api";
import { attempt, field, type ActionState } from "@/lib/actions";
const done = () => {
revalidatePath("/imports");
revalidatePath("/library");
};
/** IMVU product IDs in what someone typed or pasted: numbers, or shop links (`products_id=123`, `product-123`). */
function productIDs(text: string): number[] | undefined {
const out = new Set<number>();
for (const part of text.split(/[\s,]+/).filter(Boolean)) {
const m = part.match(/(?:products_id=|product-)(\d+)/) ?? part.match(/^(\d+)$/);
const n = m ? Number(m[1]) : NaN;
if (!Number.isSafeInteger(n) || n <= 0) return undefined;
out.add(n);
}
return [...out];
}
const answers = {
added: "It's in your library.",
queued: "Its creator lets T5DE have it: it'll be in your library once the catalog imports it.",
suggested: "Its creator brings chosen products to T5DE; they'll see you asked for this one.",
counted: "Its creator hasn't brought it to T5DE. Your request is counted, and they'll see it if they do.",
} as const;
/** Someone asks for an IMVU product (an ID or a shop link). */
export async function requestProduct(_: ActionState, form: FormData): Promise<ActionState> {
const ids = productIDs(field(form, "product"));
if (!ids || ids.length !== 1) return { error: "Give one IMVU product ID or shop link." };
return attempt(async () => {
const r = unwrap(await api.imports.requests.post({ imvuProduct: ids[0]! }));
done();
return answers[r.status];
});
}
/** A creator brings their IMVU products to a catalog. */
export async function createGrant(_: ActionState, form: FormData): Promise<ActionState> {
if (form.get("agree") !== "on") return { error: "Agree to the terms to go on." };
const scope = field(form, "scope") === "products" ? "products" : "shop";
const list = productIDs(field(form, scope === "products" ? "products" : "exclude"));
if (!list)
return {
error: "Products are IMVU product IDs or shop links, separated by spaces, commas or lines.",
};
return attempt(async () => {
unwrap(
await api.imports.grants.post({
catalog: field(form, "catalog"),
imvuId: Number(field(form, "imvuId")),
scope,
...(scope === "products" ? { products: list } : { exclude: list }),
listed: form.get("listed") === "on",
consentVersion: Number(field(form, "consentVersion")),
}),
);
done();
return "Sent. The catalog's team accepts it before anything is imported.";
});
}
/** A creator changes what a grant covers, or withdraws it. */
export async function changeGrant(_: ActionState, form: FormData): Promise<ActionState> {
const id = field(form, "id");
return attempt(async () => {
if (field(form, "intent") === "withdraw") {
const r = unwrap(await api.imports.grants({ id }).delete({}));
done();
return r.withdrawn.length ? `Withdrawn. ${r.withdrawn.length} imported products were taken away.` : "Withdrawn.";
}
const scope = field(form, "scope") === "products" ? "products" : "shop";
const list = productIDs(field(form, "list"));
if (!list) throw new ApiError(400, "invalid", "Products are IMVU product IDs or shop links.");
const r = unwrap(
await api.imports.grants({ id }).patch({
...(scope === "products" ? { products: list } : { exclude: list }),
listed: form.get("listed") === "on",
}),
);
done();
return r.withdrawn.length
? `Saved. ${r.withdrawn.length} imported products it no longer covers were taken away.`
: "Saved.";
});
}
+317
View File
@@ -0,0 +1,317 @@
import type { Metadata } from "next";
import Link from "next/link";
import { redirect } from "next/navigation";
import { ActionForm, SubmitButton } from "@/components/forms";
import { PageHeader, Tag } from "@/components/status";
import { DateTime } from "@/components/time";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Textarea } from "@/components/ui/textarea";
import { api, getMe, unwrap, type ImportGrant } from "@/lib/api";
import { changeGrant, createGrant, requestProduct } from "./actions";
export const metadata: Metadata = { title: "Imports" };
const statusTone = {
pending: "neutral",
active: "online",
declined: "danger",
suspended: "danger",
withdrawn: "neutral",
} as const;
const imvuPage = (id: number) => `https://www.imvu.com/shop/product.php?products_id=${id}`;
export default async function Imports() {
const me = await getMe();
if (!me) redirect("/signin?next=/imports");
const [account, offered, mine] = await Promise.all([
api.account.get().then(unwrap),
api.imports.catalogs.get().then(unwrap),
api.imports.grants.get().then(unwrap),
]);
const asked = await Promise.all(
account.links.map(async (l) => ({
link: l,
requests: unwrap(await api.imports.requests.get({ query: { imvuCreator: l.imvuId } })).requests,
})),
);
const open = mine.grants.filter((g) => g.status !== "withdrawn" && g.status !== "declined");
const ended = mine.grants.filter((g) => g.status === "withdrawn" || g.status === "declined");
return (
<div className="space-y-6">
<PageHeader title="IMVU Imports">
Creators can let T5DE users wear their IMVU products for free: a catalog imports them, with their permission.
</PageHeader>
<Card>
<CardHeader>
<CardTitle>Ask for a Product</CardTitle>
<CardDescription>
An IMVU product you&apos;d like on T5DE. If its creator lets T5DE have it, it comes to your library; if not,
they&apos;ll see that people asked.
</CardDescription>
</CardHeader>
<CardContent>
<ActionForm action={requestProduct}>
<div className="flex max-w-xl flex-wrap gap-2">
<Input
name="product"
required
placeholder="IMVU product ID or shop link"
aria-label="IMVU product"
className="min-w-64 flex-1"
/>
<SubmitButton pendingLabel="Asking…">Ask</SubmitButton>
</div>
</ActionForm>
</CardContent>
</Card>
{open.length > 0 && (
<Card>
<CardHeader>
<CardTitle>Your Products on T5DE</CardTitle>
</CardHeader>
<CardContent className="space-y-6">
{open.map((g) => (
<GrantRow key={g.id} grant={g} />
))}
</CardContent>
</Card>
)}
<Card>
<CardHeader>
<CardTitle>Bring Your IMVU Products</CardTitle>
<CardDescription>
Made products on IMVU? Choose a catalog to host them. Its team accepts first; then T5DE users can wear them
for free, and you can change what&apos;s included or stop any time.
</CardDescription>
</CardHeader>
<CardContent>
{account.links.length === 0 ? (
<p className="text-sm text-muted-foreground">
First{" "}
<Link href="/account" className="text-foreground underline underline-offset-4">
link your IMVU account
</Link>
, the one that made the products.
</p>
) : offered.catalogs.length === 0 ? (
<p className="text-sm text-muted-foreground">No catalog takes imports yet.</p>
) : (
<ActionForm
action={createGrant}
fields={{ consentVersion: offered.consent.version }}
className="max-w-2xl space-y-4"
>
<div className="grid gap-4 sm:grid-cols-2">
<Field>
<FieldLabel htmlFor="imvuId">Your IMVU account</FieldLabel>
<NativeSelect id="imvuId" name="imvuId">
{account.links.map((l) => (
<NativeSelectOption key={l.imvuId} value={l.imvuId}>
{l.username}
</NativeSelectOption>
))}
</NativeSelect>
</Field>
<Field>
<FieldLabel htmlFor="catalog">Catalog</FieldLabel>
<NativeSelect id="catalog" name="catalog">
{offered.catalogs.map((c) => (
<NativeSelectOption key={c.id} value={c.id}>
{c.name}
</NativeSelectOption>
))}
</NativeSelect>
</Field>
</div>
<fieldset className="space-y-2">
<legend className="mb-2 text-sm font-medium">What to bring</legend>
<label className="flex items-start gap-2 text-sm">
<input type="radio" name="scope" value="shop" defaultChecked className="mt-1" />
<span>
My whole shop, including new products
<span className="block text-muted-foreground">Leave some out below (optional).</span>
</span>
</label>
<label className="flex items-start gap-2 text-sm">
<input type="radio" name="scope" value="products" className="mt-1" />
<span>
Only the products I list
<span className="block text-muted-foreground">List them below; you can add more later.</span>
</span>
</label>
</fieldset>
<Field>
<FieldLabel htmlFor="exclude">Leave out (whole shop)</FieldLabel>
<Textarea
id="exclude"
name="exclude"
rows={2}
placeholder="IMVU product IDs or shop links"
className="font-mono text-xs"
/>
</Field>
<Field>
<FieldLabel htmlFor="products">Products (only these)</FieldLabel>
<Textarea
id="products"
name="products"
rows={2}
placeholder="IMVU product IDs or shop links"
className="font-mono text-xs"
/>
</Field>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" name="listed" defaultChecked />
Listed (shown in search and on your page; unlisted ones work by link)
</label>
<div className="rounded-md border bg-muted/40 p-3 text-sm">
<p>{offered.consent.text}</p>
<label className="mt-3 flex items-center gap-2 font-medium">
<input type="checkbox" name="agree" required />I agree
</label>
</div>
<SubmitButton pendingLabel="Sending…">Send to the catalog</SubmitButton>
</ActionForm>
)}
</CardContent>
</Card>
{asked.some((a) => a.requests.length > 0) && (
<Card>
<CardHeader>
<CardTitle>What People Asked For</CardTitle>
<CardDescription>Your IMVU products that T5DE users would like.</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{asked
.filter((a) => a.requests.length > 0)
.map((a) => (
<div key={a.link.imvuId}>
<p className="mb-2 text-sm font-medium">{a.link.username}</p>
<Table>
<TableHeader>
<TableRow>
<TableHead>Product</TableHead>
<TableHead className="text-right">People</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{a.requests.slice(0, 20).map((r) => (
<TableRow key={r.imvuProduct}>
<TableCell>
{r.imvuProduct === 0 ? (
"Your whole shop"
) : (
<a
href={imvuPage(r.imvuProduct)}
className="underline-offset-4 hover:underline"
target="_blank"
rel="noreferrer"
>
{r.name || r.imvuProduct}
</a>
)}
</TableCell>
<TableCell className="text-right tabular-nums">{r.requests}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
))}
</CardContent>
</Card>
)}
{ended.length > 0 && (
<details className="text-sm">
<summary className="cursor-pointer text-muted-foreground hover:text-foreground">Ended</summary>
<ul className="mt-2 divide-y">
{ended.map((g) => (
<li key={g.id} className="py-2">
{g.imvuName || g.imvuId} → {g.catalogName} <Tag tone={statusTone[g.status]}>{g.status}</Tag>{" "}
<span className="text-muted-foreground">{g.statusReason}</span>
</li>
))}
</ul>
</details>
)}
</div>
);
}
function GrantRow({ grant: g }: { grant: ImportGrant }) {
const list = g.scope === "products" ? g.products : g.exclude;
return (
<div className="space-y-3 border-b pb-6 last:border-b-0 last:pb-0">
<div className="flex flex-wrap items-center gap-2 text-sm">
<span className="font-medium">{g.imvuName || g.imvuId}</span>
<span className="text-muted-foreground">to</span>
<span className="font-medium">{g.catalogName}</span>
<Tag tone={statusTone[g.status]}>{g.status === "pending" ? "waiting for the catalog" : g.status}</Tag>
<span className="text-xs text-muted-foreground">
since <DateTime iso={g.createdAt} dateOnly />
</span>
</div>
{g.statusReason && <p className="text-sm text-muted-foreground">{g.statusReason}</p>}
<p className="text-sm">
{g.scope === "shop"
? `Your whole shop${g.exclude.length ? `, less ${g.exclude.length} left out` : ""}.`
: `${g.products.length} chosen product${g.products.length === 1 ? "" : "s"}.`}{" "}
{g.listed ? "Listed." : "Unlisted."}
</p>
{g.status === "suspended" ? (
<p className="text-sm text-muted-foreground">Withdraw it, then bring your products again to start over.</p>
) : null}
<ActionForm action={changeGrant} fields={{ id: g.id, scope: g.scope }} className="max-w-2xl space-y-2">
{g.status !== "suspended" && (
<>
<Field>
<FieldLabel htmlFor={`list-${g.id}`}>{g.scope === "shop" ? "Left out" : "Products"}</FieldLabel>
<Textarea
id={`list-${g.id}`}
name="list"
rows={2}
defaultValue={list.join("\n")}
className="font-mono text-xs"
/>
<FieldDescription>
{g.scope === "shop"
? "Products left out that were imported are taken away from everyone."
: "Products taken off the list that were imported are taken away from everyone."}
</FieldDescription>
</Field>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" name="listed" defaultChecked={g.listed} />
Listed
</label>
</>
)}
<div className="flex flex-wrap gap-2">
{g.status !== "suspended" && (
<SubmitButton name="intent" value="save" variant="outline" pendingLabel="Saving…">
Save
</SubmitButton>
)}
<SubmitButton
name="intent"
value="withdraw"
variant="outline"
pendingLabel="Withdrawing…"
confirm="Withdraw? Your imported products are taken away from everyone who has them."
>
Withdraw
</SubmitButton>
</div>
</ActionForm>
</div>
);
}