Files
modrinth/apps/app-frontend/src/providers/server-install.ts
T
734720e11e feat: instances v2 (#6431)
* feat: base of instances v2

* feat: use old profiles with compat layer

* prototype: instances v2

* fix: install_from using profile

* fix: skins migration fix

* fix: frontend still using profile path

* fix: add update proj multiselect guard

* fix: cargo fmt

* fix: content missing fields

* feat: break up app-lib/api/instance.rs

* fix: check_content_updates mismatch

* fix: updater modal cleanup w/new structure

* feat: better update all handling

* fix: remove preview_update_all

* fix: feedback on bulk update + lint

* fix: rem transitions

* fix: change to jsonb

* feat: app db backup after update

* fix: lint

* fix: sqlx prepare + use sqlx macros

* fix: lint

* fix: bugs

* feat: defuck the installing process up

* fix: bug of hell

* fix: shear

* fix: fmt

* fix: install progress spacing + change mc/content/overrides to bytes

* fix: lint

* fix: prepr

* fix: navtabs anim not working in app

* fix: worlds.vue improvements + browse page fixes

* feat: optimise queries + adapter fns

* fix: lint

* fix: lint

* feat: shared modrinth-content-management crate (#6469)

* feat: disable warnings setting

* feat: add instances shortcuts (#6329)

* Add modrinth://launch deep link to start a profile

Support external profile launching via modrinth://launch/{profile_path} for integrations such as Stream Deck.

* Change route to /launch/profile/{id} for future extensibility

* fix: ensure profile path is url decoded

* fix: URL-decode profile path from deep link

* fix: use urlencoding crate for URL decoding

* feat: implement app instance shortcuts

* feat: change windows shortcut creation to use windows api instead

* feat: implement creating a shortcut launching world/server

* format

* fmt

* fix multiline inline tables

* pnpm prepr

* feat: move create shortcut to last item

* refactor: split up shortcuts.rs for individual platforms

* refactor: turn profile launch url into url type

* use string literal and add safety comment

* pt2

* refactor: rename anything that's profile into instance

* update mac shortcut

---------

Co-authored-by: DJCheesusReal <134006619+DJCheesusReal@users.noreply.github.com>

---------

Co-authored-by: Truman Gao <106889354+tdgao@users.noreply.github.com>
Co-authored-by: DJCheesusReal <134006619+DJCheesusReal@users.noreply.github.com>
2026-06-25 21:19:29 +00:00

383 lines
12 KiB
TypeScript

import type { Labrinth } from '@modrinth/api-client'
import type { AbstractPopupNotificationManager } from '@modrinth/ui'
import { createContext } from '@modrinth/ui'
import { type Ref, ref } from 'vue'
import type { Router } from 'vue-router'
import { trackEvent } from '@/helpers/analytics'
import { get_project, get_project_v3, get_version } from '@/helpers/cache.js'
import {
install_create_instance,
install_create_modpack_instance,
install_existing_instance,
installJobInstanceId,
wait_for_install_job,
} from '@/helpers/install'
import { edit, get, list } from '@/helpers/instance'
import type { GameInstance } from '@/helpers/types'
import { ensureManagedServerWorldExists, getServerAddress } from '@/helpers/worlds'
import { start_join_server } from '@/helpers/worlds.ts'
import { handleSevereError } from '@/store/error.js'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
interface ModalRef<TShow extends (...args: any[]) => void = () => void> {
show: TShow
hide: () => void
}
export interface ServerInstallContext {
installingServerProjects: Ref<string[]>
startInstallingServer: (projectId: string) => void
stopInstallingServer: (projectId: string) => void
isServerInstalling: (projectId: string) => boolean
installServerProject: (serverProjectId: string) => Promise<void>
playServerProject: (projectId: string) => Promise<void>
setInstallToPlayModal: (
ref: ModalRef<
(
project: Labrinth.Projects.v3.Project,
modpackVersionId: string | null,
callback?: () => void,
) => void
>,
) => void
setUpdateToPlayModal: (
ref: ModalRef<
(instance: GameInstance, activeVersionId: string | null, callback?: () => void) => void
>,
) => void
setAddServerToInstanceModal: (
ref: ModalRef<(serverName: string, serverAddress: string) => void>,
) => void
showAddServerToInstanceModal: (serverName: string, serverAddress: string) => void
}
let _serverInstallSingleton: ServerInstallContext | null = null
const [_rawInjectServerInstall, provideServerInstall] = createContext<ServerInstallContext>(
'root',
'serverInstall',
)
export { provideServerInstall }
export function injectServerInstall(): ServerInstallContext {
try {
return _rawInjectServerInstall()
} catch {
if (_serverInstallSingleton) return _serverInstallSingleton
throw new Error('ServerInstall context not available')
}
}
export function createServerInstall(opts: {
router: Router
handleError: (err: unknown) => void
popupNotificationManager: AbstractPopupNotificationManager
}): ServerInstallContext {
const installingServerProjects = ref<string[]>([])
let installToPlayModalRef: ModalRef<
(
project: Labrinth.Projects.v3.Project,
modpackVersionId: string | null,
callback?: () => void,
) => void
> | null = null
let updateToPlayModalRef: ModalRef<
(instance: GameInstance, activeVersionId: string | null, callback?: () => void) => void
> | null = null
let addServerToInstanceModalRef: ModalRef<
(serverName: string, serverAddress: string) => void
> | null = null
function startInstallingServer(projectId: string) {
if (!installingServerProjects.value.includes(projectId)) {
installingServerProjects.value.push(projectId)
}
}
function stopInstallingServer(projectId: string) {
installingServerProjects.value = installingServerProjects.value.filter((id) => id !== projectId)
}
function isServerInstalling(projectId: string) {
return installingServerProjects.value.includes(projectId)
}
async function joinServer(instanceId: string, serverAddress: string | null) {
if (!serverAddress) return
await start_join_server(instanceId, serverAddress)
}
async function findInstalledInstance(projectId: string) {
const packs = await list()
return packs.find((pack) => pack.link?.project_id === projectId) ?? null
}
async function createVanillaInstance(
project: Labrinth.Projects.v2.Project,
gameVersion: string,
serverAddress: string | null,
) {
const job = await install_create_instance({
name: project.title,
gameVersion,
loader: 'vanilla',
loaderVersion: null,
iconPath: project.icon_url ?? null,
link: {
type: 'server_project',
project_id: project.id,
},
})
const instanceId = installJobInstanceId(job)
if (!instanceId) return null
await wait_for_install_job(job.job_id)
await ensureManagedServerWorldExists(instanceId, project.title, serverAddress)
return instanceId
}
async function updateVanillaGameVersion(instance: GameInstance, targetGameVersion: string) {
if (instance.game_version === targetGameVersion) return
await edit(instance.id, { game_version: targetGameVersion })
const job = await install_existing_instance(instance.id, false)
await wait_for_install_job(job.job_id)
}
function showModpackInstallSuccess(project: GameInstance, serverAddress: string | null) {
opts.popupNotificationManager.addPopupNotification({
title: 'Install complete',
text: `${project.name} is installed and ready to play.`,
type: 'success',
buttons: [
...(serverAddress
? [
{
label: 'Launch game',
action: async () => {
try {
await joinServer(project.id, serverAddress)
trackEvent('InstanceStart', {
loader: project.loader,
game_version: project.game_version,
source: 'ServerProject',
})
} catch (err) {
handleSevereError(err, { instanceId: project.id })
}
},
color: 'brand' as const,
},
]
: []),
{
label: 'Instance',
action: () => opts.router.push(`/instance/${encodeURIComponent(project.id)}`),
},
],
autoCloseMs: null,
})
}
function showUpdateSuccess(instance: GameInstance, serverAddress: string | null) {
opts.popupNotificationManager.addPopupNotification({
title: 'Update complete',
text: `${instance.name} has been updated and is ready to play.`,
type: 'success',
buttons: [
...(serverAddress
? [
{
label: 'Launch game',
action: async () => {
try {
if (serverAddress) await start_join_server(instance.id, serverAddress)
trackEvent('InstanceStart', {
loader: instance.loader,
game_version: instance.game_version,
source: 'ServerProject',
})
} catch (err) {
handleSevereError(err, { instanceId: instance.id })
}
},
color: 'brand' as const,
},
]
: []),
{
label: 'Instance',
action: () => opts.router.push(`/instance/${encodeURIComponent(instance.id)}`),
},
],
autoCloseMs: null,
})
}
/**
* Server projects that use modpack content have link.project_id as
* the server project id and link.version_id as the modpack content version id.
* The modpack content version can be of the same server project, or from a different project.
*/
async function installServerProject(serverProjectId: string) {
const [project, projectV3] = await Promise.all([
get_project(serverProjectId, 'bypass'),
get_project_v3(serverProjectId, 'bypass'),
])
const serverAddress = getServerAddress(projectV3?.minecraft_java_server)
const content = projectV3?.minecraft_java_server?.content
if (!content || content.kind !== 'modpack') return
const contentVersionId = content.version_id
const contentVersion = await get_version(contentVersionId, 'bypass')
const contentProjectId = contentVersion.project_id
const createJob = await install_create_modpack_instance(
{
type: 'fromVersionId',
project_id: contentProjectId,
version_id: contentVersionId,
title: project.title,
},
{
name: project.title,
iconPath: project.icon_url ?? null,
link: {
type: 'server_project_modpack',
server_project_id: serverProjectId,
content_project_id: contentProjectId,
content_version_id: contentVersionId,
project_id: serverProjectId,
version_id: contentVersionId,
},
},
)
const instanceId = installJobInstanceId(createJob)
if (!instanceId) return
await wait_for_install_job(createJob.job_id)
await ensureManagedServerWorldExists(instanceId, project.title, serverAddress)
}
/**
* Handles logic when clicking "Play" on a server project. This includes:
* - Checking if need to install modpack content. If so, opens install to play modal
* - Checking if need to update modpack content. If so, open update to play modal
* - Checking if need to create instance for vanilla server. If so, creates instance.
* - Adding server to worlds list if not already there
* - Joining server
*/
async function playServerProject(projectId: string) {
const [project, projectV3] = await Promise.all([
get_project(projectId, 'bypass'),
get_project_v3(projectId, 'bypass'),
])
if (projectV3?.minecraft_server == null) {
console.warn('playServerProject failed: project is not a server project')
return
}
const content = projectV3?.minecraft_java_server?.content
const serverAddress = getServerAddress(projectV3?.minecraft_java_server)
const isVanilla = content?.kind === 'vanilla'
const isModpack = content?.kind === 'modpack'
const modpackVersionId = content?.version_id ?? null
const recommendedGameVersion = content?.recommended_game_version
let instance = await findInstalledInstance(project.id)
if (isVanilla && !instance) {
if (installingServerProjects.value.includes(projectId)) return
startInstallingServer(projectId)
try {
const instanceId = await createVanillaInstance(
project,
recommendedGameVersion,
serverAddress,
)
if (instanceId) {
instance = await get(instanceId)
if (instance) showModpackInstallSuccess(instance, serverAddress)
}
} finally {
stopInstallingServer(projectId)
}
return
}
if (isModpack && !instance) {
installToPlayModalRef?.show(projectV3, modpackVersionId, async () => {
const newInstance = await findInstalledInstance(project.id)
if (!newInstance) return
showModpackInstallSuccess(newInstance, serverAddress)
})
return
}
if (!instance) return
await ensureManagedServerWorldExists(instance.id, project.title, serverAddress)
// Update existing instance if needed
if (isModpack && instance.link?.version_id !== modpackVersionId) {
updateToPlayModalRef?.show(instance, modpackVersionId, () => {
showUpdateSuccess(instance, serverAddress)
})
return
}
if (isVanilla && instance.game_version !== recommendedGameVersion) {
if (installingServerProjects.value.includes(projectId)) return
startInstallingServer(projectId)
try {
await updateVanillaGameVersion(instance, recommendedGameVersion)
showUpdateSuccess(instance, serverAddress)
} finally {
stopInstallingServer(projectId)
}
return
}
// Join server
try {
await joinServer(instance.id, serverAddress)
trackEvent('InstanceStart', {
loader: instance.loader,
game_version: instance.game_version,
source: 'ServerProject',
})
} catch (err) {
handleSevereError(err, { instanceId: instance.id })
}
}
const context: ServerInstallContext = {
installingServerProjects,
startInstallingServer,
stopInstallingServer,
isServerInstalling,
installServerProject,
playServerProject,
setInstallToPlayModal(ref) {
installToPlayModalRef = ref
},
setUpdateToPlayModal(ref) {
updateToPlayModalRef = ref
},
setAddServerToInstanceModal(ref) {
addServerToInstanceModalRef = ref
},
showAddServerToInstanceModal(serverName: string, serverAddress: string) {
addServerToInstanceModalRef?.show(serverName, serverAddress)
},
}
_serverInstallSingleton = context
return context
}