feat: whole shops listed on IMVU, and GET /imports/available
Pull request / title (pull_request) Successful in 1s
CI / test (pull_request) Successful in 1m22s
CI / image (apps/api/Dockerfile, t5de-hub-api) (pull_request) Skipped
CI / image (apps/web/Dockerfile, t5de-hub-web) (pull_request) Skipped

Whole-shop grants now import the shop's products, not only those people asked for. The hub lists the shop on
IMVU's public API (general-rated products) when the grant is accepted, daily after, and on "List the shop again".
Each listing keeps the products' info and queues what isn't imported yet, less exclusions. IMVU's small pages
overlap and miss products, so the hub asks for pages of 1000 and drops repeats.

GET /imports/available tells the proxy what T5DE has of IMVU products and shops, from what the hub knows only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
dhkatzandClaude Opus 5.5 committed 2026-11-07 15:16:33 -08:00
1 parent 8f6dacba10
commit b4eed85bd6
15 files changed
+4954 -20

No files matched your search

+36
View File
@@ -403,6 +403,9 @@ export function createApp({
consentKind: r.grant.consentKind as "verified" | "recorded",
consentProven: r.grant.proofCheckedAt !== null, // recorded, and the creator put the code in their tagline
consentVersion: r.grant.consentVersion,
// A whole shop: when the hub last listed its products on IMVU (null: not yet), and how many IMVU listed.
shopListedAt: r.grant.shopListedAt?.toISOString() ?? null,
shopListed: r.grant.shopListed,
status: r.grant.status as "pending" | "active" | "declined" | "suspended" | "withdrawn",
statusReason: r.grant.statusReason,
createdAt: r.grant.createdAt.toISOString(),
@@ -2103,6 +2106,7 @@ export function createApp({
await need(me, "import:grant-on-behalf", hubScope);
}
const { grant, withdrawn } = await productCall(() => imports.updateGrant(g.id, body));
if (grant.status === "active" && grant.scope === "shop" && !grant.shopListedAt) imports.listShopSoon(grant.id);
await audited(
me,
"import.grant_change",
@@ -2130,6 +2134,7 @@ export function createApp({
const decision = params.decision;
const reason = body?.reason?.trim() ?? "";
const done = await productCall(() => imports.decide(g.id, decision, me.id, reason));
if (done.grant.status === "active" && done.grant.scope === "shop") imports.listShopSoon(g.id);
await audited(
me,
`import.grant_${decision}`,
@@ -2173,6 +2178,37 @@ export function createApp({
},
{ signedIn: true, body: t.Optional(t.Object({ reason: t.Optional(t.String({ maxLength: 500 })) })) },
)
.post(
"/imports/grants/:id/list",
async ({ me, params }) => {
const g = await productCall(() => imports.grant(params.id));
if (g.creatorId !== me.id) await need(me, "import:run", catalogScope(g.catalogId));
if (g.status !== "active" || g.scope !== "shop") throw new Problem(409, "not_shop", "Only an active grant of a whole shop is listed.");
// A listing is a few large IMVU calls.
if (!limiter.allow(`shop-list:${g.id}`, 3, 60 * 60 * 1000)) throw new Problem(429, "rate_limited", "Listed recently. Try again in a while.");
const done = await productCall(() => imvuSafe(() => imports.listShop(g.id)));
return { grant: grantView({ grant: await imports.grant(g.id) }), ...done };
},
{ signedIn: true },
)
// What T5DE has of IMVU products and shops (for the proxy's "Get on T5DE" in IMVU's shop). Anyone; signed in, it
// also says what the person asked for, and adult products show only to adult accounts.
.get(
"/imports/available",
async ({ person, query }) => {
const list = (v?: string) => {
const ids = (v ?? "").split(",").filter(Boolean).map(Number);
if (ids.length > 100 || ids.some((n) => !Number.isSafeInteger(n) || n <= 0))
throw new Problem(400, "invalid", "Give up to 100 IMVU IDs, separated by commas.");
return ids;
};
const products = list(query.products);
const creators = list(query.creators);
const viewer = person ? { id: person.id, adult: await personAdult(person) } : undefined;
return imports.available(products, creators, viewer);
},
{ query: t.Object({ products: t.Optional(t.String({ maxLength: 2000 })), creators: t.Optional(t.String({ maxLength: 2000 })) }) },
)
.post(
"/imports/requests",
async ({ me, body }) => {
+208 -10
View File
@@ -3,7 +3,7 @@
// registers the revisions as an ordinary product owned by the creator. The routes are in app.ts.
import { createHash, timingSafeEqual } from "node:crypto";
import { and, asc, desc, eq, inArray, lt, ne, sql, schema, type Database, type FileEntry } from "@t5de/db";
import { ImvuUnavailable, type ImvuClient, type ImvuUser } from "./imvu";
import { ImvuUnavailable, NoSuchImvuUser, type ImvuClient, type ImvuUser } from "./imvu";
import type { Signer } from "./keys";
import { BlockedUpload, checkFiles, newProductID, ProductError, type Catalog } from "./products";
@@ -35,6 +35,8 @@ const backoff = [60_000, 600_000, 3_600_000, 86_400_000];
const maxAttempts = 5;
/** IMVU product info is looked up again after this long. */
const infoFresh = 24 * 60 * 60 * 1000;
// Whole-shop grants' products are listed on IMVU again daily.
const shopFresh = 24 * 60 * 60 * 1000;
const sha256 = (s: string) => createHash("sha256").update(s).digest("hex");
const randomKey = () => Buffer.from(crypto.getRandomValues(new Uint8Array(24))).toString("base64url");
@@ -474,15 +476,24 @@ export class Imports {
});
}
/** Queues imports for what an active grant covers and isn't imported in its catalog yet: a grant's listed products,
* and the creator's products people asked for. */
/** Queues imports for what an active grant covers and isn't imported in its catalog yet: a grant's listed products;
* for a whole shop, the creator's products the hub knows of (from its listing on IMVU, and those people asked for). */
private async queueCovered(g: Grant): Promise<number> {
const asked = await this.db
.selectDistinct({ id: importRequest.imvuProduct })
.from(importRequest)
.where(and(eq(importRequest.imvuCreator, g.imvuId), ne(importRequest.imvuProduct, 0)));
const wanted = new Set<number>(g.scope === "products" ? g.products : asked.map((a) => a.id).filter((id) => !g.exclude.includes(id)));
if (g.scope === "products") for (const a of asked) if (g.products.includes(a.id)) wanted.add(a.id);
let wanted: Set<number>;
if (g.scope === "products") wanted = new Set(g.products);
else {
const [asked, known] = await Promise.all([
this.db
.selectDistinct({ id: importRequest.imvuProduct })
.from(importRequest)
.where(and(eq(importRequest.imvuCreator, g.imvuId), ne(importRequest.imvuProduct, 0))),
this.db
.select({ id: imvuProductInfo.id })
.from(imvuProductInfo)
.where(and(eq(imvuProductInfo.creatorId, g.imvuId), eq(imvuProductInfo.found, true))),
]);
wanted = new Set([...asked, ...known].map((r) => r.id).filter((id) => !g.exclude.includes(id)));
}
if (wanted.size === 0) return 0;
const done = await this.db
.select({ imvuProduct: product.imvuProduct })
@@ -490,11 +501,114 @@ export class Imports {
.innerJoin(hosting, and(eq(hosting.productId, product.id), eq(hosting.catalogId, g.catalogId)))
.where(inArray(product.imvuProduct, [...wanted]));
for (const d of done) wanted.delete(d.imvuProduct!);
const ids = [...wanted];
let n = 0;
for (const id of wanted) if (await this.queue(g, id, "import")) n++;
for (let i = 0; i < ids.length; i += 500) {
const made = await this.db
.insert(importJob)
.values(ids.slice(i, i + 500).map((imvuProduct) => ({ id: newProductID(), catalogId: g.catalogId, grantId: g.id, imvuProduct, kind: "import" })))
.onConflictDoNothing()
.returning({ id: importJob.id });
n += made.length;
}
return n;
}
// ---- whole shops ----
private listing: Promise<unknown> = Promise.resolve();
/** Lists a whole-shop grant's products on IMVU in the background, one shop at a time. */
listShopSoon(grantId: string) {
this.listing = this.listing.then(() => this.listShop(grantId)).catch((e) => console.error("shop listing:", e));
}
/** Resolves once the background listings started so far are done. */
listingsDone(): Promise<unknown> {
return this.listing;
}
/**
* Lists an active whole-shop grant's products on IMVU (as IMVU lists them signed out: general-rated only), keeps
* their info, and queues imports for those not imported yet. The IMVU account is looked up first: listing goes by
* its current username.
*/
async listShop(grantId: string): Promise<{ listed: number; queued: number }> {
const g = await this.grant(grantId);
if (g.status !== "active" || g.scope !== "shop" || !this.imvu) return { listed: 0, queued: 0 };
let listed: Awaited<ReturnType<ImvuClient["shop"]>>["products"];
try {
const owner = await this.imvu.byId(g.imvuId);
listed = (await this.imvu.shop(owner.username)).products.filter((p) => p.creatorId === g.imvuId);
} catch (e) {
if (!(e instanceof NoSuchImvuUser)) throw e;
listed = []; // the account is gone from IMVU: nothing to list (rechecks withdraw what was imported)
}
const now = new Date();
for (let i = 0; i < listed.length; i += 500) {
const rows = listed.slice(i, i + 500).map((p) => ({
id: p.id,
found: true,
name: p.name,
creatorId: p.creatorId,
creatorName: p.creatorName,
rating: p.adult ? "adult" : "general",
purchasable: p.purchasable,
checkedAt: now,
}));
await this.db
.insert(imvuProductInfo)
.values(rows)
.onConflictDoUpdate({
target: imvuProductInfo.id,
set: {
found: true,
name: sql`excluded.name`,
creatorId: sql`excluded.creator_id`,
creatorName: sql`excluded.creator_name`,
rating: sql`excluded.rating`,
purchasable: sql`excluded.purchasable`,
checkedAt: now,
},
});
}
const [updated] = await this.db
.update(importGrant)
.set({ shopListedAt: now, shopListed: listed.length })
.where(eq(importGrant.id, g.id))
.returning();
const queued = updated?.status === "active" && updated.scope === "shop" ? await this.queueCovered(updated) : 0;
return { listed: listed.length, queued };
}
/** Lists the whole-shop grants not listed in a day, never-listed ones first. */
async listShops(limit = 5): Promise<{ shops: number; queued: number }> {
const due = await this.db
.select({ id: importGrant.id })
.from(importGrant)
.where(
and(
eq(importGrant.status, "active"),
eq(importGrant.scope, "shop"),
sql`(${importGrant.shopListedAt} is null or ${importGrant.shopListedAt} < ${new Date(Date.now() - shopFresh)})`,
),
)
.orderBy(sql`${importGrant.shopListedAt} asc nulls first`)
.limit(limit);
let shops = 0;
let queued = 0;
for (const d of due) {
try {
queued += (await this.listShop(d.id)).queued;
shops++;
} catch (e) {
if (e instanceof ImvuUnavailable) break; // IMVU isn't answering: next time
throw e;
}
}
return { shops, queued };
}
// ---- requests ----
/**
@@ -565,6 +679,90 @@ export class Imports {
.limit(limit);
}
/**
* What T5DE has of IMVU products and shops (the proxy's "Get on T5DE" in IMVU's shop), from what the hub knows
* only: it asks IMVU nothing. Per product: `imported` (with the hub product), `adult` (imported, but the viewer
* can't see adult products), `queued`, `covered` (a grant covers it: asking queues it) or `none` (asking counts
* it); `requested` if the viewer asked for it. Per shop: whether a whole-shop grant is active, and how many of its
* products are on T5DE.
*/
async available(imvuProducts: number[], imvuCreators: number[], viewer?: { id: string; adult: boolean }) {
const ids = [...new Set(imvuProducts)];
const [imported, infos, open, asked] = ids.length
? await Promise.all([
this.db
.select({ id: product.id, imvuProduct: product.imvuProduct, rating: product.rating })
.from(product)
.where(
and(
inArray(product.imvuProduct, ids),
sql`${product.removedAt} is null and ${product.deletedAt} is null`,
eq(product.status, "published"),
sql`${product.latest} > 0`,
),
),
this.db.select().from(imvuProductInfo).where(and(inArray(imvuProductInfo.id, ids), eq(imvuProductInfo.found, true))),
this.db
.selectDistinct({ imvuProduct: importJob.imvuProduct })
.from(importJob)
.where(and(inArray(importJob.imvuProduct, ids), inArray(importJob.status, ["queued", "claimed"]))),
viewer
? this.db
.select({ imvuProduct: importRequest.imvuProduct })
.from(importRequest)
.where(and(eq(importRequest.userId, viewer.id), inArray(importRequest.imvuProduct, ids)))
: Promise.resolve([]),
])
: [[], [], [], []];
const creators = [...new Set([...imvuCreators, ...infos.map((i) => i.creatorId).filter((c) => c > 0)])];
const grants = creators.length
? await this.db
.select()
.from(importGrant)
.where(and(inArray(importGrant.imvuId, creators), eq(importGrant.status, "active")))
: [];
const byProduct = new Map(imported.map((p) => [p.imvuProduct!, p]));
const info = new Map(infos.map((i) => [i.id, i]));
const queued = new Set(open.map((j) => j.imvuProduct));
const requested = new Set(asked.map((r) => r.imvuProduct));
const products = ids.map((id) => {
const p = byProduct.get(id);
const i = info.get(id);
const status: "imported" | "adult" | "queued" | "covered" | "none" = p
? p.rating === "adult" && !viewer?.adult
? "adult"
: "imported"
: queued.has(id)
? "queued"
: i && grants.some((g) => covers(g, id, i.creatorId))
? "covered"
: "none";
return { imvuProduct: id, status, product: status === "imported" ? p!.id : null, ...(viewer ? { requested: requested.has(id) } : {}) };
});
const shopIds = [...new Set(imvuCreators)];
const counts = shopIds.length
? await this.db
.select({ creatorId: imvuProductInfo.creatorId, n: sql<number>`count(distinct ${product.id})::int` })
.from(product)
.innerJoin(imvuProductInfo, eq(imvuProductInfo.id, product.imvuProduct))
.where(
and(
inArray(imvuProductInfo.creatorId, shopIds),
sql`${product.removedAt} is null and ${product.deletedAt} is null`,
eq(product.status, "published"),
sql`${product.latest} > 0`,
),
)
.groupBy(imvuProductInfo.creatorId)
: [];
const shops = shopIds.map((c) => ({
imvuCreator: c,
shop: grants.some((g) => g.imvuId === c && g.scope === "shop"),
products: counts.find((r) => r.creatorId === c)?.n ?? 0,
}));
return { products, shops };
}
/** Puts an imported product in the libraries of those who asked for it. */
private async fulfil(imvuProduct: number, productId: string) {
const waiting = await this.db
+48
View File
@@ -38,6 +38,17 @@ export type ImvuProduct = {
purchasable: boolean; // false once retired
};
/** A shop's products as IMVU lists them to the signed out: general-rated ones only. */
export type ImvuShop = {
products: (ImvuProduct & { id: number })[];
total: number; // IMVU's count; more than products.length if the listing stopped early
};
// IMVU's listing pages overlap when paged in small pages (2026-11-07: 100 a page gave 580 different products of 639),
// but one page of up to 1000 holds them all, so shops are listed in pages of 1000, at most this many.
const shopPage = 1000;
const shopPages = 10;
export class NoSuchImvuUser extends Error {
constructor(readonly status = 404) {
super("no such IMVU account");
@@ -103,6 +114,28 @@ export class ImvuClient {
return parseProduct(answer, id) ?? "missing";
}
/** The products IMVU lists for a shop (by its current username), at most 10,000. */
async shop(username: string): Promise<ImvuShop> {
const name = username.trim();
if (!name || name.length > 64) throw new NoSuchImvuUser();
const seen = new Map<number, ImvuProduct & { id: number }>();
let total = 0;
let path: string | undefined = `/product?creator=${encodeURIComponent(name)}&limit=${shopPage}`;
for (let page = 0; path && page < shopPages; page++) {
const answer = await this.get(path);
const listed = parseShop(answer);
if (!listed) throw new ImvuUnavailable("IMVU's shop listing wasn't understood");
total = Math.max(total, listed.total);
for (const id of listed.items) {
const p = seen.has(id) ? undefined : parseProduct(answer, id);
if (p) seen.set(id, { ...p, id });
}
// Only ever follow IMVU's own API.
path = listed.next?.startsWith(this.base + "/") ? listed.next.slice(this.base.length) : undefined;
}
return { products: [...seen.values()], total };
}
private async wait() {
const now = Date.now();
const at = Math.max(now, this.next);
@@ -168,6 +201,21 @@ export function imvuImage(v: unknown): string | null {
return url.href;
}
/** A shop listing's own entry: its product IDs (in order), IMVU's count and the next page's URL. */
export function parseShop(answer: unknown): { items: number[]; total: number; next?: string } | null {
const a = answer as { id?: unknown; denormalized?: Record<string, { data?: Record<string, unknown>; relations?: Record<string, unknown> }> };
const entry = typeof a?.id === "string" ? a.denormalized?.[a.id] : undefined;
const items = entry?.data?.items;
if (!entry || !Array.isArray(items)) return null;
const ids = items.flatMap((i) => {
const n = typeof i === "string" ? Number(i.match(/\/product\/product-(\d+)$/)?.[1]) : NaN;
return Number.isSafeInteger(n) && n > 0 ? [n] : [];
});
const total = Number(entry.data?.total_count);
const next = entry.relations && !Array.isArray(entry.relations) ? entry.relations.next : undefined;
return { items: ids, total: Number.isSafeInteger(total) && total > 0 ? total : ids.length, next: typeof next === "string" ? next : undefined };
}
export function parseProduct(answer: unknown, id: number): ImvuProduct | null {
const den = (answer as { denormalized?: Record<string, { data?: Record<string, unknown> }> })?.denormalized ?? {};
const entry = Object.entries(den).find(([key]) => key.endsWith(`/product/product-${id}`));
+7
View File
@@ -90,8 +90,15 @@ const importRecheck = () =>
.recheck(200)
.then((r) => (r.queued || r.withdrawn.length) && console.log(`imports: ${r.queued} rechecks queued, ${r.withdrawn.length} withdrawn`))
.catch((e) => console.error("import rechecks:", e));
// Whole-shop grants: their products listed on IMVU daily (new ones queued), a few shops each hour.
const shopListing = () =>
imports
.listShops(5)
.then((r) => r.queued && console.log(`imports: ${r.shops} shops listed, ${r.queued} products queued`))
.catch((e) => console.error("shop listings:", e));
setInterval(() => {
importRecheck();
shopListing();
importers
.expireSealed()
.then((n) => n && console.log(`imports: ${n} sealed importer passwords expired`))
+103 -1
View File
@@ -2,7 +2,7 @@
// accepts; requests queue jobs; the importer claims them, gets a token, uploads, and the catalog registers the
// revision; narrowing or withdrawing a grant withdraws products.
import { afterAll, beforeAll, expect, test } from "bun:test";
import { openDatabase, type Database } from "@t5de/db";
import { eq, openDatabase, schema, type Database } from "@t5de/db";
import { createApp } from "../src/app";
import { createAuth } from "../src/auth";
import { ImvuClient, type ImvuUser } from "../src/imvu";
@@ -14,8 +14,23 @@ const apiURL = "http://api.test";
const accounts = new Map<number, ImvuUser>();
const imvuProducts = new Map<number, Record<string, unknown>>();
const hiddenProducts = new Set<number>(); // answered 401, as IMVU does for Access Pass products
const shops = new Map<string, number[]>(); // IMVU username (lowercase) → the products IMVU lists for it
const fakeIMVU = (async (input: RequestInfo | URL) => {
const url = new URL(String(input));
if (url.pathname === "/product" && url.searchParams.has("creator")) {
// Pages of 2 that overlap by one, as IMVU's small pages do: the client follows `next` and drops repeats.
const creator = url.searchParams.get("creator")!;
const ids = shops.get(creator.toLowerCase()) ?? [];
const offset = Number(url.searchParams.get("offset") ?? 0);
const page = ids.slice(offset, offset + 2);
const self = `http://imvu.test/product?creator=${creator}&offset=${offset}`;
const next = offset + 2 < ids.length ? { next: `http://imvu.test/product?creator=${creator}&offset=${offset + 1}` } : [];
const den: Record<string, unknown> = {
[self]: { data: { items: page.map((id) => `https://api.imvu.com/product/product-${id}`), total_count: ids.length }, relations: next },
};
for (const id of page) den[`https://api.imvu.com/product/product-${id}`] = { data: { product_id: id, ...imvuProducts.get(id) } };
return Response.json({ status: "success", id: self, denormalized: den });
}
const pm = url.pathname.match(/^\/product\/product-(\d+)$/);
if (pm) {
const p = imvuProducts.get(Number(pm[1]));
@@ -141,6 +156,7 @@ test("grants, requests, the importer's jobs, and withdrawal", async () => {
expect((await call(maker, "POST", `/api/v1/imports/grants/${grantID}/accept`)).status).toBe(403);
const accepted = await call(owner, "POST", `/api/v1/imports/grants/${grantID}/accept`);
expect(accepted.json).toMatchObject({ grant: { status: "active" }, queued: 1 });
await imports.listingsDone(); // the shop's listing (IMVU lists nothing for it here)
expect((await call(maker, "GET", "/api/v1/notifications")).json.notifications[0]).toMatchObject({ type: "import_grant_decided" });
// Paused: no jobs handed out.
@@ -398,3 +414,89 @@ test("recorded grants, unclaimed creators, proof, and claiming", async () => {
const actions = (await call(admin, "GET", "/api/v1/console/audit")).json.entries.map((e: any) => e.action);
expect(actions).toEqual(expect.arrayContaining(["import.grant_record", "import.grant_proof", "import.claim"]));
});
test("whole shops listed on IMVU, and what's available", async () => {
const owner = await person("stall");
const keeper = await person("shopkeep", 901);
const fan = await person("browser");
const reg = await call(owner, "POST", "/api/v1/catalogs", { name: "Shop Shelf", url: "https://shops.example.test", contact: "[email protected]", visibility: "public", membership: "open" });
const catalogID = reg.json.catalog.id as string;
const catalogAuth = { Authorization: `Catalog ${catalogID}:${reg.json.key}` };
expect((await call(rootAdmin, "POST", `/api/v1/console/catalogs/${catalogID}/approve`)).status).toBe(200);
const on = await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer`, { enabled: true });
const importer = { Authorization: `Importer ${catalogID}:${on.json.key}` };
const version = (await call(undefined, "GET", "/api/v1/imports/catalogs")).json.consent.version;
for (const [id, name] of [[9301, "Keeper Coat"], [9302, "Keeper Boots"], [9303, "Keeper Scarf"]] as const)
imvuProducts.set(id, { ...imvuProduct(name, 901), creator_name: "shopkeepAv" });
shops.set("shopkeepav", [9301, 9302, 9303, 9100]); // 9100 is another creator's: left out
// Nothing yet.
const none = await call(undefined, "GET", "/api/v1/imports/available?products=9301,9999&creators=901");
expect(none.json).toEqual({
products: [
{ imvuProduct: 9301, status: "none", product: null },
{ imvuProduct: 9999, status: "none", product: null },
],
shops: [{ imvuCreator: 901, shop: false, products: 0 }],
});
expect((await call(undefined, "GET", "/api/v1/imports/available?products=9301,abc")).status).toBe(400);
// Accepting a whole-shop grant lists the shop on IMVU: its products are queued, less those left out.
const made = await call(keeper, "POST", "/api/v1/imports/grants", { catalog: catalogID, imvuId: 901, scope: "shop", exclude: [9303], consentVersion: version });
expect(made.json.grant).toMatchObject({ shopListedAt: null, shopListed: 0 });
const grantID = made.json.grant.id as string;
expect((await call(owner, "POST", `/api/v1/imports/grants/${grantID}/accept`)).json.queued).toBe(0);
await imports.listingsDone();
const view = (await call(owner, "GET", `/api/v1/catalogs/${catalogID}/importer`)).json;
expect(view.grants[0]).toMatchObject({ shopListed: 3, shopListedAt: expect.any(String) });
expect(view.jobs.map((j: any) => j.imvuProduct).sort()).toEqual([9301, 9302]);
expect(await imports.info(9302)).toMatchObject({ found: true, name: "Keeper Boots", creatorId: 901 });
// Queued, covered, left out; the fan's own request shows.
expect((await call(fan, "POST", "/api/v1/imports/requests", { imvuProduct: 9302 })).json).toEqual({ status: "queued" });
const queued = await call(fan, "GET", "/api/v1/imports/available?products=9301,9302,9303&creators=901");
expect(queued.json.products).toEqual([
{ imvuProduct: 9301, status: "queued", product: null, requested: false },
{ imvuProduct: 9302, status: "queued", product: null, requested: true },
{ imvuProduct: 9303, status: "none", product: null, requested: false },
]);
expect(queued.json.shops).toEqual([{ imvuCreator: 901, shop: true, products: 0 }]);
// Imported: the hub product; an adult one only for adult accounts.
const jobs = (await call(undefined, "POST", "/api/v1/importer/jobs/claim", { limit: 5 }, importer)).json.jobs;
const imported: Record<number, string> = {};
for (const j of jobs) {
const tok = await call(undefined, "POST", `/api/v1/importer/jobs/${j.id}/token`, { imvuRevision: 1 }, importer);
const rating = j.imvuProduct === 9302 ? "adult" : "general";
const files = [file("index.xml", j.imvuProduct)];
const r = await call(undefined, "POST", "/api/v1/catalog/revisions", { importToken: tok.json.token, files, rating, parent: 0, name: "x" }, catalogAuth);
expect(r.status).toBe(201);
imported[j.imvuProduct] = r.json.product;
}
const done = await call(undefined, "GET", "/api/v1/imports/available?products=9301,9302&creators=901");
expect(done.json).toEqual({
products: [
{ imvuProduct: 9301, status: "imported", product: imported[9301] },
{ imvuProduct: 9302, status: "adult", product: null },
],
shops: [{ imvuCreator: 901, shop: true, products: 2 }],
});
// A new product on IMVU: listed again (by the team, or daily), it's queued.
imvuProducts.set(9304, { ...imvuProduct("Keeper Gloves", 901), creator_name: "shopkeepAv" });
shops.set("shopkeepav", [9301, 9302, 9303, 9304]);
expect((await call(fan, "POST", `/api/v1/imports/grants/${grantID}/list`)).status).toBe(403);
const again = await call(owner, "POST", `/api/v1/imports/grants/${grantID}/list`);
expect(again.json).toMatchObject({ listed: 4, queued: 1, grant: { shopListed: 4 } });
imvuProducts.set(9305, { ...imvuProduct("Keeper Belt", 901), creator_name: "shopkeepAv" });
shops.set("shopkeepav", [9301, 9302, 9303, 9304, 9305]);
expect(await imports.listShops()).toEqual({ shops: 0, queued: 0 }); // listed within a day
await db.update(schema.importGrant).set({ shopListedAt: new Date(Date.now() - 2 * 86_400_000) }).where(eq(schema.importGrant.id, grantID));
expect(await imports.listShops()).toEqual({ shops: 1, queued: 1 });
// Grants of chosen products aren't listed.
const chooser = await person("chooser", 902);
const g2 = await call(chooser, "POST", "/api/v1/imports/grants", { catalog: catalogID, imvuId: 902, scope: "products", products: [9401], consentVersion: version });
await call(owner, "POST", `/api/v1/imports/grants/${g2.json.grant.id}/accept`);
expect((await call(owner, "POST", `/api/v1/imports/grants/${g2.json.grant.id}/list`)).json.error).toBe("not_shop");
});
@@ -10,7 +10,15 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@
import { api, unwrap, type ImportGrant } from "@/lib/api";
import { ConsoleNav, requireConsole } from "../../../console-nav";
import { shortFingerprint } from "@/lib/importer";
import { changeImporterAccount, decideGrant, retryJob, setImporter, setImporterSettings } from "../../actions";
import {
changeImporterAccount,
decideGrant,
listShop,
retryJob,
setImporter,
setImporterSettings,
} from "../../actions";
import { ShopListing } from "@/components/shop-listing";
import { ImporterAccountForm } from "./importer-account-form";
export const metadata: Metadata = { title: "Imports" };
@@ -325,7 +333,7 @@ export default async function CatalogImports({
</CardHeader>
<CardContent className="divide-y">
{others.map((g) => (
<GrantRow key={g.id} id={id} grant={g} accept={can.accept} withdraw={can.withdraw} />
<GrantRow key={g.id} id={id} grant={g} accept={can.accept} withdraw={can.withdraw} run={can.run} />
))}
</CardContent>
</Card>
@@ -415,11 +423,13 @@ function GrantRow({
grant: g,
accept,
withdraw,
run = false,
}: {
id: string;
grant: ImportGrant;
accept: boolean;
withdraw: boolean;
run?: boolean;
}) {
const open = g.status === "pending" || g.status === "active" || g.status === "suspended";
return (
@@ -440,8 +450,16 @@ function GrantRow({
? `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."}
<ShopListing grant={g} />
</p>
{g.statusReason && <p className="text-sm text-muted-foreground">{g.statusReason}</p>}
{run && g.status === "active" && g.scope === "shop" && (
<ActionForm action={listShop} fields={{ id, grant: g.id }}>
<SubmitButton size="sm" variant="outline" pendingLabel="Listing…">
{g.shopListedAt ? "List the shop again" : "List the shop now"}
</SubmitButton>
</ActionForm>
)}
{open && (accept || withdraw) && (
<ActionForm action={decideGrant} fields={{ id, grant: g.id }}>
<div className="flex max-w-2xl flex-wrap gap-2">
+13 -1
View File
@@ -156,7 +156,19 @@ export async function decideGrant(_: ActionState, form: FormData): Promise<Actio
.grants({ id: grant })({ decision })
.post(reason ? { reason } : {}),
);
return decision === "accept" ? `Accepted. ${r.queued} queued for the importer.` : "Declined.";
if (decision !== "accept") return "Declined.";
return r.grant.scope === "shop"
? `Accepted. ${r.queued} queued for the importer; the shop's other products follow once it's listed on IMVU.`
: `Accepted. ${r.queued} queued for the importer.`;
});
}
/** Lists a whole-shop grant's products on IMVU again (new ones are queued). */
export async function listShop(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
revalidatePath(`/console/catalogs/${id}/imports`);
const r = unwrap(await api.imports.grants({ id: field(form, "grant") }).list.post());
return `${r.listed} product${r.listed === 1 ? "" : "s"} on IMVU; ${r.queued} new queued.`;
});
}
+2
View File
@@ -2,6 +2,7 @@ import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { ActionForm, SubmitButton } from "@/components/forms";
import { PageHeader, Tag } from "@/components/status";
import { ShopListing } from "@/components/shop-listing";
import { DateTime } from "@/components/time";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field";
@@ -222,6 +223,7 @@ function RecordedRow({ grant: g }: { grant: Recorded }) {
? `The 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."}
<ShopListing grant={g} />
</p>
{g.claimed ? (
<p className="text-sm text-muted-foreground">The creator claimed it: they manage it now.</p>
+2
View File
@@ -3,6 +3,7 @@ import Link from "next/link";
import { redirect } from "next/navigation";
import { ActionForm, SubmitButton } from "@/components/forms";
import { PageHeader, Tag } from "@/components/status";
import { ShopListing } from "@/components/shop-listing";
import { DateTime } from "@/components/time";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field";
@@ -267,6 +268,7 @@ function GrantRow({ grant: g }: { grant: ImportGrant }) {
? `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."}
<ShopListing grant={g} />
</p>
{g.status === "suspended" ? (
<p className="text-sm text-muted-foreground">Withdraw it, then bring your products again to start over.</p>
+19
View File
@@ -0,0 +1,19 @@
import { DateTime } from "@/components/time";
/** For an active whole-shop grant: how many products IMVU lists in the shop, and when the hub last looked. */
export function ShopListing({
grant: g,
}: {
grant: { scope: string; status: string; shopListedAt: string | null; shopListed: number };
}) {
if (g.scope !== "shop" || g.status !== "active") return null;
if (!g.shopListedAt) return <> Not checked on IMVU yet.</>;
return (
<>
{" "}
On IMVU: {g.shopListed} general-rated product{g.shopListed === 1 ? "" : "s"} (checked{" "}
<DateTime iso={g.shopListedAt} />
).
</>
);
}