// Imports (docs/imports.md): creators grant a catalog leave to import their IMVU products; the catalog's team accepts; // requests and grants queue jobs; the catalog's importer claims them, uploads the files to its catalog, and the hub // 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, NoSuchImvuUser, type ImvuClient, type ImvuUser } from "./imvu"; import type { Signer } from "./keys"; import { BlockedUpload, checkFiles, newProductID, ProductError, type Catalog } from "./products"; const { catalog, catalogChange, fileBlock, hosting, imvuLink, imvuProductInfo, importerAccount, importGrant, importJob, importRequest, library, product, productRevision, user, } = schema; export type Grant = typeof importGrant.$inferSelect; export type Job = typeof importJob.$inferSelect; export type ImvuInfo = typeof imvuProductInfo.$inferSelect; /** The consent a creator agrees to; its version is stored with each grant. A new text means a new version. */ export const consent = { version: 1, text: "I made these products on IMVU and I let this catalog copy them from IMVU and give them to T5DE users for free, " + "to wear in IMVU Classic with T5DE. They stay mine: I can change what's included or withdraw at any time, and " + "withdrawn products are taken away from everyone who has them. Products that derive from someone else's keep " + "using that product from IMVU.", }; /** Requests a person may make a day. */ export const requestsPerDay = 50; /** Products a grant by products may list (and a shop grant may exclude). */ export const maxGrantProducts = 1000; /** Claimed jobs not reported within this long go back to the queue. */ const claimTimeout = 30 * 60 * 1000; /** Retries after a failure: 1 min, 10 min, 1 h, then daily; failed for good after 5 attempts. */ 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"); const productIDs = (v: unknown): number[] | undefined => { if (v === undefined) return []; if (!Array.isArray(v) || v.length > maxGrantProducts) return undefined; const out = new Set(); for (const x of v) { const n = Number(x); if (!Number.isSafeInteger(n) || n <= 0) return undefined; out.add(n); } return [...out].sort((a, b) => a - b); }; /** A grant's IMVU account's name: its link's, or its unclaimed creator's. */ const imvuNameOf = sql`coalesce(${imvuLink.username}, (select u.display_username from "user" u where u.unclaimed_imvu_id = ${importGrant.imvuId}))`; /** An unclaimed creator's username: reserved (people can't sign up with the prefix). */ export const unclaimedUsername = (imvuId: number) => `imvu_${imvuId}`; /** Whether a grant covers an IMVU product (by its IMVU creator): active, the creator's, and in its scope. */ /** A product as an importer's IMVU account sees it (docs/imports.md, "Access Pass products"). */ export type SeenProduct = { id: number; name: string; rating: string; creatorId: number; creatorName: string; purchasable: boolean }; /** Checks what an importer says it saw: null if it isn't a product. */ function checkSeen(p: SeenProduct): SeenProduct | null { if (!Number.isSafeInteger(p.id) || p.id <= 0 || !Number.isSafeInteger(p.creatorId) || p.creatorId <= 0) return null; if (p.rating !== "general" && p.rating !== "adult") return null; return { id: p.id, name: String(p.name ?? "").trim().slice(0, 200), rating: p.rating, creatorId: p.creatorId, creatorName: String(p.creatorName ?? "").trim().slice(0, 64), purchasable: p.purchasable !== false, }; } export function covers(g: Grant, imvuProduct: number, creatorId: number): boolean { if (g.status !== "active" || creatorId !== g.imvuId) return false; return g.scope === "shop" ? !g.exclude.includes(imvuProduct) : g.products.includes(imvuProduct); } export class Imports { constructor( private readonly db: Database, private readonly signer: Signer, private readonly imvu?: ImvuClient, ) {} // ---- IMVU product info ---- /** An IMVU product's info (from the cache when it's fresh). Undefined if IMVU doesn't show it publicly. Throws * ImvuUnavailable if IMVU can't be reached and nothing is cached. */ async info(id: number, fresh = false): Promise { if (!Number.isSafeInteger(id) || id <= 0) return undefined; const [known] = await this.db.select().from(imvuProductInfo).where(eq(imvuProductInfo.id, id)); if (known && !fresh && Date.now() - known.checkedAt.getTime() < infoFresh) return known.found ? known : undefined; if (!this.imvu) { if (known) return known.found ? known : undefined; throw new ImvuUnavailable("no IMVU client"); } let answer; try { answer = await this.imvu.lookup(id); } catch (e) { if (known && e instanceof ImvuUnavailable) return known.found ? known : undefined; throw e; } // IMVU hides Access Pass products from anonymous callers (401, as for deleted and made-up IDs): keep what was // last seen rather than treat a product that became AP as gone. if (answer === "hidden" && known?.found) return known; const p = typeof answer === "string" ? null : answer; const row = { id, found: p !== null, name: p?.name ?? "", creatorId: p?.creatorId ?? 0, creatorName: p?.creatorName ?? "", rating: p?.adult ? "adult" : "general", purchasable: p?.purchasable ?? false, checkedAt: new Date(), }; const [saved] = await this.db .insert(imvuProductInfo) .values(row) .onConflictDoUpdate({ target: imvuProductInfo.id, set: row }) .returning(); return saved!.found ? saved : undefined; } // ---- catalogs and their importers ---- /** Approved catalogs with imports on (accepting grants). */ async catalogs() { return this.db .select({ id: catalog.id, name: catalog.name, url: catalog.url, contact: catalog.contact, maxRating: catalog.maxRating }) .from(catalog) .where(and(eq(catalog.status, "approved"), ne(catalog.importer, "off"))) .orderBy(catalog.name); } /** Turns a catalog's importer on (a new key, returned once), off, or pauses and resumes it. */ async setImporter(catalogId: string, state: "on" | "off" | "paused"): Promise<{ catalog: Catalog; key?: string }> { const [c] = await this.db.select().from(catalog).where(eq(catalog.id, catalogId)); if (!c) throw new ProductError(404, "not_found", "No such catalog."); if (state !== "off" && c.status !== "approved") throw new ProductError(409, "not_approved", "Imports need the catalog to be approved first."); const key = c.importer === "off" && state !== "off" ? randomKey() : undefined; const [updated] = await this.db .update(catalog) .set({ importer: state, ...(key ? { importerKeyHash: sha256(key) } : {}), ...(state === "off" ? { importerKeyHash: null } : {}) }) .where(eq(catalog.id, catalogId)) .returning(); return { catalog: updated!, key }; } /** A new importer key; the old one stops working at once. */ async rotateImporterKey(catalogId: string): Promise { const key = randomKey(); const [c] = await this.db .update(catalog) .set({ importerKeyHash: sha256(key) }) .where(and(eq(catalog.id, catalogId), ne(catalog.importer, "off"))) .returning(); if (!c) throw new ProductError(409, "imports_off", "Turn imports on first."); return key; } /** The catalog an `Authorization: Importer :` header names: approved, imports on (or paused). */ async importerFor(header: string | null): Promise { const m = header?.match(/^Importer ([a-z2-7]{10}):(\S+)$/); if (!m) return undefined; const [c] = await this.db.select().from(catalog).where(eq(catalog.id, m[1]!)); if (!c || c.status !== "approved" || c.importer === "off" || !c.importerKeyHash) return undefined; return timingSafeEqual(Buffer.from(sha256(m[2]!)), Buffer.from(c.importerKeyHash)) ? c : undefined; } // ---- grants ---- async grant(id: string): Promise { const [g] = await this.db.select().from(importGrant).where(eq(importGrant.id, id)); if (!g) throw new ProductError(404, "not_found", "No such grant."); return g; } /** A creator grants a catalog leave to import their products from one of their linked IMVU accounts. */ async createGrant( personId: string, input: { catalog: string; imvuId: number; scope: string; products?: unknown; exclude?: unknown; listed?: boolean; consentVersion: number }, ): Promise { const [link] = await this.db.select().from(imvuLink).where(eq(imvuLink.imvuId, input.imvuId)); if (!link || link.userId !== personId) throw new ProductError(403, "not_linked", "Link that IMVU account to your T5DE account first."); const [c] = await this.db.select().from(catalog).where(eq(catalog.id, input.catalog)); if (!c || c.status !== "approved" || c.importer === "off") throw new ProductError(404, "not_found", "That catalog doesn't take imports."); if (input.consentVersion !== consent.version) throw new ProductError(409, "consent_changed", "The consent text changed. Read it again and agree to the new one."); const scope = this.checkScope(input.scope, input.products, input.exclude); const [open] = await this.db .select({ id: importGrant.id }) .from(importGrant) .where(and(eq(importGrant.catalogId, c.id), eq(importGrant.imvuId, input.imvuId), inArray(importGrant.status, ["pending", "active", "suspended"]))); if (open) throw new ProductError(409, "exists", "That IMVU account already has a grant with this catalog. Change that one instead."); const [g] = await this.db .insert(importGrant) .values({ id: newProductID(), catalogId: c.id, creatorId: personId, imvuId: input.imvuId, ...scope, listed: input.listed !== false, consentVersion: consent.version, }) .returning(); return g!; } // ---- recorded grants and unclaimed creators (docs/imports.md "Unclaimed creators and claiming") ---- /** The unclaimed creator standing in for an IMVU account, made if there's none yet. */ private async placeholderFor(imvu: ImvuUser): Promise { const [known] = await this.db.select({ id: user.id }).from(user).where(eq(user.unclaimedImvuId, imvu.id)); if (known) return known.id; const id = crypto.randomUUID().replaceAll("-", ""); await this.db.insert(user).values({ id, name: `${imvu.username}, on IMVU`, // Never delivered (.invalid); there's no password, so nobody signs in as it. email: `imvu-${imvu.id}@unclaimed.invalid`, username: unclaimedUsername(imvu.id), displayUsername: imvu.username, unclaimedImvuId: imvu.id, }); return id; } /** * An admin records a creator's consent (they won't make an account): a grant for an unclaimed creator standing in * for their IMVU account. Pending until the catalog's team accepts, like any grant. */ async recordGrant( byId: string, imvu: ImvuUser, input: { catalog: string; scope: string; products?: unknown; exclude?: unknown; listed?: boolean; evidence: string }, ): Promise { const evidence = input.evidence.trim(); if (!evidence) throw new ProductError(400, "invalid", "Say how they agreed (where and when)."); const [link] = await this.db.select().from(imvuLink).where(eq(imvuLink.imvuId, imvu.id)); if (link) throw new ProductError(409, "linked", `${imvu.username} is on T5DE: they bring their products themselves, from their account.`); const [c] = await this.db.select().from(catalog).where(eq(catalog.id, input.catalog)); if (!c || c.status !== "approved" || c.importer === "off") throw new ProductError(404, "not_found", "That catalog doesn't take imports."); const scope = this.checkScope(input.scope, input.products, input.exclude); const [open] = await this.db .select({ id: importGrant.id }) .from(importGrant) .where(and(eq(importGrant.catalogId, c.id), eq(importGrant.imvuId, imvu.id), inArray(importGrant.status, ["pending", "active", "suspended"]))); if (open) throw new ProductError(409, "exists", "That IMVU account already has a grant with this catalog. Change that one instead."); const creatorId = await this.placeholderFor(imvu); const [g] = await this.db .insert(importGrant) .values({ id: newProductID(), catalogId: c.id, creatorId, imvuId: imvu.id, ...scope, listed: input.listed !== false, consentVersion: consent.version, consentKind: "recorded", evidence: evidence.slice(0, 1000), recordedBy: byId, }) .returning(); return g!; } /** Grants admins recorded, newest first: their catalog, IMVU name, who recorded them, and whether claimed. */ async recordedGrants() { const recorder = sql`(select u.username from "user" u where u.id = ${importGrant.recordedBy})`; return this.db .select({ grant: importGrant, catalogName: catalog.name, imvuName: imvuNameOf, recordedByName: recorder, claimed: sql`not exists (select 1 from "user" u where u.id = ${importGrant.creatorId} and u.unclaimed_imvu_id is not null)`, }) .from(importGrant) .innerJoin(catalog, eq(catalog.id, importGrant.catalogId)) .leftJoin(imvuLink, eq(imvuLink.imvuId, importGrant.imvuId)) .where(eq(importGrant.consentKind, "recorded")) .orderBy(desc(importGrant.createdAt)); } /** Whether a grant's creator is still an unclaimed placeholder. */ async unclaimed(g: Grant): Promise { const [u] = await this.db.select({ imvu: user.unclaimedImvuId }).from(user).where(eq(user.id, g.creatorId)); return u?.imvu != null; } /** The code for a recorded grant's proof (made once): the creator puts it in their IMVU tagline. */ async proofCode(id: string, code: string): Promise { const g = await this.grant(id); if (g.consentKind !== "recorded") throw new ProductError(409, "not_recorded", "Only recorded grants need proof."); if (g.proofCode) return g.proofCode; await this.db.update(importGrant).set({ proofCode: code }).where(eq(importGrant.id, g.id)); return code; } /** Checks a recorded grant's proof against the IMVU account's tagline. */ async checkProof(id: string, tagline: string): Promise { const g = await this.grant(id); if (!g.proofCode) throw new ProductError(409, "no_code", "Make a code first, and send it to the creator."); if (!tagline.includes(g.proofCode)) throw new ProductError(409, "not_found", `The code isn't in that IMVU account's tagline yet. It must say ${g.proofCode}.`); const [updated] = await this.db.update(importGrant).set({ proofCheckedAt: new Date() }).where(eq(importGrant.id, g.id)).returning(); return updated!; } /** What a person could claim: unclaimed creators for IMVU accounts they've linked, with their products and grants. */ async claimable(personId: string) { return this.db .select({ imvuId: user.unclaimedImvuId, username: user.displayUsername, products: sql`(select count(*)::int from ${product} p where p.creator_id = ${user.id} and p.removed_at is null)`, grants: sql`(select count(*)::int from ${importGrant} g where g.creator_id = ${user.id} and g.status in ('pending', 'active', 'suspended'))`, }) .from(user) .innerJoin(imvuLink, eq(imvuLink.imvuId, user.unclaimedImvuId)) .where(eq(imvuLink.userId, personId)); } /** * Someone who linked an IMVU account claims its unclaimed creator: its products and grants become theirs, and the * placeholder is deleted. */ async claimCreator(personId: string, imvuId: number): Promise<{ products: number; grants: number }> { const [link] = await this.db.select().from(imvuLink).where(eq(imvuLink.imvuId, imvuId)); if (!link || link.userId !== personId) throw new ProductError(403, "not_linked", "Link that IMVU account first."); const [placeholder] = await this.db.select().from(user).where(eq(user.unclaimedImvuId, imvuId)); if (!placeholder) throw new ProductError(404, "not_found", "Nothing waits for that IMVU account."); return this.db.transaction(async (tx) => { const products = await tx.update(product).set({ creatorId: personId }).where(eq(product.creatorId, placeholder.id)).returning({ id: product.id }); await tx.update(productRevision).set({ uploadedBy: personId }).where(eq(productRevision.uploadedBy, placeholder.id)); const grants = await tx.update(importGrant).set({ creatorId: personId }).where(eq(importGrant.creatorId, placeholder.id)).returning({ id: importGrant.id }); await tx.delete(user).where(eq(user.id, placeholder.id)); return { products: products.length, grants: grants.length }; }); } private checkScope(scope: string, products: unknown, exclude: unknown) { if (scope !== "shop" && scope !== "products") throw new ProductError(400, "invalid", "Choose the whole shop or listed products."); const p = productIDs(products); const x = productIDs(exclude); if (!p || !x) throw new ProductError(400, "invalid", `Products are IMVU product IDs, at most ${maxGrantProducts}.`); if (scope === "products" && p.length === 0) throw new ProductError(400, "invalid", "List at least one product."); return scope === "shop" ? { scope, products: [], exclude: x } : { scope, products: p, exclude: [] }; } /** A person's grants (as the creator), newest first, with their catalogs' names. */ async grantsOf(personId: string) { return this.db .select({ grant: importGrant, catalogName: catalog.name, imvuName: imvuNameOf }) .from(importGrant) .innerJoin(catalog, eq(catalog.id, importGrant.catalogId)) .leftJoin(imvuLink, eq(imvuLink.imvuId, importGrant.imvuId)) .where(eq(importGrant.creatorId, personId)) .orderBy(desc(importGrant.createdAt)); } /** A catalog's grants, pending first. */ async grantsFor(catalogId: string) { return this.db .select({ grant: importGrant, catalogName: catalog.name, imvuName: imvuNameOf }) .from(importGrant) .innerJoin(catalog, eq(catalog.id, importGrant.catalogId)) .leftJoin(imvuLink, eq(imvuLink.imvuId, importGrant.imvuId)) .where(eq(importGrant.catalogId, catalogId)) .orderBy(sql`${importGrant.status} <> 'pending'`, desc(importGrant.createdAt)); } /** The creator changes a grant's scope or listing. Products it no longer covers are withdrawn; newly covered ones * people asked for are queued. */ async updateGrant(id: string, patch: { scope?: string; products?: unknown; exclude?: unknown; listed?: boolean }) { const g = await this.grant(id); if (g.status === "withdrawn" || g.status === "declined") throw new ProductError(409, "ended", "This grant has ended."); const scope = this.checkScope(patch.scope ?? g.scope, patch.products ?? g.products, patch.exclude ?? g.exclude); const [updated] = await this.db .update(importGrant) .set({ ...scope, ...(patch.listed !== undefined ? { listed: patch.listed } : {}) }) .where(eq(importGrant.id, id)) .returning(); const withdrawn = await this.withdrawUncovered(updated!, "Its creator took it out of the import."); if (updated!.status === "active") await this.queueCovered(updated!); return { grant: updated!, withdrawn }; } /** The catalog's team accepts or declines a pending grant. Accepting queues what it covers that people asked for * (and the products a grant lists). */ async decide(id: string, decision: "accept" | "decline", byId: string, reason = ""): Promise<{ grant: Grant; queued: number }> { const g = await this.grant(id); if (g.status !== "pending") throw new ProductError(409, "decided", "This grant isn't waiting for a decision."); const [updated] = await this.db .update(importGrant) .set({ status: decision === "accept" ? "active" : "declined", statusReason: reason, decidedAt: new Date(), decidedBy: byId }) .where(eq(importGrant.id, id)) .returning(); const queued = decision === "accept" ? await this.queueCovered(updated!) : 0; return { grant: updated!, queued }; } /** Ends a grant (its creator, the catalog's team or a moderator): its products are withdrawn (from this catalog * only, if another active grant still covers them). */ async withdraw(id: string, reason: string): Promise<{ grant: Grant; withdrawn: string[] }> { const g = await this.grant(id); if (g.status === "withdrawn" || g.status === "declined") throw new ProductError(409, "ended", "This grant has ended already."); const [updated] = await this.db .update(importGrant) .set({ status: "withdrawn", statusReason: reason }) .where(eq(importGrant.id, id)) .returning(); await this.db.update(importJob).set({ status: "failed", reason: "The grant was withdrawn." }).where(and(eq(importJob.grantId, id), inArray(importJob.status, ["queued", "claimed"]))); return { grant: updated!, withdrawn: await this.withdrawUncovered(updated!, reason) }; } /** Suspends the active and pending grants of an IMVU account (unlinked, or linked to someone else): until its * owner grants again, nothing is imported, and the products are withdrawn. */ async suspendFor(imvuId: number, reason: string): Promise { const gs = await this.db .update(importGrant) .set({ status: "suspended", statusReason: reason }) .where( and( eq(importGrant.imvuId, imvuId), inArray(importGrant.status, ["pending", "active"]), // An unclaimed creator's grants stand on the consent an admin recorded, whoever links the account. sql`not exists (select 1 from "user" u where u.id = ${importGrant.creatorId} and u.unclaimed_imvu_id is not null)`, ), ) .returning(); for (const g of gs) { await this.db.update(importJob).set({ status: "failed", reason }).where(and(eq(importJob.grantId, g.id), inArray(importJob.status, ["queued", "claimed"]))); await this.withdrawUncovered(g, reason); } return gs.length; } /** The imported products a catalog hosts for a grant's IMVU account that no active grant covers any more (in that * catalog: delisted; anywhere: withdrawn as moderation removes, its files deleted). Returns the products withdrawn * everywhere. */ private async withdrawUncovered(g: Grant, reason: string): Promise { const hosted = await this.db .selectDistinct({ id: product.id, imvuProduct: product.imvuProduct }) .from(product) .innerJoin(hosting, and(eq(hosting.productId, product.id), eq(hosting.catalogId, g.catalogId))) // The grant's IMVU account's products (a creator may have several accounts). .innerJoin(imvuProductInfo, and(eq(imvuProductInfo.id, product.imvuProduct), eq(imvuProductInfo.creatorId, g.imvuId))) .where(and(eq(product.creatorId, g.creatorId), sql`${product.removedAt} is null`)); if (hosted.length === 0) return []; const active = await this.db.select().from(importGrant).where(and(eq(importGrant.imvuId, g.imvuId), eq(importGrant.status, "active"))); const gone: string[] = []; for (const p of hosted) { const imvuProduct = p.imvuProduct!; if (active.some((a) => a.catalogId === g.catalogId && covers(a, imvuProduct, g.imvuId))) continue; const elsewhere = active.some((a) => covers(a, imvuProduct, g.imvuId)); await this.unhost(p.id, elsewhere ? g.catalogId : undefined); if (!elsewhere) { await this.db .update(product) .set({ removedAt: new Date(), removedReason: `Withdrawn: ${reason}` }) .where(eq(product.id, p.id)); gone.push(p.id); } } return gone; } /** Stops hosting a product (in one catalog, or all): its catalogs are told to delete the files. */ private async unhost(productId: string, catalogId?: string) { await this.db.transaction(async (tx) => { const where = catalogId ? and(eq(hosting.productId, productId), eq(hosting.catalogId, catalogId)) : eq(hosting.productId, productId); const rows = await tx .select({ catalogId: hosting.catalogId, number: hosting.number, files: productRevision.files }) .from(hosting) .innerJoin(productRevision, and(eq(productRevision.productId, hosting.productId), eq(productRevision.number, hosting.number))) .where(where); for (const h of rows) await tx.insert(catalogChange).values({ catalogId: h.catalogId, data: { type: "delete", product: productId, revision: h.number, files: h.files } }); await tx.delete(hosting).where(where); }); } /** 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 { let wanted: Set; 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 }) .from(product) .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 (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 = 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 { 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>["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(); await this.keepSeen( listed.map((p) => ({ id: p.id, name: p.name, rating: p.adult ? "adult" : "general", creatorId: p.creatorId, creatorName: p.creatorName, purchasable: p.purchasable })), now, ); const [updated] = await this.db .update(importGrant) .set({ shopListedAt: now, shopListed: listed.length, shopListedSignedIn: false }) .where(eq(importGrant.id, g.id)) .returning(); const queued = updated?.status === "active" && updated.scope === "shop" ? await this.queueCovered(updated) : 0; if (updated) await this.queueListing(updated); return { listed: listed.length, queued }; } /** Keeps products' info as seen (by the hub's listing, or an importer's account), in batches. */ private async keepSeen(seen: SeenProduct[], now: Date) { for (let i = 0; i < seen.length; i += 500) { const rows = seen.slice(i, i + 500).map((p) => ({ ...p, found: true, 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, }, }); } } /** * Queues a signed-in listing of a whole-shop grant's shop for its catalog's importer, if one of the importer's IMVU * accounts signed in with Access Pass: IMVU lists Access Pass products only to them. */ async queueListing(g: Grant): Promise { if (g.status !== "active" || g.scope !== "shop") return false; const [ap] = await this.db .select({ id: importerAccount.id }) .from(importerAccount) .where(and(eq(importerAccount.catalogId, g.catalogId), eq(importerAccount.state, "ok"), eq(importerAccount.accessPass, true))) .limit(1); if (!ap) return false; const [j] = await this.db .insert(importJob) .values({ id: newProductID(), catalogId: g.catalogId, grantId: g.id, imvuProduct: g.imvuId, kind: "list" }) .onConflictDoNothing() .returning(); return j !== undefined; } /** * The importer lists a whole shop signed in (a "list" job): the products it saw are kept (only the grant's IMVU * account's: an importer can't vouch for another creator's), and those not imported yet are queued. */ async reportListing(c: Catalog, jobId: string, products: SeenProduct[]): Promise<{ listed: number; queued: number }> { const job = await this.claimedJob(c, jobId); if (job.kind !== "list") throw new ProductError(409, "not_list", "That job isn't a shop listing."); const g = await this.grant(job.grantId); const seen = new Map(); for (const p of products) { const ok = checkSeen(p); if (ok && ok.creatorId === g.imvuId) seen.set(ok.id, ok); } const now = new Date(); await this.keepSeen([...seen.values()], now); await this.db.update(importJob).set({ status: "done", reason: "", claimedAt: null }).where(eq(importJob.id, job.id)); const [updated] = await this.db .update(importGrant) .set({ shopListedAt: now, shopListed: seen.size, shopListedSignedIn: true }) .where(and(eq(importGrant.id, g.id), eq(importGrant.status, "active"), eq(importGrant.scope, "shop"))) .returning(); const queued = updated ? await this.queueCovered(updated) : 0; return { listed: seen.size, queued }; } /** * The importer says what its IMVU account sees of a claimed job's product, which IMVU hides from the hub (Access * Pass products): kept, so the job can go on. What IMVU shows the hub publicly wins. */ async reportInfo(c: Catalog, jobId: string, seen: SeenProduct & { found: boolean }): Promise<{ rating: string | null; covered: boolean }> { const job = await this.claimedJob(c, jobId); if (job.kind === "list") throw new ProductError(409, "not_product", "That job is a shop listing."); const g = await this.grant(job.grantId); const answer = this.imvu ? await this.imvu.lookup(job.imvuProduct) : "hidden"; let info: ImvuInfo | undefined; if (typeof answer !== "string") info = await this.info(job.imvuProduct, true); else if (!seen.found) { // Gone, as the importer's account sees it too: rechecks withdraw it. const now = new Date(); await this.db .insert(imvuProductInfo) .values({ id: job.imvuProduct, found: false, checkedAt: now }) .onConflictDoUpdate({ target: imvuProductInfo.id, set: { found: false, checkedAt: now } }); } else { const ok = checkSeen({ ...seen, id: job.imvuProduct }); if (!ok) throw new ProductError(400, "invalid", "That isn't a product's info."); await this.keepSeen([ok], new Date()); [info] = await this.db.select().from(imvuProductInfo).where(eq(imvuProductInfo.id, job.imvuProduct)); } return { rating: info?.rating ?? null, covered: !!info && covers(g, job.imvuProduct, info.creatorId) }; } /** Queues signed-in listings of a catalog's whole-shop grants (once its importer has an Access Pass account). */ async queueListings(catalogId: string): Promise { const grants = await this.db .select() .from(importGrant) .where(and(eq(importGrant.catalogId, catalogId), eq(importGrant.status, "active"), eq(importGrant.scope, "shop"))); let n = 0; for (const g of grants) if (await this.queueListing(g)) n++; return n; } /** A job of this catalog's that its importer has claimed. */ private async claimedJob(c: Catalog, jobId: string): Promise { const [job] = await this.db.select().from(importJob).where(and(eq(importJob.id, jobId), eq(importJob.catalogId, c.id))); if (!job) throw new ProductError(404, "not_found", "No such job."); if (job.status !== "claimed") throw new ProductError(409, "not_claimed", "That job isn't claimed."); return job; } /** 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 ---- /** * Someone asks for an IMVU product (or a creator's whole shop). Covered by an active grant: queued, or added to * their library if it's imported already. Otherwise: a suggestion to a creator who grants by products, or counted. */ async request( personId: string, target: { imvuProduct?: number; imvuCreator?: number }, ): Promise<{ status: "added" | "queued" | "suggested" | "counted"; product?: string }> { const [today] = await this.db .select({ n: sql`count(*)::int` }) .from(importRequest) .where(and(eq(importRequest.userId, personId), sql`${importRequest.createdAt} > now() - interval '1 day'`)); if ((today?.n ?? 0) >= requestsPerDay) throw new ProductError(429, "rate_limited", `You can ask for ${requestsPerDay} a day. Try again tomorrow.`); if (target.imvuCreator !== undefined) { if (!Number.isSafeInteger(target.imvuCreator) || target.imvuCreator <= 0) throw new ProductError(400, "invalid", "That isn't an IMVU account ID."); await this.db.insert(importRequest).values({ userId: personId, imvuCreator: target.imvuCreator, imvuProduct: 0 }).onConflictDoNothing(); return { status: "counted" }; } const id = target.imvuProduct ?? 0; const info = await this.info(id); if (!info) throw new ProductError(404, "not_found", "IMVU doesn't show that product publicly."); if (!info.creatorId) throw new ProductError(502, "imvu_unclear", "IMVU didn't say who made that product. Try again later."); await this.db.insert(importRequest).values({ userId: personId, imvuCreator: info.creatorId, imvuProduct: id }).onConflictDoNothing(); const grants = await this.db.select().from(importGrant).where(eq(importGrant.imvuId, info.creatorId)); const covering = grants.filter((g) => covers(g, id, info.creatorId)); if (covering.length) { const [imported] = await this.db.select().from(product).where(eq(product.imvuProduct, id)); if (imported && !imported.removedAt && imported.latest > 0) { await this.fulfil(id, imported.id); return { status: "added", product: imported.id }; } for (const g of covering) await this.queue(g, id, "import"); return { status: "queued" }; } if (grants.some((g) => g.status === "active" && g.scope === "products")) return { status: "suggested" }; return { status: "counted" }; } /** How many people asked for an IMVU creator's products: per product (0: the whole shop), most asked first. */ async requestCounts(imvuCreator: number) { const rows = await this.db .select({ imvuProduct: importRequest.imvuProduct, n: sql`count(*)::int`, name: imvuProductInfo.name }) .from(importRequest) .leftJoin(imvuProductInfo, eq(imvuProductInfo.id, importRequest.imvuProduct)) .where(eq(importRequest.imvuCreator, imvuCreator)) .groupBy(importRequest.imvuProduct, imvuProductInfo.name) .orderBy(desc(sql`count(*)`), asc(importRequest.imvuProduct)) .limit(200); return rows.map((r) => ({ imvuProduct: r.imvuProduct, name: r.name ?? "", requests: r.n })); } /** IMVU creators people asked for most (for admins: whom it's worth asking). */ async topRequested(limit = 50) { return this.db .select({ imvuCreator: importRequest.imvuCreator, name: sql`coalesce((select max(i.creator_name) from ${imvuProductInfo} i where i.creator_id = ${importRequest.imvuCreator}), '')`, people: sql`count(distinct ${importRequest.userId})::int`, products: sql`count(distinct ${importRequest.imvuProduct}) filter (where ${importRequest.imvuProduct} <> 0)::int`, }) .from(importRequest) .groupBy(importRequest.imvuCreator) .orderBy(desc(sql`count(distinct ${importRequest.userId})`)) .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`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 .update(importRequest) .set({ fulfilledAt: new Date() }) .where(and(eq(importRequest.imvuProduct, imvuProduct), sql`${importRequest.fulfilledAt} is null`)) .returning({ userId: importRequest.userId }); if (waiting.length) await this.db .insert(library) .values(waiting.map((w) => ({ userId: w.userId, productId }))) .onConflictDoNothing(); } // ---- jobs ---- /** Queues a job (unless one is open for that product in that catalog). Returns whether it was queued. */ async queue(g: Grant, imvuProduct: number, kind: "import" | "recheck"): Promise { const [j] = await this.db .insert(importJob) .values({ id: newProductID(), catalogId: g.catalogId, grantId: g.id, imvuProduct, kind }) .onConflictDoNothing() .returning(); return j !== undefined; } /** An importer claims queued jobs (none while its catalog's importer is paused). Claims older than the timeout go * back to the queue first. */ async claim(c: Catalog, limit: number) { if (c.importer !== "on") return []; await this.db .update(importJob) .set({ status: "queued", claimedAt: null }) .where(and(eq(importJob.catalogId, c.id), eq(importJob.status, "claimed"), lt(importJob.claimedAt, new Date(Date.now() - claimTimeout)))); const n = Math.min(Math.max(Math.trunc(limit) || 1, 1), 20); const jobs = await this.db.transaction(async (tx) => { const due = await tx .select({ id: importJob.id }) .from(importJob) .where(and(eq(importJob.catalogId, c.id), eq(importJob.status, "queued"), sql`${importJob.nextAt} <= now()`)) .orderBy(asc(importJob.nextAt)) .limit(n) .for("update", { skipLocked: true }); if (due.length === 0) return []; return tx .update(importJob) .set({ status: "claimed", claimedAt: new Date() }) .where(inArray(importJob.id, due.map((d) => d.id))) .returning(); }); const last = jobs.length ? await this.db .select({ imvuProduct: product.imvuProduct, imvuRevision: sql`max(${productRevision.imvuRevision})` }) .from(product) .innerJoin(productRevision, eq(productRevision.productId, product.id)) .where(inArray(product.imvuProduct, jobs.map((j) => j.imvuProduct))) .groupBy(product.imvuProduct) : []; // IMVU's rating, as the hub knows it: the importer writes it into index.xml (IMVU's files have no ProductRating), // so the files agree with the revision's rating (the higher of the two). const infos = jobs.length ? await this.db .select({ id: imvuProductInfo.id, rating: imvuProductInfo.rating }) .from(imvuProductInfo) .where(and(inArray(imvuProductInfo.id, jobs.map((j) => j.imvuProduct)), eq(imvuProductInfo.found, true))) : []; return jobs.map((j) => j.kind === "list" ? { id: j.id, kind: j.kind, imvuProduct: 0, imvuCreator: j.imvuProduct, lastRevision: 0, rating: null } : { id: j.id, kind: j.kind, imvuProduct: j.imvuProduct, lastRevision: last.find((l) => l.imvuProduct === j.imvuProduct)?.imvuRevision ?? 0, rating: infos.find((i) => i.id === j.imvuProduct)?.rating ?? null, }, ); } /** A claimed job of this catalog's, whose grant still covers its product. */ private async liveJob(c: Catalog, jobId: string): Promise<{ job: Job; grant: Grant; info: ImvuInfo }> { const [job] = await this.db.select().from(importJob).where(and(eq(importJob.id, jobId), eq(importJob.catalogId, c.id))); if (!job) throw new ProductError(404, "not_found", "No such job."); if (job.status !== "claimed") throw new ProductError(409, "not_claimed", "That job isn't claimed."); if (job.kind === "list") throw new ProductError(409, "not_product", "That job is a shop listing."); const g = await this.grant(job.grantId); const info = await this.info(job.imvuProduct); if (!info || !covers(g, job.imvuProduct, info.creatorId)) throw new ProductError(409, "not_covered", "The grant no longer covers this product."); return { job, grant: g, info }; } /** A `t5de-import` token for a claimed job's revision, and where to upload it. */ async jobToken(c: Catalog, jobId: string, imvuRevision: number) { if (!Number.isSafeInteger(imvuRevision) || imvuRevision <= 0) throw new ProductError(400, "invalid", "imvuRevision must be a revision number."); const { job } = await this.liveJob(c, jobId); const token = await this.signer.sign( "t5de-import", { sub: job.id, catalog: c.id, imvuProduct: job.imvuProduct, imvuRevision }, 30 * 60, ); return { token, url: `${c.url}/api/v1/uploads` }; } /** The importer reports a job's outcome. Failures retry with backoff, then fail for good. */ async report(c: Catalog, jobId: string, body: { status: string; imvuRevision?: number; reason?: string }): Promise { const [job] = await this.db.select().from(importJob).where(and(eq(importJob.id, jobId), eq(importJob.catalogId, c.id))); if (!job) throw new ProductError(404, "not_found", "No such job."); if (job.status !== "claimed") throw new ProductError(409, "not_claimed", "That job isn't claimed."); const reason = (body.reason ?? "").trim().slice(0, 500); let set: Partial; if (body.status === "done" || body.status === "unchanged") { set = { status: "done", imvuRevision: body.imvuRevision ?? job.imvuRevision, reason: body.status === "unchanged" ? "unchanged" : "", claimedAt: null }; } else if (body.status === "failed") { const attempts = job.attempts + 1; set = attempts >= maxAttempts ? { status: "failed", attempts, reason: reason || "failed", claimedAt: null } : { status: "queued", attempts, reason: reason || "failed", claimedAt: null, nextAt: new Date(Date.now() + backoff[attempts - 1]!) }; } else throw new ProductError(400, "invalid", "status is done, unchanged or failed."); const [updated] = await this.db.update(importJob).set(set).where(eq(importJob.id, job.id)).returning(); return updated!; } /** A catalog's jobs, newest first (optionally by status). */ async jobs(catalogId: string, status?: string, limit = 100) { return this.db .select({ job: importJob, name: imvuProductInfo.name }) .from(importJob) .leftJoin(imvuProductInfo, eq(imvuProductInfo.id, importJob.imvuProduct)) .where(and(eq(importJob.catalogId, catalogId), status ? eq(importJob.status, status) : undefined)) .orderBy(desc(importJob.updatedAt)) .limit(limit); } /** The catalog's team retries a failed job (or re-imports a product): queued now, attempts reset. */ async retry(catalogId: string, jobId: string): Promise { const [job] = await this.db .update(importJob) .set({ status: "queued", attempts: 0, reason: "", nextAt: new Date(), claimedAt: null }) .where(and(eq(importJob.id, jobId), eq(importJob.catalogId, catalogId), inArray(importJob.status, ["failed", "done"]))) .returning(); if (!job) throw new ProductError(404, "not_found", "No such finished job."); const g = await this.grant(job.grantId); if (g.status !== "active") throw new ProductError(409, "not_covered", "Its grant isn't active."); return job; } // ---- registering imported revisions (from the catalog, after the importer's upload) ---- /** * A catalog registers an imported revision (`importToken` instead of `uploadToken`): the job must be claimed and * its grant still cover the product. A new product is published at once, owned by the grant's creator; a revision * another catalog imported already is hosted here too (same files only). The job is done, and those who asked get * the product. */ async register(c: Catalog, body: { importToken: string; files: unknown; rating: string; parent: number; name: string; notes?: string }) { const claims = await this.signer.verify(body.importToken, "t5de-import"); if (!claims || claims.catalog !== c.id || typeof claims.sub !== "string") throw new ProductError(401, "bad_token", "The import token isn't valid for this catalog."); const imvuRevision = Number(claims.imvuRevision); const { job, grant: g, info } = await this.liveJob(c, claims.sub); if (Number(claims.imvuProduct) !== job.imvuProduct) throw new ProductError(401, "bad_token", "The import token isn't for this job."); const files = checkFiles(body.files); if (!files) throw new ProductError(400, "invalid", "The file list isn't valid."); if (body.rating !== "general" && body.rating !== "adult") throw new ProductError(400, "invalid", "The rating must be general or adult."); // The higher of IMVU's rating and the files'. const rating = body.rating === "adult" || info.rating === "adult" ? "adult" : "general"; if (rating === "adult" && c.maxRating === "general") throw new ProductError(400, "rating_ceiling", "This catalog hosts general-audience products only."); const parent = Number.isSafeInteger(body.parent) && body.parent > 0 ? body.parent : 0; const blocked = await this.db .select({ sha256: fileBlock.sha256 }) .from(fileBlock) .where(inArray(fileBlock.sha256, [...new Set(files.map((f) => f.sha256))])); if (blocked.length) { const hit = new Set(blocked.map((b) => b.sha256)); throw new BlockedUpload(g.creatorId, c.id, files.filter((f) => hit.has(f.sha256))); } const made = await this.db.transaction(async (tx) => { let [p] = await tx.select().from(product).where(eq(product.imvuProduct, job.imvuProduct)).for("update"); if (p?.removedAt) throw new ProductError(410, "removed", "This product was removed or withdrawn on T5DE."); if (!p) { const name = (info.name || body.name || "Untitled").trim().slice(0, 64); const description = `

Imported from IMVU with its creator's permission. ` + `Its IMVU page.

`; [p] = await tx .insert(product) .values({ id: newProductID(), creatorId: g.creatorId, name, description, rating, status: "published", publishedAt: new Date(), listed: g.listed, imvuProduct: job.imvuProduct, }) .returning(); } const [same] = await tx .select() .from(productRevision) .where(and(eq(productRevision.productId, p!.id), eq(productRevision.imvuRevision, imvuRevision))); if (same) { if (!sameFiles(same.files, files)) throw new ProductError(409, "different_files", "That IMVU revision was imported with other files."); await tx.insert(hosting).values({ catalogId: c.id, productId: p!.id, number: same.number }).onConflictDoNothing(); return { product: p!.id, revision: same.number, draft: false }; } const number = p!.latest + 1; const token = await this.signer.sign("t5de-revision", { product: p!.id, revision: number, rating, files, parent }); await tx.insert(productRevision).values({ productId: p!.id, number, files, rating, parent, notes: `Imported from IMVU revision ${imvuRevision}.`, token, uploadedBy: g.creatorId, imvuRevision, }); await tx .update(product) .set({ latest: number, rating: p!.rating === "adult" || rating === "adult" ? "adult" : "general" }) .where(eq(product.id, p!.id)); await tx.insert(hosting).values({ catalogId: c.id, productId: p!.id, number }); return { product: p!.id, revision: number, draft: false }; }); await this.db.update(importJob).set({ status: "done", imvuRevision, reason: "", claimedAt: null }).where(eq(importJob.id, job.id)); await this.fulfil(job.imvuProduct, made.product); return { ...made, creatorId: g.creatorId }; } // ---- upkeep ---- /** * Daily: re-checks imported products with IMVU (gone, or another creator's: withdrawn; rated AP: adult) and queues * a recheck job (new revisions) for each active grant's imported products not checked in a day. */ async recheck(limit = 200): Promise<{ queued: number; withdrawn: string[] }> { const rows = await this.db .select({ grant: importGrant, productId: product.id, imvuProduct: product.imvuProduct, rating: product.rating }) .from(importGrant) .innerJoin(hosting, eq(hosting.catalogId, importGrant.catalogId)) .innerJoin(product, and(eq(product.id, hosting.productId), eq(product.creatorId, importGrant.creatorId))) // As last seen: the grant's IMVU account's products. .innerJoin(imvuProductInfo, and(eq(imvuProductInfo.id, product.imvuProduct), eq(imvuProductInfo.creatorId, importGrant.imvuId))) .where( and( eq(importGrant.status, "active"), sql`${product.imvuProduct} is not null`, sql`${product.removedAt} is null`, sql`not exists (select 1 from ${importJob} j where j.catalog_id = ${importGrant.catalogId} and j.imvu_product = ${product.imvuProduct} and j.updated_at > now() - interval '1 day')`, ), ) .limit(limit); let queued = 0; const withdrawn: string[] = []; const seen = new Set(); for (const r of rows) { const key = `${r.grant.catalogId}:${r.imvuProduct}`; if (seen.has(key)) continue; seen.add(key); let info: ImvuInfo | undefined; try { info = await this.info(r.imvuProduct!, true); } catch { continue; // IMVU unavailable: next time } if (!info || info.creatorId !== r.grant.imvuId) { await this.unhost(r.productId); await this.db .update(product) .set({ removedAt: new Date(), removedReason: info ? "Withdrawn: another creator's on IMVU now." : "Withdrawn: gone from IMVU." }) .where(eq(product.id, r.productId)); withdrawn.push(r.productId); continue; } if (info.rating === "adult" && r.rating !== "adult") await this.db.update(product).set({ rating: "adult" }).where(eq(product.id, r.productId)); if (covers(r.grant, r.imvuProduct!, info.creatorId) && (await this.queue(r.grant, r.imvuProduct!, "recheck"))) queued++; } return { queued, withdrawn }; } } // Field by field: stored lists come back from JSONB with their keys in another order. const sameFiles = (a: FileEntry[], b: FileEntry[]) => a.length === b.length && a.every((f, i) => f.name === b[i]!.name && f.sha256 === b[i]!.sha256 && f.size === b[i]!.size);