328 lines
9.7 KiB
TypeScript
328 lines
9.7 KiB
TypeScript
import { MatrixClient } from 'matrix-js-sdk';
|
|
import { StoredCollectible } from './profileFields';
|
|
|
|
export type CollectibleKind = 'profile_effect' | 'nameplate' | 'avatar_decoration';
|
|
|
|
export type DiscordCollectibleAsset = {
|
|
role: string;
|
|
url: string;
|
|
filename: string;
|
|
mimeType: string;
|
|
};
|
|
|
|
export type DiscordCollectibleItem = {
|
|
id: string;
|
|
skuId: string;
|
|
name: string;
|
|
type: CollectibleKind;
|
|
category: string;
|
|
label: string;
|
|
thumbnailUrl?: string;
|
|
previewAspectRatio?: number;
|
|
previewColors?: number[];
|
|
previewGradient?: string;
|
|
palette?: string;
|
|
paletteLabel?: string;
|
|
assets: DiscordCollectibleAsset[];
|
|
effect?: {
|
|
animationType?: number;
|
|
thumbnailPreviewSrc?: string;
|
|
reducedMotionSrc?: string;
|
|
effects?: Array<Record<string, unknown>>;
|
|
};
|
|
};
|
|
|
|
export type DownloadedCollectibleAsset = DiscordCollectibleAsset & {
|
|
data: Uint8Array;
|
|
};
|
|
|
|
const CDN_HOST_RE = /(^|\.)(discordapp\.com|discordapp\.net|discord\.com)$/i;
|
|
const PUBLISHED_CATALOG_URLS = [
|
|
'https://github.com/litruv/discord-collectibles/releases/download/latest/profileeffects.json',
|
|
'https://github.com/litruv/discord-collectibles/releases/download/latest/nameplate.json',
|
|
'https://github.com/litruv/discord-collectibles/releases/download/latest/avatardecorations.json',
|
|
];
|
|
const CATALOG_CACHE_KEY = 'paarrot.discordCollectiblesCatalog';
|
|
const CATALOG_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
|
|
|
|
type PublishedCatalog = {
|
|
schema_version: number;
|
|
fetchedAt: string;
|
|
items: DiscordCollectibleItem[];
|
|
};
|
|
|
|
function isPublishedCatalog(
|
|
value: unknown,
|
|
): value is { schema_version: number; items: DiscordCollectibleItem[] } {
|
|
if (!value || typeof value !== 'object') return false;
|
|
const catalog = value as Record<string, unknown>;
|
|
return (
|
|
catalog.schema_version === 1 &&
|
|
Array.isArray(catalog.items) &&
|
|
catalog.items.every(
|
|
(item) =>
|
|
item &&
|
|
typeof item === 'object' &&
|
|
typeof (item as DiscordCollectibleItem).id === 'string' &&
|
|
Array.isArray((item as DiscordCollectibleItem).assets),
|
|
)
|
|
);
|
|
}
|
|
|
|
function loadCachedCatalog(): PublishedCatalog | undefined {
|
|
try {
|
|
const raw = localStorage.getItem(CATALOG_CACHE_KEY);
|
|
if (!raw) return undefined;
|
|
const cached = JSON.parse(raw) as PublishedCatalog;
|
|
if (
|
|
!isPublishedCatalog(cached) ||
|
|
typeof cached.fetchedAt !== 'string' ||
|
|
Date.now() - Date.parse(cached.fetchedAt) >= CATALOG_CACHE_TTL_MS
|
|
) {
|
|
return undefined;
|
|
}
|
|
return cached;
|
|
} catch {
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
function saveCachedCatalog(catalog: PublishedCatalog): void {
|
|
try {
|
|
localStorage.setItem(CATALOG_CACHE_KEY, JSON.stringify(catalog));
|
|
} catch {
|
|
// A full or unavailable storage backend should not prevent catalog use.
|
|
}
|
|
}
|
|
|
|
export async function fetchPublishedCollectiblesCatalog(
|
|
force = false,
|
|
): Promise<DiscordCollectibleItem[]> {
|
|
const cached = loadCachedCatalog();
|
|
if (!force && cached) return cached.items;
|
|
|
|
try {
|
|
const documents = await Promise.all(
|
|
PUBLISHED_CATALOG_URLS.map(async (url) => {
|
|
const response = await fetch(url);
|
|
if (!response.ok) throw new Error(`Catalog request failed with HTTP ${response.status}.`);
|
|
const catalog = await response.json();
|
|
if (!isPublishedCatalog(catalog)) throw new Error('Catalog has an unsupported schema.');
|
|
return catalog;
|
|
}),
|
|
);
|
|
const items = documents.flatMap((catalog) => catalog.items);
|
|
if (items.length === 0) throw new Error('Catalog is empty.');
|
|
|
|
saveCachedCatalog({ schema_version: 1, fetchedAt: new Date().toISOString(), items });
|
|
return items;
|
|
} catch (error) {
|
|
if (cached) return cached.items;
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
function isCdnUrl(value: unknown): value is string {
|
|
if (typeof value !== 'string' || !value.startsWith('http')) return false;
|
|
try {
|
|
return CDN_HOST_RE.test(new URL(value).hostname);
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function replaceCdnUrls<T>(value: T, urlToMxc: Map<string, string>): T {
|
|
if (value == null) return value;
|
|
if (typeof value === 'string') {
|
|
return (isCdnUrl(value) && urlToMxc.has(value) ? urlToMxc.get(value) : value) as T;
|
|
}
|
|
if (Array.isArray(value)) {
|
|
return value.map((entry) => replaceCdnUrls(entry, urlToMxc)) as T;
|
|
}
|
|
if (typeof value === 'object') {
|
|
const out: Record<string, unknown> = {};
|
|
Object.entries(value as Record<string, unknown>).forEach(([key, entry]) => {
|
|
out[key] = replaceCdnUrls(entry, urlToMxc);
|
|
});
|
|
return out as T;
|
|
}
|
|
return value;
|
|
}
|
|
|
|
export async function downloadCollectibleAssets(
|
|
assets: DiscordCollectibleAsset[],
|
|
): Promise<DownloadedCollectibleAsset[]> {
|
|
const api = window.electron?.discordCollectibles;
|
|
if (api) {
|
|
const result = await api.downloadAssets(assets);
|
|
if (!result?.success || !result.data) {
|
|
throw new Error(result?.error || 'Failed to download collectible assets from Discord CDN.');
|
|
}
|
|
return result.data.map((asset) => ({
|
|
role: asset.role,
|
|
url: asset.url,
|
|
filename: asset.filename,
|
|
mimeType: asset.mimeType,
|
|
data: asset.data instanceof Uint8Array ? asset.data : new Uint8Array(asset.data),
|
|
}));
|
|
}
|
|
|
|
return Promise.all(
|
|
assets.map(async (asset) => {
|
|
if (!isCdnUrl(asset.url)) throw new Error('Collectible asset URL is not a Discord CDN URL.');
|
|
const response = await fetch(asset.url);
|
|
if (!response.ok)
|
|
throw new Error(`Failed to download ${asset.filename}: HTTP ${response.status}.`);
|
|
return {
|
|
...asset,
|
|
data: new Uint8Array(await response.arrayBuffer()),
|
|
};
|
|
}),
|
|
);
|
|
}
|
|
|
|
export async function uploadCollectibleToMatrix(
|
|
mx: MatrixClient,
|
|
item: DiscordCollectibleItem,
|
|
onProgress?: (message: string) => void,
|
|
): Promise<StoredCollectible> {
|
|
onProgress?.('Downloading from Discord…');
|
|
const downloaded = await downloadCollectibleAssets(item.assets);
|
|
|
|
const urlToMxc = new Map<string, string>();
|
|
const assets: Record<string, string> = {};
|
|
|
|
for (let i = 0; i < downloaded.length; i += 1) {
|
|
const asset = downloaded[i];
|
|
onProgress?.(`Uploading ${asset.filename}…`);
|
|
const blob = new Blob([asset.data], { type: asset.mimeType });
|
|
const file = new File([blob], asset.filename, { type: asset.mimeType });
|
|
const response = await mx.uploadContent(file, {
|
|
name: asset.filename,
|
|
type: asset.mimeType,
|
|
includeFilename: true,
|
|
});
|
|
if (!response.content_uri) {
|
|
throw new Error(`Failed to upload ${asset.filename} to Matrix.`);
|
|
}
|
|
urlToMxc.set(asset.url, response.content_uri);
|
|
assets[asset.role] = response.content_uri;
|
|
}
|
|
|
|
const stored: StoredCollectible = {
|
|
sku_id: item.skuId,
|
|
name: item.name,
|
|
assets,
|
|
};
|
|
|
|
if (item.effect) {
|
|
stored.effect = replaceCdnUrls(item.effect, urlToMxc);
|
|
}
|
|
|
|
return stored;
|
|
}
|
|
|
|
export function collectibleKindLabel(kind: CollectibleKind): string {
|
|
switch (kind) {
|
|
case 'profile_effect':
|
|
return 'Profile effect';
|
|
case 'nameplate':
|
|
return 'Nameplate';
|
|
case 'avatar_decoration':
|
|
return 'Avatar decoration';
|
|
default:
|
|
return kind;
|
|
}
|
|
}
|
|
|
|
export type CollectibleVariantGroup = {
|
|
id: string;
|
|
name: string;
|
|
category: string;
|
|
items: DiscordCollectibleItem[];
|
|
};
|
|
|
|
function stripBundleSuffix(name: string): string {
|
|
return name.replace(/\s+Bundle$/i, '').trim();
|
|
}
|
|
|
|
function stripVariantSuffix(name: string): string {
|
|
return name.replace(/\s*\([^)]+\)\s*$/, '').trim();
|
|
}
|
|
|
|
export function variantGroupKey(item: DiscordCollectibleItem): string {
|
|
const baseName = stripVariantSuffix(stripBundleSuffix(item.name));
|
|
return `${item.type}:${baseName}`;
|
|
}
|
|
|
|
export function variantGroupDisplayName(item: DiscordCollectibleItem): string {
|
|
return stripVariantSuffix(stripBundleSuffix(item.name));
|
|
}
|
|
|
|
export function variantItemLabel(item: DiscordCollectibleItem): string {
|
|
if (item.paletteLabel) return item.paletteLabel;
|
|
const nameMatch = item.name.match(/\(([^)]+)\)\s*$/);
|
|
if (nameMatch) return nameMatch[1];
|
|
const labelMatch = item.label.match(/\(([^)]+)\)\s*$/);
|
|
if (labelMatch) return labelMatch[1];
|
|
if (item.label && item.label !== item.name) return item.label;
|
|
return 'Default';
|
|
}
|
|
|
|
function dedupeVariantItems(items: DiscordCollectibleItem[]): DiscordCollectibleItem[] {
|
|
const seen = new Set<string>();
|
|
return items.filter((item) => {
|
|
if (seen.has(item.skuId)) return false;
|
|
seen.add(item.skuId);
|
|
return true;
|
|
});
|
|
}
|
|
|
|
export function groupCollectibleItems(items: DiscordCollectibleItem[]): CollectibleVariantGroup[] {
|
|
const map = new Map<string, DiscordCollectibleItem[]>();
|
|
|
|
items.forEach((item) => {
|
|
const key = variantGroupKey(item);
|
|
const list = map.get(key);
|
|
if (list) list.push(item);
|
|
else map.set(key, [item]);
|
|
});
|
|
|
|
return [...map.entries()]
|
|
.map(([id, groupItems]) => {
|
|
const sortedItems = dedupeVariantItems(groupItems).sort((a, b) =>
|
|
variantItemLabel(a).localeCompare(variantItemLabel(b)),
|
|
);
|
|
return {
|
|
id,
|
|
name: variantGroupDisplayName(sortedItems[0]),
|
|
category: sortedItems[0].category,
|
|
items: sortedItems,
|
|
};
|
|
})
|
|
.sort((a, b) => a.name.localeCompare(b.name));
|
|
}
|
|
|
|
export function defaultPreviewAspectRatio(kind: CollectibleKind): number {
|
|
switch (kind) {
|
|
case 'profile_effect':
|
|
return 450 / 880;
|
|
case 'nameplate':
|
|
return 448 / 84;
|
|
case 'avatar_decoration':
|
|
return 1;
|
|
default:
|
|
return 1;
|
|
}
|
|
}
|
|
|
|
export function gradientFromPreviewColors(colors?: number[]): string | undefined {
|
|
if (!colors?.length) return undefined;
|
|
const toRgb = (value: number) => {
|
|
const n = value >>> 0;
|
|
return `rgb(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255})`;
|
|
};
|
|
if (colors.length === 1) return toRgb(colors[0]);
|
|
return `linear-gradient(135deg, ${toRgb(colors[0])}, ${toRgb(colors[1])})`;
|
|
}
|