feat: IMVU imports on the hub: grants, requests and the importer's job queue
Pull request / title (pull_request) Successful in 1s
CI / test (pull_request) Successful in 1m15s
CI / image (apps/api/Dockerfile, t5de-hub-api) (pull_request) Skipped
CI / image (apps/web/Dockerfile, t5de-hub-web) (pull_request) Skipped

Creators grant a catalog leave to import their IMVU products (whole shop less
exclusions, or listed products) from a linked IMVU account, agreeing to a versioned
consent text; the catalog's team accepts or declines. Requests queue covered
products (or add them to the library when imported already), suggest, or count.
Importers claim jobs with the catalog's importer key, get t5de-import tokens, and
the catalog registers imported revisions as published products owned by the creator.
Narrowing or withdrawing a grant withdraws products; unlinking suspends grants;
an hourly batch rechecks imported products with IMVU daily. Website: /imports and
the console's catalog imports page.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
dhkatzandClaude Opus 5.5 committed 2026-11-05 19:46:10 -08:00
1 parent eca1884918
commit 7d708aebdb
24 files changed
+6521 -153

No files matched your search

+7
View File
@@ -89,6 +89,13 @@ export default async function Account({ searchParams }: { searchParams: Promise<
Other people can&apos;t see which IMVU accounts are yours. Adult IMVU accounts can see adult community
products: those IMVU has age verified (or with Access Pass), or all of them once you verify your age below.
</p>
<p className="text-sm text-muted-foreground">
Made products on IMVU?{" "}
<Link href="/imports" className="text-foreground underline underline-offset-4">
Bring them to T5DE
</Link>
.
</p>
</CardContent>
</Card>
+23 -82
View File
@@ -9,13 +9,7 @@ import { ErrorText } from "@/components/forms";
import { Tag } from "@/components/status";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { authClient } from "@/lib/auth-client";
@@ -25,13 +19,7 @@ type Stage =
| { kind: "setup"; uri: string; codes: string[] }
| { kind: "codes"; codes: string[] };
export function TwoFactorCard({
enabled,
neededFor,
}: {
enabled: boolean;
neededFor: string[];
}) {
export function TwoFactorCard({ enabled, neededFor }: { enabled: boolean; neededFor: string[] }) {
const router = useRouter();
const [stage, setStage] = useState<Stage>({ kind: "idle" });
const [error, setError] = useState("");
@@ -45,10 +33,7 @@ export function TwoFactorCard({
setPending(false);
}
async function withPassword(
then: "enable" | "codes" | "disable",
password: string,
) {
async function withPassword(then: "enable" | "codes" | "disable", password: string) {
if (then === "enable") {
const { data, error } = await authClient.twoFactor.enable({ password });
if (error || !data || !("totpURI" in data) || !data.totpURI)
@@ -62,8 +47,7 @@ export function TwoFactorCard({
const { data, error } = await authClient.twoFactor.generateBackupCodes({
password,
});
if (error || !data)
return error?.message ?? "That didn't work. Try again.";
if (error || !data) return error?.message ?? "That didn't work. Try again.";
setStage({ kind: "codes", codes: data.backupCodes });
} else {
const { error } = await authClient.twoFactor.disable({ password });
@@ -82,13 +66,11 @@ export function TwoFactorCard({
router.refresh();
}
const submitTo =
(fn: (form: FormData) => Promise<string | void>) =>
(e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const form = new FormData(e.currentTarget);
void run(() => fn(form));
};
const submitTo = (fn: (form: FormData) => Promise<string | void>) => (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const form = new FormData(e.currentTarget);
void run(() => fn(form));
};
return (
<Card>
@@ -97,8 +79,7 @@ export function TwoFactorCard({
Two-Factor Sign-In {enabled && <Tag tone="strong">on</Tag>}
</CardTitle>
<CardDescription>
Signing in asks for a code from an authenticator app on your phone as
well as your password.
Signing in asks for a code from an authenticator app on your phone as well as your password.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
@@ -123,34 +104,19 @@ export function TwoFactorCard({
{stage.kind === "idle" &&
(enabled ? (
<div className="flex flex-wrap gap-2">
<Button
variant="outline"
onClick={() => setStage({ kind: "password", then: "codes" })}
>
<Button variant="outline" onClick={() => setStage({ kind: "password", then: "codes" })}>
New backup codes
</Button>
<Button
variant="outline"
onClick={() => setStage({ kind: "password", then: "disable" })}
>
<Button variant="outline" onClick={() => setStage({ kind: "password", then: "disable" })}>
Turn off
</Button>
</div>
) : (
<Button
onClick={() => setStage({ kind: "password", then: "enable" })}
>
Turn on
</Button>
<Button onClick={() => setStage({ kind: "password", then: "enable" })}>Turn on</Button>
))}
{stage.kind === "password" && (
<form
onSubmit={submitTo((f) =>
withPassword(stage.then, String(f.get("password"))),
)}
className="space-y-3"
>
<form onSubmit={submitTo((f) => withPassword(stage.then, String(f.get("password"))))} className="space-y-3">
<p className="text-sm">
{stage.then === "disable"
? neededFor.length > 0
@@ -170,22 +136,10 @@ export function TwoFactorCard({
aria-label="Password"
className="max-w-xs"
/>
<Button
type="submit"
variant={stage.then === "disable" ? "destructive" : "default"}
disabled={pending}
>
{pending
? "Checking…"
: stage.then === "disable"
? "Turn off"
: "Continue"}
<Button type="submit" variant={stage.then === "disable" ? "destructive" : "default"} disabled={pending}>
{pending ? "Checking…" : stage.then === "disable" ? "Turn off" : "Continue"}
</Button>
<Button
type="button"
variant="ghost"
onClick={() => setStage({ kind: "idle" })}
>
<Button type="button" variant="ghost" onClick={() => setStage({ kind: "idle" })}>
Cancel
</Button>
</div>
@@ -197,8 +151,8 @@ export function TwoFactorCard({
<ol className="list-decimal space-y-4 pl-5 text-sm">
<li className="space-y-2">
<p>
Scan this with an authenticator app (such as Google
Authenticator, Microsoft Authenticator or 1Password).
Scan this with an authenticator app (such as Google Authenticator, Microsoft Authenticator or
1Password).
</p>
<div
className="w-44 rounded-md bg-white p-2 [&>svg]:h-auto [&>svg]:w-full"
@@ -216,10 +170,7 @@ export function TwoFactorCard({
</p>
</li>
<li className="space-y-2">
<p>
Keep these backup codes somewhere safe. Each signs you in once
if you lose your phone.
</p>
<p>Keep these backup codes somewhere safe. Each signs you in once if you lose your phone.</p>
<BackupCodes codes={stage.codes} />
</li>
<li className="space-y-2">
@@ -242,11 +193,7 @@ export function TwoFactorCard({
<Button type="submit" disabled={pending}>
{pending ? "Checking…" : "Turn on"}
</Button>
<Button
type="button"
variant="ghost"
onClick={() => setStage({ kind: "idle" })}
>
<Button type="button" variant="ghost" onClick={() => setStage({ kind: "idle" })}>
Cancel
</Button>
</form>
@@ -257,15 +204,9 @@ export function TwoFactorCard({
{stage.kind === "codes" && (
<div className="space-y-2 text-sm">
<p>
Your new backup codes. Keep them somewhere safe: they won&apos;t
be shown again.
</p>
<p>Your new backup codes. Keep them somewhere safe: they won&apos;t be shown again.</p>
<BackupCodes codes={stage.codes} />
<Button
variant="outline"
onClick={() => setStage({ kind: "idle" })}
>
<Button variant="outline" onClick={() => setStage({ kind: "idle" })}>
Done
</Button>
</div>
@@ -0,0 +1,305 @@
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } 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 { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { api, unwrap, type ImportGrant } from "@/lib/api";
import { ConsoleNav, requireConsole } from "../../../console-nav";
import { decideGrant, retryJob, setImporter } from "../../actions";
export const metadata: Metadata = { title: "Imports" };
const statuses = ["queued", "claimed", "failed", "done"] as const;
const grantTone = {
pending: "strong",
active: "online",
declined: "neutral",
suspended: "danger",
withdrawn: "neutral",
} as const;
const jobTone = {
queued: "neutral",
claimed: "strong",
failed: "danger",
done: "online",
} as const;
const imvuPage = (id: number) => `https://www.imvu.com/shop/product.php?products_id=${id}`;
export default async function CatalogImports({
params,
searchParams,
}: {
params: Promise<{ id: string }>;
searchParams: Promise<{ status?: string }>;
}) {
const { id } = await params;
await requireConsole(`/console/catalogs/${id}/imports`);
const wanted = (await searchParams).status;
const status = statuses.find((s) => s === wanted);
const [catalogAnswer, answer] = await Promise.all([
api.catalogs({ id }).get(),
api.catalogs({ id }).importer.get({ query: status ? { status } : {} }),
]);
if (catalogAnswer.error || answer.error) notFound();
const c = unwrap(catalogAnswer).catalog;
const data = unwrap(answer);
const can = data.permissions;
const pending = data.grants.filter((g) => g.status === "pending");
const others = data.grants.filter((g) => g.status !== "pending");
return (
<>
<PageHeader title={`${c.name}: Imports`}>
<Link href={`/console/catalogs/${id}`} className="underline-offset-4 hover:underline">
Back to the catalog
</Link>
</PageHeader>
<ConsoleNav />
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
Importer{" "}
<Tag tone={data.importer === "on" ? "online" : data.importer === "paused" ? "strong" : "neutral"}>
{data.importer}
</Tag>
</CardTitle>
<CardDescription>
{data.importer === "off"
? "With imports on, creators can bring their IMVU products here, and your importer (t5de-importer, run beside the catalog) imports what they allow."
: `The importer signs in with the catalog's ID (${id}) and its importer key. ${data.counts.queued} queued, ${data.counts.claimed} working, ${data.counts.failed} failed, ${data.counts.done} done.`}
</CardDescription>
</CardHeader>
{(can.run || can.pause) && (
<CardContent>
<ActionForm action={setImporter} fields={{ id }}>
<div className="flex flex-wrap gap-2">
{data.importer === "off" ? (
can.run && (
<SubmitButton name="intent" value="on" pendingLabel="Turning on…">
Turn imports on
</SubmitButton>
)
) : (
<>
{can.pause &&
(data.importer === "paused" ? (
<SubmitButton name="intent" value="resume" pendingLabel="Resuming…">
Resume
</SubmitButton>
) : (
<SubmitButton name="intent" value="pause" variant="outline" pendingLabel="Pausing…">
Pause
</SubmitButton>
))}
{can.run && (
<SubmitButton
name="intent"
value="key"
variant="outline"
pendingLabel="Making one…"
confirm="The old importer key stops working at once. Go on?"
>
New key
</SubmitButton>
)}
{can.run && (
<SubmitButton
name="intent"
value="off"
variant="outline"
pendingLabel="Turning off…"
confirm="Turn imports off? No new grants, and the importer stops. What's imported stays."
>
Turn off
</SubmitButton>
)}
</>
)}
</div>
</ActionForm>
</CardContent>
)}
</Card>
{pending.length > 0 && (
<Card>
<CardHeader>
<CardTitle>Waiting for You</CardTitle>
<CardDescription>
Creators asking this catalog to host their IMVU products. Nothing is imported until you accept.
</CardDescription>
</CardHeader>
<CardContent className="divide-y">
{pending.map((g) => (
<GrantRow key={g.id} id={id} grant={g} accept={can.accept} withdraw={can.withdraw} />
))}
</CardContent>
</Card>
)}
{others.length > 0 && (
<Card>
<CardHeader>
<CardTitle>Grants</CardTitle>
</CardHeader>
<CardContent className="divide-y">
{others.map((g) => (
<GrantRow key={g.id} id={id} grant={g} accept={can.accept} withdraw={can.withdraw} />
))}
</CardContent>
</Card>
)}
<Card>
<CardHeader>
<CardTitle>Queue</CardTitle>
<CardDescription className="flex flex-wrap gap-3">
{[undefined, ...statuses].map((s) => (
<Link
key={s ?? "all"}
href={`/console/catalogs/${id}/imports${s ? `?status=${s}` : ""}`}
className={s === status ? "font-medium text-foreground" : "underline-offset-4 hover:underline"}
>
{s ?? "all"}
</Link>
))}
</CardDescription>
</CardHeader>
<CardContent>
{data.jobs.length === 0 ? (
<p className="text-sm text-muted-foreground">Nothing here.</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>IMVU product</TableHead>
<TableHead>Job</TableHead>
<TableHead>Status</TableHead>
<TableHead>Updated</TableHead>
<TableHead />
</TableRow>
</TableHeader>
<TableBody>
{data.jobs.map((j) => (
<TableRow key={j.id}>
<TableCell>
<a
href={imvuPage(j.imvuProduct)}
target="_blank"
rel="noreferrer"
className="underline-offset-4 hover:underline"
>
{j.name || j.imvuProduct}
</a>
</TableCell>
<TableCell className="text-muted-foreground">
{j.kind}
{j.imvuRevision ? ` · revision ${j.imvuRevision}` : ""}
</TableCell>
<TableCell className="whitespace-normal">
<Tag tone={jobTone[j.status]}>{j.status}</Tag>
{j.reason && j.reason !== "unchanged" && (
<span className="ml-2 text-xs text-muted-foreground">
{j.reason}
{j.attempts > 0 && ` (attempt ${j.attempts})`}
</span>
)}
</TableCell>
<TableCell className="text-muted-foreground">
<DateTime iso={j.updatedAt} />
</TableCell>
<TableCell className="text-right">
{can.run && (j.status === "failed" || j.status === "done") && (
<ActionForm action={retryJob} fields={{ id, job: j.id }}>
<SubmitButton size="sm" variant="outline" pendingLabel="Queuing…">
{j.status === "failed" ? "Retry" : "Again"}
</SubmitButton>
</ActionForm>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
</div>
</>
);
}
function GrantRow({
id,
grant: g,
accept,
withdraw,
}: {
id: string;
grant: ImportGrant;
accept: boolean;
withdraw: boolean;
}) {
const open = g.status === "pending" || g.status === "active" || g.status === "suspended";
return (
<div className="space-y-2 py-4 first:pt-0 last:pb-0">
<div className="flex flex-wrap items-center gap-2 text-sm">
<span className="font-medium">{g.imvuName || `IMVU account ${g.imvuId}`}</span>
<span className="text-muted-foreground">(IMVU {g.imvuId})</span>
<Tag tone={grantTone[g.status]}>{g.status}</Tag>
{g.consentKind === "recorded" && <Tag>consent recorded by an admin</Tag>}
<span className="text-xs text-muted-foreground">
<DateTime iso={g.createdAt} dateOnly />
</span>
</div>
<p className="text-sm">
{g.scope === "shop"
? `The whole shop${g.exclude.length ? `, less ${g.exclude.length} left out` : ""}.`
: `${g.products.length} chosen product${g.products.length === 1 ? "" : "s"}: ${g.products.slice(0, 10).join(", ")}${g.products.length > 10 ? "…" : ""}.`}{" "}
{g.listed ? "Listed." : "Unlisted."}
</p>
{g.statusReason && <p className="text-sm text-muted-foreground">{g.statusReason}</p>}
{open && (accept || withdraw) && (
<ActionForm action={decideGrant} fields={{ id, grant: g.id }}>
<div className="flex max-w-2xl flex-wrap gap-2">
{(g.status === "pending" || withdraw) && (
<Input
name="reason"
maxLength={500}
placeholder={g.status === "pending" ? "Reason (if declining)" : "Reason (if ending)"}
aria-label="Reason"
className="min-w-56 flex-1"
/>
)}
{g.status === "pending" && accept && (
<>
<SubmitButton name="intent" value="accept" pendingLabel="Accepting…">
Accept
</SubmitButton>
<SubmitButton name="intent" value="decline" variant="outline" pendingLabel="Declining…">
Decline
</SubmitButton>
</>
)}
{g.status !== "pending" && withdraw && (
<SubmitButton
name="intent"
value="end"
variant="outline"
pendingLabel="Ending…"
confirm="End this grant? Its imported products are taken away from everyone who has them."
>
End
</SubmitButton>
)}
</div>
</ActionForm>
)}
</div>
);
}
@@ -162,6 +162,24 @@ export default async function ManageCatalog({ params }: { params: Promise<{ id:
</CardContent>
</Card>
{(has("import:accept") || has("import:pause")) && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
Imports <Tag tone={c.importer === "on" ? "online" : "neutral"}>{c.importer}</Tag>
</CardTitle>
<CardDescription>
Creators&apos; IMVU products, imported with their permission: grants, the importer and its queue.
</CardDescription>
</CardHeader>
<CardContent>
<Link href={`/console/catalogs/${id}/imports`} className="text-sm underline underline-offset-4">
Manage imports
</Link>
</CardContent>
</Card>
)}
{has("catalog:rotate-key") && (
<Card>
<CardHeader>
+53
View File
@@ -120,3 +120,56 @@ export async function membership(_: ActionState, form: FormData): Promise<Action
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.";
});
}
+4 -20
View File
@@ -3,14 +3,7 @@ import { notFound, redirect } from "next/navigation";
import { cache } from "react";
import { NavLink } from "@/components/header-client";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import {
api,
getMe,
isModerator,
unwrap,
type ConsoleData,
type Person,
} from "@/lib/api";
import { api, getMe, isModerator, unwrap, type ConsoleData, type Person } from "@/lib/api";
/** The signed-in moderator, or off to sign in; others get not found (these pages aren't for them). */
export async function requireModerator(path: string): Promise<Person> {
@@ -31,9 +24,7 @@ const loadConsole = cache(async (): Promise<ConsoleData | undefined> => {
* The signed-in person and their console, or off to sign in. People who manage nothing get not found: the console
* is for those controlling a product, catalog or room.
*/
export async function requireConsole(
path: string,
): Promise<{ me: Person; console: ConsoleData }> {
export async function requireConsole(path: string): Promise<{ me: Person; console: ConsoleData }> {
const me = await getMe();
if (!me) redirect(`/signin?next=${encodeURIComponent(path)}`);
const data = await loadConsole();
@@ -67,10 +58,7 @@ export async function ConsoleNav() {
<AlertDescription>
<span>
Some of what you can do here needs it ({needed.join(", ")}).{" "}
<Link
href="/account"
className="text-foreground underline underline-offset-4"
>
<Link href="/account" className="text-foreground underline underline-offset-4">
Turn it on in your account
</Link>
.
@@ -82,11 +70,7 @@ export async function ConsoleNav() {
{tabs
.filter((t) => sections.has(t.section))
.map((t) => (
<NavLink
key={t.section}
href={t.href}
exact={t.section === "overview"}
>
<NavLink key={t.section} href={t.href} exact={t.section === "overview"}>
{t.label}
</NavLink>
))}
+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>
);
}
+10
View File
@@ -111,6 +111,16 @@ function describe(n: NotificationEntry): { text: string; href?: string } {
: `${s("name")} declined your request to join`;
return { text, href: `/catalogs/${s("catalog")}` };
}
case "import_grant_decided":
return {
text:
s("decision") === "accept"
? `${s("name")} accepted importing your IMVU products`
: `${s("name")} declined importing your IMVU products${why}`,
href: "/imports",
};
case "import_grant_ended":
return { text: `${s("name")} stopped importing your IMVU products${why}`, href: "/imports" };
default:
return { text: n.type };
}
+7 -30
View File
@@ -4,12 +4,7 @@ import { useRouter } from "next/navigation";
import { useState } from "react";
import { ErrorText } from "@/components/forms";
import { Button } from "@/components/ui/button";
import {
Field,
FieldDescription,
FieldGroup,
FieldLabel,
} from "@/components/ui/field";
import { Field, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { authClient } from "@/lib/auth-client";
@@ -33,8 +28,7 @@ export function SignInForm({ next }: { next: string }) {
password: String(form.get("password")),
});
if (error) return setError(error.message ?? "That didn't work. Try again.");
if (data && "twoFactorRedirect" in data && data.twoFactorRedirect)
return setStep("code");
if (data && "twoFactorRedirect" in data && data.twoFactorRedirect) return setStep("code");
done();
}
@@ -44,8 +38,7 @@ export function SignInForm({ next }: { next: string }) {
step === "code"
? await authClient.twoFactor.verifyTotp({ code })
: await authClient.twoFactor.verifyBackupCode({ code });
if (error)
return setError(error.message ?? "That code didn't work. Try again.");
if (error) return setError(error.message ?? "That code didn't work. Try again.");
done();
}
@@ -67,23 +60,11 @@ export function SignInForm({ next }: { next: string }) {
<FieldGroup>
<Field>
<FieldLabel htmlFor="username">Username</FieldLabel>
<Input
id="username"
name="username"
autoComplete="username"
required
autoFocus
/>
<Input id="username" name="username" autoComplete="username" required autoFocus />
</Field>
<Field>
<FieldLabel htmlFor="password">Password</FieldLabel>
<Input
id="password"
name="password"
type="password"
autoComplete="current-password"
required
/>
<Input id="password" name="password" type="password" autoComplete="current-password" required />
</Field>
{error && <ErrorText>{error}</ErrorText>}
<Field>
@@ -99,9 +80,7 @@ export function SignInForm({ next }: { next: string }) {
<FieldGroup key={step}>
<Field>
<FieldLabel htmlFor="code">
{step === "code"
? "Code from your authenticator app"
: "Backup code"}
{step === "code" ? "Code from your authenticator app" : "Backup code"}
</FieldLabel>
<Input
id="code"
@@ -133,9 +112,7 @@ export function SignInForm({ next }: { next: string }) {
setStep(step === "code" ? "backup" : "code");
}}
>
{step === "code"
? "Use a backup code instead"
: "Use your authenticator app instead"}
{step === "code" ? "Use a backup code instead" : "Use your authenticator app instead"}
</button>
</FieldDescription>
</Field>
+4
View File
@@ -48,6 +48,10 @@ export type TokenList = Data<V1["account"]["tokens"]["get"]>;
export type TokenEntry = TokenList["tokens"][number];
export type TokenScope = TokenList["scopes"][number];
export type CatalogPage = Data<ReturnType<V1["catalogs"]>["get"]>;
export type ImportCatalogs = Data<V1["imports"]["catalogs"]["get"]>;
export type ImportGrant = Data<V1["imports"]["grants"]["get"]>["grants"][number];
export type ImporterPage = Data<ReturnType<V1["catalogs"]>["importer"]["get"]>;
export type ImportJob = ImporterPage["jobs"][number];
export type CatalogMember = Data<ReturnType<V1["catalogs"]>["members"]["get"]>["members"][number];
export type CatalogInvite = Data<ReturnType<V1["catalogs"]>["invites"]["get"]>["invites"][number];
export type HostedProduct = Data<ReturnType<V1["catalogs"]>["products"]["get"]>["products"][number];