diff --git a/app/components/Avatar.tsx b/app/components/Avatar.tsx index 6c2deef0f..4a67b5c91 100644 --- a/app/components/Avatar.tsx +++ b/app/components/Avatar.tsx @@ -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 & { - customAvatarUrl?: string | null; - }; + user?: Pick; 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 (
diff --git a/app/components/BuildCard.tsx b/app/components/BuildCard.tsx index 1dbefcb6a..7667ef938 100644 --- a/app/components/BuildCard.tsx +++ b/app/components/BuildCard.tsx @@ -67,10 +67,8 @@ export interface BuildCardProps { modes: ModeShort[] | null; weapons: Array; }; - owner?: Pick & - Partial< - Pick - >; + owner?: Pick & + Partial>; /** 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({
{owner.username} diff --git a/app/components/LFGPostGraphic.tsx b/app/components/LFGPostGraphic.tsx index aac607034..d2922872e 100644 --- a/app/components/LFGPostGraphic.tsx +++ b/app/components/LFGPostGraphic.tsx @@ -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; + members: Array; } | 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({
@@ -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[]) { diff --git a/app/components/ListItem.tsx b/app/components/ListItem.tsx index 51a7f1a5e..31cece1a2 100644 --- a/app/components/ListItem.tsx +++ b/app/components/ListItem.tsx @@ -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 & { - customAvatarUrl?: string | null; - }; + user?: Pick; subtitle?: React.ReactNode; badge?: React.ReactNode; badgeVariant?: "default" | "warning"; @@ -62,9 +60,7 @@ export function ListButton({ ...rest }: { children: React.ReactNode; - user?: Pick & { - customAvatarUrl?: string | null; - }; + user?: Pick; 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 & { - customAvatarUrl?: string | null; - }; + user?: Pick; imageUrl?: string; overlayIconUrl?: string; subtitle?: React.ReactNode; diff --git a/app/components/UserLink.tsx b/app/components/UserLink.tsx index 08032deb4..847f8c1f0 100644 --- a/app/components/UserLink.tsx +++ b/app/components/UserLink.tsx @@ -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 & { customUrl?: Tables["User"]["customUrl"]; - customAvatarUrl?: string | null; }; type UnlinkedPlayer = { name: string | null } & { diff --git a/app/components/layout/GlobalSearch.tsx b/app/components/layout/GlobalSearch.tsx index 61950f414..f6b7cf93d 100644 --- a/app/components/layout/GlobalSearch.tsx +++ b/app/components/layout/GlobalSearch.tsx @@ -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 }) { diff --git a/app/components/match-page/utils.test.ts b/app/components/match-page/utils.test.ts index 90b7c4c5c..b3db72ed9 100644 --- a/app/components/match-page/utils.test.ts +++ b/app/components/match-page/utils.test.ts @@ -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, }; } diff --git a/app/db/seed/dev/misc.ts b/app/db/seed/dev/misc.ts index 592abaea3..242f2d9e9 100644 --- a/app/db/seed/dev/misc.ts +++ b/app/db/seed/dev/misc.ts @@ -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, }, }, diff --git a/app/db/seed/factories/UserFactory.ts b/app/db/seed/factories/UserFactory.ts index f0413d33d..308dfc4f4 100644 --- a/app/db/seed/factories/UserFactory.ts +++ b/app/db/seed/factories/UserFactory.ts @@ -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[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 | 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 | 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", diff --git a/app/db/seed/img/avatar-nzap.webp b/app/db/seed/img/avatar-nzap.webp new file mode 100644 index 000000000..748c4ffbc Binary files /dev/null and b/app/db/seed/img/avatar-nzap.webp differ diff --git a/app/db/seed/img/avatar-sendou.webp b/app/db/seed/img/avatar-sendou.webp new file mode 100644 index 000000000..f95460c75 Binary files /dev/null and b/app/db/seed/img/avatar-sendou.webp differ diff --git a/app/db/tables.ts b/app/db/tables.ts index d47d1e02b..747233dcc 100644 --- a/app/db/tables.ts +++ b/app/db/tables.ts @@ -1004,8 +1004,12 @@ export interface User { country: string | null; customTheme: JSONColumnTypeNullable; 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; diff --git a/app/features/api-private/routes/users.ts b/app/features/api-private/routes/users.ts deleted file mode 100644 index 6458f43f3..000000000 --- a/app/features/api-private/routes/users.ts +++ /dev/null @@ -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; - }, -); diff --git a/app/features/art/ArtRepository.server.test.ts b/app/features/art/ArtRepository.server.test.ts index d62ba9cab..d985305dc 100644 --- a/app/features/art/ArtRepository.server.test.ts +++ b/app/features/art/ArtRepository.server.test.ts @@ -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); }); diff --git a/app/features/art/ArtRepository.server.ts b/app/features/art/ArtRepository.server.ts index 84a12b615..b7a33da05 100644 --- a/app/features/art/ArtRepository.server.ts +++ b/app/features/art/ArtRepository.server.ts @@ -73,9 +73,8 @@ export async function findShowcaseArts(): Promise { 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 { 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({ diff --git a/app/features/art/actions/art.new.server.ts b/app/features/art/actions/art.new.server.ts index e29302efb..98fbfd679 100644 --- a/app/features/art/actions/art.new.server.ts +++ b/app/features/art/actions/art.new.server.ts @@ -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, }, }, diff --git a/app/features/art/art-image.server.ts b/app/features/art/art-image.server.ts index fab3485dc..1ad17bfd7 100644 --- a/app/features/art/art-image.server.ts +++ b/app/features/art/art-image.server.ts @@ -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 `-small.` thumbnail ({@link previewUrl}); returns the full image's file name. */ +/** Uploads the full image and its `-small.` 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"); diff --git a/app/features/art/art-types.ts b/app/features/art/art-types.ts index 7f2d102c5..69873c89d 100644 --- a/app/features/art/art-types.ts +++ b/app/features/art/art-types.ts @@ -13,10 +13,9 @@ export interface ListedArt { }>; linkedUsers?: Array; 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: { diff --git a/app/features/art/art-urls.test.ts b/app/features/art/art-urls.test.ts index 57cd22e24..63da9e536 100644 --- a/app/features/art/art-urls.test.ts +++ b/app/features/art/art-urls.test.ts @@ -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"); diff --git a/app/features/art/art-utils.ts b/app/features/art/art-utils.ts deleted file mode 100644 index 1f29d2220..000000000 --- a/app/features/art/art-utils.ts +++ /dev/null @@ -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}`; -} diff --git a/app/features/art/components/ArtGrid.tsx b/app/features/art/components/ArtGrid.tsx index 6bfad46b9..9ab56bc3f 100644 --- a/app/features/art/components/ArtGrid.tsx +++ b/app/features/art/components/ArtGrid.tsx @@ -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(); @@ -135,7 +134,7 @@ function BigImageDialog({ close, art }: { close: () => void; art: ListedArt }) { > @@ -170,7 +169,7 @@ function BigImageDialog({ close, art }: { close: () => void; art: ListedArt }) { {art.linkedUsers?.map((user) => ( {user.username} @@ -214,7 +213,7 @@ function ImagePreview({ const image = ( ; + return ; } const handleFileChange = async ( diff --git a/app/features/auth/core/DiscordAvatar.server.test.ts b/app/features/auth/core/DiscordAvatar.server.test.ts new file mode 100644 index 000000000..00eef9065 --- /dev/null +++ b/app/features/auth/core/DiscordAvatar.server.test.ts @@ -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`); + }); +}); diff --git a/app/features/auth/core/DiscordAvatar.server.ts b/app/features/auth/core/DiscordAvatar.server.ts new file mode 100644 index 000000000..ae8ff891d --- /dev/null +++ b/app/features/auth/core/DiscordAvatar.server.ts @@ -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 { + 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; + } +} diff --git a/app/features/auth/core/DiscordRefresh.server.ts b/app/features/auth/core/DiscordRefresh.server.ts new file mode 100644 index 000000000..2bf60987f --- /dev/null +++ b/app/features/auth/core/DiscordRefresh.server.ts @@ -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({ 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 { + 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()); +} diff --git a/app/features/auth/core/DiscordStrategy.server.ts b/app/features/auth/core/DiscordStrategy.server.ts index 760fbc1b2..d811a75d9 100644 --- a/app/features/auth/core/DiscordStrategy.server.ts +++ b/app/features/auth/core/DiscordStrategy.server.ts @@ -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; + connections: v.InferOutput; +}; + +class DiscordOAuth2Strategy extends OAuth2Strategy { + 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, ) { diff --git a/app/features/auth/core/authenticator.server.ts b/app/features/auth/core/authenticator.server.ts index 670a83b9d..e40daa4aa 100644 --- a/app/features/auth/core/authenticator.server.ts +++ b/app/features/auth/core/authenticator.server.ts @@ -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(); +export const authenticator = new Authenticator(); authenticator.use(DiscordStrategy(), "discord"); diff --git a/app/features/auth/core/routes.server.ts b/app/features/auth/core/routes.server.ts index 50d3a599c..2c6047056 100644 --- a/app/features/auth/core/routes.server.ts +++ b/app/features/auth/core/routes.server.ts @@ -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, + }); +} diff --git a/app/features/auth/routes/auth.refresh.ts b/app/features/auth/routes/auth.refresh.ts new file mode 100644 index 000000000..210050c6e --- /dev/null +++ b/app/features/auth/routes/auth.refresh.ts @@ -0,0 +1 @@ +export { refreshFromDiscordAction as action } from "~/features/auth/core/routes.server"; diff --git a/app/features/availability/components/RegistrationAvailabilityPanel.tsx b/app/features/availability/components/RegistrationAvailabilityPanel.tsx index fa26e61f1..adea7a102 100644 --- a/app/features/availability/components/RegistrationAvailabilityPanel.tsx +++ b/app/features/availability/components/RegistrationAvailabilityPanel.tsx @@ -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; diff --git a/app/features/badges/BadgeRepository.server.ts b/app/features/badges/BadgeRepository.server.ts index d7471153a..17783f389 100644 --- a/app/features/badges/BadgeRepository.server.ts +++ b/app/features/badges/BadgeRepository.server.ts @@ -49,7 +49,6 @@ const withOwners = (eb: ExpressionBuilder, badgeId: number) => { .select(({ fn }) => [ fn.sum("BadgeOwner.count").as("count"), "User.id", - "User.discordId", "User.username", ]) .where("BadgeOwner.badgeId", "=", badgeId) diff --git a/app/features/badges/routes/badges.$id.edit.tsx b/app/features/badges/routes/badges.$id.edit.tsx index 0bf18da60..25987cdaa 100644 --- a/app/features/badges/routes/badges.$id.edit.tsx +++ b/app/features/badges/routes/badges.$id.edit.tsx @@ -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>( + initialOwners, + ); const ownerDifferences = getOwnerDifferences( owners.map((o) => ({ ...o, username: o.name })), diff --git a/app/features/calendar/routes/calendar.$id.tsx b/app/features/calendar/routes/calendar.$id.tsx index ab68e9be1..2921e39c8 100644 --- a/app/features/calendar/routes/calendar.$id.tsx +++ b/app/features/calendar/routes/calendar.$id.tsx @@ -273,7 +273,10 @@ function Description() {
- + {data.event.username}
{data.event.description ? ( diff --git a/app/features/chat/ChatMentionNotification.server.ts b/app/features/chat/ChatMentionNotification.server.ts index 75d9f5dca..0c2e9d726 100644 --- a/app/features/chat/ChatMentionNotification.server.ts +++ b/app/features/chat/ChatMentionNotification.server.ts @@ -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, }, }); } diff --git a/app/features/chat/ChatProvider.tsx b/app/features/chat/ChatProvider.tsx index 78947564a..08525d4ae 100644 --- a/app/features/chat/ChatProvider.tsx +++ b/app/features/chat/ChatProvider.tsx @@ -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, }, diff --git a/app/features/chat/chat-client.test.ts b/app/features/chat/chat-client.test.ts index 92150af68..e70993058 100644 --- a/app/features/chat/chat-client.test.ts +++ b/app/features/chat/chat-client.test.ts @@ -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, }); diff --git a/app/features/chat/components/Chat.browser.test.tsx b/app/features/chat/components/Chat.browser.test.tsx index 58a0f10b5..494fb4975 100644 --- a/app/features/chat/components/Chat.browser.test.tsx +++ b/app/features/chat/components/Chat.browser.test.tsx @@ -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, diff --git a/app/features/components-showcase/routes/components.tsx b/app/features/components-showcase/routes/components.tsx index 808e361e4..1a6ddf39c 100644 --- a/app/features/components-showcase/routes/components.tsx +++ b/app/features/components-showcase/routes/components.tsx @@ -1715,7 +1715,7 @@ function AvatarSection({ id }: { id: string }) {
@@ -1723,58 +1723,34 @@ function AvatarSection({ id }: { id: string }) { - + - + - + - + - + - +
@@ -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 }) { ; 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({ { 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, }), }, diff --git a/app/features/friends/routes/friends.tsx b/app/features/friends/routes/friends.tsx index 6070dc3b1..c3665523a 100644 --- a/app/features/friends/routes/friends.tsx +++ b/app/features/friends/routes/friends.tsx @@ -104,9 +104,8 @@ function IncomingRequestsSection() { @@ -154,9 +153,8 @@ function PendingRequestsSection() { diff --git a/app/features/front-page/core/ShowcaseTournaments.server.ts b/app/features/front-page/core/ShowcaseTournaments.server.ts index 7a9699247..b0b46ea12 100644 --- a/app/features/front-page/core/ShowcaseTournaments.server.ts +++ b/app/features/front-page/core/ShowcaseTournaments.server.ts @@ -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, diff --git a/app/features/front-page/loaders/index.server.ts b/app/features/front-page/loaders/index.server.ts index 66d857f26..6c84d927a 100644 --- a/app/features/front-page/loaders/index.server.ts +++ b/app/features/front-page/loaders/index.server.ts @@ -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; @@ -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) diff --git a/app/features/img-export/components/BuildGraphic.tsx b/app/features/img-export/components/BuildGraphic.tsx index cb437490c..3f36148d5 100644 --- a/app/features/img-export/components/BuildGraphic.tsx +++ b/app/features/img-export/components/BuildGraphic.tsx @@ -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({
diff --git a/app/features/img-export/components/SeasonSummaryGraphic.tsx b/app/features/img-export/components/SeasonSummaryGraphic.tsx index 9435c4b18..9dc403dc2 100644 --- a/app/features/img-export/components/SeasonSummaryGraphic.tsx +++ b/app/features/img-export/components/SeasonSummaryGraphic.tsx @@ -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({ {user.countryCode ? ( @@ -315,7 +315,7 @@ export function SeasonSummaryGraphic({
diff --git a/app/features/img-upload/image-bytes.server.ts b/app/features/img-upload/image-bytes.server.ts index 735e394f2..c66a28e47 100644 --- a/app/features/img-upload/image-bytes.server.ts +++ b/app/features/img-upload/image-bytes.server.ts @@ -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" && diff --git a/app/features/img-upload/image-field.server.ts b/app/features/img-upload/image-field.server.ts index 7127cbcb4..923d45477 100644 --- a/app/features/img-upload/image-field.server.ts +++ b/app/features/img-upload/image-field.server.ts @@ -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; }): Promise { @@ -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, diff --git a/app/features/img-upload/s3.server.ts b/app/features/img-upload/s3.server.ts index 4fabfdd00..983318f3f 100644 --- a/app/features/img-upload/s3.server.ts +++ b/app/features/img-upload/s3.server.ts @@ -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) => { - const { endpoint, accessKey, secret, region, bucket } = ServerConfig.storage; +const IMMUTABLE_CACHE_CONTROL = "public, max-age=31536000, immutable"; + +const uploadStream = ({ Key }: Pick) => { + 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; +} diff --git a/app/features/leaderboards/routes/leaderboards.browser.test.tsx b/app/features/leaderboards/routes/leaderboards.browser.test.tsx index d508685d9..fb3c661e6 100644 --- a/app/features/leaderboards/routes/leaderboards.browser.test.tsx +++ b/app/features/leaderboards/routes/leaderboards.browser.test.tsx @@ -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, }); diff --git a/app/features/leaderboards/routes/leaderboards.tsx b/app/features/leaderboards/routes/leaderboards.tsx index a8b987585..bc935c95a 100644 --- a/app/features/leaderboards/routes/leaderboards.tsx +++ b/app/features/leaderboards/routes/leaderboards.tsx @@ -580,9 +580,7 @@ function XPTable({ entries }: { entries: XPLeaderboardItem[] }) { > {entry.placementRank} - {entry.discordId ? ( - - ) : null} + {entry.id ? : null}
{entry.name}
diff --git a/app/features/match-page-test/routes/match-page-test.tsx b/app/features/match-page-test/routes/match-page-test.tsx index fc67db012..01768d0b1 100644 --- a/app/features/match-page-test/routes/match-page-test.tsx +++ b/app/features/match-page-test/routes/match-page-test.tsx @@ -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, }, ], }, diff --git a/app/features/notifications/NotificationRepository.server.ts b/app/features/notifications/NotificationRepository.server.ts index a003ade93..e724f1f67 100644 --- a/app/features/notifications/NotificationRepository.server.ts +++ b/app/features/notifications/NotificationRepository.server.ts @@ -222,7 +222,7 @@ export function findUnseenSubscriptionsByNotificationId( .select([ "NotificationUserSubscription.id", "NotificationUserSubscription.subscription", - "User.discordId", + "NotificationUser.userId", "User.customUrl", ]) .where("NotificationUser.notificationId", "=", notificationId) diff --git a/app/features/notifications/core/notify.server.ts b/app/features/notifications/core/notify.server.ts index 237481f9d..5bbbc4c1d 100644 --- a/app/features/notifications/core/notify.server.ts +++ b/app/features/notifications/core/notify.server.ts @@ -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, }), ), diff --git a/app/features/notifications/notifications-types.ts b/app/features/notifications/notifications-types.ts index f9867971e..406d30f7c 100644 --- a/app/features/notifications/notifications-types.ts +++ b/app/features/notifications/notifications-types.ts @@ -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 } diff --git a/app/features/notifications/notifications-utils.ts b/app/features/notifications/notifications-utils.ts index 179dacf48..5efef050e 100644 --- a/app/features/notifications/notifications-utils.ts +++ b/app/features/notifications/notifications-utils.ts @@ -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; diff --git a/app/features/plus-suggestions/routes/plus.suggestions.browser.test.tsx b/app/features/plus-suggestions/routes/plus.suggestions.browser.test.tsx index c0bc2a64b..a98a309c0 100644 --- a/app/features/plus-suggestions/routes/plus.suggestions.browser.test.tsx +++ b/app/features/plus-suggestions/routes/plus.suggestions.browser.test.tsx @@ -18,15 +18,13 @@ type LoggedInUser = NonNullable< React.ComponentProps["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(); diff --git a/app/features/plus-voting/PlusVotingRepository.server.ts b/app/features/plus-voting/PlusVotingRepository.server.ts index c0ae5141c..737e00768 100644 --- a/app/features/plus-voting/PlusVotingRepository.server.ts +++ b/app/features/plus-voting/PlusVotingRepository.server.ts @@ -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 & { + 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, diff --git a/app/features/search/routes/search.ts b/app/features/search/routes/search.ts index 98a1c7f90..6fbc30447 100644 --- a/app/features/search/routes/search.ts +++ b/app/features/search/routes/search.ts @@ -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, })); diff --git a/app/features/sendouq-match/components/RejoinSections.tsx b/app/features/sendouq-match/components/RejoinSections.tsx index 1978a1564..b8fa663a5 100644 --- a/app/features/sendouq-match/components/RejoinSections.tsx +++ b/app/features/sendouq-match/components/RejoinSections.tsx @@ -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} diff --git a/app/features/sendouq-match/components/RematchVotePanel.tsx b/app/features/sendouq-match/components/RematchVotePanel.tsx index 6cf99dd83..52ca19a9e 100644 --- a/app/features/sendouq-match/components/RematchVotePanel.tsx +++ b/app/features/sendouq-match/components/RematchVotePanel.tsx @@ -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; }; diff --git a/app/features/sendouq-match/core/discord-webhook.server.ts b/app/features/sendouq-match/core/discord-webhook.server.ts index 1559f6ea5..4b23ff0d2 100644 --- a/app/features/sendouq-match/core/discord-webhook.server.ts +++ b/app/features/sendouq-match/core/discord-webhook.server.ts @@ -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<{ diff --git a/app/features/sendouq-match/core/match-timeline.test.ts b/app/features/sendouq-match/core/match-timeline.test.ts index da18d52e4..776149ed6 100644 --- a/app/features/sendouq-match/core/match-timeline.test.ts +++ b/app/features/sendouq-match/core/match-timeline.test.ts @@ -19,8 +19,7 @@ function member(overrides: Record = {}) { return { id: 1, username: "user", - discordId: "d", - discordAvatar: null, + avatar: null, customUrl: null, skillDifference: undefined, ...overrides, diff --git a/app/features/sendouq-match/core/match-timeline.ts b/app/features/sendouq-match/core/match-timeline.ts index 75b2d0b05..f80090a33 100644 --- a/app/features/sendouq-match/core/match-timeline.ts +++ b/app/features/sendouq-match/core/match-timeline.ts @@ -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!, })); diff --git a/app/features/sendouq/components/GroupCard.browser.test.tsx b/app/features/sendouq/components/GroupCard.browser.test.tsx index 987026591..03694c1a5 100644 --- a/app/features/sendouq/components/GroupCard.browser.test.tsx +++ b/app/features/sendouq/components/GroupCard.browser.test.tsx @@ -18,10 +18,8 @@ vi.mock("~/features/auth/core/user", () => ({ function createMember(overrides: Partial = {}): 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: [], diff --git a/app/features/sendouq/components/GroupCard.tsx b/app/features/sendouq/components/GroupCard.tsx index 2e8d80dc1..864f09d2d 100644 --- a/app/features/sendouq/components/GroupCard.tsx +++ b/app/features/sendouq/components/GroupCard.tsx @@ -109,7 +109,7 @@ export function GroupCard({ return ( ; }; groupBravo: { @@ -501,8 +500,7 @@ class SendouQClass { members: Array<{ id: number; username: string; - discordId: string; - discordAvatar: string | null; + avatar: string | null; }>; }; pools: ReturnType; @@ -522,8 +520,7 @@ class SendouQClass { { id: member.id, username: member.username, - discordId: member.discordId, - discordAvatar: member.discordAvatar, + avatar: member.avatar, }, ]; }), diff --git a/app/features/sendouq/loaders/q.server.ts b/app/features/sendouq/loaders/q.server.ts index 0205d5d38..906786de9 100644 --- a/app/features/sendouq/loaders/q.server.ts +++ b/app/features/sendouq/loaders/q.server.ts @@ -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, }; }; diff --git a/app/features/sendouq/routes/q.tsx b/app/features/sendouq/routes/q.tsx index a616124ec..66cf2f6c4 100644 --- a/app/features/sendouq/routes/q.tsx +++ b/app/features/sendouq/routes/q.tsx @@ -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 (
diff --git a/app/features/settings/routes/settings.tsx b/app/features/settings/routes/settings.tsx index 4c4ad3acf..687788d56 100644 --- a/app/features/settings/routes/settings.tsx +++ b/app/features/settings/routes/settings.tsx @@ -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() {

{t("common:pages.settings")}

{user ? ( -
- } - type="submit" - > - {t("common:header.logout")} - -
+
+
+ } + type="submit" + > + {t("settings:refreshFromDiscord")} + +
+
+ } + type="submit" + > + {t("common:header.logout")} + +
+
) : null}
{ 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, diff --git a/app/features/team/routes/t.$customUrl.index.tsx b/app/features/team/routes/t.$customUrl.index.tsx index 89de55635..48d37f188 100644 --- a/app/features/team/routes/t.$customUrl.index.tsx +++ b/app/features/team/routes/t.$customUrl.index.tsx @@ -66,7 +66,7 @@ export default function TeamIndexPage() { const showSections = playerMembers.length > 0 && otherMembers.length > 0; const renderMember = (member: (typeof members)[number]) => ( - + diff --git a/app/features/tier-list-maker/components/TierListGraphic.tsx b/app/features/tier-list-maker/components/TierListGraphic.tsx index 08a4764de..7e817cd44 100644 --- a/app/features/tier-list-maker/components/TierListGraphic.tsx +++ b/app/features/tier-list-maker/components/TierListGraphic.tsx @@ -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({ diff --git a/app/features/top-search/XRankPlacementRepository.server.ts b/app/features/top-search/XRankPlacementRepository.server.ts index 162023466..489d6f463 100644 --- a/app/features/top-search/XRankPlacementRepository.server.ts +++ b/app/features/top-search/XRankPlacementRepository.server.ts @@ -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( diff --git a/app/features/top-search/actions/xsearch.player.$id.server.ts b/app/features/top-search/actions/xsearch.player.$id.server.ts index 2fdb4ca44..8fcf16e4d 100644 --- a/app/features/top-search/actions/xsearch.player.$id.server.ts +++ b/app/features/top-search/actions/xsearch.player.$id.server.ts @@ -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", ); diff --git a/app/features/top-search/routes/xsearch.player.$id.tsx b/app/features/top-search/routes/xsearch.player.$id.tsx index 03c92c666..b8a90ac94 100644 --- a/app/features/top-search/routes/xsearch.player.$id.tsx +++ b/app/features/top-search/routes/xsearch.player.$id.tsx @@ -59,10 +59,10 @@ export const meta: MetaFunction = (args) => { }); }; -function hasUserLinked( +function hasUserLinked( 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 (
@@ -81,7 +80,14 @@ export default function XSearchPlayerPage() {

{hasUserLinked(placementUser) ? ( - {data.names.primary} + + {data.names.primary} + ) : ( data.names.primary )}{" "} diff --git a/app/features/tournament-admin/components/ExportDialog.tsx b/app/features/tournament-admin/components/ExportDialog.tsx index 2dc77f1a4..ff083c46f 100644 --- a/app/features/tournament-admin/components/ExportDialog.tsx +++ b/app/features/tournament-admin/components/ExportDialog.tsx @@ -83,9 +83,11 @@ const DEFAULT_FIELDS: ExportField[] = [ export function ExportDialog({ close, teams: allTeams, + memberDiscordIds, }: { close: () => void; teams: TournamentTeamFull[]; + memberDiscordIds: Record; }) { 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, ) { 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; format: ExportFormat; fields: Set; 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; diff --git a/app/features/tournament-admin/loaders/to.$id.admin.index.server.ts b/app/features/tournament-admin/loaders/to.$id.admin.index.server.ts index b2bd6a8ab..5029983e0 100644 --- a/app/features/tournament-admin/loaders/to.$id.admin.index.server.ts +++ b/app/features/tournament-admin/loaders/to.$id.admin.index.server.ts @@ -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; @@ -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), }; }; diff --git a/app/features/tournament-admin/routes/to.$id.admin._index.tsx b/app/features/tournament-admin/routes/to.$id.admin._index.tsx index a169d13b3..95d569547 100644 --- a/app/features/tournament-admin/routes/to.$id.admin._index.tsx +++ b/app/features/tournament-admin/routes/to.$id.admin._index.tsx @@ -58,7 +58,8 @@ type SortKey = "name" | "checkIn"; export default function TournamentAdminTeamsPage() { const tournament = useTournament(); - const { teams } = useLoaderData(); + const { teams, memberDiscordIds } = + useLoaderData(); const [search, setSearch] = React.useState(""); const [sort, setSort] = React.useState>(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() { {exportOpen ? ( - setExportOpen(false)} /> + setExportOpen(false)} + /> ) : null}

); @@ -244,7 +251,7 @@ function TeamRow({ {member ? ( "").length; } -function teamMatchesQuery(team: TournamentTeamFull, search: string) { +function teamMatchesQuery({ + team, + search, + memberDiscordIds, +}: { + team: TournamentTeamFull; + search: string; + memberDiscordIds: Record; +}) { 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() diff --git a/app/features/tournament-admin/routes/to.$id.admin.registration.$tid.browser.test.tsx b/app/features/tournament-admin/routes/to.$id.admin.registration.$tid.browser.test.tsx index c6a649908..02280664b 100644 --- a/app/features/tournament-admin/routes/to.$id.admin.registration.$tid.browser.test.tsx +++ b/app/features/tournament-admin/routes/to.$id.admin.registration.$tid.browser.test.tsx @@ -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, }, diff --git a/app/features/tournament-admin/routes/to.$id.admin.registration.$tid.captain-label.browser.test.tsx b/app/features/tournament-admin/routes/to.$id.admin.registration.$tid.captain-label.browser.test.tsx index a53386020..6baa022f5 100644 --- a/app/features/tournament-admin/routes/to.$id.admin.registration.$tid.captain-label.browser.test.tsx +++ b/app/features/tournament-admin/routes/to.$id.admin.registration.$tid.captain-label.browser.test.tsx @@ -34,8 +34,7 @@ const GREY = { name: "Grey", inGameName: null, avatarUrl: null, - discordId: "123", - discordAvatar: null, + avatar: null, customUrl: null, plusTier: null, }; diff --git a/app/features/tournament-admin/routes/to.$id.admin.staff.tsx b/app/features/tournament-admin/routes/to.$id.admin.staff.tsx index e485a1c13..a11850b99 100644 --- a/app/features/tournament-admin/routes/to.$id.admin.staff.tsx +++ b/app/features/tournament-admin/routes/to.$id.admin.staff.tsx @@ -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 & { + Pick & { role: Tables["TournamentStaff"]["role"]; } >; @@ -194,7 +195,7 @@ function StaffInfoRow({ roleText, testId, }: { - user: Pick; + user: Pick; roleText: string; testId?: string; }) { diff --git a/app/features/tournament-bracket/core/Tournament.server.ts b/app/features/tournament-bracket/core/Tournament.server.ts index cb8008baf..f107802ce 100644 --- a/app/features/tournament-bracket/core/Tournament.server.ts +++ b/app/features/tournament-bracket/core/Tournament.server.ts @@ -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, }, })); diff --git a/app/features/tournament-bracket/core/Tournament.ts b/app/features/tournament-bracket/core/Tournament.ts index b39903cf1..12a5c801b 100644 --- a/app/features/tournament-bracket/core/Tournament.ts +++ b/app/features/tournament-bracket/core/Tournament.ts @@ -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; }; diff --git a/app/features/tournament-bracket/core/tests/test-utils.ts b/app/features/tournament-bracket/core/tests/test-utils.ts index cfbfc2efb..2f9d9598b 100644 --- a/app/features/tournament-bracket/core/tests/test-utils.ts +++ b/app/features/tournament-bracket/core/tests/test-utils.ts @@ -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, diff --git a/app/features/tournament-bracket/routes/to.$id.brackets.finalize.tsx b/app/features/tournament-bracket/routes/to.$id.brackets.finalize.tsx index a2d0ed6b1..4541b95e8 100644 --- a/app/features/tournament-bracket/routes/to.$id.brackets.finalize.tsx +++ b/app/features/tournament-bracket/routes/to.$id.brackets.finalize.tsx @@ -296,7 +296,11 @@ function NewBadgeReceiversSelector({ userId: member.userId, })} /> - + {member.username}
@@ -353,7 +357,11 @@ function NewTrophyReceiversSelector({ isSelected={trophyReceiverUserIds.includes(member.userId)} onChange={handleReceiverSelected(member.userId)} /> - + {member.username}
diff --git a/app/features/tournament-lfg/components/LFGGroupCard.tsx b/app/features/tournament-lfg/components/LFGGroupCard.tsx index 8812eec4b..405ba430c 100644 --- a/app/features/tournament-lfg/components/LFGGroupCard.tsx +++ b/app/features/tournament-lfg/components/LFGGroupCard.tsx @@ -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({
{group.members.map((member) => ( ({ 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, diff --git a/app/features/tournament-lfg/routes/to.$id.looking.tsx b/app/features/tournament-lfg/routes/to.$id.looking.tsx index 6774931cc..035e53fe3 100644 --- a/app/features/tournament-lfg/routes/to.$id.looking.tsx +++ b/app/features/tournament-lfg/routes/to.$id.looking.tsx @@ -237,7 +237,7 @@ function SubCard({ sub }: { sub: SubEntry }) {
- +
diff --git a/app/features/tournament-match/components/TournamentMatchActionTab.tsx b/app/features/tournament-match/components/TournamentMatchActionTab.tsx index d0f6af518..502194b78 100644 --- a/app/features/tournament-match/components/TournamentMatchActionTab.tsx +++ b/app/features/tournament-match/components/TournamentMatchActionTab.tsx @@ -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( diff --git a/app/features/tournament-match/components/TournamentMatchTabs.tsx b/app/features/tournament-match/components/TournamentMatchTabs.tsx index e4da2e164..12a6cacf7 100644 --- a/app/features/tournament-match/components/TournamentMatchTabs.tsx +++ b/app/features/tournament-match/components/TournamentMatchTabs.tsx @@ -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, diff --git a/app/features/tournament-organization/core/leaderboards.server.ts b/app/features/tournament-organization/core/leaderboards.server.ts index 05a0a390a..4cd6ffef1 100644 --- a/app/features/tournament-organization/core/leaderboards.server.ts +++ b/app/features/tournament-organization/core/leaderboards.server.ts @@ -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], diff --git a/app/features/tournament-organization/routes/org.$slug.tsx b/app/features/tournament-organization/routes/org.$slug.tsx index 93bb54373..6d422215f 100644 --- a/app/features/tournament-organization/routes/org.$slug.tsx +++ b/app/features/tournament-organization/routes/org.$slug.tsx @@ -645,7 +645,7 @@ function EventWinners({
{winner.members.map((member) => ( - + ))}
@@ -697,7 +697,7 @@ function EventLeaderboard({ ) : null}
    {leaderboard.map((entry) => ( -
  1. +
  2. ))} diff --git a/app/features/tournament/TournamentRepository.server.ts b/app/features/tournament/TournamentRepository.server.ts index e679921e0..a63eee251 100644 --- a/app/features/tournament/TournamentRepository.server.ts +++ b/app/features/tournament/TournamentRepository.server.ts @@ -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) diff --git a/app/features/tournament/components/TeamWithRoster.tsx b/app/features/tournament/components/TeamWithRoster.tsx index 44077ad1c..7117615b6 100644 --- a/app/features/tournament/components/TeamWithRoster.tsx +++ b/app/features/tournament/components/TeamWithRoster.tsx @@ -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({ })} > @@ -110,8 +109,8 @@ export function TeamWithRoster({
{friendCode ? (
- {tournament.isOrganizer(user) ? ( - + {tournament.isOrganizer(user) && member.isFreshAccount ? ( + ) : null} SW-{friendCode}
@@ -126,11 +125,9 @@ export function TeamWithRoster({ ); } -function FreshAccountEmoji({ discordId }: { discordId: string }) { +function FreshAccountEmoji() { const { t } = useTranslation(["tournament"]); - if (!accountCreatedInTheLastSixMonths(discordId)) return null; - return ( 👶 diff --git a/app/features/tournament/core/sets.server.ts b/app/features/tournament/core/sets.server.ts index 88b278cfe..c1576a24c 100644 --- a/app/features/tournament/core/sets.server.ts +++ b/app/features/tournament/core/sets.server.ts @@ -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 & { + avatar: string | null; + } >; }; } diff --git a/app/features/tournament/routes/to.$id.register.tsx b/app/features/tournament/routes/to.$id.register.tsx index 227156614..345cf4ef9 100644 --- a/app/features/tournament/routes/to.$id.register.tsx +++ b/app/features/tournament/routes/to.$id.register.tsx @@ -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)} diff --git a/app/features/trophies/TrophyRepository.server.ts b/app/features/trophies/TrophyRepository.server.ts index 110f10f81..00bfe3ec7 100644 --- a/app/features/trophies/TrophyRepository.server.ts +++ b/app/features/trophies/TrophyRepository.server.ts @@ -843,7 +843,7 @@ const withTargetManager = (eb: ExpressionBuilder) => { 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) => { 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", diff --git a/app/features/trophies/routes/trophies.new.tsx b/app/features/trophies/routes/trophies.new.tsx index 00bece531..baff9edd6 100644 --- a/app/features/trophies/routes/trophies.new.tsx +++ b/app/features/trophies/routes/trophies.new.tsx @@ -772,12 +772,12 @@ function TrophyListRow({ ) : null} {pending.name} - {pending.manager?.discordId ? ( - + {pending.manager ? ( + {pending.manager.username} - ) : pending.submitterDiscordId ? ( - + ) : pending.submitterUserId ? ( + {pending.submitterUsername} ) : ( @@ -794,7 +794,7 @@ function TrophyListRow({ values={{ name: pending.creator.username }} > Created by - + {pending.creator.username} diff --git a/app/features/user-card/UserCardRepository.server.ts b/app/features/user-card/UserCardRepository.server.ts index 624a8e937..5b5d2b7ad 100644 --- a/app/features/user-card/UserCardRepository.server.ts +++ b/app/features/user-card/UserCardRepository.server.ts @@ -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), diff --git a/app/features/user-page/UserRepository.server.ts b/app/features/user-page/UserRepository.server.ts index 883fc4f19..906345691 100644 --- a/app/features/user-page/UserRepository.server.ts +++ b/app/features/user-page/UserRepository.server.ts @@ -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(); + + 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(); @@ -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`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 { diff --git a/app/features/user-page/UserRepository.test.ts b/app/features/user-page/UserRepository.test.ts index 79845f0c3..c961ea6d5 100644 --- a/app/features/user-page/UserRepository.test.ts +++ b/app/features/user-page/UserRepository.test.ts @@ -2,10 +2,12 @@ import { addDays, subDays } from "date-fns"; import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; import * as CalendarEventFactory from "~/db/seed/factories/CalendarEventFactory"; import * as CalendarEventResultFactory from "~/db/seed/factories/CalendarEventResultFactory"; +import * as ImageFactory from "~/db/seed/factories/ImageFactory"; import * as TournamentFactory from "~/db/seed/factories/TournamentFactory"; import * as TournamentTeamFactory from "~/db/seed/factories/TournamentTeamFactory"; import * as UserFactory from "~/db/seed/factories/UserFactory"; import { db } from "~/db/sql"; +import * as ImageRepository from "~/features/img-upload/ImageRepository.server"; import * as TournamentRepository from "~/features/tournament/TournamentRepository.server"; import * as TournamentTeamRepository from "~/features/tournament/TournamentTeamRepository.server"; import { dateToDatabaseTimestamp } from "~/utils/dates"; @@ -17,7 +19,6 @@ describe("UserRepository", () => { await UserRepository.upsert({ discordId: "1", discordName: "TestUser", - discordAvatar: null, }); const user = await UserRepository.findModInfoById(1); @@ -30,7 +31,6 @@ describe("UserRepository", () => { const { id } = await UserRepository.upsert({ discordId: "1", discordName: "TestUser", - discordAvatar: null, }); const user = await UserRepository.findLayoutDataById(id); @@ -40,7 +40,6 @@ describe("UserRepository", () => { await UserRepository.upsert({ discordId: "1", discordName: "UpdatedUser", - discordAvatar: null, }); const updatedUser = await UserRepository.findLayoutDataById(id); @@ -51,7 +50,6 @@ describe("UserRepository", () => { await UserRepository.upsert({ discordId: "1", discordName: "TestUser", - discordAvatar: null, }); const user = await UserRepository.findModInfoById(1); @@ -60,7 +58,6 @@ describe("UserRepository", () => { await UserRepository.upsert({ discordId: "1", discordName: "UpdatedUser", - discordAvatar: null, }); const updatedUser = await UserRepository.findModInfoById(1); @@ -71,7 +68,6 @@ describe("UserRepository", () => { const { id } = await UserRepository.upsert({ discordId: "1", discordName: "TestUser", - discordAvatar: null, }); const result = await UserRepository.findJoinOrderByUserId(id); @@ -83,13 +79,11 @@ describe("UserRepository", () => { const { id: firstId } = await UserRepository.upsert({ discordId: "1", discordName: "FirstUser", - discordAvatar: null, }); const { id: secondId } = await UserRepository.upsert({ discordId: "2", discordName: "SecondUser", - discordAvatar: null, }); expect( @@ -102,7 +96,6 @@ describe("UserRepository", () => { await UserRepository.upsert({ discordId: "1", discordName: "UpdatedFirstUser", - discordAvatar: null, }); expect( @@ -698,6 +691,61 @@ describe("UserRepository", () => { ); }); }); + + describe("avatar", () => { + const users = UserFactory.pool(); + const userId = () => users.id(1); + + beforeEach(async () => { + await users.create(1, { discordAvatar: "hash" }); + }); + + test("resolves to the synced avatar when the user has no custom one", async () => { + const user = await UserRepository.findLeanById(userId()); + + expect(user?.avatar).toBe(`avatar-${userId()}-hash.webp`); + }); + + test("resolves to the custom avatar over the synced one", async () => { + const image = await ImageFactory.create( + { submitterUserId: userId(), url: "custom.webp" }, + { isValidated: true }, + ); + await UserFactory.updateProfile(userId(), { + customAvatarImgId: image.id, + }); + + const user = await UserRepository.findLeanById(userId()); + + expect(user?.avatar).toBe("custom.webp"); + }); + }); + + describe("UserRepository.replaceSyncedAvatar", () => { + const users = UserFactory.pool(); + const userId = () => users.id(1); + + beforeEach(async () => { + await users.create(1, { discordAvatar: "old" }); + }); + + test("returns the previous file name and deletes its image row", async () => { + const { syncedAvatarImgId: previousImgId } = await db + .selectFrom("User") + .select("syncedAvatarImgId") + .where("id", "=", userId()) + .executeTakeFirstOrThrow(); + + const previousFileName = await UserRepository.replaceSyncedAvatar({ + userId: userId(), + discordAvatar: "new", + fileName: `avatar-${userId()}-new.webp`, + }); + + expect(previousFileName).toBe(`avatar-${userId()}-old.webp`); + expect(await ImageRepository.findById(previousImgId!)).toBeUndefined(); + }); + }); }); function ids(patrons: Array<{ id: number }>) { diff --git a/app/features/user-page/components/SubPageHeader.tsx b/app/features/user-page/components/SubPageHeader.tsx index d0b9827f6..f3ecd4e55 100644 --- a/app/features/user-page/components/SubPageHeader.tsx +++ b/app/features/user-page/components/SubPageHeader.tsx @@ -2,7 +2,7 @@ import clsx from "clsx"; import { Avatar } from "~/components/Avatar"; import { BackLink } from "~/components/BackLink"; import { PageHeader } from "~/components/PageHeader"; -import type { Tables } from "~/db/tables"; +import type { CommonUser } from "~/utils/kysely.server"; import { userPage } from "~/utils/urls"; import styles from "./SubPageHeader.module.css"; @@ -12,10 +12,7 @@ export function SubPageHeader({ subtitle, children, }: { - user: Pick< - Tables["User"], - "username" | "discordId" | "discordAvatar" | "customUrl" - >; + user: CommonUser; title: React.ReactNode; subtitle?: React.ReactNode; children?: React.ReactNode; diff --git a/app/features/user-page/components/Widget.tsx b/app/features/user-page/components/Widget.tsx index 7ec963bef..578f99f21 100644 --- a/app/features/user-page/components/Widget.tsx +++ b/app/features/user-page/components/Widget.tsx @@ -31,7 +31,6 @@ import { Placement } from "~/components/Placement"; import { UserLink } from "~/components/UserLink"; import type { Tables } from "~/db/tables"; import { userArtPage } from "~/features/art/art-urls"; -import { previewUrl } from "~/features/art/art-utils"; import { BadgeDisplay } from "~/features/badges/components/BadgeDisplay"; import { lfgSearchParams } from "~/features/lfg/lfg-search-params"; import { StreamPlatformIcon } from "~/features/live-streams/components/StreamPlatformIcon"; @@ -67,6 +66,7 @@ import { LFG_PAGE, modeImageUrl, navIconUrl, + smallImageFileName, teamPage, userBuildsPage, userResultsPage, @@ -81,7 +81,7 @@ export function Widget({ user, }: { widget: SerializeFrom<() => LoadedWidget>; - user: Pick; + user: Pick; }) { const { t } = useTranslation(["user", "badges", "team", "org", "lfg"]); const { formatter: patronStartedAtFormatter } = useDateTimeFormat({ @@ -820,7 +820,7 @@ function ArtWidget({ diff --git a/app/features/user-page/loaders/u.$identifier.admin.server.ts b/app/features/user-page/loaders/u.$identifier.admin.server.ts index 013242d80..8e567a749 100644 --- a/app/features/user-page/loaders/u.$identifier.admin.server.ts +++ b/app/features/user-page/loaders/u.$identifier.admin.server.ts @@ -34,8 +34,9 @@ export const loader = async () => { return { ...userData, - discordId: user.discordId, - discordAccountCreatedAt: convertSnowflakeToDate(user.discordId).getTime(), + discordAccountCreatedAt: convertSnowflakeToDate( + userData.discordId, + ).getTime(), friendCodes, reports, reportsMonthlyCounts: reportsMonthlyCounts(reports), diff --git a/app/features/user-page/loaders/u.$identifier.seasons.summary-graphic.server.ts b/app/features/user-page/loaders/u.$identifier.seasons.summary-graphic.server.ts index ac6af8fa9..c068882bf 100644 --- a/app/features/user-page/loaders/u.$identifier.seasons.summary-graphic.server.ts +++ b/app/features/user-page/loaders/u.$identifier.seasons.summary-graphic.server.ts @@ -12,7 +12,7 @@ import * as UserRepository from "~/features/user-page/UserRepository.server"; import { userPageUserId } from "~/features/user-page/user-page-context.server"; import type { SerializeFrom } from "~/utils/remix"; import { badRequest, forbidden } from "~/utils/remix.server"; -import { resolveAvatarUrl } from "~/utils/urls"; +import { avatarUrl } from "~/utils/urls"; import { userSeasonSummaryGraphicSearchParams } from "../user-page-search-params"; const BEST_SETS_COUNT = 3; @@ -131,13 +131,10 @@ export const loader = async ({ url }: LoaderFunctionArgs) => { name: mate.user.username, countryCode: countries.get(mate.user.id), }, - discordId: mate.user.discordId, - avatarUrl: resolveAvatarUrl({ - customAvatarUrl: mate.user.customAvatarUrl, - discordId: mate.user.discordId, - discordAvatar: mate.user.discordAvatar, - size: "sm", - }), + userId: mate.user.id, + avatarUrl: mate.user.avatar + ? avatarUrl(mate.user.avatar, "sm") + : undefined, setsCount: mate.setWins + mate.setLosses, })), bestStage: SeasonSummary.bestStage( diff --git a/app/features/user-page/routes/u.$identifier.admin.tsx b/app/features/user-page/routes/u.$identifier.admin.tsx index 120bb1b1b..d9f068ef5 100644 --- a/app/features/user-page/routes/u.$identifier.admin.tsx +++ b/app/features/user-page/routes/u.$identifier.admin.tsx @@ -150,7 +150,7 @@ function ModNotes() { />

By: {note.username}

Note: {note.text}

- {note.discordId === user?.discordId ? ( + {note.id === user?.id ? ( diff --git a/app/features/user-page/routes/u.$identifier.index.tsx b/app/features/user-page/routes/u.$identifier.index.tsx index a4cf9cac4..515be3a39 100644 --- a/app/features/user-page/routes/u.$identifier.index.tsx +++ b/app/features/user-page/routes/u.$identifier.index.tsx @@ -81,7 +81,7 @@ export default function UserInfoPage() { {members.map((member) => ( { test.each([ @@ -13,10 +13,10 @@ describe("userPageRedirectPath", () => { expected: "/u/sendou", }, { - why: "id -> discord id when no custom url", - url: "/u/274", + why: "discord id -> id when no custom url", + url: "/u/79237403620945920", user: WITHOUT_CUSTOM_URL, - expected: "/u/79237403620945920", + expected: "/u/274", }, { why: "discord id -> custom url", @@ -31,8 +31,8 @@ describe("userPageRedirectPath", () => { expected: null, }, { - why: "discord id stays when no custom url", - url: "/u/79237403620945920", + why: "id stays when no custom url", + url: "/u/274", user: WITHOUT_CUSTOM_URL, expected: null, }, diff --git a/app/features/user-page/user-page-urls.ts b/app/features/user-page/user-page-urls.ts index 2ab87e67c..08c3f93a9 100644 --- a/app/features/user-page/user-page-urls.ts +++ b/app/features/user-page/user-page-urls.ts @@ -64,11 +64,11 @@ export const userEditBuildPage = (user: UserLinkArgs, buildId: number) => /** * Path the given user page URL should redirect to, or `null` if it already uses the user's - * preferred identifier (custom URL, falling back to their Discord id). + * preferred identifier (custom URL, falling back to their user id). */ export function userPageRedirectPath(url: URL, user: UserLinkArgs) { const segments = url.pathname.split("/"); - const preferredIdentifier = user.customUrl ?? user.discordId; + const preferredIdentifier = user.customUrl ?? String(user.id); if (segments[2] === preferredIdentifier) return null; diff --git a/app/features/user-report/UserReportRepository.server.ts b/app/features/user-report/UserReportRepository.server.ts index ea964fe37..cd983b523 100644 --- a/app/features/user-report/UserReportRepository.server.ts +++ b/app/features/user-report/UserReportRepository.server.ts @@ -67,7 +67,6 @@ export function findAllByReportedUserId(reportedUserId: number) { "UserReport.createdAt", "UserReport.reporterUserId", "User.username as reporterUsername", - "User.discordId as reporterDiscordId", "User.customUrl as reporterCustomUrl", ]) .where("UserReport.reportedUserId", "=", reportedUserId) diff --git a/app/features/vods/vods-types.ts b/app/features/vods/vods-types.ts index 714e9c9df..ae664b3e7 100644 --- a/app/features/vods/vods-types.ts +++ b/app/features/vods/vods-types.ts @@ -1,18 +1,14 @@ import type * as v from "valibot"; import type { Tables } from "~/db/tables"; import type { MainWeaponId } from "~/modules/in-game-lists/types"; +import type { CommonUser } from "~/utils/kysely.server"; import type { videoSchema } from "./vods-schemas"; export type VideoBeingAdded = v.InferOutput; export interface Vod { id: Tables["Video"]["id"]; - pov?: - | (Pick< - Tables["User"], - "username" | "discordId" | "discordAvatar" | "customUrl" | "id" - > & { customAvatarUrl: string | null }) - | string; + pov?: CommonUser | string; title: Tables["Video"]["title"]; type: Tables["Video"]["type"]; youtubePublishedAt: Tables["Video"]["youtubePublishedAt"]; diff --git a/app/form/fields.ts b/app/form/fields.ts index 9c29526fc..542d5cd56 100644 --- a/app/form/fields.ts +++ b/app/form/fields.ts @@ -134,12 +134,14 @@ export function image(args: { bottomText?: FormsTranslationKey; dimensions?: "logo" | "thick-banner" | { width: number; height: number }; autoValidate?: boolean; + withSmallCopy?: boolean; }) { return register(imageValue, { label: prefixKey(args.label), bottomText: prefixKey(args.bottomText), dimensions: args.dimensions ?? "logo", autoValidate: args.autoValidate ?? false, + withSmallCopy: args.withSmallCopy ?? false, type: "image", initialValue: null, }); diff --git a/app/form/parse.server.ts b/app/form/parse.server.ts index 8040917bf..160a43b83 100644 --- a/app/form/parse.server.ts +++ b/app/form/parse.server.ts @@ -54,12 +54,13 @@ export async function resolveImageFields({ const user = requireUser(); const resolved = { ...(data as Record) }; - for (const { key, autoValidate } of imageFields(schema)) { + for (const { key, autoValidate, withSmallCopy } of imageFields(schema)) { if (key in resolved) { resolved[key] = await imageFieldValueToImgId({ value: resolved[key] as ImageFieldValue, user, autoValidate, + withSmallCopy, isCurrentImgId, }); } @@ -68,10 +69,10 @@ export async function resolveImageFields({ return resolved as ResolvedImages>; } -/** Every `image()` field across an object or union/variant of objects, with its `autoValidate` flag. */ +/** Every `image()` field across an object or union/variant of objects, with its upload flags. */ function imageFields( schema: AnySchema, -): Array<{ key: string; autoValidate: boolean }> { +): Array<{ key: string; autoValidate: boolean; withSmallCopy: boolean }> { const objects = schema.type === "union" || schema.type === "variant" ? ((schema as unknown as { options: AnySchema[] }).options.filter( @@ -81,17 +82,23 @@ function imageFields( ? [schema as unknown as { entries: Record }] : []; - const fields = new Map(); + const fields = new Map< + string, + { autoValidate: boolean; withSmallCopy: boolean } + >(); for (const object of objects) { for (const [key, fieldSchema] of Object.entries(object.entries)) { const meta = formRegistry.get(fieldSchema); if (meta?.type === "image") { - fields.set(key, meta.autoValidate ?? false); + fields.set(key, { + autoValidate: meta.autoValidate ?? false, + withSmallCopy: meta.withSmallCopy ?? false, + }); } } } - return [...fields].map(([key, autoValidate]) => ({ key, autoValidate })); + return [...fields].map(([key, flags]) => ({ key, ...flags })); } /** diff --git a/app/form/types.ts b/app/form/types.ts index 43d45651a..90db8b472 100644 --- a/app/form/types.ts +++ b/app/form/types.ts @@ -135,6 +135,8 @@ interface FormFieldImage extends FormFieldBase { dimensions?: ImageFieldDimensions; /** Validate uploaded images immediately, bypassing the moderator queue (e.g. trusted org logos). */ autoValidate?: boolean; + /** Also store a downscaled copy for small displays, e.g. avatars. */ + withSmallCopy?: boolean; } export interface FormFieldArray diff --git a/app/modules/discord-webhook.server.ts b/app/modules/discord-webhook.server.ts index 563a23263..6a281ffe7 100644 --- a/app/modules/discord-webhook.server.ts +++ b/app/modules/discord-webhook.server.ts @@ -9,8 +9,8 @@ interface ModWebhookEmbed { } export interface WebhookUser { + id: number; username: string; - discordId: string; customUrl: string | null; } diff --git a/app/root.tsx b/app/root.tsx index fe7816f02..5533cb80a 100644 --- a/app/root.tsx +++ b/app/root.tsx @@ -158,11 +158,9 @@ export const loader = async ({ request }: LoaderFunctionArgs) => { user: user ? { username: user.username, - discordAvatar: user.discordAvatar, - discordId: user.discordId, id: user.id, customUrl: user.customUrl, - customAvatarUrl: user.customAvatarUrl, + avatar: user.avatar, inGameName: user.inGameName, friendCode: user.friendCode, preferences: user.preferences ?? {}, diff --git a/app/routes.ts b/app/routes.ts index 6fbeef9d4..e22283a17 100644 --- a/app/routes.ts +++ b/app/routes.ts @@ -413,7 +413,6 @@ export default [ "/set-plus-voting-active", "features/api-private/routes/set-plus-voting-active.ts", ), - route("/users", "features/api-private/routes/users.ts"), route("/scanner", "features/scanner/routes/scanner.tsx"), route("/ingest", "features/scanner-ingest/routes/scanner-ingest.ts"), @@ -509,6 +508,7 @@ export default [ ...prefix("/auth", [ index("features/auth/routes/auth.ts"), route("callback", "features/auth/routes/auth.callback.ts"), + route("refresh", "features/auth/routes/auth.refresh.ts"), route("create-link", "features/auth/routes/auth.create-link.ts"), route("login", "features/auth/routes/auth.login.ts"), route("logout", "features/auth/routes/auth.logout.ts"), diff --git a/app/routines/closeExpiredCommissions.ts b/app/routines/closeExpiredCommissions.ts index d875f9fb5..c90c99cdd 100644 --- a/app/routines/closeExpiredCommissions.ts +++ b/app/routines/closeExpiredCommissions.ts @@ -10,7 +10,7 @@ export const CloseExpiredCommissionsRoutine = new Routine({ func: async () => { const usersWithExpiredCommissions = await db .selectFrom("User") - .select(["id", "discordId"]) + .select("id") .where("commissionsOpen", "=", 1) .where("commissionsOpenedAt", "is not", null) .where( @@ -43,9 +43,6 @@ export const CloseExpiredCommissionsRoutine = new Routine({ await notify({ notification: { type: "COMMISSIONS_CLOSED", - meta: { - discordId: user.discordId, - }, }, userIds: [user.id], }); diff --git a/app/utils/kysely.server.ts b/app/utils/kysely.server.ts index 4c03acbdc..be1fda36e 100644 --- a/app/utils/kysely.server.ts +++ b/app/utils/kysely.server.ts @@ -22,8 +22,8 @@ import { db } from "~/db/sql"; import type { DB, Tables } from "~/db/tables"; import * as Seasons from "~/features/mmr/core/Seasons"; import { dateToDatabaseTimestamp } from "./dates"; -import { IS_E2E_TEST_RUN } from "./e2e"; import { safeNumberParse } from "./number"; +import { USER_SUBMITTED_IMAGE_ROOT } from "./urls"; /** Base query selecting the user by URL identifier (user id, Discord id or custom URL). */ export function userByIdentifierQuery(identifier: string) { @@ -89,15 +89,13 @@ type UserIdColumn = O extends { idAs: infer I extends string } type CommonUserSelectResult = readonly [ `${UserTableAlias}.id as ${UserIdColumn}`, `${UserTableAlias}.username as ${PrefixedUserColumn}`, - `${UserTableAlias}.discordId as ${PrefixedUserColumn}`, - `${UserTableAlias}.discordAvatar as ${PrefixedUserColumn}`, `${UserTableAlias}.customUrl as ${PrefixedUserColumn}`, - AliasedRawBuilder>, + AliasedRawBuilder>, ]; /** - * Select list for the fields shared by every user representation, incl. `customAvatarUrl` (full - * supporter avatar URL or `null`). Reads from `"User"` unless `alias` is given; `prefix` prefixes + * Select list for the fields shared by every user representation, incl. `avatar` (see + * {@link userAvatar}). Reads from `"User"` unless `alias` is given; `prefix` prefixes * every output column (`sender` → `senderId`, ...), `idAs` renames only the id column and * `inTournament` resolves `username` via {@link tournamentUsername}. */ @@ -117,38 +115,34 @@ export function commonUserSelect( options?.inTournament ? tournamentUsername(alias).as(outputName("username")) : `${alias}.username as ${outputName("username")}`, - `${alias}.discordId as ${outputName("discordId")}`, - `${alias}.discordAvatar as ${outputName("discordAvatar")}`, `${alias}.customUrl as ${outputName("customUrl")}`, - customAvatarUrl(eb, alias).as(outputName("customAvatarUrl")), + userAvatar(eb, alias).as(outputName("avatar")), ] as unknown as CommonUserSelectResult; } /** - * Full URL of a user's supporter custom avatar, or `null`. Alias it when selecting directly. - * Prefer {@link commonUserSelect} / {@link commonUserJsonObject} when they fit. + * File name of the user's avatar (custom one over the one synced from their log in account) or + * `null`, the client builds the URL with `avatarUrl()`. */ -export function customAvatarUrl( - eb: ExpressionBuilder, - alias = "User", -) { - return concatUserSubmittedImagePrefix( +function userAvatar(eb: ExpressionBuilder, alias = "User") { + const imageUrlOf = (column: "customAvatarImgId" | "syncedAvatarImgId") => eb .selectFrom("UserSubmittedImage") .select("UserSubmittedImage.url") - .whereRef( - "UserSubmittedImage.id", - "=", - sql.ref(`${alias}.customAvatarImgId`), - ) - .$asScalar(), - ).$castTo(); + .whereRef("UserSubmittedImage.id", "=", sql.ref(`${alias}.${column}`)) + .$asScalar(); + + return eb.fn + .coalesce(imageUrlOf("customAvatarImgId"), imageUrlOf("syncedAvatarImgId")) + .$castTo(); } export type CommonUser = Pick< Tables["User"], - "id" | "username" | "discordId" | "discordAvatar" | "customUrl" -> & { customAvatarUrl: string | null }; + "id" | "username" | "customUrl" +> & { + avatar: string | null; +}; /** Represents User joined with PlusTier table */ export type UserWithPlusTier = Tables["User"] & { @@ -170,10 +164,8 @@ export function commonUserObjectFields(eb: ExpressionBuilder) { return { id: eb.ref("User.id"), username: eb.ref("User.username"), - discordId: eb.ref("User.discordId"), - discordAvatar: eb.ref("User.discordAvatar"), customUrl: eb.ref("User.customUrl"), - customAvatarUrl: customAvatarUrl(eb), + avatar: userAvatar(eb), }; } @@ -205,13 +197,6 @@ export function commonUserMembersAgg< .$castTo>>(); } -const USER_SUBMITTED_IMAGE_ROOT = - (process.env.NODE_ENV === "development" && !Config.prodMode) || - IS_E2E_TEST_RUN || - process.env.NODE_ENV === "test" - ? "http://127.0.0.1:9000/sendou" - : "https://sendou.nyc3.cdn.digitaloceanspaces.com"; - /** Full URL of the tournament's custom logo (via `avatarImgId`), or null when it has none. */ export function tournamentLogoOrNull( eb: ExpressionBuilder, diff --git a/app/utils/remix.server.ts b/app/utils/remix.server.ts index ee0121261..1c43fd9cf 100644 --- a/app/utils/remix.server.ts +++ b/app/utils/remix.server.ts @@ -160,11 +160,25 @@ export function successToast(message: string) { export function successToastWithRedirect({ message, url, + headers, }: { message: string; url: string; + headers?: HeadersInit; }) { - return redirect(urlWithToastParam(url, "__success", message)); + return redirect(urlWithToastParam(url, "__success", message), { headers }); +} + +export function errorToastWithRedirect({ + message, + url, + headers, +}: { + message: string; + url: string; + headers?: HeadersInit; +}) { + return redirect(urlWithToastParam(url, "__error", message), { headers }); } function urlWithToastParam( diff --git a/app/utils/urls.ts b/app/utils/urls.ts index befd60113..0282b55e3 100644 --- a/app/utils/urls.ts +++ b/app/utils/urls.ts @@ -20,39 +20,34 @@ import type { SubWeaponId, } from "~/modules/in-game-lists/types"; import type { weaponCategories } from "~/modules/in-game-lists/weapon-ids"; +import { IS_E2E_TEST_RUN } from "./e2e"; -export const discordAvatarUrl = ({ - discordId, - discordAvatar, - size, -}: { - discordId: string; - discordAvatar: string; - size: "lg" | "sm"; -}) => - `https://cdn.discordapp.com/avatars/${discordId}/${ - discordAvatar - }.webp${size === "lg" ? "?size=240" : "?size=80"}`; +/** Root of the S3 bucket holding user submitted images and self-hosted Discord avatars. */ +export const USER_SUBMITTED_IMAGE_ROOT = + (process.env.NODE_ENV === "development" && !Config.prodMode) || + IS_E2E_TEST_RUN || + process.env.NODE_ENV === "test" + ? "http://127.0.0.1:9000/sendou" + : "https://sendou.nyc3.cdn.digitaloceanspaces.com"; -/** Avatar url preferring the custom avatar over the Discord one; undefined without either. */ -export const resolveAvatarUrl = ({ - customAvatarUrl, - discordId, - discordAvatar, - size, -}: { - customAvatarUrl?: string | null; - discordId: string; - discordAvatar?: string | null; - size: "lg" | "sm"; -}) => { - if (customAvatarUrl) return customAvatarUrl; - if (discordAvatar) { - return discordAvatarUrl({ discordId, discordAvatar, size }); - } +/** Full URL of an image in the user submitted image storage by its file name. */ +export const userSubmittedImageUrl = (fileName: string) => + `${USER_SUBMITTED_IMAGE_ROOT}/${fileName}`; - return undefined; -}; +/** File name of an image's downscaled copy, stored next to it (art thumbnails, avatars). */ +export function smallImageFileName(fileName: string) { + const lastDotIndex = fileName.lastIndexOf("."); + if (lastDotIndex === -1) return fileName; + + const withoutExtension = fileName.slice(0, lastDotIndex); + const extension = fileName.slice(lastDotIndex + 1); + + return `${withoutExtension}-small.${extension}`; +} + +/** URL of a user's avatar by its file name (`CommonUser["avatar"]`). */ +export const avatarUrl = (avatar: string, size: "lg" | "sm") => + userSubmittedImageUrl(size === "sm" ? smallImageFileName(avatar) : avatar); export const SENDOU_INK_BASE_URL = "https://sendou.ink"; @@ -95,6 +90,7 @@ export const youtubeUrl = (channelId: string) => export const LOG_IN_URL = "/auth"; export const LOG_OUT_URL = "/auth/logout"; +export const DISCORD_REFRESH_URL = "/auth/refresh"; export const ADMIN_PAGE = "/admin"; export const API_PAGE = "/api"; export const ARTICLES_MAIN_PAGE = "/a"; @@ -263,7 +259,7 @@ export const trophyBackfillPage = (args: { }) => `${TROPHIES_PAGE}/${args.trophyId}/backfill/${args.seriesId}`; export interface UserLinkArgs { - discordId: Tables["User"]["discordId"]; + id: Tables["User"]["id"]; customUrl?: Tables["User"]["customUrl"]; } @@ -273,7 +269,7 @@ export const sourceFileUrl = (filePath: string) => `${SENDOU_INK_GITHUB_URL}/blob/main/${filePath}`; export const userPage = (user: UserLinkArgs) => - `/u/${user.customUrl ?? user.discordId}`; + `/u/${user.customUrl ?? user.id}`; export const userEditProfilePage = (user: UserLinkArgs) => `${userPage(user)}/edit`; export const userBuildsPage = (user: UserLinkArgs) => diff --git a/changelog/2026-10-13-refresh-from-discord.md b/changelog/2026-10-13-refresh-from-discord.md new file mode 100644 index 000000000..5547d79b9 --- /dev/null +++ b/changelog/2026-10-13-refresh-from-discord.md @@ -0,0 +1,9 @@ +--- +navItem: settings +type: feature +--- +Refresh your Discord avatar, name and connections + +- New "Refresh from Discord" button in settings updates your avatar, name and connections without logging out +- Avatars now load from sendou.ink's own storage, so they no longer break when changed on Discord +- Supporters can still set a custom avatar that differs from their Discord one diff --git a/e2e/admin.spec.ts b/e2e/admin.spec.ts index 31c4fa192..76751eb9f 100644 --- a/e2e/admin.spec.ts +++ b/e2e/admin.spec.ts @@ -1,7 +1,7 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import { addHours, addYears } from "date-fns"; -import { NZAP_TEST_DISCORD_ID } from "~/db/seed/constants"; +import { NZAP_TEST_ID } from "~/db/seed/constants"; import { ADMIN_ID } from "~/features/admin/admin-constants"; import { SPLATOON_3_XP_BADGE_VALUES } from "~/features/badges/badges-constants"; import { @@ -147,13 +147,13 @@ test.describe("Admin panel", () => { ).toContainText("+1"); const userPage = new UserPage(page); - await userPage.goto(NZAP_TEST_DISCORD_ID); + await userPage.goto(NZAP_TEST_ID); await expect(userPage.widget("x-rank-peaks")).toBeVisible(); const playerPage = await userPage.openPlacements(); await expect(playerPage.locators.heading).toBeVisible(); // the old user kept their account, now reached via the new user's Discord id - await userPage.goto(LEAVER.discordId); + await userPage.gotoWithIdentifier(LEAVER.discordId); await expect(userPage.usernameHeading(KEEPER.discordName)).toBeVisible(); }); diff --git a/e2e/art.spec.ts b/e2e/art.spec.ts index 1687d4b41..5ca265b2d 100644 --- a/e2e/art.spec.ts +++ b/e2e/art.spec.ts @@ -1,6 +1,6 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; -import { NZAP_TEST_DISCORD_ID, NZAP_TEST_ID } from "~/db/seed/constants"; +import { NZAP_TEST_ID } from "~/db/seed/constants"; import { ADMIN_ID } from "~/features/admin/admin-constants"; import { expect, impersonate, isNotVisible, test } from "./helpers/playwright"; import { NewArtPage } from "./pages/art/new-art-page"; @@ -42,7 +42,7 @@ test.describe("Art", () => { await expect(imageValidation.locators.allValidatedText).toBeVisible(); - await userArt.goto(NZAP_TEST_DISCORD_ID); + await userArt.goto(NZAP_TEST_ID); const artImage = userArt.image(0); await expect(artImage).toBeVisible(); @@ -67,7 +67,7 @@ test.describe("Art", () => { await impersonate(page, NZAP_TEST_ID); const userArt = new UserArtPage(page); - await userArt.goto(NZAP_TEST_DISCORD_ID); + await userArt.goto(NZAP_TEST_ID); await userArt.editLink(art.id).click(); const newArt = new NewArtPage(page); @@ -87,7 +87,7 @@ test.describe("Art", () => { await expect(newArt.locators.descriptionInput).toHaveValue("Squid drawing"); // both their own art and the art they are tagged in show on their page - await userArt.goto(NZAP_TEST_DISCORD_ID); + await userArt.goto(NZAP_TEST_ID); await expect(userArt.locators.images).toHaveCount(2); await userArt.unlinkFromArt(); diff --git a/e2e/builds.spec.ts b/e2e/builds.spec.ts index 3f5f4dbac..fc10d33e6 100644 --- a/e2e/builds.spec.ts +++ b/e2e/builds.spec.ts @@ -1,6 +1,6 @@ import { subDays } from "date-fns"; -import { NZAP_TEST_DISCORD_ID, NZAP_TEST_ID } from "~/db/seed/constants"; -import { ADMIN_DISCORD_ID, ADMIN_ID } from "~/features/admin/admin-constants"; +import { NZAP_TEST_ID } from "~/db/seed/constants"; +import { ADMIN_ID } from "~/features/admin/admin-constants"; import { BUILDS_PAGE_SIZE, RECENT_PATCHES, @@ -44,7 +44,7 @@ test.describe("Builds", () => { await impersonate(page, NZAP_TEST_ID); const buildForm = new BuildFormPage(page); - await buildForm.gotoNew(NZAP_TEST_DISCORD_ID); + await buildForm.gotoNew(NZAP_TEST_ID); await buildForm.form.selectWeapons("weapons", [ "Tenta Brella", @@ -89,7 +89,7 @@ test.describe("Builds", () => { await impersonate(page); const userBuilds = new UserBuildsPage(page); - await userBuilds.goto(ADMIN_DISCORD_ID); + await userBuilds.goto(ADMIN_ID); const buildIdBefore = await userBuilds.buildId(0); @@ -104,7 +104,7 @@ test.describe("Builds", () => { expect(buildIdAfter).toBe(buildIdBefore); await impersonate(page, NZAP_TEST_ID); - await userBuilds.goto(ADMIN_DISCORD_ID); + await userBuilds.goto(ADMIN_ID); await expect(userBuilds.locators.buildCards).toHaveCount(1); await expect(userBuilds.buildCard(0).privateIndicator).toHaveCount(0); }); @@ -175,7 +175,7 @@ test.describe("Builds", () => { await impersonate(page, NZAP_TEST_ID); const userBuilds = new UserBuildsPage(page); - await userBuilds.goto(ADMIN_DISCORD_ID); + await userBuilds.goto(ADMIN_ID); await expect(userBuilds.locators.buildCards).toHaveCount(5); await userBuilds.filterOption(/^Sploosh-o-matic/).click(); @@ -192,7 +192,7 @@ test.describe("Builds", () => { }); const userBuilds = new UserBuildsPage(page); - await userBuilds.goto(ADMIN_DISCORD_ID); + await userBuilds.goto(ADMIN_ID); await expect(userBuilds.locators.buildCards).toHaveCount(BUILDS_PAGE_SIZE); await userBuilds.locators.nextPageButton.click(); @@ -311,7 +311,7 @@ test.describe("Builds", () => { await impersonate(page); const userBuilds = new UserBuildsPage(page); - await userBuilds.goto(ADMIN_DISCORD_ID); + await userBuilds.goto(ADMIN_ID); await expect(userBuilds.buildCard(0).title).toContainText("Mid Build"); diff --git a/e2e/global-search.spec.ts b/e2e/global-search.spec.ts index ade91305b..08433c2de 100644 --- a/e2e/global-search.spec.ts +++ b/e2e/global-search.spec.ts @@ -1,4 +1,4 @@ -import { ADMIN_DISCORD_ID, ADMIN_ID } from "~/features/admin/admin-constants"; +import { ADMIN_ID } from "~/features/admin/admin-constants"; import { tournamentOrganizationPage } from "~/features/tournament-organization/tournament-organization-urls"; import { userPage } from "~/utils/urls"; import { expect, impersonate, navigate, test } from "./helpers/playwright"; @@ -22,7 +22,7 @@ test.describe("Global search", () => { await search.selectType("users"); await search.search("sendou"); await search.selectOption("Sendou"); - await expect(page).toHaveURL(userPage({ discordId: ADMIN_DISCORD_ID })); + await expect(page).toHaveURL(userPage({ id: ADMIN_ID })); await search.open(); await search.selectType("organizations"); diff --git a/e2e/pages/art/user-art-page.ts b/e2e/pages/art/user-art-page.ts index 594569084..33071dee4 100644 --- a/e2e/pages/art/user-art-page.ts +++ b/e2e/pages/art/user-art-page.ts @@ -18,8 +18,8 @@ export class UserArtPage { }; } - async goto(discordId: string) { - await navigate({ page: this.page, url: userArtPage({ discordId }) }); + async goto(userId: number) { + await navigate({ page: this.page, url: userArtPage({ id: userId }) }); } image(nth: number) { diff --git a/e2e/pages/builds/build-form-page.ts b/e2e/pages/builds/build-form-page.ts index d7286ff39..b5b42585b 100644 --- a/e2e/pages/builds/build-form-page.ts +++ b/e2e/pages/builds/build-form-page.ts @@ -14,8 +14,8 @@ export class BuildFormPage { this.form = createFormHelpers(page, newBuildBaseSchema); } - async gotoNew(discordId: string) { - await navigate({ page: this.page, url: userNewBuildPage({ discordId }) }); + async gotoNew(userId: number) { + await navigate({ page: this.page, url: userNewBuildPage({ id: userId }) }); } gearSelect(type: GearType) { diff --git a/e2e/pages/builds/user-builds-page.ts b/e2e/pages/builds/user-builds-page.ts index 86886415b..7462d9bb6 100644 --- a/e2e/pages/builds/user-builds-page.ts +++ b/e2e/pages/builds/user-builds-page.ts @@ -28,8 +28,8 @@ export class UserBuildsPage { }; } - async goto(discordId: string) { - await navigate({ page: this.page, url: userBuildsPage({ discordId }) }); + async goto(userId: number) { + await navigate({ page: this.page, url: userBuildsPage({ id: userId }) }); } buildCard(nth: number) { diff --git a/e2e/pages/user/user-admin-page.ts b/e2e/pages/user/user-admin-page.ts index 1a84e56d2..c2a137674 100644 --- a/e2e/pages/user/user-admin-page.ts +++ b/e2e/pages/user/user-admin-page.ts @@ -16,8 +16,8 @@ export class UserAdminPage { }; } - async goto(discordId: string) { - await navigate({ page: this.page, url: userAdminPage({ discordId }) }); + async goto(userId: number) { + await navigate({ page: this.page, url: userAdminPage({ id: userId }) }); } totalReportsText(count: number) { diff --git a/e2e/pages/user/user-edit-profile-page.ts b/e2e/pages/user/user-edit-profile-page.ts index 798f0f994..6b9931a9a 100644 --- a/e2e/pages/user/user-edit-profile-page.ts +++ b/e2e/pages/user/user-edit-profile-page.ts @@ -14,10 +14,10 @@ export class UserEditProfilePage { this.form = createFormHelpers(page, userEditProfileBaseSchema); } - async goto(discordId: string) { + async goto(userId: number) { await navigate({ page: this.page, - url: userEditProfilePage({ discordId }), + url: userEditProfilePage({ id: userId }), }); } diff --git a/e2e/pages/user/user-edit-widgets-page.ts b/e2e/pages/user/user-edit-widgets-page.ts index ac1f4766b..f05c5ffbc 100644 --- a/e2e/pages/user/user-edit-widgets-page.ts +++ b/e2e/pages/user/user-edit-widgets-page.ts @@ -16,10 +16,10 @@ export class UserEditWidgetsPage { }; } - async goto(discordId: string) { + async goto(userId: number) { await navigate({ page: this.page, - url: `${userPage({ discordId })}/edit-widgets`, + url: `${userPage({ id: userId })}/edit-widgets`, }); } diff --git a/e2e/pages/user/user-page.ts b/e2e/pages/user/user-page.ts index fc5a1d1e5..3f8bd406e 100644 --- a/e2e/pages/user/user-page.ts +++ b/e2e/pages/user/user-page.ts @@ -32,8 +32,8 @@ export class UserPage { }; } - async goto(discordId: string) { - await navigate({ page: this.page, url: userPage({ discordId }) }); + async goto(userId: number) { + await navigate({ page: this.page, url: userPage({ id: userId }) }); } /** Navigates with any of the identifiers the page accepts: user id, Discord id or custom URL. */ diff --git a/e2e/pages/user/user-results-highlights-page.ts b/e2e/pages/user/user-results-highlights-page.ts index fe651bc2b..bbb89e89e 100644 --- a/e2e/pages/user/user-results-highlights-page.ts +++ b/e2e/pages/user/user-results-highlights-page.ts @@ -10,10 +10,10 @@ export class UserResultsHighlightsPage { this.page = page; } - async goto(discordId: string) { + async goto(userId: number) { await navigate({ page: this.page, - url: userResultsEditHighlightsPage({ discordId }), + url: userResultsEditHighlightsPage({ id: userId }), }); } diff --git a/e2e/pages/user/user-results-page.ts b/e2e/pages/user/user-results-page.ts index 65a922b64..4e86c6f78 100644 --- a/e2e/pages/user/user-results-page.ts +++ b/e2e/pages/user/user-results-page.ts @@ -31,8 +31,8 @@ export class UserResultsPage { await this.page.keyboard.press("Escape"); } - async goto(discordId: string) { - await navigate({ page: this.page, url: userResultsPage({ discordId }) }); + async goto(userId: number) { + await navigate({ page: this.page, url: userResultsPage({ id: userId }) }); } tournamentName(name: string) { diff --git a/e2e/pages/user/user-seasons-page.ts b/e2e/pages/user/user-seasons-page.ts index 77bba3b1b..a5dd22364 100644 --- a/e2e/pages/user/user-seasons-page.ts +++ b/e2e/pages/user/user-seasons-page.ts @@ -17,10 +17,10 @@ export class UserSeasonsPage { }; } - async goto(discordId: string, season?: number) { + async goto(userId: number, season?: number) { await navigate({ page: this.page, - url: userSeasonsPage({ user: { discordId }, season }), + url: userSeasonsPage({ user: { id: userId }, season }), }); } diff --git a/e2e/pages/user/user-vods-page.ts b/e2e/pages/user/user-vods-page.ts index d7e649e9a..79512dded 100644 --- a/e2e/pages/user/user-vods-page.ts +++ b/e2e/pages/user/user-vods-page.ts @@ -10,8 +10,8 @@ export class UserVodsPage { this.page = page; } - async goto(discordId: string) { - await navigate({ page: this.page, url: userVodsPage({ discordId }) }); + async goto(userId: number) { + await navigate({ page: this.page, url: userVodsPage({ id: userId }) }); } vodTitle(title: string) { diff --git a/e2e/public-pages.spec.ts b/e2e/public-pages.spec.ts index c2f9920da..0d262cca9 100644 --- a/e2e/public-pages.spec.ts +++ b/e2e/public-pages.spec.ts @@ -64,7 +64,7 @@ test.describe("Public pages", () => { await expect(front.locators.welcomeBanner).toBeVisible(); const userPage = new UserPage(page); - await userPage.goto(PUBLIC_USER.discordId); + await userPage.goto(user.id); await expectNoErrorPage(page); await expect( userPage.usernameHeading(PUBLIC_USER.discordName), diff --git a/e2e/team.spec.ts b/e2e/team.spec.ts index 20b7f3a1a..31229997f 100644 --- a/e2e/team.spec.ts +++ b/e2e/team.spec.ts @@ -1,6 +1,6 @@ import { addWeeks } from "date-fns"; import { NZAP_TEST_ID } from "~/db/seed/constants"; -import { ADMIN_DISCORD_ID, ADMIN_ID } from "~/features/admin/admin-constants"; +import { ADMIN_ID } from "~/features/admin/admin-constants"; import { addTeamEventSchema, editTeamEventSchema, @@ -347,7 +347,7 @@ test.describe("Team page", () => { await secondaryTeam.makeMainTeam(); const user = new UserPage(page); - await user.goto(ADMIN_DISCORD_ID); + await user.goto(ADMIN_ID); await expect(user.teamLinks()).toHaveCount(2); await expect(user.teamLinks().first()).not.toContainText(TEAM_NAME); @@ -358,7 +358,7 @@ test.describe("Team page", () => { await expect(mainTeam.locators.mainTeamIndicator).toBeVisible(); await mainTeam.leave(); - await user.goto(ADMIN_DISCORD_ID); + await user.goto(ADMIN_ID); await expect(user.teamLinks()).toHaveCount(1); await expect(user.teamLinks().first()).toContainText(TEAM_NAME); diff --git a/e2e/top-search.spec.ts b/e2e/top-search.spec.ts index f42bb7e84..806c57590 100644 --- a/e2e/top-search.spec.ts +++ b/e2e/top-search.spec.ts @@ -1,4 +1,4 @@ -import { ADMIN_DISCORD_ID, ADMIN_ID } from "~/features/admin/admin-constants"; +import { ADMIN_ID } from "~/features/admin/admin-constants"; import { expect, test } from "./helpers/playwright"; import { TopSearchPage } from "./pages/top-search/top-search-page"; import { UserPage } from "./pages/user/user-page"; @@ -52,7 +52,7 @@ test.describe("Top search", () => { }); const user = new UserPage(page); - await user.goto(ADMIN_DISCORD_ID); + await user.goto(ADMIN_ID); const playerPlacements = await user.openPlacements(); await expect(playerPlacements.locators.heading).toContainText("Sendou"); diff --git a/e2e/tournament-bracket-elimination.spec.ts b/e2e/tournament-bracket-elimination.spec.ts index 99e7828b0..426cf255b 100644 --- a/e2e/tournament-bracket-elimination.spec.ts +++ b/e2e/tournament-bracket-elimination.spec.ts @@ -1,5 +1,5 @@ import { NZAP_TEST_ID } from "~/db/seed/constants"; -import { ADMIN_DISCORD_ID, ADMIN_ID } from "~/features/admin/admin-constants"; +import { ADMIN_ID } from "~/features/admin/admin-constants"; import { TOURNAMENT } from "~/features/tournament/tournament-constants"; import { expect, impersonate, isNotVisible, test } from "./helpers/playwright"; import { @@ -184,7 +184,7 @@ test.describe("Tournament bracket elimination", () => { await expect(results.locators.sprHeader).toBeVisible(); const userResults = new UserResultsPage(page); - await userResults.goto(ADMIN_DISCORD_ID); + await userResults.goto(ADMIN_ID); await expect(userResults.tournamentName("In The Zone 22")).toBeVisible(); diff --git a/e2e/trophies.spec.ts b/e2e/trophies.spec.ts index 9e6848d26..e53049a1d 100644 --- a/e2e/trophies.spec.ts +++ b/e2e/trophies.spec.ts @@ -1,6 +1,6 @@ import { addDays, subDays } from "date-fns"; -import { NZAP_TEST_DISCORD_ID, NZAP_TEST_ID } from "~/db/seed/constants"; -import { ADMIN_DISCORD_ID, ADMIN_ID } from "~/features/admin/admin-constants"; +import { NZAP_TEST_ID } from "~/db/seed/constants"; +import { ADMIN_ID } from "~/features/admin/admin-constants"; import { TROPHY_APPROVALS_REQUIRED } from "~/features/trophies/trophies-constants"; import { decompressFromBase64 } from "~/utils/compression"; import { dateToDatabaseTimestamp } from "~/utils/dates"; @@ -42,7 +42,7 @@ test.describe("Trophies", () => { await impersonate(page, NZAP_TEST_ID); const userPage = new UserPage(page); - await userPage.goto(ADMIN_DISCORD_ID); + await userPage.goto(ADMIN_ID); const display = page.getByTestId("trophy-display"); await expect(display).toBeVisible(); @@ -307,7 +307,7 @@ test.describe("Trophies", () => { await expect(details.locators.weaponCounts).toHaveCount(1); const userPage = new UserPage(page); - await userPage.goto(NZAP_TEST_DISCORD_ID); + await userPage.goto(NZAP_TEST_ID); await expect( userPage.locators.trophyDisplay.getByRole("button"), ).toHaveCount(2); diff --git a/e2e/user-card.spec.ts b/e2e/user-card.spec.ts index c343a0b0a..f56a28cde 100644 --- a/e2e/user-card.spec.ts +++ b/e2e/user-card.spec.ts @@ -1,4 +1,4 @@ -import { NZAP_TEST_DISCORD_ID, NZAP_TEST_ID } from "~/db/seed/constants"; +import { NZAP_TEST_ID } from "~/db/seed/constants"; import { ADMIN_ID } from "~/features/admin/admin-constants"; import { SENDOUQ_LOOKING_PAGE } from "~/utils/urls"; import { expect, impersonate, test } from "./helpers/playwright"; @@ -139,7 +139,7 @@ test.describe("User card friend request", () => { await impersonate(page); const userPage = new UserPage(page); - await userPage.goto(NZAP_TEST_DISCORD_ID); + await userPage.goto(NZAP_TEST_ID); const nzapCard = await userPage.openUserCard("N-ZAP"); await nzapCard.sendFriendRequest(); diff --git a/e2e/user-page.spec.ts b/e2e/user-page.spec.ts index 76ca46be2..9c8073ea9 100644 --- a/e2e/user-page.spec.ts +++ b/e2e/user-page.spec.ts @@ -38,12 +38,12 @@ test.describe("User page", () => { ); const userPage = new UserPage(page); - await userPage.goto(NZAP_TEST_DISCORD_ID); + await userPage.goto(NZAP_TEST_ID); await expect(userPage.locators.badgeDisplay).toBeVisible(); await isNotVisible(userPage.locators.badgePaginationButtons); - await userPage.goto(ADMIN_DISCORD_ID); + await userPage.goto(ADMIN_ID); // badges are shown newest first, so the last created one is the big badge await expect(userPage.badgeImage("Badge 12")).toBeVisible(); @@ -69,14 +69,14 @@ test.describe("User page", () => { await impersonate(page, NZAP_TEST_ID); const editWidgets = new UserEditWidgetsPage(page); - await editWidgets.goto(NZAP_TEST_DISCORD_ID); + await editWidgets.goto(NZAP_TEST_ID); await editWidgets.openWidgetSettings("badges-owned"); await editWidgets.selectFavoriteBadge(firstBadge.id); await editWidgets.save(); const userPage = new UserPage(page); - await userPage.goto(NZAP_TEST_DISCORD_ID); + await userPage.goto(NZAP_TEST_ID); await expect(userPage.badgeImage("Badge 1")).toHaveAttribute( "width", "125", @@ -97,7 +97,7 @@ test.describe("User page", () => { await impersonate(page); const editWidgets = new UserEditWidgetsPage(page); - await editWidgets.goto(ADMIN_DISCORD_ID); + await editWidgets.goto(ADMIN_ID); await editWidgets.openWidgetSettings("badges-owned"); await editWidgets.selectFavoriteBadge(badges[0].id); @@ -106,7 +106,7 @@ test.describe("User page", () => { await editWidgets.save(); const userPage = new UserPage(page); - await userPage.goto(ADMIN_DISCORD_ID); + await userPage.goto(ADMIN_ID); await expect(userPage.badgeImage("Badge 1")).toHaveAttribute( "width", "125", @@ -120,7 +120,7 @@ test.describe("User page", () => { await impersonate(page); const userPage = new UserPage(page); - await userPage.goto(ADMIN_DISCORD_ID); + await userPage.goto(ADMIN_ID); await expect(userPage.flag("FI")).toBeVisible(); const editProfile = await userPage.openEditProfile(); @@ -137,7 +137,7 @@ test.describe("User page", () => { await impersonate(page, NZAP_TEST_ID); const editProfile = new UserEditProfilePage(page); - await editProfile.goto(NZAP_TEST_DISCORD_ID); + await editProfile.goto(NZAP_TEST_ID); await editProfile.setFriendCode("0123-4567-8901"); await expect(editProfile.friendCodeButton("0123-4567-8901")).toBeVisible(); @@ -179,7 +179,7 @@ test.describe("User page", () => { await impersonate(page); const seasonsPage = new UserSeasonsPage(page); - await seasonsPage.goto(ADMIN_DISCORD_ID); + await seasonsPage.goto(ADMIN_ID); await seasonsPage.openExportDialog(); await expect(seasonsPage.exportDialogText("Best win streak")).toBeVisible(); @@ -199,7 +199,7 @@ test.describe("User page", () => { await impersonate(page, NZAP_TEST_ID); const seasonsPage = new UserSeasonsPage(page); - await seasonsPage.goto(NZAP_TEST_DISCORD_ID); + await seasonsPage.goto(NZAP_TEST_ID); await seasonsPage.openExportDialog(); await expect(seasonsPage.locators.supporterPerkExplanation).toBeVisible(); @@ -219,7 +219,7 @@ test.describe("User page", () => { await impersonate(page); const userPage = new UserPage(page); - await userPage.goto(ADMIN_DISCORD_ID); + await userPage.goto(ADMIN_ID); for (const [i, id] of [200, 1100, 2000, 4000].entries()) { await expect(userPage.weaponPoolImage(id, i + 1)).toBeVisible(); @@ -239,14 +239,14 @@ test.describe("User page", () => { await impersonate(page); const editWidgetsPage = new UserEditWidgetsPage(page); - await editWidgetsPage.goto(ADMIN_DISCORD_ID); + await editWidgetsPage.goto(ADMIN_ID); await editWidgetsPage.openWidgetSettings("weapon-pool"); await editWidgetsPage.selectWeaponPoolWeapon("Luna Blaster"); await editWidgetsPage.selectWeaponPoolWeapon("Splattershot"); await editWidgetsPage.save(); const userPage = new UserPage(page); - await userPage.goto(ADMIN_DISCORD_ID); + await userPage.goto(ADMIN_ID); await expect(userPage.weaponPoolImage(200, 1)).toBeVisible(); await expect(userPage.weaponPoolImage(40, 2)).toBeVisible(); @@ -290,7 +290,7 @@ test.describe("User page", () => { await impersonate(page); const userPage = new UserPage(page); - await userPage.goto(ADMIN_DISCORD_ID); + await userPage.goto(ADMIN_ID); const resultsPage = await userPage.openResults(); await expect(resultsPage.eventName("In The Zone 30")).toBeVisible(); @@ -304,7 +304,7 @@ test.describe("User page", () => { await isNotVisible(resultsPage.eventName("Paddling Pool 253")); await page.context().clearCookies(); - await resultsPage.goto(ADMIN_DISCORD_ID); + await resultsPage.goto(ADMIN_ID); await isNotVisible(resultsPage.eventName("Paddling Pool 253")); await resultsPage.toggleHighlightsOnly(); @@ -351,7 +351,7 @@ test.describe("User page", () => { await impersonate(page); const userPage = new UserPage(page); - await userPage.goto(ADMIN_DISCORD_ID); + await userPage.goto(ADMIN_ID); // no team, so the default layout's teams widget has nothing to show await isNotVisible(userPage.widgetHeading("Teams")); @@ -373,7 +373,7 @@ test.describe("User page", () => { await expect(vodsPage.vodTitle("Ranked grind episode 2")).toBeVisible(); const seasonsPage = new UserSeasonsPage(page); - await seasonsPage.goto(ADMIN_DISCORD_ID); + await seasonsPage.goto(ADMIN_ID); await seasonsPage.openStats(); await seasonsPage.openStatsTab("Weapons"); @@ -398,13 +398,13 @@ test.describe("User page", () => { await impersonate(page); const editWidgets = new UserEditWidgetsPage(page); - await editWidgets.goto(ADMIN_DISCORD_ID); + await editWidgets.goto(ADMIN_ID); await expect(editWidgets.supporterOnlyLabel("bio-md")).toBeVisible(); await isNotVisible(editWidgets.addWidgetButton("bio-md")); await factories.UserFactory.grant(ADMIN_ID, { patronTier: 2 }); - await editWidgets.goto(ADMIN_DISCORD_ID); + await editWidgets.goto(ADMIN_ID); await isNotVisible(editWidgets.supporterOnlyLabel("bio-md")); await editWidgets.removeWidget("bio"); @@ -433,9 +433,9 @@ test.describe("User page", () => { await userPage.gotoWithIdentifier(customUrl); await expect(page).toHaveURL(`/u/${customUrl}`); - // without a custom URL the Discord id is the preferred identifier - await userPage.gotoWithIdentifier(ADMIN_ID); - await expect(page).toHaveURL(`/u/${ADMIN_DISCORD_ID}`); + // without a custom URL the user id is the preferred identifier + await userPage.gotoWithIdentifier(ADMIN_DISCORD_ID); + await expect(page).toHaveURL(`/u/${ADMIN_ID}`); }); }); diff --git a/e2e/user-report.spec.ts b/e2e/user-report.spec.ts index 171775fdc..c9e936c18 100644 --- a/e2e/user-report.spec.ts +++ b/e2e/user-report.spec.ts @@ -1,5 +1,5 @@ import { subDays } from "date-fns"; -import { NZAP_TEST_DISCORD_ID, NZAP_TEST_ID } from "~/db/seed/constants"; +import { NZAP_TEST_ID } from "~/db/seed/constants"; import { ADMIN_ID } from "~/features/admin/admin-constants"; import { expect, impersonate, test } from "./helpers/playwright"; import { LFGPage } from "./pages/lfg/lfg-page"; @@ -41,7 +41,7 @@ test.describe("User report", () => { await impersonate(page); const adminPage = new UserAdminPage(page); - await adminPage.goto(NZAP_TEST_DISCORD_ID); + await adminPage.goto(NZAP_TEST_ID); await expect(adminPage.totalReportsText(3)).toBeVisible(); await expect(adminPage.locators.reportDetails).toHaveCount(3); diff --git a/locales/en/settings.json b/locales/en/settings.json index 6ee687b09..f55443408 100644 --- a/locales/en/settings.json +++ b/locales/en/settings.json @@ -8,6 +8,7 @@ "locale.helpTranslate": "Help translate sendou.ink", "locale.translatedPercentage": "{{percentage}}% translated", "locale.gameLanguage.bottomText": "Language of weapon, gear, stage and mode names. Pick the one your game is set to.", + "refreshFromDiscord": "Refresh from Discord", "matchProfile.maps.teamPreferencesHint": "Looking for your team's map preferences? They are on the Edit Team page.", "matchProfile.maps.avoid": "Avoid", "matchProfile.maps.prefer": "Prefer", diff --git a/migrations/20261013101844-synced-avatars.ts b/migrations/20261013101844-synced-avatars.ts new file mode 100644 index 000000000..1b0b2b72f --- /dev/null +++ b/migrations/20261013101844-synced-avatars.ts @@ -0,0 +1,33 @@ +import { type Kysely, sql } from "kysely"; + +/** + * The avatar copied from the account the user logs in with is stored as an image like a custom + * avatar. Art tag notifications refer to the adder by user id instead of Discord id. + */ +export async function up(db: Kysely): Promise { + await db.transaction().execute(async (trx) => { + await trx.schema + .alterTable("User") + .addColumn("syncedAvatarImgId", "integer", (col) => + col.references("UnvalidatedUserSubmittedImage.id").onDelete("set null"), + ) + .execute(); + await trx.schema + .createIndex("user_synced_avatar_img_id") + .on("User") + .column("syncedAvatarImgId") + .where("syncedAvatarImgId", "is not", null) + .execute(); + + await sql` + update "Notification" + set "meta" = json_set( + json_remove("meta", '$.adderDiscordId'), + '$.adderId', + (select "User"."id" from "User" where "User"."discordId" = "Notification"."meta" ->> '$.adderDiscordId') + ) + where "type" = 'TAGGED_TO_ART' + and "meta" ->> '$.adderDiscordId' is not null + `.execute(trx); + }); +} diff --git a/scripts/download-tournament-vods.ts b/scripts/download-tournament-vods.ts index b3d712ff5..ed58aa014 100644 --- a/scripts/download-tournament-vods.ts +++ b/scripts/download-tournament-vods.ts @@ -26,7 +26,7 @@ import * as TournamentMatchVodRepository from "~/features/tournament-bracket/Tou import { vodTimestampOffsetSeconds } from "~/routines/syncTournamentVods"; import { invariant } from "~/utils/invariant"; import { logger } from "~/utils/logger"; -import { resolveAvatarUrl, userPage } from "~/utils/urls"; +import { avatarUrl, userPage } from "~/utils/urls"; const SECONDS_AFTER_LAST_REPORT = 30; const MONTAGE_TOP_TEAMS_COUNT = 8; @@ -233,7 +233,7 @@ async function writeMontageManifest() { name: member.username, countryCode: member.country, avatar: await downloadImage( - resolveAvatarUrl({ ...member, size: "sm" }) ?? null, + member.avatar ? avatarUrl(member.avatar, "sm") : null, `user-${member.userId}`, ), })), @@ -273,9 +273,12 @@ async function writeMontageManifest() { pov: streamer ? { name: streamer.username, - profilePath: userPage(streamer), + profilePath: userPage({ + id: streamer.userId, + customUrl: streamer.customUrl, + }), avatar: await downloadImage( - resolveAvatarUrl({ ...streamer, size: "sm" }) ?? null, + streamer.avatar ? avatarUrl(streamer.avatar, "sm") : null, `user-${streamer.userId}`, ), } diff --git a/scripts/migrate-avatars-apply.ts b/scripts/migrate-avatars-apply.ts new file mode 100644 index 000000000..20609b253 --- /dev/null +++ b/scripts/migrate-avatars-apply.ts @@ -0,0 +1,113 @@ +// Avatar migration part 2/2, run on Render right after deploying: points users at the avatars +// `migrate-avatars-copy.ts` (part 1/2) copied to S3, then creates the small copy of every custom +// avatar uploaded before small copies existed. Users whose avatar changed since the copy are skipped, +// they get the new one copied when they next log in. Safe to rerun. +// +// usage: pnpm exec vite-node scripts/migrate-avatars-apply.ts + +import * as v from "valibot"; +import { db } from "~/db/sql"; +import { + imageExtensionFromMagicBytes, + smallImageCopy, +} from "~/features/img-upload/image-bytes.server"; +import { + existsInS3, + uploadImmutableToS3, +} from "~/features/img-upload/s3.server"; +import * as UserRepository from "~/features/user-page/UserRepository.server"; +import { invariant } from "~/utils/invariant"; +import { logger } from "~/utils/logger"; +import { smallImageFileName, userSubmittedImageUrl } from "~/utils/urls"; + +const CUSTOM_AVATAR_CONCURRENCY = 4; + +const manifestSchema = v.array( + v.object({ + userId: v.number(), + discordAvatar: v.string(), + fileName: v.string(), + }), +); + +const manifestFileName = process.argv[2]; +invariant(manifestFileName, "manifest file name is required (argument 1)"); + +await applySyncedAvatars(manifestFileName); +await createCustomAvatarSmallCopies(); + +async function applySyncedAvatars(fileName: string) { + const response = await fetch(userSubmittedImageUrl(fileName)); + invariant(response.ok, `Manifest responded with ${response.status}`); + const manifest = v.parse(manifestSchema, await response.json()); + + const stats = { applied: 0, alreadyApplied: 0, avatarChanged: 0 }; + for (const entry of manifest) { + const user = await db + .selectFrom("User") + .select(["User.discordAvatar", "User.syncedAvatarImgId"]) + .where("User.id", "=", entry.userId) + .executeTakeFirst(); + + if (user?.syncedAvatarImgId) { + stats.alreadyApplied++; + continue; + } + if (user?.discordAvatar !== entry.discordAvatar) { + stats.avatarChanged++; + continue; + } + + await UserRepository.replaceSyncedAvatar({ + userId: entry.userId, + discordAvatar: entry.discordAvatar, + fileName: entry.fileName, + }); + stats.applied++; + } + + logger.info(`Synced avatars done: ${JSON.stringify(stats)}`); +} + +async function createCustomAvatarSmallCopies() { + const images = await db + .selectFrom("User") + .innerJoin( + "UnvalidatedUserSubmittedImage", + "UnvalidatedUserSubmittedImage.id", + "User.customAvatarImgId", + ) + .select("UnvalidatedUserSubmittedImage.url") + .execute(); + + let created = 0; + for (let i = 0; i < images.length; i += CUSTOM_AVATAR_CONCURRENCY) { + await Promise.all( + images.slice(i, i + CUSTOM_AVATAR_CONCURRENCY).map(async ({ url }) => { + const smallFileName = smallImageFileName(url); + if (await existsInS3(smallFileName)) return; + + const response = await fetch(userSubmittedImageUrl(url)); + if (!response.ok) { + logger.warn(`Custom avatar ${url} responded with ${response.status}`); + return; + } + + const buffer = Buffer.from(await response.arrayBuffer()); + const extension = imageExtensionFromMagicBytes(buffer); + invariant(extension, `Custom avatar ${url} is not a supported image`); + + await uploadImmutableToS3({ + key: smallFileName, + body: await smallImageCopy(buffer, extension), + contentType: `image/${extension}`, + }); + created++; + }), + ); + } + + logger.info( + `Custom avatar small copies done: ${created} created of ${images.length}`, + ); +} diff --git a/scripts/migrate-avatars-copy.ts b/scripts/migrate-avatars-copy.ts new file mode 100644 index 000000000..d0e5ad4c7 --- /dev/null +++ b/scripts/migrate-avatars-copy.ts @@ -0,0 +1,221 @@ +// Avatar migration part 1/2, run locally against a fresh production snapshot so the Discord CDN +// rate limits hit your machine instead of Render: copies the Discord avatars of users active in the +// last year to S3 and uploads a manifest of them, which `migrate-avatars-apply.ts` (part 2/2) then +// writes to the production database. Inactive users get theirs copied when they next log in. +// Resumable: avatars already in S3 are not downloaded again. +// +// usage: pnpm run download-prod-db && cross-env DB_PATH=db-sandbox.sqlite3 \ +// STORAGE_END_POINT=... STORAGE_ACCESS_KEY=... STORAGE_SECRET=... STORAGE_REGION=... STORAGE_BUCKET=... \ +// vite-node scripts/migrate-avatars-copy.ts [concurrency=4] + +import { subYears } from "date-fns"; +import type { NotNull } from "kysely"; +import { db } from "~/db/sql"; +import * as DiscordAvatar from "~/features/auth/core/DiscordAvatar.server"; +import { + existsInS3, + uploadImmutableToS3, +} from "~/features/img-upload/s3.server"; +import { dateToDatabaseTimestamp } from "~/utils/dates"; +import { logger } from "~/utils/logger"; +import { smallImageFileName } from "~/utils/urls"; + +const MAX_ATTEMPTS = 5; +const DEFAULT_RETRY_DELAY_MS = 5_000; +const DELAY_BETWEEN_BATCHES_MS = 100; +const PROGRESS_LOG_EVERY = 500; + +const concurrency = Number(process.argv[2] ?? 4); + +const users = await activeUsersWithDiscordAvatar(subYears(new Date(), 1)); +logger.info( + `Copying the avatars of ${users.length} users active in the last year`, +); + +const manifest: Array<{ + userId: number; + discordAvatar: string; + fileName: string; +}> = []; +const stats = { copied: 0, alreadyCopied: 0, notFound: 0, failed: 0 }; +const failedUserIds: number[] = []; + +for (let i = 0; i < users.length; i += concurrency) { + await Promise.all( + users.slice(i, i + concurrency).map(async (user) => { + const hash = user.discordAvatar!; + const fileName = DiscordAvatar.fileNameOf({ userId: user.id, hash }); + + // the small copy is uploaded last so it existing means both do + if (await existsInS3(smallImageFileName(fileName))) { + manifest.push({ userId: user.id, discordAvatar: hash, fileName }); + stats.alreadyCopied++; + return; + } + + const result = await withRetries(() => + DiscordAvatar.store({ + userId: user.id, + discordId: user.discordId, + hash, + }), + ); + + if (result === undefined) { + stats.failed++; + failedUserIds.push(user.id); + } else if (result === null) { + stats.notFound++; + } else { + manifest.push({ userId: user.id, discordAvatar: hash, fileName }); + stats.copied++; + } + }), + ); + await sleep(DELAY_BETWEEN_BATCHES_MS); + + const processed = Math.min(i + concurrency, users.length); + if ( + Math.floor(processed / PROGRESS_LOG_EVERY) > + Math.floor(i / PROGRESS_LOG_EVERY) + ) { + logger.info(`${processed}/${users.length}: ${JSON.stringify(stats)}`); + } +} + +logger.info(`Copying done: ${JSON.stringify(stats)}`); +if (failedUserIds.length > 0) { + logger.warn( + `Failed users (rerun the script to retry): ${failedUserIds.join(",")}`, + ); +} + +const manifestFileName = `avatar-manifest-${Date.now()}.json`; +await uploadImmutableToS3({ + key: manifestFileName, + body: new TextEncoder().encode(JSON.stringify(manifest)), + contentType: "application/json", +}); + +logger.info( + `Uploaded the manifest of ${manifest.length} avatars, after deploying run on Render: pnpm exec vite-node scripts/migrate-avatars-apply.ts ${manifestFileName}`, +); + +function activeUsersWithDiscordAvatar(since: Date) { + const cutoff = dateToDatabaseTimestamp(since); + + const activeUserIds = db + .selectFrom("User") + .select("id as userId") + .where("createdAt", ">", cutoff) + .union( + db + .selectFrom("TournamentTeamMember") + .select("userId") + .where("createdAt", ">", cutoff), + ) + .union( + db + .selectFrom("GroupMember") + .select("userId") + .where("createdAt", ">", cutoff), + ) + .union( + db + .selectFrom("Build") + .select("ownerId as userId") + .where("updatedAt", ">", cutoff), + ) + .union( + db + .selectFrom("ChatMessage") + .select("authorUserId as userId") + .where("authorUserId", "is not", null) + .where("createdAt", ">", cutoff) + .$narrowType<{ userId: NotNull }>(), + ) + .union( + db + .selectFrom("LFGPost") + .select("authorId as userId") + .where("updatedAt", ">", cutoff), + ) + .union( + db + .selectFrom("Art") + .select("authorId as userId") + .where("createdAt", ">", cutoff), + ) + .union( + db + .selectFrom("TeamMember") + .select("userId") + .where("createdAt", ">", cutoff), + ) + .union( + db + .selectFrom("FriendRequest") + .select("senderId as userId") + .where("createdAt", ">", cutoff), + ) + .union( + db + .selectFrom("UserFriendCode") + .select("userId") + .where("createdAt", ">", cutoff), + ) + .union( + db + .selectFrom("ScrimPostUser") + .innerJoin("ScrimPost", "ScrimPost.id", "ScrimPostUser.scrimPostId") + .select("ScrimPostUser.userId") + .where("ScrimPost.createdAt", ">", cutoff), + ) + .union( + db + .selectFrom("VoiceSession") + .select("userId") + .where("createdAt", ">", cutoff), + ); + + return db + .selectFrom("User") + .select(["User.id", "User.discordId", "User.discordAvatar"]) + .where("User.discordAvatar", "is not", null) + .where("User.syncedAvatarImgId", "is", null) + .where("User.id", "in", activeUserIds) + .orderBy("User.id", "asc") + .execute(); +} + +/** `undefined` when every attempt failed. Only Discord CDN and network failures are retried. */ +async function withRetries(fn: () => Promise): Promise { + for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) { + try { + return await fn(); + } catch (error) { + const isRetryable = + error instanceof DiscordAvatar.DiscordCdnError || + error instanceof TypeError; + if (!isRetryable) throw error; + + const retryAfterMs = + error instanceof DiscordAvatar.DiscordCdnError && + error.retryAfterSeconds + ? error.retryAfterSeconds * 1000 + : DEFAULT_RETRY_DELAY_MS * attempt; + + logger.warn( + `Attempt ${attempt} failed, retrying in ${retryAfterMs}ms`, + error, + ); + await sleep(retryAfterMs); + } + } + + return undefined; +} + +function sleep(ms: number) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/scripts/seed-art-urls.ts b/scripts/seed-art-urls.ts index b34baaf07..0e47ae01d 100644 --- a/scripts/seed-art-urls.ts +++ b/scripts/seed-art-urls.ts @@ -1,4 +1,10 @@ import { Config } from "~/config"; +import { + ADMIN_TEST_AVATAR, + NZAP_TEST_AVATAR, + NZAP_TEST_ID, +} from "~/db/seed/constants"; +import { ADMIN_ID } from "~/features/admin/admin-constants"; export const SEED_ART_URLS = [ "https://images.unsplash.com/photo-1611627474565-2367887415d1?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwxfDB8MXxyYW5kb218MHx8bmF0dXJlLDF8fHx8fHwxNjg4NTU1NTA2&ixlib=rb-4.0.3&q=80&utm_campaign=api-credit&utm_medium=referral&utm_source=unsplash_source&w=1080", @@ -55,6 +61,19 @@ export const SEED_DEFAULT_TOURNAMENT_LOGO = { filename: Config.tournamentDefaultLogo, }; +/** Avatars in `app/db/seed/img`, uploaded under the file name the seeded users' synced avatar + * points to. */ +export const SEED_AVATARS = [ + { + sourceFilename: "avatar-sendou.webp", + filename: `avatar-${ADMIN_ID}-${ADMIN_TEST_AVATAR}.webp`, + }, + { + sourceFilename: "avatar-nzap.webp", + filename: `avatar-${NZAP_TEST_ID}-${NZAP_TEST_AVATAR}.webp`, + }, +]; + /** How many numbered logos are uploaded. A seed run needing more than this many * ends up with logos that 404 — raise it rather than reusing one, the url column * being unique. */ diff --git a/scripts/seed-images.ts b/scripts/seed-images.ts index 9b89444e1..a5d96fb1c 100644 --- a/scripts/seed-images.ts +++ b/scripts/seed-images.ts @@ -7,6 +7,7 @@ import { logger } from "~/utils/logger"; import { getArtFilename, SEED_ART_URLS, + SEED_AVATARS, SEED_DEFAULT_TOURNAMENT_LOGO, SEED_LOGO_FILENAMES, SEED_NUMBERED_LOGOS, @@ -158,6 +159,7 @@ export async function seedImages(): Promise { })), SEED_DEFAULT_TOURNAMENT_LOGO, ...SEED_NUMBERED_LOGOS, + ...SEED_AVATARS, ].map(({ filename, sourceFilename }) => ({ filename, loadImage: () => readLocalImage(sourceFilename),