-
Notifications
You must be signed in to change notification settings - Fork 429
Expand file tree
/
Copy pathcontent-install.ts
More file actions
627 lines (576 loc) · 18.7 KB
/
content-install.ts
File metadata and controls
627 lines (576 loc) · 18.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
import type { Labrinth } from '@modrinth/api-client'
import type { ContentInstallInstance, ContentInstallProjectInfo, ContentItem } from '@modrinth/ui'
import { createContext } from '@modrinth/ui'
import { convertFileSrc } from '@tauri-apps/api/core'
import { openUrl } from '@tauri-apps/plugin-opener'
import dayjs from 'dayjs'
import { nextTick, type Ref, ref } from 'vue'
import type { Router } from 'vue-router'
import { trackEvent } from '@/helpers/analytics'
import {
get_organization,
get_project,
get_project_v3_many,
get_team,
get_version_many,
} from '@/helpers/cache.js'
import { create_profile_and_install as packInstall } from '@/helpers/pack'
import {
add_project_from_version,
check_installed_batch,
create,
get,
get_projects,
list,
remove_project,
rename_project_companion_files,
} from '@/helpers/profile.js'
import { get_game_versions } from '@/helpers/tags'
import type { GameInstance, InstanceLoader } from '@/helpers/types'
import {
findPreferredVersion,
installVersionDependencies,
isVersionCompatible,
} from '@/store/install.js'
interface ModalRef {
show: () => void
hide: () => void
}
interface ModpackAlreadyInstalledModalRef {
show: (instanceName: string, instancePath: string) => void
}
interface IncompatibilityWarningModalRef {
show: (
instance: GameInstance,
project: Labrinth.Projects.v2.Project,
versions: Labrinth.Versions.v2.Version[],
version: Labrinth.Versions.v2.Version,
callback: (versionId?: string) => void,
) => void
}
const LOADER_ORDER = ['vanilla', 'fabric', 'quilt', 'neoforge', 'forge']
const SUPPORTED_LOADERS: Set<string> = new Set(['vanilla', 'forge', 'fabric', 'quilt', 'neoforge'])
const VANILLA_COMPATIBLE_LOADERS: Set<string> = new Set(['minecraft', 'datapack'])
function sortLoaders(loaders: string[]): string[] {
return loaders.slice().sort((a, b) => {
const aIdx = LOADER_ORDER.indexOf(a)
const bIdx = LOADER_ORDER.indexOf(b)
if (aIdx === -1 && bIdx === -1) return a.localeCompare(b)
if (aIdx === -1) return 1
if (bIdx === -1) return -1
return aIdx - bIdx
})
}
export interface ContentInstallContext {
instances: Ref<ContentInstallInstance[]>
compatibleLoaders: Ref<string[]>
gameVersions: Ref<string[]>
loading: Ref<boolean>
defaultTab: Ref<'existing' | 'new'>
preferredLoader: Ref<string | null>
preferredGameVersion: Ref<string | null>
releaseGameVersions: Ref<Set<string>>
projectInfo: Ref<ContentInstallProjectInfo | null>
handleInstallToInstance: (instance: ContentInstallInstance) => Promise<void>
handleCreateAndInstall: (data: {
name: string
iconPath: string | null
iconPreviewUrl: string | null
loader: string
gameVersion: string
}) => Promise<void>
handleNavigate: (instance: ContentInstallInstance) => void
handleCancel: () => void
setContentInstallModal: (ref: ModalRef) => void
setModpackAlreadyInstalledModal: (ref: ModpackAlreadyInstalledModalRef) => void
handleModpackDuplicateCreateAnyway: () => Promise<void>
handleModpackDuplicateGoToInstance: (instancePath: string) => void
setIncompatibilityWarningModal: (ref: IncompatibilityWarningModalRef) => void
install: (
projectId: string,
versionId?: string | null,
instancePath?: string | null,
source?: string,
callback?: (versionId?: string) => void,
createInstanceCallback?: (profile: string) => void,
hints?: { preferredLoader?: string; preferredGameVersion?: string; showProjectInfo?: boolean },
) => Promise<void>
installingItems: Ref<Map<string, ContentItem[]>>
}
export const [injectContentInstall, provideContentInstall] = createContext<ContentInstallContext>(
'root',
'contentInstall',
)
export function createContentInstall(opts: {
router: Router
handleError: (err: unknown) => void
}): ContentInstallContext {
const instances = ref<ContentInstallInstance[]>([])
const compatibleLoaders = ref<string[]>([])
const gameVersions = ref<string[]>([])
const loading = ref(false)
const defaultTab = ref<'existing' | 'new'>('existing')
const preferredLoader = ref<string | null>(null)
const preferredGameVersion = ref<string | null>(null)
const releaseGameVersions = ref<Set<string>>(new Set())
const projectInfo = ref<ContentInstallProjectInfo | null>(null)
const installingItems = ref<Map<string, ContentItem[]>>(new Map())
function addInstallingItem(
instancePath: string,
project: {
id: string
slug?: string | null
title: string
icon_url?: string | null
project_type?: string
},
version?: Labrinth.Versions.v2.Version,
) {
const primaryFile = version?.files?.find((f) => f.primary) ?? version?.files?.[0]
const placeholder: ContentItem = {
id: `__installing_${project.id}`,
file_name: `__installing_${project.id}`,
project: {
id: project.id,
slug: project.slug ?? '',
title: project.title,
icon_url: project.icon_url ?? undefined,
},
version: version
? {
id: version.id,
version_number: version.version_number,
file_name: primaryFile?.filename ?? '',
}
: undefined,
project_type: project.project_type ?? 'mod',
has_update: false,
update_version_id: null,
enabled: true,
installing: true,
}
const next = new Map(installingItems.value)
const items = next.get(instancePath) ?? []
if (items.some((i) => i.file_name === placeholder.file_name)) return
next.set(instancePath, [...items, placeholder])
installingItems.value = next
}
function removeInstallingItems(instancePath: string, projectIds: string[]) {
const next = new Map(installingItems.value)
const items = next.get(instancePath)
if (items) {
const idsToRemove = new Set(projectIds.map((id) => `__installing_${id}`))
const filtered = items.filter((i) => !idsToRemove.has(i.file_name))
if (filtered.length > 0) {
next.set(instancePath, filtered)
} else {
next.delete(instancePath)
}
installingItems.value = next
}
}
let modalRef: ModalRef | null = null
let modpackAlreadyInstalledModalRef: ModpackAlreadyInstalledModalRef | null = null
let incompatibilityWarningModalRef: IncompatibilityWarningModalRef | null = null
let currentProject: Labrinth.Projects.v2.Project | null = null
let currentVersions: Labrinth.Versions.v2.Version[] = []
let currentCallback: (versionId?: string) => void = () => {}
let profileMap: Record<string, GameInstance> = {}
let pendingModpackInstall: {
project: Labrinth.Projects.v2.Project
version: string
source: string
callback: (versionId?: string) => void
createInstanceCallback: (profile: string) => void
} | null = null
async function showModInstallModal(
project: Labrinth.Projects.v2.Project,
versions: Labrinth.Versions.v2.Version[],
onInstall: (versionId?: string) => void,
hints?: { preferredLoader?: string; preferredGameVersion?: string; showProjectInfo?: boolean },
) {
currentProject = project
currentVersions = versions
currentCallback = onInstall
instances.value = []
defaultTab.value = 'existing'
if (hints?.showProjectInfo) {
projectInfo.value = {
title: project.title,
iconUrl: project.icon_url,
link: `/project/${project.slug ?? project.id}`,
}
if (project.organization) {
get_organization(project.organization)
.then((org: { id: string; slug: string; name: string; icon_url?: string }) => {
if (projectInfo.value) {
const orgSlug = org.slug ?? org.id
projectInfo.value = {
...projectInfo.value,
owner: {
name: org.name,
iconUrl: org.icon_url,
circle: false,
link: () => openUrl(`https://modrinth.com/organization/${orgSlug}`),
},
}
}
})
.catch(() => {})
} else if (project.team) {
get_team(project.team)
.then(
(
members: {
user: { id: string; username: string; avatar_url?: string }
is_owner: boolean
}[],
) => {
const owner = members.find((m) => m.is_owner)
if (owner && projectInfo.value) {
projectInfo.value = {
...projectInfo.value,
owner: {
name: owner.user.username,
iconUrl: owner.user.avatar_url,
circle: true,
link: () => openUrl(`https://modrinth.com/user/${owner.user.username}`),
},
}
}
},
)
.catch(() => {})
}
} else {
projectInfo.value = null
}
const loaderSet = new Set<string>()
const gameVersionSet = new Set<string>()
for (const v of versions) {
for (const l of v.loaders) loaderSet.add(l)
for (const gv of v.game_versions) gameVersionSet.add(gv)
}
const mappedLoaders = new Set<string>()
for (const l of loaderSet) {
if (SUPPORTED_LOADERS.has(l)) mappedLoaders.add(l)
else if (VANILLA_COMPATIBLE_LOADERS.has(l)) mappedLoaders.add('vanilla')
}
compatibleLoaders.value = sortLoaders([...mappedLoaders])
try {
const allGameVersions = await get_game_versions()
const releases = new Set<string>()
const ordered: string[] = []
for (const gv of allGameVersions) {
if (gameVersionSet.has(gv.version)) {
ordered.push(gv.version)
if (gv.version_type === 'release') {
releases.add(gv.version)
}
}
}
gameVersions.value = ordered
releaseGameVersions.value = releases
} catch {
gameVersions.value = [...gameVersionSet]
releaseGameVersions.value = new Set(gameVersionSet)
}
preferredLoader.value =
hints?.preferredLoader && loaderSet.has(hints.preferredLoader) ? hints.preferredLoader : null
preferredGameVersion.value =
hints?.preferredGameVersion && gameVersionSet.has(hints.preferredGameVersion)
? hints.preferredGameVersion
: null
try {
let profiles = await list()
const linkedProjectIds = profiles
.filter((p) => p.linked_data?.project_id)
.map((p) => p.linked_data!.project_id)
if (linkedProjectIds.length > 0) {
const linkedProjects = await get_project_v3_many(linkedProjectIds, 'must_revalidate').catch(
() => [],
)
const serverProjectIds = new Set(
linkedProjects
.filter((p: { id: string; minecraft_server?: unknown }) => p?.minecraft_server != null)
.map((p: { id: string }) => p.id),
)
profiles = profiles.filter(
(p) => !p.linked_data?.project_id || !serverProjectIds.has(p.linked_data.project_id),
)
}
const newProfileMap: Record<string, GameInstance> = {}
const installedMap = await check_installed_batch(project.id)
const newInstances: ContentInstallInstance[] = profiles.map((profile) => {
newProfileMap[profile.path] = profile
return {
id: profile.path,
name: profile.name,
iconUrl: profile.icon_path ? convertFileSrc(profile.icon_path) : null,
installed: installedMap[profile.path] ?? false,
compatible: versions.some((v) => isVersionCompatible(v, project, profile)),
installing: false,
}
})
profileMap = newProfileMap
instances.value = newInstances
if (!newInstances.some((i) => i.compatible && !i.installed)) {
defaultTab.value = 'new'
}
} catch (err) {
opts.handleError(err)
}
await nextTick()
modalRef?.show()
trackEvent('ProjectInstallStart', { source: 'ProjectInstallModal' })
}
async function handleInstallToInstance(instance: ContentInstallInstance) {
const profile = profileMap[instance.id]
const storeInstance = instances.value.find((i) => i.id === instance.id)
if (storeInstance) storeInstance.installing = true
const version = findPreferredVersion(currentVersions, currentProject, profile)
if (!version) {
if (storeInstance) storeInstance.installing = false
opts.handleError('No compatible version found')
return
}
const installedProjectIds: string[] = []
if (currentProject) {
addInstallingItem(instance.id, currentProject, version)
installedProjectIds.push(currentProject.id)
}
try {
await add_project_from_version(instance.id, version.id)
await installVersionDependencies(
profile,
version,
(depProject: Labrinth.Projects.v2.Project, depVersion?: Labrinth.Versions.v2.Version) => {
addInstallingItem(instance.id, depProject, depVersion)
installedProjectIds.push(depProject.id)
},
)
if (storeInstance) {
storeInstance.installed = true
storeInstance.installing = false
}
trackEvent('ProjectInstall', {
loader: profile.loader,
game_version: profile.game_version,
id: currentProject!.id,
version_id: version.id,
project_type: currentProject!.project_type,
title: currentProject!.title,
source: 'ProjectInstallModal',
})
currentCallback(version.id)
} catch (err) {
if (storeInstance) storeInstance.installing = false
opts.handleError(err)
} finally {
removeInstallingItems(instance.id, installedProjectIds)
}
}
async function handleCreateAndInstall(data: {
name: string
iconPath: string | null
iconPreviewUrl: string | null
loader: string
gameVersion: string
}) {
const loaderCandidates =
data.loader === 'vanilla' ? ['vanilla', 'datapack', 'minecraft'] : [data.loader]
const version =
currentVersions.find(
(v) =>
v.game_versions.includes(data.gameVersion) &&
loaderCandidates.some((l) => v.loaders.includes(l)),
) ?? currentVersions[0]
try {
const id = await create(
data.name,
data.gameVersion,
data.loader as InstanceLoader,
'latest',
data.iconPath,
false,
)
if (!id) return
await add_project_from_version(id, version.id)
await opts.router.push(`/instance/${encodeURIComponent(id)}/`)
const instance = await get(id)
await installVersionDependencies(instance, version)
trackEvent('InstanceCreate', {
source: 'ProjectInstallModal',
})
trackEvent('ProjectInstall', {
loader: data.loader,
game_version: data.gameVersion,
id: currentProject!.id,
version_id: version.id,
project_type: currentProject!.project_type,
title: currentProject!.title,
source: 'ProjectInstallModal',
})
currentCallback(version.id)
modalRef?.hide()
} catch (err) {
opts.handleError(err)
}
}
function handleNavigate(instance: ContentInstallInstance) {
modalRef?.hide()
opts.router.push(`/instance/${encodeURIComponent(instance.id)}/`)
}
function handleCancel() {
currentCallback?.()
}
async function install(
projectId: string,
versionId?: string | null,
instancePath?: string | null,
source: string = 'unknown',
callback: (versionId?: string) => void = () => {},
createInstanceCallback: (profile: string) => void = () => {},
hints?: { preferredLoader?: string; preferredGameVersion?: string; showProjectInfo?: boolean },
) {
const project: Labrinth.Projects.v2.Project = await get_project(projectId, 'must_revalidate')
if (project.project_type === 'modpack') {
const version = versionId ?? project.versions[project.versions.length - 1]
const packs = await list()
const existingPack = packs.find((pack) => pack.linked_data?.project_id === project.id)
if (existingPack) {
pendingModpackInstall = { project, version, source, callback, createInstanceCallback }
modpackAlreadyInstalledModalRef?.show(existingPack.name, existingPack.path)
return
}
await packInstall(
project.id,
version,
project.title,
project.icon_url,
createInstanceCallback,
)
trackEvent('PackInstall', {
id: project.id,
version_id: version,
title: project.title,
source,
})
callback(version)
} else if (instancePath) {
const [instanceOrNull, instanceProjects, versions] = await Promise.all([
get(instancePath),
get_projects(instancePath),
get_version_many(project.versions, 'must_revalidate') as Promise<
Labrinth.Versions.v2.Version[]
>,
])
if (!instanceOrNull) return
const instance = instanceOrNull
const projectVersions = versions.sort(
(a, b) => dayjs(b.date_published).valueOf() - dayjs(a.date_published).valueOf(),
)
let version = versionId
? projectVersions.find((v) => v.id === versionId)
: findPreferredVersion(projectVersions, project, instance)
if (!version) version = projectVersions[0]
if (isVersionCompatible(version, project, instance)) {
let projectOldPath: string | null = null
for (const [path, file] of Object.entries(instanceProjects)) {
if (file.metadata?.project_id === project.id) {
await remove_project(instance.path, path)
projectOldPath = path
}
}
const installedProjectIds: string[] = [project.id]
addInstallingItem(instancePath, project, version)
try {
const projectPath = await add_project_from_version(instance.path, version.id)
await installVersionDependencies(
instance,
version,
(
depProject: Labrinth.Projects.v2.Project,
depVersion?: Labrinth.Versions.v2.Version,
) => {
addInstallingItem(instancePath, depProject, depVersion)
installedProjectIds.push(depProject.id)
},
)
if (project.project_type == 'shader' && projectOldPath) {
await rename_project_companion_files(instance.path, projectOldPath, projectPath)
}
trackEvent('ProjectInstall', {
loader: instance.loader,
game_version: instance.game_version,
id: project.id,
project_type: project.project_type,
version_id: version.id,
title: project.title,
source,
})
callback(version.id)
} finally {
removeInstallingItems(instancePath, installedProjectIds)
}
} else {
incompatibilityWarningModalRef?.show(instance, project, projectVersions, version, callback)
}
} else {
let versions = (
(await get_version_many(project.versions)) as Labrinth.Versions.v2.Version[]
).sort((a, b) => dayjs(b.date_published).valueOf() - dayjs(a.date_published).valueOf())
if (versionId) versions = versions.filter((v) => v.id === versionId)
await showModInstallModal(project, versions, callback, hints)
}
}
return {
instances,
compatibleLoaders,
gameVersions,
loading,
defaultTab,
preferredLoader,
preferredGameVersion,
releaseGameVersions,
projectInfo,
handleInstallToInstance,
handleCreateAndInstall,
handleNavigate,
handleCancel,
setContentInstallModal(ref: ModalRef) {
modalRef = ref
},
setModpackAlreadyInstalledModal(ref: ModpackAlreadyInstalledModalRef) {
modpackAlreadyInstalledModalRef = ref
},
async handleModpackDuplicateCreateAnyway() {
if (!pendingModpackInstall) return
const { project, version, source, callback, createInstanceCallback } = pendingModpackInstall
pendingModpackInstall = null
await packInstall(
project.id,
version,
project.title,
project.icon_url,
createInstanceCallback,
)
trackEvent('PackInstall', {
id: project.id,
version_id: version,
title: project.title,
source,
})
callback(version)
},
handleModpackDuplicateGoToInstance(instancePath: string) {
pendingModpackInstall = null
opts.router.push(`/instance/${encodeURIComponent(instancePath)}/`)
},
setIncompatibilityWarningModal(ref: IncompatibilityWarningModalRef) {
incompatibilityWarningModalRef = ref
},
install,
installingItems,
}
}