Files
modrinth/apps/frontend/src/helpers/moderation.ts
T
Calum H.andsychic e58af98f21 feat: instance sharing thru shared-instances service (#6569)
* feat: implement instance share page + search_users backend call

* feat: invite players modal

* feat: use tanstack queries for friends sync across app pages

* feat: base shared instances implementation

* fix: admon style

* feat: impl instance admonitions like server panel

* fix: impl get + del usage

* feat: support modpack links

* feat: invite notif accepting

* fix: lint + fmt

* feat: impl install to play

* feat: impl usage of UpdateToPlayModal

* feat: warnings on deleting/disabling shared-instance version content

* fix: send instance name

* feat: align with backend

* feat: shared instances qa

* feat: wrong account protection

* feat: qa

* fix: smartly apply updates

* fix: install bug

* fix: 401/404 differentiation

* fix: fmt+prepr

* feat: qa

* feat: qa

* fix: signing out messes up revoke/deleted checks

* feat: qa

* fix: fmt + lint

* feat: lock content if part of shared instance

* fix: lint

* [do not merge] feat: rough invite links impl temp (#6666)

* fix: wrong cmd

* feat: invite page

* fix: server-manager DTO mismatch

* fix: drop anonymous invite link acceptance

* refactor: structured shared-instance unavailable errors

* refactor: centralise error presentations

* refactor: dedupe shared instance diff detection

* fix: logging in reqwests

* refactor: move app.vue shared instances into handler

* refactor: break up Share.vue

* refactor: split up shared instances state outside of instance index

* refactor: dedicated shared instances install/update modals + split up page

* refactor: centralized managed content

* refactor: split up install shared to own runner + shared.rs split up

* refactor: dedupe sql for instance metadata enrichmnt

* refactor: friends composable + dedupe friends logic across usages

* chore: reduced unused code

* fix: align with backend

* fix: lint

* fix: file sha changes

* fix: invite links not working due to icon signed

* feat: qa

* feat: reporting frontend dummy

* fix: try use header

* remove: file hash field

* fix: pin box

* feat: malware warning for shared instances

* fix: cache rule

* feat: config files syncing

* feat: disable config sharing

* fix: header

* fix: use mark ready

* fix: dont cause push update for configs

* fix: lint

* feat: sharing page in settings

* feat: move config + change flow

* fix: qa

* fix: lint prepr

* feat: proxy file upload thru shared instances backend

* fix: use collapisible

* fix: push config

* fix: config

* feat: swap out sign in modal for new one

* fix: report flow

* fix: exclude configs.zip from external warnings

* fix: nuxi init

* fix: config bundle downloading

* fix: error notif

* fix: polling

* fix: qa

* fix: lint + prepr

* feat: shared instances moderation frontend + hook up report flow

* fix: report copy

* fix: lint

* fix: lint

* fix: modrinth ids being undefined

* feat: instance quarantining

* fix: prepr + fmt

* fix: quarantined -> locked terminology

* fix: missing endpoint impls + fmt

* fix: missing api in build.rs

* fix: share tab jittery

* fix: fmt

*PT bug

* fix: invites count as users even if pending

* fix: prepr

* fix: invite page owner in users list

* fix: lint

* fix: qa

* fix: lint

* fix: members stale not clearing

* fix: invite use joined_at field

* fix: lint

* fix: qa

---------

Co-authored-by: sychic <47618543+Sychic@users.noreply.github.com>
2026-07-24 13:06:38 +00:00

238 lines
7.4 KiB
TypeScript

import type { AbstractModrinthClient, Labrinth, SharedInstances } from '@modrinth/api-client'
import type { ExtendedReport, OwnershipTarget } from '@modrinth/moderation'
import type { Organization, Project, TeamMember, Thread, User, Version } from '@modrinth/utils'
export const useModerationCache = () => ({
threads: useState<Map<string, Thread>>('moderation-report-cache-threads', () => new Map()),
users: useState<Map<string, User>>('moderation-report-cache-users', () => new Map()),
projects: useState<Map<string, Project>>('moderation-report-cache-projects', () => new Map()),
versions: useState<Map<string, Version>>('moderation-report-cache-versions', () => new Map()),
teams: useState<Map<string, TeamMember[]>>('moderation-report-cache-teams', () => new Map()),
orgs: useState<Map<string, Organization>>('moderation-report-cache-orgs', () => new Map()),
sharedInstances: useState<Map<string, SharedInstances.Instances.v1.Instance>>(
'moderation-report-cache-shared-instances',
() => new Map(),
),
})
// TODO: @AlexTMjugador - backend should do all of these functions.
export async function enrichReportBatch(
reports: Labrinth.Reports.v3.Report[],
client: AbstractModrinthClient,
): Promise<ExtendedReport[]> {
if (reports.length === 0) return []
const cache = useModerationCache()
const threadIDs = reports
.map((r) => r.thread_id)
.filter(Boolean)
.filter((id) => !cache.threads.value.has(id))
const userIDs = [
...reports.filter((r) => r.item_type === 'user').map((r) => r.item_id),
...reports.map((r) => r.reporter),
].filter((id) => !cache.users.value.has(id))
const versionIDs = reports
.filter((r) => r.item_type === 'version')
.map((r) => r.item_id)
.filter((id) => !cache.versions.value.has(id))
const projectIDs = reports
.filter((r) => r.item_type === 'project')
.map((r) => r.item_id)
.filter((id) => !cache.projects.value.has(id))
const sharedInstanceIDs = [
...new Set(
reports
.filter((r) => r.item_type === 'shared-instance')
.map((r) => r.item_id)
.filter((id) => !cache.sharedInstances.value.has(id)),
),
]
const [newThreads, newVersions, newUsers, newSharedInstances] = await Promise.all([
threadIDs.length > 0
? (fetchSegmented(threadIDs, (ids) => `threads?ids=${asEncodedJsonArray(ids)}`) as Promise<
Thread[]
>)
: Promise.resolve([]),
versionIDs.length > 0
? (fetchSegmented(versionIDs, (ids) => `versions?ids=${asEncodedJsonArray(ids)}`) as Promise<
Version[]
>)
: Promise.resolve([]),
[...new Set(userIDs)].length > 0
? (fetchSegmented(
[...new Set(userIDs)],
(ids) => `users?ids=${asEncodedJsonArray(ids)}`,
) as Promise<User[]>)
: Promise.resolve([]),
Promise.allSettled(
sharedInstanceIDs.map(async (instanceId) => ({
id: instanceId,
instance: await client.sharedinstances.instances_v1.get(instanceId),
})),
),
])
newThreads.forEach((t) => cache.threads.value.set(t.id, t))
newVersions.forEach((v) => cache.versions.value.set(v.id, v))
newUsers.forEach((u) => cache.users.value.set(u.id, u))
newSharedInstances.forEach((result) => {
if (result.status === 'fulfilled') {
cache.sharedInstances.value.set(result.value.id, result.value.instance)
}
})
const allVersions = [...newVersions, ...Array.from(cache.versions.value.values())]
const fullProjectIds = new Set([
...projectIDs,
...allVersions
.filter((v) => versionIDs.includes(v.id))
.map((v) => v.project_id)
.filter(Boolean),
])
const uncachedProjectIds = Array.from(fullProjectIds).filter(
(id) => !cache.projects.value.has(id),
)
const newProjects =
uncachedProjectIds.length > 0
? ((await fetchSegmented(
uncachedProjectIds,
(ids) => `projects?ids=${asEncodedJsonArray(ids)}`,
)) as Project[])
: []
newProjects.forEach((p) => cache.projects.value.set(p.id, p))
const allProjects = [...newProjects, ...Array.from(cache.projects.value.values())]
const teamIds = [...new Set(allProjects.map((p) => p.team).filter(Boolean))].filter(
(id) => !cache.teams.value.has(id || 'invalid team id'),
)
const orgIds = [...new Set(allProjects.map((p) => p.organization).filter(Boolean))].filter(
(id) => !cache.orgs.value.has(id),
)
const [newTeams, newOrgs] = await Promise.all([
teamIds.length > 0
? (fetchSegmented(teamIds, (ids) => `teams?ids=${asEncodedJsonArray(ids)}`) as Promise<
TeamMember[][]
>)
: Promise.resolve([]),
orgIds.length > 0
? (fetchSegmented(orgIds, (ids) => `organizations?ids=${asEncodedJsonArray(ids)}`, {
apiVersion: 3,
}) as Promise<Organization[]>)
: Promise.resolve([]),
])
newTeams.forEach((team) => {
if (team.length > 0) cache.teams.value.set(team[0].team_id, team)
})
newOrgs.forEach((org) => cache.orgs.value.set(org.id, org))
return reports.map((report) => {
const thread = cache.threads.value.get(report.thread_id) || ({} as Thread)
const version =
report.item_type === 'version' ? cache.versions.value.get(report.item_id) : undefined
const project =
report.item_type === 'project'
? cache.projects.value.get(report.item_id)
: report.item_type === 'version' && version
? cache.projects.value.get(version.project_id)
: undefined
let target: OwnershipTarget | undefined
if (report.item_type === 'user') {
const targetUser = cache.users.value.get(report.item_id)
if (targetUser) {
target = {
name: targetUser.username,
slug: targetUser.username,
avatar_url: targetUser.avatar_url,
type: 'user',
}
}
} else if (project) {
let owner: TeamMember | null = null
let org: Organization | null = null
if (project.team) {
const teamMembers = cache.teams.value.get(project.team)
if (teamMembers) {
owner = teamMembers.find((member) => member.role === 'Owner') || null
}
}
if (project.organization) {
org = cache.orgs.value.get(project.organization) || null
}
if (org) {
target = {
name: org.name,
avatar_url: org.icon_url,
type: 'organization',
slug: org.slug,
}
} else if (owner) {
target = {
name: owner.user.username,
avatar_url: owner.user.avatar_url,
type: 'user',
slug: owner.user.username,
}
}
}
return {
...report,
thread,
reporter_user: cache.users.value.get(report.reporter) || ({} as User),
project,
user: report.item_type === 'user' ? cache.users.value.get(report.item_id) : undefined,
version,
target,
shared_instance:
report.item_type === 'shared-instance'
? cache.sharedInstances.value.get(report.item_id)
: undefined,
}
})
}
// Doesn't need to be in @modrinth/moderation because it is specific to the frontend.
export interface ModerationOwnershipUser {
kind: 'user'
id: string
name: string
icon_url: string | null
}
export interface ModerationOwnershipOrganization {
kind: 'organization'
id: string
name: string
icon_url: string | null
}
export type ModerationOwnership = ModerationOwnershipUser | ModerationOwnershipOrganization
export type ProjectWithOwnership = Labrinth.Moderation.Internal.QueueProject
export interface ModerationProject {
project: Omit<ProjectWithOwnership, 'ownership' | 'external_dependencies_count'>
ownership: ModerationOwnership | null
external_dependencies_count: number
}
export function toModerationProjects(projects: ProjectWithOwnership[]): ModerationProject[] {
return projects.map(({ ownership, external_dependencies_count, ...project }) => ({
project,
ownership: ownership ?? null,
external_dependencies_count: external_dependencies_count,
}))
}