feat: whole shops listed on IMVU, and GET /imports/available (#16)
Co-authored-by: dhkatz <[email protected]>
This commit was merged in pull request #16.
This commit is contained in:
1 parent
8f6dacba10
commit
efc7d6b808
15 files changed
+4954
-20
No files matched your search
+208
-10
@@ -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
|
||||
|
||||
Reference in new issue
Block a user