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
+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`))