all repos — stealth-developers @ 370c3cfed785af5c63907c6152427e81b5f1c7ba

src/utils/profile.ts (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
import { roblox } from "@/roblox/client";
import type {
	GetUserResponse,
	RobloxUserId,
	UserRestrictionLog,
} from "@/roblox/types";
import {
	ActionRowBuilder,
	ButtonBuilder,
	ButtonStyle,
	ContainerBuilder,
	SectionBuilder,
	SeparatorBuilder,
	TextDisplayBuilder,
} from "discord.js";
import { text, thumbnail } from "./components";

// -- utils ----------------------------------------------------------------------------------------

// ---- timing -----------------------------------------------------------------
export function tsExact(d: string | Date) {
	const date = new Date(d);
	return `<t:${Math.floor(date.getTime() / 1000)}:f>`;
}

export function tsRelative(d: string | Date) {
	const date = new Date(d);
	return `<t:${Math.floor(date.getTime() / 1000)}:R>`;
}

export function durationToMs(duration?: string | undefined): number | null {
	if (!duration) return null;
	const m = duration.trim().match(/^(-?\d+(?:\.\d+)?)(ms|s|m|h|d)$/i);
	if (!m) return null;
	const value = Number.parseFloat(m[1]);
	const unit = m[2].toLowerCase();

	switch (unit) {
		case "ms":
			return value;
		case "s":
			return value * 1000;
		case "m":
			return value * 60 * 1000;
		case "h":
			return value * 60 * 60 * 1000;
		case "d":
			return value * 24 * 60 * 60 * 1000;
		default:
			return null;
	}
}

export function formatDurationShort(duration?: string | null) {
	if (!duration) return "permanent";
	const ms = durationToMs(duration);
	if (ms == null) return "permanent";

	if (ms < 1000) return `${ms}ms`;
	const secs = Math.floor(ms / 1000);
	if (secs < 60) return `${secs}s`;
	const mins = Math.floor(secs / 60);
	if (mins < 60) return `${mins}m`;
	const hours = Math.floor(mins / 60);
	if (hours < 24) return `${hours}h`;
	const days = Math.floor(hours / 24);
	return `${days}d`;
}

export function getDurationString(opts: {
	duration?: string;
	startDate?: Date;
	inclDuration?: boolean;
}): {
	endRelative: string;
	endAbsolute: string;
} {
	const { duration, startDate } = opts;
	const perm = {
		endRelative: "permanent",
		endAbsolute: "permanent",
	};
	if (!duration) return perm;
	if (!startDate) return perm;

	const durationMs = durationToMs(duration);
	if (!durationMs) return perm;

	const startMs = startDate.getTime();
	const endMs = startMs + durationMs;
	const endDate = new Date(endMs);

	return {
		endAbsolute: tsExact(endDate),
		endRelative: tsRelative(endDate),
	};
}

// ---- moderators -------------------------------------------------------------
const ModeratorCache = new Map<RobloxUserId, string>();

export async function moderatorMention(
	moderator:
		| { robloxUser: `users/${RobloxUserId}` }
		| { gameServerScript: unknown },
) {
	if ("gameServerScript" in moderator) {
		return "Banned in-game";
	}
	if ("robloxUser" in moderator) {
		const id = moderator.robloxUser.split("/").pop();
		if (!id) return moderator.robloxUser;

		let moderatorUsername = ModeratorCache.get(id);
		if (!moderatorUsername) {
			const [userRes] = await roblox.getUser(id);
			if (!userRes) return id;

			moderatorUsername = userRes.displayName;
			ModeratorCache.set(id, moderatorUsername);
		}

		const url = `https://www.roblox.com/users/${id}/profile`;
		return `[${moderatorUsername || id}](${url})`;
	}
	return "Unknown";
}

// -- cards ----------------------------------------------------------------------------------------

// ---- bans -------------------------------------------------------------------
export async function constructBansContainer(
	bans: UserRestrictionLog[] | null,
	opts: { limit?: number; showPrivate?: boolean; userId?: string } = {},
) {
	const limit = opts.limit ?? 5;
	const showPrivate = Boolean(opts.showPrivate);

	if (!bans || bans.length === 0) {
		const c = new ContainerBuilder().addTextDisplayComponents(
			new TextDisplayBuilder().setContent(
				"### Bans\n-# No restriction logs found",
			),
		);
		return { container: c, total: 0 };
	}

	type EnrichedLog = UserRestrictionLog & {
		startMs: number;
		endMs: number;
		nowActive: boolean;
	};
	const now = Date.now();
	const enriched: EnrichedLog[] = bans.map((log) => {
		const startMs = new Date(log.startTime).getTime();
		const durationMs = durationToMs(log.duration ?? undefined);
		const endMs =
			durationMs == null ? Number.POSITIVE_INFINITY : startMs + durationMs;
		const nowActive = now < endMs;
		return { ...log, startMs, endMs, nowActive };
	});

	const sorted = enriched.sort((a, b) => b.startMs - a.startMs);

	const newerIntervals: { startMs: number; endMs: number }[] = [];
	const statuses = new Map<string, "ACTIVE" | "SUPERSEDED" | "EXPIRED">();

	for (const log of sorted) {
		const isSuperseded = newerIntervals.some(
			(n) => n.startMs <= log.endMs && n.endMs >= log.startMs,
		);

		if (isSuperseded) statuses.set(log.createTime, "SUPERSEDED");
		else if (log.nowActive && log.active)
			statuses.set(log.createTime, "ACTIVE");
		else statuses.set(log.createTime, "EXPIRED");

		newerIntervals.push({ startMs: log.startMs, endMs: log.endMs });
	}

	const shown = sorted.slice(0, limit);

	const lines = shown.map(async (log) => {
		if (!log) return undefined;

		const reason = log.displayReason || "no public reason";
		const moderator = await moderatorMention(log.moderator);
		const startRel = tsRelative(log.createTime);
		const { endAbsolute, endRelative } = getDurationString({
			duration: log.duration,
			startDate: new Date(log.createTime),
		});

		const bannedFor =
			formatDurationShort(log.duration) === "permanent"
				? "permanently"
				: `for ${formatDurationShort(log.duration)}`;
		const endString =
			endAbsolute === "permanent"
				? undefined
				: `> **Ends:** ${endAbsolute} (${endRelative})`;

		return [
			`Banned **${bannedFor}**, ${startRel}, by **${moderator}**`,
			`> **Reason:** ${reason}`,
			showPrivate
				? `> **Private Reason:** ${log.privateReason || "no private reason"}`
				: undefined,
			endString,
		]
			.filter(Boolean)
			.join("\n");
	});
	const awaitedLines = await Promise.all(lines).then((lines) =>
		lines.filter(Boolean),
	);

	const header = `### Bans - showing ${shown.length} of ${bans.length}`;
	const container = new ContainerBuilder()
		.addTextDisplayComponents(
			new TextDisplayBuilder().setContent(
				`${header}\n\n${awaitedLines.join("\n\n")}`,
			),
		)
		.addSeparatorComponents(
			new SeparatorBuilder().setDivider(false).setSpacing(1),
		);

	return { container, total: bans.length };
}

// ---- user -------------------------------------------------------------------
export async function constructUserContainer(
	profile: GetUserResponse,
	extras?: {
		bans: UserRestrictionLog[] | null;
		thumbnailUri: string | null;
		showPrivate?: boolean;
	},
) {
	const createdAt = new Date(profile.createTime);
	const createdAtMs = Math.round(createdAt.getTime() / 1000);
	const createdAtString = `<t:${createdAtMs}> (<t:${createdAtMs}:R>)`;

	const profileUrl = `https://www.roblox.com/users/${profile.id}/profile`;

	const bodyText = text(
		[
			`## ${profile.displayName}`,
			`@${profile.name} - ${profile.id} - created ${createdAtString}`,
		].join("\n"),
	);
	const aboutText = text(
		["### About", profile.about ? profile.about : "-# No bio provided"].join(
			"\n",
		),
	);

	const section = new SectionBuilder().addTextDisplayComponents(bodyText);
	const icon = thumbnail(extras?.thumbnailUri ?? undefined);
	if (icon) section.setThumbnailAccessory(icon);

	const mainContainer = new ContainerBuilder()
		.addSectionComponents(section)
		.addSeparatorComponents(new SeparatorBuilder())
		.addTextDisplayComponents(aboutText);

	const bans = await constructBansContainer(extras?.bans ?? null, {
		limit: 5,
		userId: profile.id,
		showPrivate: extras?.showPrivate ?? false,
	});

	const profileButton = new ButtonBuilder()
		.setLabel("View Profile")
		.setStyle(ButtonStyle.Link)
		.setURL(profileUrl);

	mainContainer.addActionRowComponents(
		new ActionRowBuilder<ButtonBuilder>().addComponents(profileButton),
	);

	return { mainContainer, bans, buttons: [profileButton] };
}