feat: whole shops listed on IMVU, and GET /imports/available (#16)
Release / release (push) Successful in 4s
CI / test (push) Successful in 1m35s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 6s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 14s

Co-authored-by: dhkatz <[email protected]>
This commit was merged in pull request #16.
This commit is contained in:
dhkatz authored and dhkatz committed 2026-11-08 00:51:00 +00:00
1 parent 8f6dacba10
commit efc7d6b808
15 files changed
+4952 -18

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 }) => {
+206 -8
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
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)));
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);
.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} />
).
</>
);
}
+27 -6
View File
@@ -110,7 +110,7 @@ import_job(id, catalog, grant, imvu_product, kind ("import" | "recheck"), status
```
- **Queued by the hub**: a request covered by a grant, a product added to a grant, a "shop" grant accepted (the
products people requested so far, and all the shop's products if a way to list them is found), and a daily
products people requested so far, and the shop's products as IMVU lists them: "Whole shops" below), and a daily
**recheck** of each imported product.
- **The hub checks IMVU's public API** before queuing and at each recheck (rate-limited, as for parents): the
product exists, its creator is the grant's account, its rating. Gone from IMVU: withdrawn. Rating changed to AP:
@@ -121,6 +121,21 @@ import_job(id, catalog, grant, imvu_product, kind ("import" | "recheck"), status
console. The catalog's team can retry or re-import one product, and pause the importer (`import:pause`): the hub
hands out no jobs while paused.
## Whole shops
IMVU lists a shop's products to the signed out (`api.imvu.com/product?creator=<username>`, general-rated only: no
Access Pass products). The hub lists a "shop" grant's shop when the grant is accepted (or becomes a whole shop), then
daily (a few shops an hour, oldest listing first), and when the catalog's team (`import:run`) or the creator asks
("List the shop again", at most 3 times an hour). Each listing looks the IMVU account up by ID first (listing goes
by its current username), keeps every listed product's info (`imvu_product_info`, as a lookup would; so their
rechecks need no lookup for a day), records when and how many (`import_grant.shop_listed_at`, `shop_listed`), and
queues imports for the creator's known products not imported in that catalog yet, less exclusions. A product that
disappears from the listing isn't withdrawn for it: it may have become Access Pass; rechecks decide.
IMVU's paging is unreliable: in pages of 100 (or its default 50) pages overlap and products are missed (2026-11-07:
580 different products of 639), but one page of up to 1000 returns them all. So the hub asks for pages of 1000,
follows `next` (on IMVU's API only), drops repeats, and stops at 10 pages.
## Withdrawal
A withdrawn imported product (grant withdrawn or narrowed, gone from IMVU, account link moved) is removed as
@@ -182,6 +197,8 @@ passwords never reach the hub readable, and are kept only by the importer.
| `PATCH /api/v1/imports/grants/:id` | (its creator; for an unclaimed creator, `import:grant-on-behalf`) `{products?, exclude?, listed?}` → `{grant, withdrawn}`: products no longer covered are withdrawn; newly covered ones people asked for are queued |
| `POST /api/v1/imports/grants/:id/accept`, `.../decline` | (`import:accept` at the catalog) `{reason?}` → `{grant, queued}`. The creator is notified. |
| `DELETE /api/v1/imports/grants/:id` | (its creator, or `import:withdraw` at the catalog) `{reason?}` → `{grant, withdrawn}` |
| `POST /api/v1/imports/grants/:id/list` | (its creator, or `import:run` at the catalog) → `{grant, listed, queued}`: an active whole-shop grant's shop listed on IMVU now. 409 `not_shop`; 429 after 3 an hour. |
| `GET /api/v1/imports/available?products=&creators=` | (anyone) up to 100 IMVU product IDs and 100 IMVU account IDs, comma-separated → `{products: [{imvuProduct, status, product, requested?}], shops: [{imvuCreator, shop, products}]}`. `status`: `imported` (`product` is the hub product), `adult` (imported, but the person can't see adult products), `queued`, `covered` (a grant covers it: asking queues it) or `none` (asking counts it). `requested` (signed in): they asked for it. `shop`: an active whole-shop grant; `products`: how many of the shop's are on T5DE. From what the hub knows only (it asks IMVU nothing), for the proxy's "Get on T5DE". |
| `POST /api/v1/imports/requests` | `{imvuProduct}` or `{imvuCreator}` → `{status: "added" \| "queued" \| "suggested" \| "counted", product?}` (`added`: imported already, now in their library). At most 50 a day. |
| `GET /api/v1/imports/requests?imvuCreator=` | `{requests: [{imvuProduct (0: the whole shop), name, requests}]}` for a linked account of theirs (moderators: any); without `imvuCreator`, moderators get `{creators}`: the most asked-for IMVU creators |
| `GET /api/v1/catalogs/:id/importer` | (`import:accept` or `import:pause`) `{importer, grants, jobs, counts, permissions}`; `?status=` filters jobs |
@@ -201,6 +218,8 @@ passwords never reach the hub readable, and are kept only by the importer.
| `DELETE /api/v1/catalogs/:id/importer/accounts/:account` | (`import:run`) |
| `POST /api/v1/catalogs/:id/importer/settings` | (`import:run`) `{rate (0.2-10 requests a second to IMVU), concurrency (1-8 jobs at once)}` |
Grants also carry `shopListedAt` (null: not listed yet) and `shopListed` (how many products IMVU listed).
`GET /api/v1/catalogs/:id/importer` also has `program: {version, seenAt, fingerprint, publicKey}` (`publicKey` only
with `import:run`), `settings`, and `accounts: [{id, imvuId, username, state, stateMessage, stateAt, accessPass,
ageVerified}]` (state: `waiting` for the importer, `received`, `ok`, `sign_in_failed`, `needs_password`). Never a
@@ -228,11 +247,13 @@ deleted ones and IDs that never existed (404 only for a few very old IDs), so th
says "Not Found". For AP products, the importer's IMVU account (with Access Pass) reports the product info to the
hub ("IMVU accounts" above). Also signed out: `client-dynamic.imvu.com/api/shop/product.php` and
`api.imvu.com/creator/creator-<id>` need an account, and search refuses AP (`ap_search_denied`, with
`product_rating` other than `0,5`), but `api.imvu.com/product?creator=<username>` lists a shop's other products
(100 a page, `next` relation), which whole-shop grants use.
`product_rating` other than `0,5`), but `api.imvu.com/product?creator=<username>` lists a shop's general-rated
products ("Whole shops").
Still to do: `GET /imports/available` for the proxy's shop button; listing whole-shop grants' products
(`api.imvu.com/product?creator=`); t5de-catalog accepting `t5de-import` tokens on uploads; the spike and `t5de-importer`.
Built (2026-11-07): whole shops listed on IMVU ("Whole shops" above), and `GET /imports/available`.
t5de-catalog takes `t5de-import` tokens on uploads (its PR #2). Still to do: the spike and `t5de-importer` (and
its report of Access Pass products' info).
## Spike (before building the importer)
@@ -240,7 +261,7 @@ Still to do: `GET /imports/available` for the proxy's shop button; listing whole
client wear it as a T5 product, with the parent loading from IMVU? (Never committed: it's IMVU's files.)
2. Do typical IMVU products fit the `pack` limits?
3. How many HEAD requests does probing take for real shops; does the CDN limit them?
4. Is there a public way to list a creator's products (for importing a whole shop at once)?
4. ~~Is there a public way to list a creator's products?~~ Yes, general-rated ones ("Whole shops").
## Later
@@ -0,0 +1,2 @@
ALTER TABLE "import_grant" ADD COLUMN "shop_listed_at" timestamp with time zone;--> statement-breakpoint
ALTER TABLE "import_grant" ADD COLUMN "shop_listed" integer DEFAULT 0 NOT NULL;
File diff suppressed because it is too large. Load diff
+7
View File
@@ -134,6 +134,13 @@
"when": 1794078168609,
"tag": "0018_recorded_grants",
"breakpoints": true
},
{
"idx": 19,
"version": "7",
"when": 1794092472616,
"tag": "0019_shop_listing",
"breakpoints": true
}
]
}
+4
View File
@@ -753,6 +753,10 @@ export const importGrant = pgTable(
// Recorded: proof without an account, a code the creator put in their IMVU tagline, and when the hub saw it.
proofCode: text("proof_code"),
proofCheckedAt: timestamp("proof_checked_at", { withTimezone: true }),
// Scope "shop": when the hub last listed the shop's products on IMVU, and how many it listed (general-rated only:
// IMVU lists no Access Pass products to the signed out).
shopListedAt: timestamp("shop_listed_at", { withTimezone: true }),
shopListed: integer("shop_listed").notNull().default(0),
// "pending" (the catalog's team hasn't accepted), "active", "declined", "suspended", "withdrawn".
status: text("status").notNull().default("pending"),
statusReason: text("status_reason").notNull().default(""),