Stored Discord avatars (#3455)

This commit is contained in:
Kalle
2026-10-23 18:35:27 +03:00
committed by GitHub
parent 93fec1b232
commit 32b8689d8d
157 changed files with 1707 additions and 919 deletions

View File

@@ -1,8 +1,8 @@
import clsx from "clsx";
import * as React from "react";
import type { Tables } from "~/db/tables";
import { generateIdenticon } from "~/utils/identicon";
import { resolveAvatarUrl } from "~/utils/urls";
import type { CommonUser } from "~/utils/kysely.server";
import { avatarUrl } from "~/utils/urls";
import styles from "./Avatar.module.css";
const dimensions = {
@@ -28,9 +28,7 @@ export function Avatar({
loading = "lazy",
...rest
}: {
user?: Pick<Tables["User"], "discordId" | "discordAvatar"> & {
customAvatarUrl?: string | null;
};
user?: Pick<CommonUser, "id" | "avatar">;
url?: string | null;
identiconInput?: string;
className?: string;
@@ -46,21 +44,17 @@ export function Avatar({
if (img?.complete && img.naturalWidth === 0) setIsErrored(true);
};
const identiconSource = identiconInput ?? user?.discordId ?? "unknown";
const identiconSource =
identiconInput ?? (user ? String(user.id) : "unknown");
const userAvatarUrl = user
? resolveAvatarUrl({
customAvatarUrl: user.customAvatarUrl,
discordId: user.discordId,
discordAvatar: user.discordAvatar,
size: size === "lg" || size === "xmd" ? "lg" : "sm",
})
const userAvatarUrl = user?.avatar
? avatarUrl(user.avatar, size === "lg" || size === "xmd" ? "lg" : "sm")
: undefined;
const avatarUrl = url ?? userAvatarUrl;
const imageUrl = url ?? userAvatarUrl;
const src =
avatarUrl && !isErrored ? avatarUrl : generateIdenticon(identiconSource);
imageUrl && !isErrored ? imageUrl : generateIdenticon(identiconSource);
return (
<div className={clsx(styles.avatarWrapper, className)}>

View File

@@ -67,10 +67,8 @@ export interface BuildCardProps {
modes: ModeShort[] | null;
weapons: Array<BuildWeaponWithTop500Info>;
};
owner?: Pick<UserWithPlusTier, "discordId" | "username" | "plusTier"> &
Partial<
Pick<BuildGraphicOwner, "customUrl" | "discordAvatar" | "customAvatarUrl">
>;
owner?: Pick<UserWithPlusTier, "id" | "username" | "plusTier"> &
Partial<Pick<BuildGraphicOwner, "customUrl" | "avatar">>;
/** false when the page already shows the owner (e.g. their own builds page) */
showOwner?: boolean;
/** Shown at the end of the owner row */
@@ -176,11 +174,7 @@ export function BuildCard({
<div className={styles.owner}>
<Link to={userBuildsPage(owner)} className={styles.ownerLink}>
<Avatar
user={{
discordId: owner.discordId,
discordAvatar: owner.discordAvatar ?? null,
customAvatarUrl: owner.customAvatarUrl,
}}
user={{ id: owner.id, avatar: owner.avatar ?? null }}
size="xxxs"
/>
<span className="truncate">{owner.username}</span>

View File

@@ -1,5 +1,4 @@
import { useTranslation } from "react-i18next";
import type { Tables } from "~/db/tables";
import {
GraphicContainer,
GraphicDateSubtitle,
@@ -13,7 +12,7 @@ import { lfgSearchParams } from "~/features/lfg/lfg-search-params";
import type { UnifiedLanguageCode } from "~/modules/i18n/config";
import type { MainWeaponId } from "~/modules/in-game-lists/types";
import { databaseTimestampToDate } from "~/utils/dates";
import { LFG_PAGE, resolveAvatarUrl } from "~/utils/urls";
import { avatarUrl, LFG_PAGE } from "~/utils/urls";
import { Avatar } from "./Avatar";
import { Flag } from "./Flag";
import { WeaponImage } from "./Image";
@@ -24,10 +23,9 @@ const WEAPON_SIZE = 40;
const MEMBER_WEAPON_SIZE = 28;
interface LFGPostGraphicUser {
id: number;
username: string;
discordId: string;
discordAvatar: Tables["User"]["discordAvatar"];
customAvatarUrl: string | null;
avatar: string | null;
country: string | null;
weaponPool: Array<{
weaponSplId: MainWeaponId;
@@ -47,7 +45,7 @@ export interface LFGPostGraphicPost {
team: {
name: string;
avatarUrl: string | null;
members: Array<LFGPostGraphicUser & { id: number }>;
members: Array<LFGPostGraphicUser>;
} | null;
}
@@ -82,7 +80,7 @@ function PostHeader({ post }: { post: LFGPostGraphicPost }) {
}
: {
avatarUrl: userAvatarUrl(post.author),
identiconInput: post.author.discordId,
identiconInput: String(post.author.id),
};
return (
@@ -147,7 +145,7 @@ function TeamMembersList({
<div key={member.id} className={styles.member}>
<Avatar
url={userAvatarUrl(member)}
identiconInput={member.discordId}
identiconInput={String(member.id)}
size="xxs"
alt=""
/>
@@ -163,12 +161,7 @@ function TeamMembersList({
}
function userAvatarUrl(user: LFGPostGraphicUser) {
return resolveAvatarUrl({
customAvatarUrl: user.customAvatarUrl,
discordId: user.discordId,
discordAvatar: user.discordAvatar,
size: "lg",
});
return user.avatar ? avatarUrl(user.avatar, "lg") : undefined;
}
function languagesLabel(languages: UnifiedLanguageCode[]) {

View File

@@ -1,7 +1,7 @@
import clsx from "clsx";
import type * as React from "react";
import { Link } from "react-router";
import type { Tables } from "~/db/tables";
import type { CommonUser } from "~/utils/kysely.server";
import { Avatar } from "./Avatar";
import styles from "./ListItem.module.css";
@@ -23,9 +23,7 @@ export function ListLink({
icon?: React.ReactNode;
imageUrl?: string;
overlayIconUrl?: string;
user?: Pick<Tables["User"], "discordId" | "discordAvatar"> & {
customAvatarUrl?: string | null;
};
user?: Pick<CommonUser, "id" | "avatar">;
subtitle?: React.ReactNode;
badge?: React.ReactNode;
badgeVariant?: "default" | "warning";
@@ -62,9 +60,7 @@ export function ListButton({
...rest
}: {
children: React.ReactNode;
user?: Pick<Tables["User"], "discordId" | "discordAvatar"> & {
customAvatarUrl?: string | null;
};
user?: Pick<CommonUser, "id" | "avatar">;
subtitle?: string | null;
badge?: string | null;
badgeVariant?: "default" | "warning";
@@ -147,9 +143,7 @@ function ListItemContent({
children: React.ReactNode;
/** Custom leading visual, takes precedence over `user` and `imageUrl` */
icon?: React.ReactNode;
user?: Pick<Tables["User"], "discordId" | "discordAvatar"> & {
customAvatarUrl?: string | null;
};
user?: Pick<CommonUser, "id" | "avatar">;
imageUrl?: string;
overlayIconUrl?: string;
subtitle?: React.ReactNode;

View File

@@ -2,16 +2,13 @@ import clsx from "clsx";
import type * as React from "react";
import { Link } from "react-router";
import type { Tables } from "~/db/tables";
import type { CommonUser } from "~/utils/kysely.server";
import { userPage } from "~/utils/urls";
import { Avatar } from "./Avatar";
import styles from "./UserLink.module.css";
type UserLinkUser = Pick<
Tables["User"],
"username" | "discordId" | "discordAvatar"
> & {
type UserLinkUser = Pick<CommonUser, "id" | "username" | "avatar"> & {
customUrl?: Tables["User"]["customUrl"];
customAvatarUrl?: string | null;
};
type UnlinkedPlayer = { name: string | null } & {

View File

@@ -450,7 +450,7 @@ function getResultHref(result: SearchResult): string {
switch (result.type) {
case "user":
return userPage({
discordId: result.discordId,
id: result.id,
customUrl: result.customUrl,
});
case "team":
@@ -469,8 +469,8 @@ function ResultItem({ result }: { result: SearchResult }) {
<SearchResultsItemRow>
<Avatar
user={{
discordId: result.discordId,
discordAvatar: result.discordAvatar,
id: result.id,
avatar: result.avatar,
}}
size="xxs"
/>

View File

@@ -6,10 +6,8 @@ function user(id: number): CommonUser {
return {
id,
username: `user${id}`,
discordId: `discord${id}`,
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
};
}

View File

@@ -8,7 +8,7 @@ import {
getArtFilename,
SEED_ART_URLS,
} from "../../../../scripts/seed-art-urls";
import { NZAP_TEST_DISCORD_ID, NZAP_YOUTUBE_ID } from "../constants";
import { NZAP_TEST_ID, NZAP_YOUTUBE_ID } from "../constants";
import { faker } from "../core/faker";
import placements from "../data/placements.json";
import * as ArtFactory from "../factories/ArtFactory";
@@ -238,7 +238,7 @@ async function seedNotifications(
type: "TAGGED_TO_ART",
meta: {
adderUsername: "N-ZAP",
adderDiscordId: NZAP_TEST_DISCORD_ID,
adderId: NZAP_TEST_ID,
artId: 1,
},
},

View File

@@ -4,6 +4,7 @@ import type { Tables } from "~/db/tables";
import type { CustomTheme, Pronouns, UserPreferences } from "~/db/tables-json";
import * as AdminRepository from "~/features/admin/AdminRepository.server";
import { ADMIN_ID } from "~/features/admin/admin-constants";
import * as DiscordAvatar from "~/features/auth/core/DiscordAvatar.server";
import * as MatchProfileRepository from "~/features/match-profile/MatchProfileRepository.server";
import * as UserCardRepository from "~/features/user-card/UserCardRepository.server";
import * as UserRepository from "~/features/user-page/UserRepository.server";
@@ -21,6 +22,8 @@ import { pinUserId } from "../core/pinUserId";
import * as SplatoonFaker from "../core/SplatoonFaker";
type UpsertArgs = Parameters<typeof UserRepository.upsert>[0] & {
/** Discord avatar hash, stored as a synced avatar without copying any files to S3. */
discordAvatar?: string | null;
/** Profile fields, saved as the profile page saves them. `null` for a bare profile. */
profile?: Partial<ProfileArgs> | null;
/** Nintendo friend code, `null` for a user who never submitted one. */
@@ -100,9 +103,18 @@ export const { create, createMany } = defineFactory({
profile: fakeProfile(),
friendCode: fakeFriendCode(),
}),
insert: async ({ profile, friendCode, ...args }: UpsertArgs) => {
insert: async ({
profile,
friendCode,
discordAvatar,
...args
}: UpsertArgs) => {
const user = await UserRepository.upsert(args);
if (discordAvatar) {
await insertSyncedAvatar(user.id, discordAvatar);
}
if (profile && Object.keys(profile).length > 0) {
await updateProfile(user.id, profile);
}
@@ -248,20 +260,34 @@ export const createDev = (
options?: Options,
) => createPinned(DEV_TEST_ID, overrides, options);
function insertSyncedAvatar(userId: number, discordAvatar: string) {
return UserRepository.replaceSyncedAvatar({
userId,
discordAvatar,
fileName: DiscordAvatar.fileNameOf({ userId, hash: discordAvatar }),
});
}
async function createPinned(
pinnedId: number,
overrides?: Partial<UpsertArgs> | null,
options?: Options,
) {
// rows keyed by the user id have to wait until after the pinning changes it
const { profile, friendCode, ...upsertOverrides } = overrides ?? {};
const { profile, friendCode, discordAvatar, ...upsertOverrides } =
overrides ?? {};
const user = await create({
...upsertOverrides,
discordAvatar: null,
profile: null,
friendCode: null,
});
const id = await pinUserId(user.id, pinnedId);
if (discordAvatar) {
await insertSyncedAvatar(id, discordAvatar);
}
if (profile && Object.keys(profile).length > 0) {
await updateProfile(id, profile);
}
@@ -407,7 +433,6 @@ async function linkConnections(
.select([
"discordId",
"discordName",
"discordAvatar",
"discordUniqueName",
"twitch",
"youtubeId",

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

View File

@@ -1004,8 +1004,12 @@ export interface User {
country: string | null;
customTheme: JSONColumnTypeNullable<CustomTheme>;
customUrl: string | null;
/** Hash of the Discord avatar `syncedAvatarImgId` was copied from, for noticing when it changes. */
discordAvatar: string | null;
/** Avatar uploaded by the user, shown over `syncedAvatarImgId`. */
customAvatarImgId: number | null;
/** Avatar copied from the account the user logs in with. */
syncedAvatarImgId: number | null;
discordId: string;
discordName: string;
customName: string | null;

View File

@@ -1,31 +0,0 @@
import * as v from "valibot";
import * as UserRepository from "~/features/user-page/UserRepository.server";
import { defineAction } from "~/form/define-action.server";
import { canAccessLohiEndpoint, forbidden } from "~/utils/remix.server";
const updateUsersSchema = v.array(
v.object({
discordId: v.string(),
discordName: v.nullable(v.string()),
discordAvatar: v.optional(v.nullable(v.string()), null),
discordUniqueName: v.optional(v.nullable(v.string()), null),
}),
);
export const action = defineAction(
{
body: updateUsersSchema,
onInvalidBody: "badRequest",
// every member of the crawled Discord servers in one batch
maxBodyBytes: 32 * 1024 * 1024,
},
async ({ request, body }) => {
if (!canAccessLohiEndpoint(request)) {
forbidden();
}
await UserRepository.updateMany(body);
return null;
},
);

View File

@@ -20,7 +20,7 @@ describe("findShowcaseArts", () => {
const result = await ArtRepository.findShowcaseArts();
expect(result).toHaveLength(3);
const authorIds = result.map((art) => art.author?.discordId);
const authorIds = result.map((art) => art.author?.id);
expect(new Set(authorIds).size).toBe(3);
});

View File

@@ -73,9 +73,8 @@ export async function findShowcaseArts(): Promise<ListedArt[]> {
isShowcase: Boolean(a.isShowcase),
author: {
commissionsOpen: a.commissionsOpen,
discordAvatar: a.discordAvatar,
customAvatarUrl: a.customAvatarUrl,
discordId: a.discordId,
avatar: a.avatar,
id: a.userId,
username: a.username,
},
permissions: artPermissions({
@@ -131,9 +130,8 @@ export async function findShowcaseArtsByTag(
isShowcase: Boolean(a.isShowcase),
author: {
commissionsOpen: a.commissionsOpen,
discordAvatar: a.discordAvatar,
customAvatarUrl: a.customAvatarUrl,
discordId: a.discordId,
avatar: a.avatar,
id: a.userId,
username: a.username,
},
permissions: artPermissions({
@@ -170,9 +168,8 @@ export async function findRecentlyUploadedArts(): Promise<ListedArt[]> {
isShowcase: Boolean(a.isShowcase),
author: {
commissionsOpen: a.commissionsOpen,
discordAvatar: a.discordAvatar,
customAvatarUrl: a.customAvatarUrl,
discordId: a.discordId,
avatar: a.avatar,
id: a.userId,
username: a.username,
},
permissions: artPermissions({
@@ -312,10 +309,9 @@ export async function findArtsByUserId(
tags: row.tags.length > 0 ? row.tags : undefined,
linkedUsers: row.linkedUsers.length > 0 ? row.linkedUsers : undefined,
author: {
discordId: row.discordId,
id: row.userId,
username: row.username,
discordAvatar: row.discordAvatar,
customAvatarUrl: row.customAvatarUrl,
avatar: row.avatar,
commissionsOpen: row.commissionsOpen,
},
permissions: artPermissions({

View File

@@ -44,7 +44,7 @@ export const action = defineAction(
type: "TAGGED_TO_ART",
meta: {
adderUsername: user.username,
adderDiscordId: user.discordId,
adderId: user.id,
artId: editedArtId,
},
},
@@ -66,7 +66,7 @@ export const action = defineAction(
type: "TAGGED_TO_ART",
meta: {
adderUsername: user.username,
adderDiscordId: user.discordId,
adderId: user.id,
artId: addedArt.id,
},
},

View File

@@ -4,11 +4,11 @@ import { dataUrlToImageBuffer } from "~/features/img-upload/image-bytes.server";
import { uploadStreamToS3 } from "~/features/img-upload/s3.server";
import { shortNanoid } from "~/utils/id";
import { invariant } from "~/utils/invariant";
import { previewUrl } from "./art-utils";
import { smallImageFileName } from "~/utils/urls";
const ALLOWED_ART_IMAGE_EXTENSIONS = ["png", "jpeg", "webp"] as const;
/** Uploads the full image and its `<name>-small.<ext>` thumbnail ({@link previewUrl}); returns the full image's file name. */
/** Uploads the full image and its `<name>-small.<ext>` thumbnail ({@link smallImageFileName}); returns the full image's file name. */
export async function uploadArtImage({
dataUrl,
thumbnailDataUrl,
@@ -31,7 +31,10 @@ export async function uploadArtImage({
const [uploadedLocation] = await Promise.all([
uploadStreamToS3(Readable.from(image.buffer), fileName),
uploadStreamToS3(Readable.from(thumbnail.buffer), previewUrl(fileName)),
uploadStreamToS3(
Readable.from(thumbnail.buffer),
smallImageFileName(fileName),
),
]);
invariant(uploadedLocation, "Art image upload failed");

View File

@@ -13,10 +13,9 @@ export interface ListedArt {
}>;
linkedUsers?: Array<CommonUser>;
author?: {
discordId: Tables["User"]["discordId"];
id: Tables["User"]["id"];
username: Tables["User"]["username"];
discordAvatar: Tables["User"]["discordAvatar"];
customAvatarUrl: string | null;
avatar: CommonUser["avatar"];
commissionsOpen: Tables["User"]["commissionsOpen"];
};
permissions: {

View File

@@ -3,7 +3,7 @@ import { userArtPage } from "./art-urls";
describe("userArtPage()", () => {
test("joins source and bigArtId params with a single query string", () => {
const url = userArtPage({ discordId: "123" }, "MADE-BY", 456);
const url = userArtPage({ id: 123 }, "MADE-BY", 456);
const params = new URLSearchParams(url.split("?")[1]);
expect(params.get("source")).toBe("MADE-BY");

View File

@@ -1,9 +0,0 @@
export function previewUrl(url: string) {
const lastDotIndex = url.lastIndexOf(".");
if (lastDotIndex === -1) return url;
const urlWithoutExtension = url.slice(0, lastDotIndex);
const extension = url.slice(lastDotIndex + 1);
return `${urlWithoutExtension}-small.${extension}`;
}

View File

@@ -16,12 +16,11 @@ import { usePagination } from "~/hooks/usePagination";
import { useHasPermission } from "~/modules/permissions/hooks";
import { useSearchParam } from "~/modules/search-params/hooks";
import { databaseTimestampToDate } from "~/utils/dates";
import { userPage } from "~/utils/urls";
import { smallImageFileName, userPage } from "~/utils/urls";
import { ResponsiveMasonry } from "../../../modules/responsive-masonry/components/ResponsiveMasonry";
import { ART_PER_PAGE } from "../art-constants";
import { artGridSearchParams } from "../art-search-params";
import type { ListedArt } from "../art-types";
import { previewUrl } from "../art-utils";
import styles from "./ArtGrid.module.css";
const preloadedImageUrls = new Set<string>();
@@ -135,7 +134,7 @@ function BigImageDialog({ close, art }: { close: () => void; art: ListedArt }) {
>
<img
alt=""
src={previewUrl(art.url)}
src={smallImageFileName(art.url)}
className={styles.lightboxPlaceholder}
ref={placeholderRef}
/>
@@ -170,7 +169,7 @@ function BigImageDialog({ close, art }: { close: () => void; art: ListedArt }) {
{art.linkedUsers?.map((user) => (
<Link
to={userPage(user)}
key={user.discordId}
key={user.id}
className={clsx(styles.dialogTag, styles.dialogTagUser)}
>
{user.username}
@@ -214,7 +213,7 @@ function ImagePreview({
const image = (
<img
alt=""
src={previewUrl(art.url)}
src={smallImageFileName(art.url)}
loading="lazy"
ref={imageRef}
className={enablePreview ? styles.thumbnail : undefined}

View File

@@ -5,13 +5,13 @@ import { useTranslation } from "react-i18next";
import type { CustomFieldRenderProps } from "~/form";
import { FormFieldWrapper } from "~/form/fields/FormFieldWrapper";
import { logger } from "~/utils/logger";
import { smallImageFileName } from "~/utils/urls";
import { ART } from "../art-constants";
import {
ART_IMAGE_TOO_LARGE_ERROR,
type ArtImageValue,
isArtImageTooLarge,
} from "../art-image";
import { previewUrl } from "../art-utils";
import styles from "./ArtImageFormField.module.css";
type ArtImageFormFieldProps = Omit<
@@ -33,7 +33,7 @@ export function ArtImageFormField({
const { t } = useTranslation(["common"]);
if (value?.type === "EXISTING") {
return <img src={previewUrl(value.url)} alt="" />;
return <img src={smallImageFileName(value.url)} alt="" />;
}
const handleFileChange = async (

View File

@@ -0,0 +1,121 @@
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import * as UserFactory from "~/db/seed/factories/UserFactory";
import { db } from "~/db/sql";
import {
deleteFromS3,
uploadImmutableToS3,
} from "~/features/img-upload/s3.server";
import * as UserRepository from "~/features/user-page/UserRepository.server";
import * as DiscordAvatar from "./DiscordAvatar.server";
vi.mock("~/features/img-upload/s3.server", () => ({
uploadImmutableToS3: vi.fn(),
deleteFromS3: vi.fn(),
}));
const DISCORD_ID = "79237403620945920";
const respondWith = (status: number) =>
vi.stubGlobal(
"fetch",
vi.fn(async () => new Response(new Uint8Array([1, 2, 3]), { status })),
);
const avatarOf = async (id: number) =>
(await UserRepository.findLeanById(id))?.avatar;
const users = UserFactory.pool();
const userId = () => users.id(1);
const userAsLoggingIn = () =>
db
.selectFrom("User")
.select(["id", "discordAvatar", "syncedAvatarImgId"])
.where("id", "=", userId())
.executeTakeFirstOrThrow();
const sync = async (newHash: string) =>
DiscordAvatar.syncForUser({
user: await userAsLoggingIn(),
discordId: DISCORD_ID,
newHash,
});
describe("DiscordAvatar.syncForUser", () => {
beforeEach(async () => {
await users.create(1, { discordId: DISCORD_ID, discordAvatar: "old" });
});
afterEach(() => {
vi.unstubAllGlobals();
vi.clearAllMocks();
});
test("stores the new avatar with its small copy and deletes the previous one", async () => {
respondWith(200);
await sync("new");
expect(await avatarOf(userId())).toBe(`avatar-${userId()}-new.webp`);
expect(
vi.mocked(uploadImmutableToS3).mock.calls.map(([args]) => args.key),
).toEqual([
`avatar-${userId()}-new.webp`,
`avatar-${userId()}-new-small.webp`,
]);
expect(deleteFromS3).toHaveBeenCalledWith([
`avatar-${userId()}-old.webp`,
`avatar-${userId()}-old-small.webp`,
]);
});
test("clears the avatar when Discord no longer has it", async () => {
respondWith(404);
await sync("new");
expect(await avatarOf(userId())).toBeNull();
expect(uploadImmutableToS3).not.toHaveBeenCalled();
});
test("keeps the previous avatar when the Discord CDN fails", async () => {
respondWith(500);
await sync("new");
expect(await avatarOf(userId())).toBe(`avatar-${userId()}-old.webp`);
expect(deleteFromS3).not.toHaveBeenCalled();
});
test("keeps the stored files when an overlapping sync already stored the same avatar", async () => {
respondWith(200);
await sync("new");
vi.mocked(deleteFromS3).mockClear();
await sync("new");
expect(await avatarOf(userId())).toBe(`avatar-${userId()}-new.webp`);
expect(deleteFromS3).not.toHaveBeenCalled();
});
test("does nothing when the avatar is unchanged", async () => {
respondWith(200);
await sync("old");
expect(fetch).not.toHaveBeenCalled();
expect(deleteFromS3).not.toHaveBeenCalled();
});
test("stores an unchanged avatar that was never stored", async () => {
respondWith(200);
await DiscordAvatar.syncForUser({
user: { id: userId(), discordAvatar: "old", syncedAvatarImgId: null },
discordId: DISCORD_ID,
newHash: "old",
});
expect(fetch).toHaveBeenCalled();
expect(await avatarOf(userId())).toBe(`avatar-${userId()}-old.webp`);
});
});

View File

@@ -0,0 +1,112 @@
import {
deleteFromS3,
uploadImmutableToS3,
} from "~/features/img-upload/s3.server";
import * as UserRepository from "~/features/user-page/UserRepository.server";
import { logger } from "~/utils/logger";
import { smallImageFileName } from "~/utils/urls";
const DISCORD_CDN_SIZE_PX = 240;
const DISCORD_CDN_SMALL_SIZE_PX = 80;
/**
* Brings the user's synced avatar up to date with their Discord avatar `newHash`: copies the new
* avatar to S3 as an image and deletes the previous one. Also copies an unchanged avatar that was
* never stored (users skipped by the avatar migration). Never throws, a failed copy keeps the
* previous avatar.
*/
export async function syncForUser({
user,
discordId,
newHash,
}: {
user: {
id: number;
discordAvatar: string | null;
syncedAvatarImgId: number | null;
};
discordId: string;
newHash: string | null;
}) {
const isStored = !newHash || user.syncedAvatarImgId !== null;
if (user.discordAvatar === newHash && isStored) return;
try {
const fileName = newHash
? await store({ userId: user.id, discordId, hash: newHash })
: null;
const previousFileName = await UserRepository.replaceSyncedAvatar({
userId: user.id,
discordAvatar: fileName ? newHash : null,
fileName,
});
// an overlapping sync of the same hash already stored the same keys
if (previousFileName && previousFileName !== fileName) {
await deleteFromS3([
previousFileName,
smallImageFileName(previousFileName),
]);
}
} catch (error) {
logger.error(`Failed to sync Discord avatar of user ${user.id}`, error);
}
}
/**
* Copies a Discord avatar and its small copy to S3, animated avatars as their still frame. Returns
* the file name, or `null` when Discord doesn't have the avatar (anymore). Throws on other failures.
*/
export async function store({
userId,
discordId,
hash,
}: {
userId: number;
discordId: string;
hash: string;
}): Promise<string | null> {
const fileName = fileNameOf({ userId, hash });
const files: Array<{ key: string; body: Uint8Array }> = [];
for (const [key, sizePx] of [
[fileName, DISCORD_CDN_SIZE_PX],
[smallImageFileName(fileName), DISCORD_CDN_SMALL_SIZE_PX],
] as const) {
const response = await fetch(
`https://cdn.discordapp.com/avatars/${discordId}/${hash}.webp?size=${sizePx}`,
);
if (response.status === 404) return null;
if (!response.ok) {
throw new DiscordCdnError(response);
}
files.push({ key, body: new Uint8Array(await response.arrayBuffer()) });
}
for (const { key, body } of files) {
await uploadImmutableToS3({ key, body, contentType: "image/webp" });
}
return fileName;
}
/** File name a Discord avatar is stored under, its small copy is next to it. */
export function fileNameOf({ userId, hash }: { userId: number; hash: string }) {
return `avatar-${userId}-${hash}.webp`;
}
/** Non-404 failure response from the Discord CDN. */
export class DiscordCdnError extends Error {
readonly status: number;
readonly retryAfterSeconds: number | null;
constructor(response: Response) {
super(`Discord CDN responded with status code ${response.status}`);
this.status = response.status;
const retryAfter = Number(response.headers.get("retry-after"));
this.retryAfterSeconds = retryAfter > 0 ? retryAfter : null;
}
}

View File

@@ -0,0 +1,48 @@
import { createCookie } from "react-router";
import { ServerConfig } from "~/config.server";
import { LRUCache } from "~/modules/cache";
import { IS_E2E_TEST_RUN } from "~/utils/e2e";
const COOLDOWN_MS = 10 * 60 * 1000;
const FLAG_MAX_AGE_SECONDS = 10 * 60;
const flagCookie = createCookie("discord_refresh", {
sameSite: "lax",
path: "/auth",
httpOnly: true,
secrets: [ServerConfig.sessionSecret],
secure: ServerConfig.isProduction && !IS_E2E_TEST_RUN,
maxAge: FLAG_MAX_AGE_SECONDS,
});
const lastRefreshedAt = new LRUCache<number, number>({ max: 10_000 });
/**
* `Set-Cookie` value marking the next OAuth callback as a profile refresh of the given user
* instead of a log in.
*/
export function flagCookieHeader(userId: number) {
return flagCookie.serialize(userId);
}
export function clearFlagCookieHeader() {
return flagCookie.serialize("", { maxAge: 0 });
}
/** The id of the user who started a profile refresh, or `null` if the OAuth flow is a regular log in. */
export async function flaggedUserId(request: Request): Promise<number | null> {
const value = await flagCookie.parse(request.headers.get("Cookie"));
return typeof value === "number" ? value : null;
}
/** Whether the user refreshed recently. Each refresh costs Discord API calls shared with log in's rate limit. */
export function isOnCooldown(userId: number) {
const refreshedAt = lastRefreshedAt.get(userId);
return refreshedAt !== undefined && Date.now() - refreshedAt < COOLDOWN_MS;
}
export function startCooldown(userId: number) {
lastRefreshedAt.set(userId, Date.now());
}

View File

@@ -5,6 +5,8 @@ import { Config } from "~/config";
import { ServerConfig } from "~/config.server";
import * as UserRepository from "~/features/user-page/UserRepository.server";
import { logger } from "~/utils/logger";
import { DISCORD_REFRESH_URL } from "~/utils/urls";
import * as DiscordAvatar from "./DiscordAvatar.server";
let discordApiCooldownUntil: number | null = null;
@@ -75,7 +77,7 @@ export const DiscordStrategy = () => {
]);
};
return new OAuth2Strategy(
return new DiscordOAuth2Strategy(
{
clientId: ServerConfig.discord.clientId,
clientSecret: ServerConfig.discord.clientSecret,
@@ -97,24 +99,7 @@ export const DiscordStrategy = () => {
discordResponses,
);
const isAlreadyRegistered = Boolean(
await UserRepository.findIdByIdentifier(user.id),
);
if (!isAlreadyRegistered && !user.verified) {
logger.info(`User is not verified with id: ${user.id}`);
throw new Error("Unverified user");
}
const userFromDb = await UserRepository.upsert({
discordAvatar: user.avatar ?? null,
discordId: user.id,
discordName: user.global_name ?? user.username,
discordUniqueName: user.global_name ? user.username : null,
...parseConnections(connections),
});
return userFromDb.id;
return { user, connections };
} catch (e) {
logger.error("Failed to finish authentication:\n", e);
throw e;
@@ -123,6 +108,56 @@ export const DiscordStrategy = () => {
);
};
export type DiscordProfile = {
user: v.InferOutput<typeof partialDiscordUserSchema>;
connections: v.InferOutput<typeof partialDiscordConnectionsSchema>;
};
class DiscordOAuth2Strategy extends OAuth2Strategy<DiscordProfile> {
protected override authorizationParams(
params: URLSearchParams,
request: Request,
) {
const result = new URLSearchParams(params);
// already authorized users skip the consent screen
if (new URL(request.url).pathname === DISCORD_REFRESH_URL) {
result.set("prompt", "none");
}
return result;
}
}
/**
* Creates or updates the user (name, avatar, connections) from their Discord profile and returns
* their id. Unverified Discord accounts can't register.
*/
export async function upsertUser({ user, connections }: DiscordProfile) {
const isAlreadyRegistered = Boolean(
await UserRepository.findIdByIdentifier(user.id),
);
if (!isAlreadyRegistered && !user.verified) {
logger.info(`User is not verified with id: ${user.id}`);
throw new Error("Unverified user");
}
const userFromDb = await UserRepository.upsert({
discordId: user.id,
discordName: user.global_name ?? user.username,
discordUniqueName: user.global_name ? user.username : null,
...parseConnections(connections),
});
await DiscordAvatar.syncForUser({
user: userFromDb,
discordId: user.id,
newHash: user.avatar ?? null,
});
return userFromDb.id;
}
function parseConnections(
connections: v.InferOutput<typeof partialDiscordConnectionsSchema>,
) {

View File

@@ -1,9 +1,9 @@
import { Authenticator } from "remix-auth";
import { DiscordStrategy } from "./DiscordStrategy.server";
import { type DiscordProfile, DiscordStrategy } from "./DiscordStrategy.server";
export const SESSION_KEY = "user";
export const IMPERSONATED_SESSION_KEY = "impersonated_user";
export const authenticator = new Authenticator<number>();
export const authenticator = new Authenticator<DiscordProfile>();
authenticator.use(DiscordStrategy(), "discord");

View File

@@ -3,7 +3,6 @@ import type { LoaderFunction } from "react-router";
import { redirect } from "react-router";
import * as v from "valibot";
import { DANGEROUS_CAN_ACCESS_DEV_CONTROLS } from "~/features/admin/core/dev-controls";
import { requireUser } from "~/features/auth/core/user.server";
import * as UserRepository from "~/features/user-page/UserRepository.server";
import { defineAction } from "~/form/define-action.server";
import { isAdmin, isStaff } from "~/modules/permissions/utils";
@@ -12,22 +11,32 @@ import {
badRequest,
canAccessLohiEndpoint,
errorToastRedirect,
errorToastWithRedirect,
forbidden,
safeReturnTo,
successToastWithRedirect,
} from "~/utils/remix.server";
import type { AnySyncSchema } from "~/utils/schema";
import { ADMIN_PAGE, authErrorUrl } from "~/utils/urls";
import { ADMIN_PAGE, authErrorUrl, SETTINGS_PAGE } from "~/utils/urls";
import * as LogInLinkRepository from "../LogInLinkRepository.server";
import {
authenticator,
IMPERSONATED_SESSION_KEY,
SESSION_KEY,
} from "./authenticator.server";
import * as DiscordAvatar from "./DiscordAvatar.server";
import * as DiscordRefresh from "./DiscordRefresh.server";
import { upsertUser } from "./DiscordStrategy.server";
import type { AuthErrorCode } from "./errors";
import { authSessionStorage } from "./session.server";
import { getUser } from "./user.server";
import { getUser, isImpersonating, requireUser } from "./user.server";
export const callbackLoader: LoaderFunction = async ({ request, url }) => {
const refreshingUserId = await DiscordRefresh.flaggedUserId(request);
if (refreshingUserId !== null) {
return refreshCallback({ request, url, refreshingUserId });
}
// biome-ignore lint/plugin: OAuth callback param, its name and values defined by the provider
if (url.searchParams.get("error") === "access_denied") {
// https://www.oauth.com/oauth2-servers/server-side-apps/possible-errors/
@@ -36,7 +45,8 @@ export const callbackLoader: LoaderFunction = async ({ request, url }) => {
}
try {
const userId = await authenticator.authenticate("discord", request);
const profile = await authenticator.authenticate("discord", request);
const userId = await upsertUser(profile);
const session = await authSessionStorage.getSession(
request.headers.get(SESSION_KEY),
@@ -62,6 +72,38 @@ export const callbackLoader: LoaderFunction = async ({ request, url }) => {
}
};
export const refreshFromDiscordAction = defineAction(async ({ request }) => {
const user = requireUser();
if (await isImpersonating(request)) {
throw errorToastWithRedirect({
url: SETTINGS_PAGE,
message: "Can't refresh from Discord while impersonating",
});
}
if (DiscordRefresh.isOnCooldown(user.id)) {
throw errorToastWithRedirect({
url: SETTINGS_PAGE,
message: REFRESH_COOLDOWN_MESSAGE,
});
}
try {
return await authenticator.authenticate("discord", request);
} catch (error) {
// starting the OAuth flow always throws the redirect to Discord
if (error instanceof Response) {
error.headers.append(
"Set-Cookie",
await DiscordRefresh.flagCookieHeader(user.id),
);
}
throw error;
}
});
export const logOutAction = defineAction(async ({ request }) => {
const session = await authSessionStorage.getSession(
request.headers.get(SESSION_KEY),
@@ -72,7 +114,19 @@ export const logOutAction = defineAction(async ({ request }) => {
});
export const logInAction = defineAction(async ({ request }) => {
return await authenticator.authenticate("discord", request);
try {
return await authenticator.authenticate("discord", request);
} catch (error) {
// a refresh abandoned midway must not turn this log in into one
if (error instanceof Response) {
error.headers.append(
"Set-Cookie",
await DiscordRefresh.clearFlagCookieHeader(),
);
}
throw error;
}
});
const returnToSchema = v.object({
@@ -178,7 +232,8 @@ const createLogInLinkActionSchema = v.object({
discordAvatar: v.optional(v.nullable(v.string())),
discordName: v.string(),
discordUniqueName: v.string(),
updateOnly: v.picklist(["true", "false"]),
// the name & avatar sync it was used for is retired
updateOnly: v.optional(v.picklist(["true", "false"])),
});
export const createLogInLinkAction = defineAction(async ({ request }) => {
@@ -191,14 +246,19 @@ export const createLogInLinkAction = defineAction(async ({ request }) => {
forbidden();
}
if (data.updateOnly === "true") return null;
const user = await UserRepository.upsert({
discordAvatar: data.discordAvatar ?? null,
discordId: data.discordId,
discordName: data.discordName,
discordUniqueName: data.discordUniqueName,
});
if (data.updateOnly === "true") return null;
await DiscordAvatar.syncForUser({
user,
discordId: data.discordId,
newHash: data.discordAvatar ?? null,
});
const createdLink = await LogInLinkRepository.insert(user.id);
@@ -267,3 +327,67 @@ function classifyAuthError(error: Error): AuthErrorCode {
return "unknown";
}
const REFRESH_COOLDOWN_MESSAGE =
"You can refresh from Discord once every 10 minutes";
async function refreshCallback({
request,
url,
refreshingUserId,
}: {
request: Request;
url: URL;
refreshingUserId: number;
}) {
const headers = {
"Set-Cookie": await DiscordRefresh.clearFlagCookieHeader(),
};
const failed = (message: string) =>
errorToastWithRedirect({ url: SETTINGS_PAGE, message, headers });
// biome-ignore lint/plugin: OAuth callback param, its name and values defined by the provider
if (url.searchParams.has("error")) {
return failed("Refreshing from Discord was canceled");
}
const user = getUser();
if (
!user ||
user.id !== refreshingUserId ||
(await isImpersonating(request))
) {
return failed("Refreshing from Discord failed");
}
if (DiscordRefresh.isOnCooldown(user.id)) {
return failed(REFRESH_COOLDOWN_MESSAGE);
}
DiscordRefresh.startCooldown(user.id);
try {
const profile = await authenticator.authenticate("discord", request);
if (profile.user.id !== user.discordId) {
return failed(
"The Discord account you authorized is not the one linked to your sendou.ink account",
);
}
await upsertUser(profile);
} catch (error) {
logger.error("Error during refresh from Discord:", error);
return failed(
error instanceof Error && classifyAuthError(error) === "discordOverloaded"
? "Discord is overloaded right now, try again later"
: "Refreshing from Discord failed",
);
}
return successToastWithRedirect({
url: SETTINGS_PAGE,
message: "Your avatar, name and connections were refreshed from Discord",
headers,
});
}

View File

@@ -0,0 +1 @@
export { refreshFromDiscordAction as action } from "~/features/auth/core/routes.server";

View File

@@ -21,9 +21,7 @@ import { useRangeText } from "./ScheduleDayCell";
export interface AvailabilityPanelUser {
id: number;
username: string;
discordId: string;
discordAvatar: string | null;
customAvatarUrl?: string | null;
avatar: string | null;
}
export type AvailabilityPanelData = SerializeFrom<RegistrationAvailability>;

View File

@@ -49,7 +49,6 @@ const withOwners = (eb: ExpressionBuilder<DB, "Badge">, badgeId: number) => {
.select(({ fn }) => [
fn.sum<number>("BadgeOwner.count").as("count"),
"User.id",
"User.discordId",
"User.username",
])
.where("BadgeOwner.badgeId", "=", badgeId)

View File

@@ -115,13 +115,12 @@ function Owners({ data }: { data: BadgeDetailsLoaderData }) {
const initialOwners = data.badge.owners.map((o) => ({
id: o.id,
name: o.username,
discordId: o.discordId,
count: o.count,
}));
const [owners, setOwners] =
React.useState<
Array<{ id: number; name: string; discordId: string; count: number }>
>(initialOwners);
React.useState<Array<{ id: number; name: string; count: number }>>(
initialOwners,
);
const ownerDifferences = getOwnerDifferences(
owners.map((o) => ({ ...o, username: o.name })),

View File

@@ -273,7 +273,10 @@ function Description() {
<Section title={t("forms.description")}>
<div className="stack sm">
<div className={styles.author}>
<Avatar user={data.event} size="xs" />
<Avatar
user={{ id: data.event.authorId, avatar: data.event.avatar }}
size="xs"
/>
{data.event.username}
</div>
{data.event.description ? (

View File

@@ -1,7 +1,7 @@
import { notify } from "~/features/notifications/core/notify.server";
import * as NotificationRepository from "~/features/notifications/NotificationRepository.server";
import { hasPermission } from "~/modules/permissions/utils";
import { resolveAvatarUrl } from "~/utils/urls";
import { avatarUrl } from "~/utils/urls";
import type * as ChatRoomResolver from "./ChatRoomResolver.server";
import type { ChatMessageWithAuthor } from "./chat-types";
import * as Mentions from "./core/Mentions";
@@ -39,7 +39,9 @@ export async function notifyMentioned({
mentionerUsername: message.author.username,
roomUrl: room.url,
},
pictureUrl: resolveAvatarUrl({ ...message.author, size: "sm" }),
pictureUrl: message.author.avatar
? avatarUrl(message.author.avatar, "sm")
: undefined,
},
});
}

View File

@@ -271,10 +271,8 @@ function ChatProviderInner({
author: {
id: user.id,
username: user.username,
discordId: user.discordId,
discordAvatar: user.discordAvatar,
customUrl: user.customUrl ?? null,
customAvatarUrl: user.customAvatarUrl ?? null,
avatar: user.avatar ?? null,
pronouns: null,
chatNameHue: null,
},

View File

@@ -17,10 +17,8 @@ const READ_DEBOUNCE_MS = 20;
const author = (id: number): ChatMessageAuthor => ({
id,
username: `user-${id}`,
discordId: String(id),
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
pronouns: null,
chatNameHue: null,
});

View File

@@ -62,10 +62,8 @@ afterEach(() => {
const ALICE: ChatMessageAuthor = {
id: 1,
username: "Alice",
discordId: "1",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
pronouns: null,
chatNameHue: null,
};
@@ -608,8 +606,8 @@ describe("Chat", () => {
});
describe("mentions", () => {
const BOB = { ...ALICE, id: 2, username: "Bob", discordId: "2" };
const CAROL = { ...ALICE, id: 3, username: "Carol", discordId: "3" };
const BOB = { ...ALICE, id: 2, username: "Bob" };
const CAROL = { ...ALICE, id: 3, username: "Carol" };
const renderComposer = async () => {
const onSend = vi.fn();
@@ -670,7 +668,7 @@ describe("Chat", () => {
});
test("sends the picked one of two users sharing a name", async () => {
const otherBob = { ...BOB, id: 5, discordId: "5" };
const otherBob = { ...BOB, id: 5 };
const onSend = vi.fn();
const screen = await renderChat([], {
onSend,
@@ -690,7 +688,7 @@ describe("Chat", () => {
});
test("holds back mentioning the same user again while on cooldown, telling how long", async () => {
const dave = { ...ALICE, id: 7, username: "Dave", discordId: "7" };
const dave = { ...ALICE, id: 7, username: "Dave" };
const onSend = vi.fn();
const screen = await renderChat([], {
onSend,

View File

@@ -1715,7 +1715,7 @@ function AvatarSection({ id }: { id: string }) {
<div className="stack md">
<ComponentRow label="Size xxxs">
<Avatar
user={{ discordId: "1", discordAvatar: null }}
user={{ id: 1, avatar: null }}
size="xxxs"
alt="User avatar"
/>
@@ -1723,58 +1723,34 @@ function AvatarSection({ id }: { id: string }) {
<ComponentRow label="Size xxxsm">
<Avatar
user={{ discordId: "22", discordAvatar: null }}
user={{ id: 2, avatar: null }}
size="xxxsm"
alt="User avatar"
/>
</ComponentRow>
<ComponentRow label="Size xxs">
<Avatar
user={{ discordId: "333", discordAvatar: null }}
size="xxs"
alt="User avatar"
/>
<Avatar user={{ id: 3, avatar: null }} size="xxs" alt="User avatar" />
</ComponentRow>
<ComponentRow label="Size xs">
<Avatar
user={{ discordId: "4444", discordAvatar: null }}
size="xs"
alt="User avatar"
/>
<Avatar user={{ id: 4, avatar: null }} size="xs" alt="User avatar" />
</ComponentRow>
<ComponentRow label="Size sm (default)">
<Avatar
user={{ discordId: "55555", discordAvatar: null }}
size="sm"
alt="User avatar"
/>
<Avatar user={{ id: 5, avatar: null }} size="sm" alt="User avatar" />
</ComponentRow>
<ComponentRow label="Size xsm">
<Avatar
user={{ discordId: "123456", discordAvatar: null }}
size="xsm"
alt="User avatar"
/>
<Avatar user={{ id: 6, avatar: null }} size="xsm" alt="User avatar" />
</ComponentRow>
<ComponentRow label="Size md">
<Avatar
user={{ discordId: "313762200286396416", discordAvatar: null }}
size="md"
alt="User avatar"
/>
<Avatar user={{ id: 7, avatar: null }} size="md" alt="User avatar" />
</ComponentRow>
<ComponentRow label="Size lg">
<Avatar
user={{ discordId: "79237403620945920", discordAvatar: null }}
size="lg"
alt="User avatar"
/>
<Avatar user={{ id: 8, avatar: null }} size="lg" alt="User avatar" />
</ComponentRow>
</div>
</Section>
@@ -1784,10 +1760,8 @@ function AvatarSection({ id }: { id: string }) {
const USER_CARD_DATA = {
id: 1,
username: "Sendou",
discordId: "79237403620945920",
discordAvatar: null,
avatar: null,
customUrl: "sendou",
customAvatarUrl: null,
banner: { type: "STAGE", stageId: 5 },
shortBio: "Very show bio goes here maybe max two lines that gets clamped.",
customTheme: null,
@@ -2185,30 +2159,30 @@ const SEASON_SUMMARY_STATS: SeasonSummaryGraphicStats = {
topMates: [
{
player: { name: "Grey", countryCode: "FR" },
discordId: "289132480999030784",
userId: 2,
setsCount: 23,
},
{
player: { name: "sunni" },
discordId: "437750362188120075",
userId: 3,
setsCount: 17,
},
{
player: { name: "まるお", countryCode: "JP" },
discordId: "196628310288564224",
userId: 4,
setsCount: 9,
},
{
player: { name: "Chara", countryCode: "US" },
discordId: "455039198672814090",
userId: 5,
setsCount: 8,
},
{
player: { name: "Silver", countryCode: "FR" },
discordId: "224378380316540929",
userId: 6,
setsCount: 6,
},
{ player: { name: "Yeti" }, discordId: "153113232128507904", setsCount: 4 },
{ player: { name: "Yeti" }, userId: 7, setsCount: 4 },
],
bestStage: { stageId: 14, winratePercentage: 78 },
peakSp: Math.max(...SEASON_SUMMARY_DAYS.map(([, sp]) => sp)),
@@ -2241,8 +2215,8 @@ function SeasonSummaryGraphicSection({ id }: { id: string }) {
<ComponentRow label="Season summary export image">
<SeasonSummaryGraphic
user={{
id: 1,
name: "Sendou",
discordId: "79237403620945920",
customUrl: "sendou",
countryCode: "FI",
avatarUrl: `${RESULTS_GRAPHIC_IMG_ROOT}/dBYwiLjlhVBwW-oyyNJkC-1721997877357.webp`,
@@ -2261,10 +2235,9 @@ function SeasonSummaryGraphicSection({ id }: { id: string }) {
}
const LFG_GRAPHIC_AUTHOR: LFGPostGraphicPost["author"] = {
id: 1,
username: "Sendou",
discordId: "79237403620945920",
discordAvatar: null,
customAvatarUrl: `${RESULTS_GRAPHIC_IMG_ROOT}/dBYwiLjlhVBwW-oyyNJkC-1721997877357.webp`,
avatar: null,
country: "FI",
weaponPool: [
{ weaponSplId: 40, isFavorite: 1, isTenStar: 1 },

View File

@@ -34,9 +34,8 @@ const ACTIVITY_BADGE_TRANSLATION_KEY = {
} as const satisfies Record<FriendActivityBadge, string>;
export function FriendMenu({
discordId,
discordAvatar,
customAvatarUrl,
id,
avatar,
name,
subtitle,
badge,
@@ -48,9 +47,8 @@ export function FriendMenu({
friendshipId,
friendshipCreatedAt,
}: {
discordId: string;
discordAvatar: string | null;
customAvatarUrl: string | null;
id: number;
avatar: string | null;
name: string;
subtitle: string | null;
badge: string | null;
@@ -86,7 +84,7 @@ export function FriendMenu({
<SendouMenu
trigger={
<ListButton
user={{ discordId, discordAvatar, customAvatarUrl }}
user={{ id, avatar }}
subtitle={subtitle}
badge={
stream

View File

@@ -52,11 +52,9 @@ export const loader = async () => {
id: friend.id,
friendshipId: friend.friendshipId as number,
username: friend.username,
discordId: friend.discordId,
discordAvatar: friend.discordAvatar,
customAvatarUrl: friend.customAvatarUrl,
avatar: friend.avatar,
url: userPage({
discordId: friend.discordId,
id: friend.id,
customUrl: friend.customUrl,
}),
subtitle: activity.subtitle,
@@ -92,11 +90,9 @@ export const loader = async () => {
return {
id: tm.id,
username: tm.username,
discordId: tm.discordId,
discordAvatar: tm.discordAvatar,
customAvatarUrl: tm.customAvatarUrl,
avatar: tm.avatar,
url: userPage({
discordId: tm.discordId,
id: tm.id,
customUrl: tm.customUrl,
}),
subtitle: activity.subtitle,
@@ -121,11 +117,9 @@ export const loader = async () => {
sender: {
id: req.senderId,
username: req.senderUsername,
discordId: req.senderDiscordId,
discordAvatar: req.senderDiscordAvatar,
customAvatarUrl: req.senderCustomAvatarUrl,
avatar: req.senderAvatar,
url: userPage({
discordId: req.senderDiscordId,
id: req.senderId,
customUrl: req.senderCustomUrl,
}),
},
@@ -136,11 +130,9 @@ export const loader = async () => {
receiver: {
id: req.receiverId,
username: req.receiverUsername,
discordId: req.receiverDiscordId,
discordAvatar: req.receiverDiscordAvatar,
customAvatarUrl: req.receiverCustomAvatarUrl,
avatar: req.receiverAvatar,
url: userPage({
discordId: req.receiverDiscordId,
id: req.receiverId,
customUrl: req.receiverCustomUrl,
}),
},

View File

@@ -104,9 +104,8 @@ function IncomingRequestsSection() {
<Link to={request.sender.url} className={styles.pendingUser}>
<Avatar
user={{
discordId: request.sender.discordId,
discordAvatar: request.sender.discordAvatar,
customAvatarUrl: request.sender.customAvatarUrl,
id: request.sender.id,
avatar: request.sender.avatar,
}}
size="xxsm"
/>
@@ -154,9 +153,8 @@ function PendingRequestsSection() {
<Link to={request.receiver.url} className={styles.pendingUser}>
<Avatar
user={{
discordId: request.receiver.discordId,
discordAvatar: request.receiver.discordAvatar,
customAvatarUrl: request.receiver.customAvatarUrl,
id: request.receiver.id,
avatar: request.receiver.avatar,
}}
size="xxsm"
/>

View File

@@ -382,9 +382,7 @@ function buildFirstPlacerEntry(
const members = withMembers
? rows.slice(0, MEMBERS_TO_SHOW).map((row) => ({
customUrl: row.customUrl,
customAvatarUrl: row.customAvatarUrl,
discordAvatar: row.discordAvatar,
discordId: row.discordId,
avatar: row.avatar,
id: row.id,
username: row.username,
country: row.country,

View File

@@ -10,7 +10,7 @@ import * as SplatoonRotationRepository from "~/features/splatoon-rotations/Splat
import { cache, IN_MILLISECONDS, ttl } from "~/utils/cache.server";
import { databaseTimestampNow } from "~/utils/dates";
import type { SerializeFrom } from "~/utils/remix";
import { discordAvatarUrl, teamPage, userPage } from "~/utils/urls";
import { avatarUrl, teamPage, userPage } from "~/utils/urls";
import * as ShowcaseTournaments from "../core/ShowcaseTournaments.server";
export type FrontPageLoaderData = SerializeFrom<typeof loader>;
@@ -83,15 +83,7 @@ function cachedLeaderboards(): Promise<{
power: entry.power,
name: entry.username,
url: userPage(entry),
avatarUrl: entry.customAvatarUrl
? entry.customAvatarUrl
: entry.discordAvatar
? discordAvatarUrl({
discordAvatar: entry.discordAvatar,
discordId: entry.discordId,
size: "sm",
})
: null,
avatarUrl: entry.avatar ? avatarUrl(entry.avatar, "sm") : null,
})),
team: team
.filter((entry) => entry.team)

View File

@@ -29,12 +29,11 @@ import { GraphicContainer } from "./Graphic";
const BUILD_GRAPHIC_WIDTH = 380;
export interface BuildGraphicOwner {
id: number;
username: string;
discordId: string;
plusTier: number | null;
customUrl?: Tables["User"]["customUrl"];
discordAvatar?: Tables["User"]["discordAvatar"];
customAvatarUrl?: string | null;
avatar?: string | null;
}
export function BuildGraphic({
@@ -94,11 +93,7 @@ export function BuildGraphic({
</div>
<div className={styles.owner}>
<Avatar
user={{
discordId: owner.discordId,
discordAvatar: owner.discordAvatar ?? null,
customAvatarUrl: owner.customAvatarUrl,
}}
user={{ id: owner.id, avatar: owner.avatar ?? null }}
size="xxxsm"
alt=""
/>

View File

@@ -72,7 +72,7 @@ export interface SeasonSummaryGraphicStats {
};
topMates: Array<{
player: GraphicPlayer;
discordId: string;
userId: number;
avatarUrl?: string;
setsCount: number;
}>;
@@ -101,8 +101,8 @@ export function SeasonSummaryGraphic({
stats,
}: {
user: {
id: number;
name: string;
discordId: string;
customUrl?: string;
countryCode?: string;
avatarUrl?: string;
@@ -144,7 +144,7 @@ export function SeasonSummaryGraphic({
<GraphicContainer>
<GraphicHeader
avatarUrl={user.avatarUrl}
identiconInput={user.discordId}
identiconInput={String(user.id)}
titleRow={
<>
{user.countryCode ? (
@@ -315,7 +315,7 @@ export function SeasonSummaryGraphic({
<div key={mate.player.name} className={styles.mateRow}>
<Avatar
url={mate.avatarUrl}
identiconInput={mate.discordId}
identiconInput={String(mate.userId)}
size="xxs"
alt=""
/>

View File

@@ -1,5 +1,8 @@
import sharp from "sharp";
import { invariant } from "~/utils/invariant";
const SMALL_COPY_SIZE_PX = 80;
export type ImageExtension = "webp" | "png" | "jpeg";
/** Format is resolved from the magic bytes, not the client-declared mime type, and must be in `allowedExtensions`. */
@@ -19,7 +22,20 @@ export function dataUrlToImageBuffer(
return { buffer, extension };
}
function imageExtensionFromMagicBytes(buffer: Buffer): ImageExtension | null {
/** Square downscaled copy of an image in the same format, for small displays such as avatars. */
export function smallImageCopy(
image: Buffer | Uint8Array,
extension: ImageExtension,
) {
return sharp(image)
.resize(SMALL_COPY_SIZE_PX, SMALL_COPY_SIZE_PX, { fit: "cover" })
.toFormat(extension)
.toBuffer();
}
export function imageExtensionFromMagicBytes(
buffer: Buffer,
): ImageExtension | null {
if (
buffer.length > 12 &&
buffer.toString("ascii", 0, 4) === "RIFF" &&

View File

@@ -6,8 +6,9 @@ import { databaseTimestampNow } from "~/utils/dates";
import { shortNanoid } from "~/utils/id";
import { invariant } from "~/utils/invariant";
import { errorToastIfFalsy } from "~/utils/remix.server";
import { smallImageFileName } from "~/utils/urls";
import * as ImageRepository from "./ImageRepository.server";
import { dataUrlToImageBuffer } from "./image-bytes.server";
import { dataUrlToImageBuffer, smallImageCopy } from "./image-bytes.server";
import { uploadStreamToS3 } from "./s3.server";
import { MAX_UNVALIDATED_IMG_COUNT } from "./upload-constants";
@@ -24,12 +25,15 @@ export async function imageFieldValueToImgId({
value,
user,
autoValidate = false,
withSmallCopy = false,
isCurrentImgId,
}: {
value: ImageFieldValue;
user: AuthenticatedUser;
/** Bypass the moderator queue (e.g. trusted org logos). */
autoValidate?: boolean;
/** Also upload a downscaled copy next to the image, see `smallImageFileName`. */
withSmallCopy?: boolean;
/** Whether the entity being edited already holds this image, letting co-editors keep one someone else uploaded. */
isCurrentImgId?: (imgId: number) => boolean | Promise<boolean>;
}): Promise<number | null> {
@@ -70,6 +74,13 @@ export async function imageFieldValueToImgId({
invariant(uploadedFileLocation, "Image upload failed");
const fileName = basename(uploadedFileLocation);
if (withSmallCopy) {
await uploadStreamToS3(
Readable.from(await smallImageCopy(buffer, extension)),
smallImageFileName(fileName),
);
}
const img = await ImageRepository.insert({
submitterUserId: user.id,
url: fileName,

View File

@@ -2,28 +2,21 @@
import { PassThrough } from "node:stream";
import type { PutObjectCommandInput } from "@aws-sdk/client-s3";
import { S3 } from "@aws-sdk/client-s3";
import { NotFound, S3, S3ServiceException } from "@aws-sdk/client-s3";
import { Upload } from "@aws-sdk/lib-storage";
import { writeAsyncIterableToWritable } from "@react-router/node";
import { ServerConfig } from "~/config.server";
const uploadStream = ({ Key }: Pick<PutObjectCommandInput, "Key">) => {
const { endpoint, accessKey, secret, region, bucket } = ServerConfig.storage;
const IMMUTABLE_CACHE_CONTROL = "public, max-age=31536000, immutable";
const uploadStream = ({ Key }: Pick<PutObjectCommandInput, "Key">) => {
const { bucket } = ServerConfig.storage;
const s3 = new S3({
endpoint,
forcePathStyle: false,
credentials: {
accessKeyId: accessKey,
secretAccessKey: secret,
},
region,
});
const pass = new PassThrough();
return {
writeStream: pass,
promise: new Upload({
client: s3,
client: s3Client(),
params: { Bucket: bucket, Key, Body: pass, ACL: "public-read" },
}).done(),
};
@@ -37,3 +30,70 @@ export async function uploadStreamToS3(data: any, filename: string) {
const file = await stream.promise;
return file.Location;
}
/** Uploads a publicly readable object that never changes under its key, so it is cached forever. */
export async function uploadImmutableToS3({
key,
body,
contentType,
}: {
key: string;
body: Uint8Array;
contentType: string;
}) {
await s3Client().putObject({
Bucket: ServerConfig.storage.bucket,
Key: key,
Body: body,
ACL: "public-read",
ContentType: contentType,
CacheControl: IMMUTABLE_CACHE_CONTROL,
});
}
export async function existsInS3(key: string) {
try {
await s3Client().headObject({
Bucket: ServerConfig.storage.bucket,
Key: key,
});
return true;
} catch (error) {
if (
error instanceof NotFound ||
(error instanceof S3ServiceException &&
error.$metadata.httpStatusCode === 404)
) {
return false;
}
throw error;
}
}
export async function deleteFromS3(keys: string[]) {
if (keys.length === 0) return;
await s3Client().deleteObjects({
Bucket: ServerConfig.storage.bucket,
Delete: { Objects: keys.map((Key) => ({ Key })) },
});
}
let client: S3 | null = null;
function s3Client() {
if (client) return client;
const { endpoint, accessKey, secret, region } = ServerConfig.storage;
client = new S3({
endpoint,
forcePathStyle: false,
credentials: {
accessKeyId: accessKey,
secretAccessKey: secret,
},
region,
});
return client;
}

View File

@@ -44,9 +44,7 @@ const teamEntry = ({
power: 1500,
isSkipped,
placementRank,
members: [
{ id: entryId, username, discordId: `${entryId}`, customUrl: null },
],
members: [{ id: entryId, username, customUrl: null }],
team: undefined,
});

View File

@@ -580,9 +580,7 @@ function XPTable({ entries }: { entries: XPLeaderboardItem[] }) {
>
<RankTableInnerRow>
<RankTableRank>{entry.placementRank}</RankTableRank>
{entry.discordId ? (
<Avatar size="xxs" user={entry as any} />
) : null}
{entry.id ? <Avatar size="xxs" user={entry as any} /> : null}
<RankTableWeaponImage weaponSplId={entry.weaponSplId} />
<div>{entry.name}</div>
<div className={leaderboardsStyles.tablePower}>

View File

@@ -113,68 +113,52 @@ export default function MatchPageTestRoute() {
{
id: 1,
username: "Sendou",
discordId: "123",
discordAvatar: null,
avatar: null,
customUrl: "sendou",
customAvatarUrl: null,
},
{
id: 2,
username: "Lean",
discordId: "456",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
{
id: 3,
username: "Kiver",
discordId: "789",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
{
id: 4,
username: "Brian",
discordId: "012",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
],
bravo: [
{
id: 5,
username: "Naga",
discordId: "345",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
{
id: 6,
username: "Grey",
discordId: "678",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
{
id: 7,
username: "Zack",
discordId: "901",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
{
id: 8,
username: "Lime",
discordId: "234",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
],
}}
@@ -200,48 +184,38 @@ export default function MatchPageTestRoute() {
{
id: 1,
username: "Sendou",
discordId: "123",
discordAvatar: null,
avatar: null,
customUrl: "sendou",
tier: { name: "LEVIATHAN", isPlus: true },
weaponPool: [0, 2000, 4000],
customAvatarUrl: null,
},
{
id: 2,
username: "Lean",
discordId: "456",
discordAvatar: null,
avatar: null,
customUrl: null,
tier: { name: "DIAMOND", isPlus: false },
weaponPool: [20, 1100],
customAvatarUrl: null,
},
{
id: 3,
username: "Kiver",
discordId: "789",
discordAvatar: null,
avatar: null,
customUrl: null,
tier: "CALCULATING",
customAvatarUrl: null,
},
{
id: 4,
username: "Brian",
discordId: "012",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
{
id: 9,
username: "Poppy",
discordId: "567",
discordAvatar: null,
avatar: null,
customUrl: null,
tier: { name: "GOLD", isPlus: true },
customAvatarUrl: null,
},
],
subbedOut: [9],
@@ -252,38 +226,30 @@ export default function MatchPageTestRoute() {
{
id: 5,
username: "Naga",
discordId: "345",
discordAvatar: null,
avatar: null,
customUrl: null,
tier: { name: "PLATINUM", isPlus: false },
weaponPool: [40, 3000],
customAvatarUrl: null,
},
{
id: 6,
username: "Grey",
discordId: "678",
discordAvatar: null,
avatar: null,
customUrl: null,
tier: { name: "SILVER", isPlus: true },
customAvatarUrl: null,
},
{
id: 7,
username: "Zack",
discordId: "901",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
{
id: 8,
username: "Lime",
discordId: "234",
discordAvatar: null,
avatar: null,
customUrl: null,
tier: { name: "BRONZE", isPlus: false },
customAvatarUrl: null,
},
],
},
@@ -390,10 +356,8 @@ export default function MatchPageTestRoute() {
user: {
id: 1,
username: "Sendou",
discordId: "123",
discordAvatar: null,
avatar: null,
customUrl: "sendou",
customAvatarUrl: null,
},
skillDifference: {
calculated: true,
@@ -406,10 +370,8 @@ export default function MatchPageTestRoute() {
user: {
id: 2,
username: "Lean",
discordId: "456",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
skillDifference: {
calculated: true,
@@ -422,10 +384,8 @@ export default function MatchPageTestRoute() {
user: {
id: 3,
username: "Kiver",
discordId: "789",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
skillDifference: {
calculated: false,
@@ -437,10 +397,8 @@ export default function MatchPageTestRoute() {
user: {
id: 4,
username: "Brian",
discordId: "012",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
skillDifference: {
calculated: false,
@@ -462,10 +420,8 @@ export default function MatchPageTestRoute() {
user: {
id: 5,
username: "Naga",
discordId: "345",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
skillDifference: {
calculated: true,
@@ -478,10 +434,8 @@ export default function MatchPageTestRoute() {
user: {
id: 6,
username: "Grey",
discordId: "678",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
skillDifference: {
calculated: true,
@@ -494,10 +448,8 @@ export default function MatchPageTestRoute() {
user: {
id: 7,
username: "Zack",
discordId: "901",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
skillDifference: {
calculated: true,
@@ -510,10 +462,8 @@ export default function MatchPageTestRoute() {
user: {
id: 8,
username: "Lime",
discordId: "234",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
skillDifference: {
calculated: true,
@@ -545,68 +495,52 @@ export default function MatchPageTestRoute() {
{
id: 1,
username: "Sendou",
discordId: "123",
discordAvatar: null,
avatar: null,
customUrl: "sendou",
customAvatarUrl: null,
},
{
id: 2,
username: "Lean",
discordId: "456",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
{
id: 3,
username: "Kiver",
discordId: "789",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
{
id: 4,
username: "Brian",
discordId: "012",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
],
bravo: [
{
id: 5,
username: "Naga",
discordId: "345",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
{
id: 6,
username: "Grey",
discordId: "678",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
{
id: 7,
username: "Zack",
discordId: "901",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
{
id: 8,
username: "Lime",
discordId: "234",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
],
},
@@ -625,68 +559,52 @@ export default function MatchPageTestRoute() {
{
id: 1,
username: "Sendou",
discordId: "123",
discordAvatar: null,
avatar: null,
customUrl: "sendou",
customAvatarUrl: null,
},
{
id: 2,
username: "Lean",
discordId: "456",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
{
id: 3,
username: "Kiver",
discordId: "789",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
{
id: 4,
username: "Brian",
discordId: "012",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
],
bravo: [
{
id: 5,
username: "Naga",
discordId: "345",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
{
id: 6,
username: "Grey",
discordId: "678",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
{
id: 7,
username: "Zack",
discordId: "901",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
{
id: 8,
username: "Lime",
discordId: "234",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
],
},
@@ -789,68 +707,52 @@ export default function MatchPageTestRoute() {
{
id: 1,
username: "Sendou",
discordId: "123",
discordAvatar: null,
avatar: null,
customUrl: "sendou",
customAvatarUrl: null,
},
{
id: 2,
username: "Lean",
discordId: "456",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
{
id: 3,
username: "Kiver",
discordId: "789",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
{
id: 4,
username: "Brian",
discordId: "012",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
],
bravo: [
{
id: 5,
username: "Naga",
discordId: "345",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
{
id: 6,
username: "Grey",
discordId: "678",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
{
id: 9,
username: "Poppy",
discordId: "567",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
{
id: 8,
username: "Lime",
discordId: "234",
discordAvatar: null,
avatar: null,
customUrl: null,
customAvatarUrl: null,
},
],
},

View File

@@ -222,7 +222,7 @@ export function findUnseenSubscriptionsByNotificationId(
.select([
"NotificationUserSubscription.id",
"NotificationUserSubscription.subscription",
"User.discordId",
"NotificationUser.userId",
"User.customUrl",
])
.where("NotificationUser.notificationId", "=", notificationId)

View File

@@ -134,13 +134,13 @@ async function sendPushNotificationsToUnseen({
const limit = pLimit(50);
await Promise.all(
subscriptions.map(({ id, subscription, discordId, customUrl }) =>
subscriptions.map(({ id, subscription, userId, customUrl }) =>
limit(() =>
sendPushNotification({
subscription,
subscriptionId: id,
notification,
recipient: { discordId, customUrl },
recipient: { id: userId, customUrl },
t,
}),
),

View File

@@ -68,7 +68,7 @@ export type Notification =
| NotificationItem<"PLUS_SUGGESTION_ADDED", { tier: number }>
| NotificationItem<
"TAGGED_TO_ART",
{ adderUsername: string; adderDiscordId: string; artId: number }
{ adderUsername: string; adderId: number; artId: number }
>
| NotificationItem<"SEASON_STARTED", { seasonNth: number }>
| NotificationItem<"SEASON_ENDED", { seasonNth: number }>
@@ -98,7 +98,7 @@ export type Notification =
{ tournamentId: number; matchId: number; opponentTeamName: string }
>
| NotificationItem<"SCRIM_AUTO_DELETED", { at: number }>
| NotificationItem<"COMMISSIONS_CLOSED", { discordId: string }>
| NotificationItem<"COMMISSIONS_CLOSED">
| NotificationItem<
"FRIEND_REQUEST_RECEIVED",
{ senderId: number; senderUsername: string }

View File

@@ -5,6 +5,7 @@ import { tournamentBracketsPage } from "~/features/tournament-bracket/tournament
import { userSeasonsPage } from "~/features/user-page/user-page-urls";
import { assertUnreachable } from "~/utils/types";
import {
ART_PAGE,
badgePage,
EVENTS_PAGE,
FRIENDS_PAGE,
@@ -114,7 +115,7 @@ export const notificationLink = (
return SENDOUQ_READY_PAGE;
case "TAGGED_TO_ART":
return userArtPage(
{ discordId: notification.meta.adderDiscordId },
{ id: notification.meta.adderId },
"MADE-BY",
notification.meta.artId,
);
@@ -141,7 +142,7 @@ export const notificationLink = (
return scrimPage(notification.meta.id);
}
case "COMMISSIONS_CLOSED": {
return userEditProfilePage({ discordId: notification.meta.discordId });
return recipient ? userEditProfilePage(recipient) : ART_PAGE;
}
case "FRIEND_REQUEST_RECEIVED": {
return FRIENDS_PAGE;

View File

@@ -18,15 +18,13 @@ type LoggedInUser = NonNullable<
React.ComponentProps<typeof UserProvider>["user"]
>;
const AUTHOR_AS_LOGGED_IN_USER = { id: AUTHOR.id, discordId: "1005" };
const AUTHOR_AS_LOGGED_IN_USER = { id: AUTHOR.id };
const suggestedUser = (id: number, username: string) => ({
id,
username,
discordId: String(1000 + id),
discordAvatar: null,
customUrl: null,
customAvatarUrl: null,
avatar: null,
});
const NOW_TIMESTAMP = databaseTimestampNow();

View File

@@ -1,7 +1,7 @@
import { type InferResult, sql } from "kysely";
import * as R from "remeda";
import { db } from "~/db/sql";
import type { Tables, TablesInsertable } from "~/db/tables";
import type { TablesInsertable } from "~/db/tables";
import * as PlusSuggestionRepository from "~/features/plus-suggestions/PlusSuggestionRepository.server";
import {
type MonthYear,
@@ -10,7 +10,7 @@ import {
} from "~/features/plus-voting/core";
import { databaseTimestampNow } from "~/utils/dates";
import { invariant } from "~/utils/invariant";
import { commonUserSelect } from "~/utils/kysely.server";
import { type CommonUser, commonUserSelect } from "~/utils/kysely.server";
import type { Unwrapped } from "~/utils/types";
import * as PlusVoting from "./core/PlusVoting";
@@ -128,10 +128,9 @@ function groupPlusVotingResults(rows: EnrichedRow[]) {
type Bio = { text: string; markdown: boolean };
export type UsersForVoting = {
user: Pick<
Tables["User"],
"id" | "discordId" | "username" | "discordAvatar"
> & { customAvatarUrl: string | null; bio: Bio | null };
user: Pick<CommonUser, "id" | "username" | "avatar"> & {
bio: Bio | null;
};
suggestion?: PlusSuggestionRepository.FindAllByMonthItem;
}[];
@@ -166,10 +165,8 @@ export async function findAllUsersForVoting(loggedInUser: {
result.push({
user: {
id: member.id,
discordId: member.discordId,
username: member.username,
discordAvatar: member.discordAvatar,
customAvatarUrl: member.customAvatarUrl,
avatar: member.avatar,
bio: bios.get(member.id) ?? null,
},
});
@@ -179,10 +176,8 @@ export async function findAllUsersForVoting(loggedInUser: {
result.push({
user: {
id: suggestion.suggested.id,
discordId: suggestion.suggested.discordId,
username: suggestion.suggested.username,
discordAvatar: suggestion.suggested.discordAvatar,
customAvatarUrl: suggestion.suggested.customAvatarUrl,
avatar: suggestion.suggested.avatar,
bio: bios.get(suggestion.suggested.id) ?? null,
},
suggestion,

View File

@@ -51,8 +51,7 @@ async function searchByType({
inGameName: u.inGameName,
tournamentName: u.tournamentName,
avatarUrl: null,
discordId: u.discordId,
discordAvatar: u.discordAvatar,
avatar: u.avatar,
customUrl: u.customUrl,
plusTier: u.plusTier,
}));

View File

@@ -44,8 +44,7 @@ export function MatchmadeRejoinSection({
members={viewerGroup.members.map((m) => ({
id: m.id,
username: m.username,
discordId: m.discordId,
discordAvatar: m.discordAvatar,
avatar: m.avatar,
customUrl: m.customUrl,
}))}
votes={votes}

View File

@@ -14,8 +14,7 @@ import styles from "./RematchVotePanel.module.css";
export type RematchVoteMember = {
id: number;
username: string;
discordId: string;
discordAvatar: string | null;
avatar: string | null;
customUrl: string | null;
};

View File

@@ -8,8 +8,6 @@ import {
import { invariant } from "~/utils/invariant";
import { SENDOU_INK_BASE_URL, sendouQMatchPage } from "~/utils/urls";
type MatchMember = WebhookUser & { id: number };
interface CancelReport {
authorUserId: number;
reason: string;
@@ -19,7 +17,7 @@ interface CancelReport {
/** Posts a rich embed about a finalized SendouQ cancellation to the cancels channel webhook. Fire-and-forget (see `sendSQCancelDiscordWebhook`). */
export function sendMatchCanceledWebhook(args: {
matchId: number;
members: MatchMember[];
members: WebhookUser[];
/** Both teams' cancel reports, requester's first. */
reports: CancelReport[];
nominationCounts: Array<{

View File

@@ -19,8 +19,7 @@ function member(overrides: Record<string, unknown> = {}) {
return {
id: 1,
username: "user",
discordId: "d",
discordAvatar: null,
avatar: null,
customUrl: null,
skillDifference: undefined,
...overrides,

View File

@@ -103,10 +103,8 @@ export function resolveTimelineSpChanges(
user: {
id: m.id,
username: m.username,
discordId: m.discordId,
discordAvatar: m.discordAvatar,
customUrl: m.customUrl,
customAvatarUrl: m.customAvatarUrl,
avatar: m.avatar,
},
skillDifference: m.skillDifference!,
}));

View File

@@ -18,10 +18,8 @@ vi.mock("~/features/auth/core/user", () => ({
function createMember(overrides: Partial<SQGroupMember> = {}): SQGroupMember {
return {
id: 1,
discordId: "123456789",
username: "TestUser",
discordAvatar: null,
customAvatarUrl: null,
avatar: null,
customUrl: null,
vc: "NO",
languages: [],
@@ -78,10 +76,8 @@ function createOwnGroupMember(
): OwnGroupMember {
return {
id: 1,
discordId: "123456789",
username: "TestUser",
discordAvatar: null,
customAvatarUrl: null,
avatar: null,
customUrl: null,
vc: "NO",
languages: [],

View File

@@ -109,7 +109,7 @@ export function GroupCard({
return (
<GroupMember
member={member}
key={member.discordId}
key={member.id}
hideVc={hideVc}
hideWeapons={hideWeapons}
hideNote={hideNote}

View File

@@ -492,8 +492,7 @@ class SendouQClass {
members: Array<{
id: number;
username: string;
discordId: string;
discordAvatar: string | null;
avatar: string | null;
}>;
};
groupBravo: {
@@ -501,8 +500,7 @@ class SendouQClass {
members: Array<{
id: number;
username: string;
discordId: string;
discordAvatar: string | null;
avatar: string | null;
}>;
};
pools: ReturnType<typeof matchMapPools>;
@@ -522,8 +520,7 @@ class SendouQClass {
{
id: member.id,
username: member.username,
discordId: member.discordId,
discordAvatar: member.discordAvatar,
avatar: member.avatar,
},
];
}),

View File

@@ -4,6 +4,7 @@ import * as Seasons from "~/features/mmr/core/Seasons";
import * as UserRepository from "~/features/user-page/UserRepository.server";
import { SendouQ, sqRedirectIfNeeded } from "../core/SendouQ.server";
import { qSearchParams } from "../q-search-params";
import { userCanJoinQueueAt } from "../q-utils";
export const loader = async ({ url }: LoaderFunctionArgs) => {
const user = getUser();
@@ -23,15 +24,19 @@ export const loader = async ({ url }: LoaderFunctionArgs) => {
const season = Seasons.current();
const upcomingSeason = !season ? Seasons.next() : undefined;
const friendCode = user
? await UserRepository.findCurrentFriendCodeByUserId(user.id)
: undefined;
return {
season: season ? seasonWithTimestamps(season) : undefined,
upcomingSeason: upcomingSeason
? seasonWithTimestamps(upcomingSeason)
: undefined,
groupInvitedTo,
friendCode: user
? await UserRepository.findCurrentFriendCodeByUserId(user.id)
: undefined,
friendCode,
queueJoinStatus:
user && friendCode ? userCanJoinQueueAt(user, friendCode) : null,
};
};

View File

@@ -38,7 +38,6 @@ import { action } from "../actions/q.server";
import { loader } from "../loaders/q.server";
import { frontPageSchema } from "../q-action-schemas";
import { FULL_GROUP_SIZE } from "../q-constants";
import { userCanJoinQueueAt } from "../q-utils";
import styles from "./q.module.css";
export { action, loader };
@@ -74,8 +73,7 @@ export default function QPage() {
minute: "numeric",
});
const queueJoinStatus =
user && data.friendCode ? userCanJoinQueueAt(user, data.friendCode) : null;
const { queueJoinStatus } = data;
return (
<Main halfWidth className="stack lg">

View File

@@ -3,6 +3,7 @@ import {
LogOut,
Map as MapIcon,
Palette,
RefreshCcw,
SlidersHorizontal,
Volume2,
} from "lucide-react";
@@ -13,7 +14,12 @@ import { useUser } from "~/features/auth/core/user";
import { useSearchParam } from "~/modules/search-params/hooks";
import { metaTags, ogPageImage } from "~/utils/remix";
import type { SendouRouteHandle } from "~/utils/remix.server";
import { LOG_OUT_URL, navIconUrl, SETTINGS_PAGE } from "~/utils/urls";
import {
DISCORD_REFRESH_URL,
LOG_OUT_URL,
navIconUrl,
SETTINGS_PAGE,
} from "~/utils/urls";
import { SendouButton } from "../../../components/elements/Button";
import {
SendouTab,
@@ -70,16 +76,28 @@ export default function SettingsPage() {
<div className="stack horizontal justify-between items-center">
<h2 className="text-lg">{t("common:pages.settings")}</h2>
{user ? (
<form method="post" action={LOG_OUT_URL}>
<SendouButton
size="small"
variant="outlined"
icon={<LogOut />}
type="submit"
>
{t("common:header.logout")}
</SendouButton>
</form>
<div className="stack horizontal sm flex-wrap justify-end">
<form method="post" action={DISCORD_REFRESH_URL}>
<SendouButton
size="small"
variant="outlined"
icon={<RefreshCcw />}
type="submit"
>
{t("settings:refreshFromDiscord")}
</SendouButton>
</form>
<form method="post" action={LOG_OUT_URL}>
<SendouButton
size="small"
variant="outlined"
icon={<LogOut />}
type="submit"
>
{t("common:header.logout")}
</SendouButton>
</form>
</div>
) : null}
</div>
<SendouTabs

View File

@@ -46,8 +46,8 @@ import { cache, ttl } from "~/utils/cache.server";
import { databaseTimestampNow, dateToDatabaseTimestamp } from "~/utils/dates";
import type { CommonUser } from "~/utils/kysely.server";
import {
avatarUrl,
BLANK_IMAGE_URL,
discordAvatarUrl,
navIconUrl,
teamSchedulePage,
tournamentMatchPage,
@@ -70,9 +70,7 @@ export type SidebarEvent = {
export type SidebarFriend = {
id: number;
name: string;
discordId: string;
discordAvatar: string | null;
customAvatarUrl: string | null;
avatar: CommonUser["avatar"];
url: string;
subtitle: string;
badge: string;
@@ -292,15 +290,7 @@ async function combinedStreams(): Promise<SidebarStream[]> {
stream: {
id: `xrank-${row.id}`,
name: row.username,
imageUrl: row.customAvatarUrl
? row.customAvatarUrl
: row.discordAvatar
? discordAvatarUrl({
discordId: row.discordId,
discordAvatar: row.discordAvatar,
size: "sm",
})
: BLANK_IMAGE_URL,
imageUrl: row.avatar ? avatarUrl(row.avatar, "sm") : BLANK_IMAGE_URL,
url: LiveStream.url(row),
subtitle: "",
startsAt: databaseTimestampNow(),
@@ -433,10 +423,8 @@ function rowToSidebarFriend(
return {
id: row.id,
name: row.username,
discordId: row.discordId,
discordAvatar: row.discordAvatar,
customAvatarUrl: row.customAvatarUrl,
url: userPage({ discordId: row.discordId, customUrl: row.customUrl }),
avatar: row.avatar,
url: userPage({ id: row.id, customUrl: row.customUrl }),
subtitle: activity.subtitle ?? "",
badge: activity.badge ?? "",
activityType: activity.type,

View File

@@ -66,7 +66,7 @@ export default function TeamIndexPage() {
const showSections = playerMembers.length > 0 && otherMembers.length > 0;
const renderMember = (member: (typeof members)[number]) => (
<React.Fragment key={member.discordId}>
<React.Fragment key={member.id}>
<MemberRow member={member} number={members.indexOf(member)} />
<MobileMemberCard member={member} />
</React.Fragment>

View File

@@ -15,9 +15,9 @@ import styles from "./TierListGraphic.module.css";
import { TierListItemImage } from "./TierListItemImage";
export interface TierListGraphicAuthor {
id: number;
username: string;
discordId: string;
discordAvatar: string | null;
avatar: string | null;
}
export function TierListGraphic({

View File

@@ -123,7 +123,7 @@ function xRankPlacementsQueryBase() {
])
.innerJoin("SplatoonPlayer", "XRankPlacement.playerId", "SplatoonPlayer.id")
.leftJoin("User", "SplatoonPlayer.userId", "User.id")
.select(["User.discordId", "User.customUrl"]);
.select(["SplatoonPlayer.userId", "User.customUrl"]);
}
export async function findPlacementsOfMonth(

View File

@@ -19,10 +19,8 @@ export const action = defineAction(
const placements = notFoundIfNullish(
await XRankPlacementRepository.findPlacementsByPlayerId(id),
);
const currentLinkedUserDiscordId = placements[0].discordId;
errorToastIfFalsy(
currentLinkedUserDiscordId === user.discordId,
placements[0].userId === user.id,
"This player is not linked to you",
);

View File

@@ -59,10 +59,10 @@ export const meta: MetaFunction<typeof loader> = (args) => {
});
};
function hasUserLinked<T extends { discordId: string | null }>(
function hasUserLinked<T extends { userId: number | null }>(
user: T,
): user is T & { discordId: string } {
return user.discordId !== null;
): user is T & { userId: number } {
return user.userId !== null;
}
export default function XSearchPlayerPage() {
@@ -72,8 +72,7 @@ export default function XSearchPlayerPage() {
const placementUser = data.placements[0];
const isLinkedToCurrentUser =
user && user?.discordId === placementUser.discordId;
const isLinkedToCurrentUser = user && user?.id === placementUser.userId;
return (
<Main halfWidth className="stack lg">
@@ -81,7 +80,14 @@ export default function XSearchPlayerPage() {
<div>
<h2 className="text-lg">
{hasUserLinked(placementUser) ? (
<Link to={userPage(placementUser)}>{data.names.primary}</Link>
<Link
to={userPage({
id: placementUser.userId,
customUrl: placementUser.customUrl,
})}
>
{data.names.primary}
</Link>
) : (
data.names.primary
)}{" "}

View File

@@ -83,9 +83,11 @@ const DEFAULT_FIELDS: ExportField[] = [
export function ExportDialog({
close,
teams: allTeams,
memberDiscordIds,
}: {
close: () => void;
teams: TournamentTeamFull[];
memberDiscordIds: Record<number, string>;
}) {
const tournament = useTournament();
@@ -128,6 +130,7 @@ export function ExportDialog({
});
const content = buildContent({
teams,
memberDiscordIds,
format,
fields,
captainsOnly: roster === "captains",
@@ -362,6 +365,7 @@ function teamFieldValue(
function memberFieldValue(
member: TournamentTeamFull["members"][number],
field: (typeof MEMBER_FIELDS)[number],
memberDiscordIds: Record<number, string>,
) {
switch (field) {
case "memberUsername":
@@ -369,14 +373,17 @@ function memberFieldValue(
case "memberInGameName":
return member.inGameName ?? "";
case "memberDiscord":
return member.discordId ? `<@${member.discordId}>` : "";
return memberDiscordIds[member.userId]
? `<@${memberDiscordIds[member.userId]}>`
: "";
case "memberProfileUrl":
return `${BASE_URL}${userPage(member)}`;
return `${BASE_URL}${userPage({ ...member, id: member.userId })}`;
}
}
function buildContent({
teams,
memberDiscordIds,
format,
fields,
captainsOnly,
@@ -385,6 +392,7 @@ function buildContent({
notCheckedInLabel,
}: {
teams: TournamentTeamFull[];
memberDiscordIds: Record<number, string>;
format: ExportFormat;
fields: Set<ExportField>;
captainsOnly: boolean;
@@ -425,7 +433,7 @@ function buildContent({
const memberValues = Array.from({ length: maxRoster }).flatMap((_, i) => {
const member = teamMembers[i];
return memberFields.map((field) =>
member ? memberFieldValue(member, field) : "",
member ? memberFieldValue(member, field, memberDiscordIds) : "",
);
});
return [...teamValues, ...memberValues];
@@ -447,7 +455,7 @@ function buildContent({
if (!hasMemberFields) return teamLine;
const memberLines = membersOf(team).map((member) => {
const memberLine = memberFields
.map((field) => memberFieldValue(member, field))
.map((field) => memberFieldValue(member, field, memberDiscordIds))
.filter(Boolean)
.join(" - ");
return groupByTeam ? ` ${memberLine}` : memberLine;

View File

@@ -3,6 +3,7 @@ import {
tournamentFromParams,
tournamentTeamsFullInSeedOrder,
} from "~/features/tournament-bracket/core/Tournament.server";
import * as UserRepository from "~/features/user-page/UserRepository.server";
import type { SerializeFrom } from "~/utils/remix";
export type TournamentAdminTeamsLoaderData = SerializeFrom<typeof loader>;
@@ -12,7 +13,13 @@ export const loader = async ({ params }: LoaderFunctionArgs) => {
for: "organizer",
});
const teams = await tournamentTeamsFullInSeedOrder({ tournament, user });
const discordIds = await UserRepository.findDiscordIdsByUserIds(
teams.flatMap((team) => team.members.map((member) => member.userId)),
);
return {
teams: await tournamentTeamsFullInSeedOrder({ tournament, user }),
teams,
memberDiscordIds: Object.fromEntries(discordIds),
};
};

View File

@@ -58,7 +58,8 @@ type SortKey = "name" | "checkIn";
export default function TournamentAdminTeamsPage() {
const tournament = useTournament();
const { teams } = useLoaderData<TournamentAdminTeamsLoaderData>();
const { teams, memberDiscordIds } =
useLoaderData<TournamentAdminTeamsLoaderData>();
const [search, setSearch] = React.useState("");
const [sort, setSort] = React.useState<SortState<SortKey>>(null);
@@ -69,7 +70,9 @@ export default function TournamentAdminTeamsPage() {
...teams.map((team) => team.members.length),
);
const filteredTeams = teams.filter((team) => teamMatchesQuery(team, search));
const filteredTeams = teams.filter((team) =>
teamMatchesQuery({ team, search, memberDiscordIds }),
);
const sortedTeams = sortTeams(filteredTeams, sort);
return (
@@ -155,7 +158,11 @@ export default function TournamentAdminTeamsPage() {
</Table>
{exportOpen ? (
<ExportDialog teams={teams} close={() => setExportOpen(false)} />
<ExportDialog
teams={teams}
memberDiscordIds={memberDiscordIds}
close={() => setExportOpen(false)}
/>
) : null}
</div>
);
@@ -244,7 +251,7 @@ function TeamRow({
<td key={`player-${i}`}>
{member ? (
<Link
to={userPage(member)}
to={userPage({ ...member, id: member.userId })}
className={clsx("stack horizontal xxs items-center", {
"font-bold": member.role === "OWNER",
})}
@@ -568,7 +575,15 @@ function activeCheckInCount(team: TournamentTeamFull) {
return activeCheckInLabels(team, () => "").length;
}
function teamMatchesQuery(team: TournamentTeamFull, search: string) {
function teamMatchesQuery({
team,
search,
memberDiscordIds,
}: {
team: TournamentTeamFull;
search: string;
memberDiscordIds: Record<number, string>;
}) {
const query = search.trim();
if (!query) return true;
@@ -587,7 +602,7 @@ function teamMatchesQuery(team: TournamentTeamFull, search: string) {
return team.members.some((member) => {
if ("id" in identifier) return member.userId === identifier.id;
if ("discordId" in identifier) {
return member.discordId === identifier.discordId;
return memberDiscordIds[member.userId] === identifier.discordId;
}
return (
member.customUrl?.toLowerCase() === identifier.customUrl.toLowerCase()

View File

@@ -32,8 +32,7 @@ const SEARCHABLE_USERS = [
name: "sanu",
inGameName: null,
avatarUrl: null,
discordId: "1",
discordAvatar: null,
avatar: null,
customUrl: null,
plusTier: null,
},
@@ -43,8 +42,7 @@ const SEARCHABLE_USERS = [
name: "Jolt",
inGameName: null,
avatarUrl: null,
discordId: "2",
discordAvatar: null,
avatar: null,
customUrl: null,
plusTier: null,
},

View File

@@ -34,8 +34,7 @@ const GREY = {
name: "Grey",
inGameName: null,
avatarUrl: null,
discordId: "123",
discordAvatar: null,
avatar: null,
customUrl: null,
plusTier: null,
};

View File

@@ -9,6 +9,7 @@ import { useTournament } from "~/features/tournament/tournament-context";
import { TOURNAMENT_ORGANIZATION_ROLES } from "~/features/tournament-organization/tournament-organization-constants";
import { tournamentOrganizationEditPage } from "~/features/tournament-organization/tournament-organization-urls";
import { SendouForm } from "~/form/SendouForm";
import type { CommonUser } from "~/utils/kysely.server";
import { adminStaffFormSchema } from "../tournament-admin-staff-schemas";
export { action } from "../actions/to.$id.admin.staff.server";
@@ -38,7 +39,7 @@ export default function TournamentAdminStaffPage() {
}
type EventStaff = Array<
Pick<Tables["User"], "id" | "username" | "discordId" | "discordAvatar"> & {
Pick<CommonUser, "id" | "username" | "avatar"> & {
role: Tables["TournamentStaff"]["role"];
}
>;
@@ -194,7 +195,7 @@ function StaffInfoRow({
roleText,
testId,
}: {
user: Pick<Tables["User"], "id" | "username" | "discordId" | "discordAvatar">;
user: Pick<CommonUser, "id" | "username" | "avatar">;
roleText: string;
testId?: string;
}) {

View File

@@ -95,10 +95,8 @@ export async function fetchTournamentStreams(
user: {
id: stream.id,
username: stream.username,
discordId: stream.discordId,
discordAvatar: stream.discordAvatar,
customUrl: stream.customUrl,
customAvatarUrl: stream.customAvatarUrl,
avatar: stream.avatar,
},
}));

View File

@@ -93,10 +93,8 @@ export type TournamentStream = StreamAccount & {
user: {
id: number;
username: string;
discordId: string;
discordAvatar: string | null;
customUrl: string | null;
customAvatarUrl: string | null;
avatar: string | null;
} | null;
};

View File

@@ -119,9 +119,7 @@ export const testTournamentData = ({
teams: nTeams(participant.length, Math.min(...participant)),
author: {
customUrl: null,
customAvatarUrl: null,
discordAvatar: null,
discordId: "123",
avatar: null,
username: "test",
pronouns: null,
id: 1,

View File

@@ -296,7 +296,11 @@ function NewBadgeReceiversSelector({
userId: member.userId,
})}
/>
<Avatar user={member} size="xxs" className="mr-2" />
<Avatar
user={{ ...member, id: member.userId }}
size="xxs"
className="mr-2"
/>
{member.username}
</div>
<div className="stack horizontal sm items-end">
@@ -353,7 +357,11 @@ function NewTrophyReceiversSelector({
isSelected={trophyReceiverUserIds.includes(member.userId)}
onChange={handleReceiverSelected(member.userId)}
/>
<Avatar user={member} size="xxs" className="mr-2" />
<Avatar
user={{ ...member, id: member.userId }}
size="xxs"
className="mr-2"
/>
{member.username}
</div>
<div className="stack horizontal sm items-end">

View File

@@ -32,9 +32,7 @@ import styles from "./LFGGroupCard.module.css";
export type LFGGroupMember = {
id: number;
username: string;
discordId: string;
discordAvatar: string | null;
customAvatarUrl: string | null;
avatar: string | null;
customUrl: string | null;
languages: UnifiedLanguageCode[];
vc: "YES" | "NO" | "LISTEN_ONLY" | null;
@@ -96,7 +94,7 @@ export function LFGGroupCard({
<div className="stack md">
{group.members.map((member) => (
<LFGGroupMemberRow
key={member.discordId}
key={member.id}
member={member}
showActions={showActions}
isOwnGroup={isOwnGroup}

View File

@@ -133,9 +133,7 @@ async function subsMode({
teamId: group.id,
userId: member.id,
username: member.username,
discordId: member.discordId,
discordAvatar: member.discordAvatar,
customAvatarUrl: member.customAvatarUrl,
avatar: member.avatar,
customUrl: member.customUrl,
vc: member.vc,
languages,
@@ -184,9 +182,7 @@ async function resolveOwnTeam({
const members: LFGGroupMember[] = team.members.map((m) => ({
id: m.userId,
username: m.username,
discordId: m.discordId,
discordAvatar: m.discordAvatar,
customAvatarUrl: m.customAvatarUrl,
avatar: m.avatar,
customUrl: m.customUrl,
languages: [],
vc: null,
@@ -220,9 +216,7 @@ function transformMembers(
return {
id: m.id,
username: m.username,
discordId: m.discordId,
discordAvatar: m.discordAvatar,
customAvatarUrl: m.customAvatarUrl,
avatar: m.avatar,
customUrl: m.customUrl,
languages,
vc: m.vc,

View File

@@ -237,7 +237,7 @@ function SubCard({ sub }: { sub: SubEntry }) {
<div className={styles.subsSectionAvatar}>
<UserCard userId={sub.userId} withMutualFriends>
<NoteAvatar sentiment={cardData?.privateNote?.sentiment} size="sm">
<Avatar user={sub} size="sm" />
<Avatar user={{ ...sub, id: sub.userId }} size="sm" />
</NoteAvatar>
</UserCard>
</div>

View File

@@ -254,17 +254,13 @@ function buildSetEndingData({
const memberToCommonUser = (m: {
userId: number;
username: string;
discordId: string;
discordAvatar: string | null;
customUrl: string | null;
customAvatarUrl: string | null;
avatar: string | null;
}): CommonUser => ({
id: m.userId,
username: m.username,
discordId: m.discordId,
discordAvatar: m.discordAvatar,
customUrl: m.customUrl,
customAvatarUrl: m.customAvatarUrl,
avatar: m.avatar,
});
const teamOneMembersMap = new Map(

View File

@@ -157,10 +157,8 @@ function resolveTimelineMaps(
.map((u) => ({
id: u.id,
username: u.username,
discordId: u.discordId,
discordAvatar: u.discordAvatar,
customUrl: u.customUrl,
customAvatarUrl: u.customAvatarUrl,
avatar: u.avatar,
}));
return data.results.map((result, mapIndex) => {
@@ -361,10 +359,8 @@ function TournamentMatchRosterTab({
members: team.members.map((m) => ({
id: m.userId,
username: m.username,
discordId: m.discordId,
discordAvatar: m.discordAvatar,
customUrl: m.customUrl,
customAvatarUrl: m.customAvatarUrl,
avatar: m.avatar,
inGameName: m.inGameName,
})),
subbedOut,

View File

@@ -11,14 +11,7 @@ const FIRST_PLACE_POINTS = SECOND_PLACE_POINTS * 2;
const POINTS_TIE_EPSILON = 0.0001;
const USER_KEYS = [
"id",
"username",
"discordId",
"discordAvatar",
"customUrl",
"customAvatarUrl",
] as const;
const USER_KEYS = ["id", "username", "customUrl", "avatar"] as const;
type EventLeaderboardEvent = Unpacked<
Awaited<
@@ -120,7 +113,6 @@ function addCalendarEventPoints(
...R.pick(result, USER_KEYS),
id: result.id,
username: result.username!,
discordId: result.discordId!,
},
placement: result.placement,
teamSize: teamSizes[result.teamId],

View File

@@ -645,7 +645,7 @@ function EventWinners({
</div>
<div className="stack xs horizontal">
{winner.members.map((member) => (
<Avatar key={member.discordId} user={member} size="xxs" />
<Avatar key={member.id} user={member} size="xxs" />
))}
</div>
</div>
@@ -697,7 +697,7 @@ function EventLeaderboard({
) : null}
<ol className={styles.leaderboardList}>
{leaderboard.map((entry) => (
<li key={entry.user.discordId}>
<li key={entry.user.id}>
<EventLeaderboardRow entry={entry} />
</li>
))}

View File

@@ -47,6 +47,7 @@ import {
tournamentUsername,
} from "~/utils/kysely.server";
import type { Unwrapped } from "~/utils/types";
import { accountCreatedInTheLastSixMonths } from "~/utils/users";
import type { TournamentTierNumber } from "./core/tiering";
import type { TournamentStaffRole } from "./tournament-constants";
import { updatedCastedMatchesInfo } from "./tournament-utils";
@@ -534,6 +535,7 @@ export async function findTeamsFullByTournamentId(tournamentId: number) {
idAs: "userId",
inTournament: true,
}),
"User.discordId",
"User.country",
"User.tournamentName",
"SeedingSkill.ordinal",
@@ -602,7 +604,10 @@ export async function findTeamsFullByTournamentId(tournamentId: number) {
return teams.map((team) => ({
...team,
members: team.members.map((member) => R.omit(member, ["ordinal"])),
members: team.members.map(({ ordinal: _, discordId, ...member }) => ({
...member,
isFreshAccount: accountCreatedInTheLastSixMonths(discordId),
})),
avgSeedingSkillOrdinal: nullifyingAvg(
team.members
.map((member) => member.ordinal)

View File

@@ -9,7 +9,6 @@ import { useTournament } from "~/features/tournament/tournament-context";
import type { TournamentTeamFull } from "~/features/tournament-bracket/core/Tournament.server";
import { modesShort } from "~/modules/in-game-lists/modes";
import { userPage } from "~/utils/urls";
import { accountCreatedInTheLastSixMonths } from "~/utils/users";
import { useTournamentFriendCodes } from "../routes/to.$id";
import styles from "./TeamWithRoster.module.css";
@@ -93,7 +92,7 @@ export function TeamWithRoster({
})}
>
<Avatar
user={member}
user={{ ...member, id: member.userId }}
size="xxs"
className={clsx({
[styles.teamWithRosterMemberAvatarInactive]:
@@ -101,7 +100,7 @@ export function TeamWithRoster({
})}
/>
<Link
to={userPage(member)}
to={userPage({ ...member, id: member.userId })}
className={clsx(styles.teamMemberName, "truncate")}
data-testid="team-member-name"
>
@@ -110,8 +109,8 @@ export function TeamWithRoster({
</div>
{friendCode ? (
<div className="text-xs text-lighter">
{tournament.isOrganizer(user) ? (
<FreshAccountEmoji discordId={member.discordId} />
{tournament.isOrganizer(user) && member.isFreshAccount ? (
<FreshAccountEmoji />
) : null}
SW-{friendCode}
</div>
@@ -126,11 +125,9 @@ export function TeamWithRoster({
);
}
function FreshAccountEmoji({ discordId }: { discordId: string }) {
function FreshAccountEmoji() {
const { t } = useTranslation(["tournament"]);
if (!accountCreatedInTheLastSixMonths(discordId)) return null;
return (
<span className="text-md mr-2" title={t("tournament:roster.freshAccount")}>
👶

View File

@@ -33,15 +33,9 @@ export interface PlayedSet {
id: number;
name: string;
roster: Array<
Pick<
Tables["User"],
| "id"
| "username"
| "discordAvatar"
| "discordId"
| "customUrl"
| "country"
> & { customAvatarUrl: string | null }
Pick<Tables["User"], "id" | "username" | "customUrl" | "country"> & {
avatar: string | null;
}
>;
};
}

View File

@@ -779,9 +779,7 @@ function FillRoster({
user={{
id: member.userId,
username: member.username,
discordId: member.discordId,
discordAvatar: member.discordAvatar,
customAvatarUrl: member.customAvatarUrl,
avatar: member.avatar,
}}
entry={entryByUserId?.get(member.userId)}
showAvailability={Boolean(entryByUserId)}

View File

@@ -843,7 +843,7 @@ const withTargetManager = (eb: ExpressionBuilder<DB, "PendingTrophy">) => {
return jsonObjectFrom(
eb
.selectFrom("User")
.select(["User.id", "User.username", "User.discordId"])
.select(["User.id", "User.username"])
.whereRef("User.id", "=", "PendingTrophy.managerId"),
).as("manager");
};
@@ -852,7 +852,7 @@ const withPendingCreator = (eb: ExpressionBuilder<DB, "PendingTrophy">) => {
return jsonObjectFrom(
eb
.selectFrom("User")
.select(["User.id", "User.username", "User.discordId"])
.select(["User.id", "User.username"])
.whereRef("User.id", "=", "PendingTrophy.creatorId"),
).as("creator");
};
@@ -891,7 +891,6 @@ function pendingBaseQuery() {
"PendingTrophy.managerId",
"PendingTrophy.creatorId",
"Submitter.username as submitterUsername",
"Submitter.discordId as submitterDiscordId",
"Decliner.username as declinedByUsername",
"TournamentOrganization.name as organizationName",
"TournamentOrganization.slug as organizationSlug",

View File

@@ -772,12 +772,12 @@ function TrophyListRow({
) : null}
<span className={styles.pendingName}>{pending.name}</span>
<span className={styles.pendingMeta}>
{pending.manager?.discordId ? (
<Link to={userPage({ discordId: pending.manager.discordId })}>
{pending.manager ? (
<Link to={userPage({ id: pending.manager.id })}>
{pending.manager.username}
</Link>
) : pending.submitterDiscordId ? (
<Link to={userPage({ discordId: pending.submitterDiscordId })}>
) : pending.submitterUserId ? (
<Link to={userPage({ id: pending.submitterUserId })}>
{pending.submitterUsername}
</Link>
) : (
@@ -794,7 +794,7 @@ function TrophyListRow({
values={{ name: pending.creator.username }}
>
Created by
<Link to={userPage({ discordId: pending.creator.discordId })}>
<Link to={userPage({ id: pending.creator.id })}>
{pending.creator.username}
</Link>
</Trans>

View File

@@ -628,10 +628,8 @@ function enrichUserCardData(
return {
id: cardData.id,
username: cardData.username,
discordId: cardData.discordId,
discordAvatar: cardData.discordAvatar,
customUrl: cardData.customUrl,
customAvatarUrl: cardData.customAvatarUrl,
avatar: cardData.avatar,
shortBio: cardData.shortBio,
customTheme: cardData.customTheme,
banner: enrichBanner(cardData.banner),

View File

@@ -28,7 +28,6 @@ import {
asJson,
commonUserSelect,
concatUserSubmittedImagePrefix,
customAvatarUrl,
jsonArrayFrom,
jsonObjectFrom,
tournamentLogoOrNull,
@@ -53,7 +52,7 @@ export function findIdByIdentifier(identifier: string) {
/** Identity of the user a `/u/:identifier` page is about, incl. what their canonical page URL needs. */
export function findPageUserByIdentifier(identifier: string) {
return userByIdentifierQuery(identifier)
.select(["User.discordId", "User.customUrl"])
.select("User.customUrl")
.executeTakeFirst();
}
@@ -72,6 +71,19 @@ export async function findCountriesByUserIds(userIds: number[]) {
return new Map(rows.map((row) => [row.id, row.country]));
}
/** Discord ids of the given users keyed by user id. Not for public responses. */
export async function findDiscordIdsByUserIds(userIds: number[]) {
if (userIds.length === 0) return new Map<number, string>();
const rows = await db
.selectFrom("User")
.select(["User.id", "User.discordId"])
.where("User.id", "in", userIds)
.execute();
return new Map(rows.map((row) => [row.id, row.discordId]));
}
/** Plus tiers of the given users keyed by user id, users without a tier absent. */
export async function findPlusTiersByUserIds(userIds: number[]) {
if (userIds.length === 0) return new Map<number, number>();
@@ -213,7 +225,13 @@ export async function findProfileByUserId(userId: number) {
"PlusTier.tier as plusTier",
"User.pronouns",
"User.customAvatarImgId",
customAvatarUrl(eb).as("customAvatarUrl"),
concatUserSubmittedImagePrefix(
eb
.selectFrom("UserSubmittedImage")
.select("UserSubmittedImage.url")
.whereRef("UserSubmittedImage.id", "=", "User.customAvatarImgId")
.$asScalar(),
).as("customAvatarUrl"),
jsonArrayFrom(
eb
.selectFrom("TeamMemberWithSecondary")
@@ -324,7 +342,7 @@ export async function findWidgetsByUserId(
export function findByCustomUrl(customUrl: string) {
return db
.selectFrom("User")
.select(["User.id", "User.discordId", "User.customUrl", "User.patronTier"])
.select(["User.id", "User.customUrl", "User.patronTier"])
.where("customUrl", "=", customUrl)
.executeTakeFirst();
}
@@ -355,6 +373,7 @@ export async function findLeanById(id: number) {
.where("User.id", "=", id)
.select(({ eb }) => [
...commonUserSelect(eb),
"User.discordId",
"User.createdAt",
"User.customTheme",
"User.isArtist",
@@ -411,6 +430,7 @@ export function findModInfoById(id: number) {
return db
.selectFrom("User")
.select((eb) => [
"User.discordId",
"User.discordUniqueName",
"User.isVideoAdder",
"User.isArtist",
@@ -473,7 +493,6 @@ export async function findAllPatronsForFooter() {
.selectFrom("User")
.select([
"User.id",
"User.discordId",
"User.username",
asJson(
sql<CustomTheme | null>`IIF(COALESCE("User"."patronTier", 0) >= 2, "User"."customTheme", null)`,
@@ -1233,12 +1252,12 @@ export function insertFriendCode(args: TablesInsertable["UserFriendCode"]) {
return db.insertInto("UserFriendCode").values(args).execute();
}
/** Inserts or updates the user by Discord id. The avatar is stored separately via {@link replaceSyncedAvatar}. */
export function upsert(
args: Pick<
TablesInsertable["User"],
| "discordId"
| "discordName"
| "discordAvatar"
| "discordUniqueName"
| "twitch"
| "youtubeId"
@@ -1266,10 +1285,68 @@ export function upsert(
...R.omit(args, ["discordId"]),
});
})
.returning("id")
.returning(["id", "discordAvatar", "syncedAvatarImgId"])
.executeTakeFirstOrThrow();
}
/**
* Points the user's synced avatar at a newly stored image file (`null` = no avatar) and deletes the
* previous image row. Returns the previous file name so its files can be deleted from storage.
*/
export function replaceSyncedAvatar({
userId,
discordAvatar,
fileName,
}: {
userId: number;
/** Hash of the Discord avatar the file was copied from. */
discordAvatar: string | null;
fileName: string | null;
}) {
return db.transaction().execute(async (trx) => {
const previous = await trx
.selectFrom("User")
.leftJoin(
"UnvalidatedUserSubmittedImage",
"UnvalidatedUserSubmittedImage.id",
"User.syncedAvatarImgId",
)
.select([
"UnvalidatedUserSubmittedImage.id",
"UnvalidatedUserSubmittedImage.url",
])
.where("User.id", "=", userId)
.executeTakeFirstOrThrow();
const image = fileName
? await trx
.insertInto("UnvalidatedUserSubmittedImage")
.values({
submitterUserId: userId,
url: fileName,
validatedAt: databaseTimestampNow(),
})
.returning("id")
.executeTakeFirstOrThrow()
: null;
await trx
.updateTable("User")
.set({ discordAvatar, syncedAvatarImgId: image?.id ?? null })
.where("id", "=", userId)
.execute();
if (previous.id) {
await trx
.deleteFrom("UnvalidatedUserSubmittedImage")
.where("id", "=", previous.id)
.execute();
}
return previous.url;
});
}
type UpdateProfileArgs = Pick<
TablesInsertable["User"],
| "country"
@@ -1325,7 +1402,7 @@ export function updateOwnProfile(args: UpdateProfileArgs) {
customAvatarImgId: args.customAvatarImgId ?? null,
})
.where("id", "=", userId)
.returning(["User.id", "User.customUrl", "User.discordId"])
.returning(["User.id", "User.customUrl"])
.executeTakeFirstOrThrow();
const inGameNameUpdatedTournamentIds = args.inGameName
@@ -1482,36 +1559,6 @@ export function updatePatronData(users: UpdatePatronDataArgs) {
});
}
/** Syncs Discord profile data by Discord id, a `null` name keeps the stored one. */
export function updateMany(
argsArr: Array<{
discordId: string;
discordAvatar: string | null;
discordName: string | null;
discordUniqueName: string | null;
}>,
) {
return db.transaction().execute(async (trx) => {
for (const updateArgs of argsArr) {
await trx
.updateTable("User")
.set((eb) => ({
discordAvatar: updateArgs.discordAvatar,
discordName: eb.fn.coalesce(
eb.val(updateArgs.discordName),
"User.discordName",
),
discordUniqueName: eb.fn.coalesce(
eb.val(updateArgs.discordUniqueName),
"User.discordUniqueName",
),
}))
.where("User.discordId", "=", updateArgs.discordId)
.execute();
}
});
}
export async function anyUserPrefersNoScreen(
userIds: number[],
): Promise<boolean> {

Some files were not shown because too many files have changed in this diff Show More