'use client' import '@/styles/globals.css' import { useCallback, useEffect, useRef, useState } from 'react' import Sidebar from '@/components/Sidebar' import { DownloadProgress } from '@/types/DownloadProgress' import { app } from '@tauri-apps/api' import { GlobalProvider } from '@/providers/GlobalProvider' import { Roboto } from 'next/font/google' import { ServerVersionsResponse } from '@/types/ServerVersionsResponse' import { listen } from '@tauri-apps/api/event' import { usePathname } from 'next/navigation' import { arch, platform } from '@tauri-apps/plugin-os' import { isPermissionGranted, requestPermission } from '@tauri-apps/plugin-notification' import { BaseDirectory, copyFile, exists, readTextFile, remove } from '@tauri-apps/plugin-fs' import { fetch } from '@tauri-apps/plugin-http' import { openFolder, verifySignature } from '@/lib/util' import { getCurrentWindow, UserAttentionType } from '@tauri-apps/api/window' import { Mod } from '@/types/Mod' import { load, Store } from '@tauri-apps/plugin-store' import { notifyUser } from '@/lib/notifications' import { GameVersion } from '@/types/GameVersion' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faChevronLeft, faXmark } from '@fortawesome/free-solid-svg-icons' import { invoke } from '@tauri-apps/api/core' import semver from 'semver' import { exit } from '@tauri-apps/plugin-process' import { ask, message } from '@tauri-apps/plugin-dialog' import VersionsDownloadPopup from '@/popups/VersionsDownload' import GamesDownloadPopup from '@/popups/GamesDownload' import DownloadsPopup from '@/popups/Downloads' import ManageVersionPopup from '@/popups/ManageVersion' import ModDownloadsPopup from '@/popups/ModDownloads' import VersionChangelogPopup from '@/popups/VersionChangelog' import ManageGamePopup from '@/popups/ManageGame' const roboto = Roboto({ subsets: ['latin'] }) export default function RootLayout ({ children }: { children: React.ReactNode }) { const [loading, setLoading] = useState(true) const [version, setVersion] = useState(null) const [platformName, setPlatformName] = useState(null) const [serverVersionList, setServerVersionList] = useState(null) const [selectedVersionList, setSelectedVersionList] = useState([]) const [showPopup, setShowPopup] = useState(false) const [popupMode, setPopupMode] = useState(null) const [fadeOut, setFadeOut] = useState(false) const [downloadProgress, setDownloadProgress] = useState( [] ) const [downloadQueue, setDownloadQueue] = useState([]) const [isProcessingQueue, setIsProcessingQueue] = useState(false) const [managingVersion, setManagingVersion] = useState(null) const [managingGame, setManagingGame] = useState(null) const [viewingInfoFromDownloads, setViewingInfoFromDownloads] = useState(false) const [selectedGame, setSelectedGame] = useState(null) const [category, setCategory] = useState(-1) const [showModInfo, setShowModInfo] = useState(null) const pathname = usePathname() const revisionCheck = useRef(false) const [settings, setSettings] = useState(null) const [versions, setVersions] = useState(null) const [account, setAccount] = useState(null) const [sidebarShowGames, setSidebarShowGames] = useState(false) const [linuxUseWine, setLinuxUseWine] = useState(false) const [linuxWineCommand, setLinuxWineCommand] = useState('wine %path%') const [theme, setTheme] = useState('dark') const [customDataLocation, setCustomDataLocation] = useState('') const [developerMode, setDeveloperMode] = useState(false) const [versionsList, setVersionsList] = useState>({}) const [modsList, setModsList] = useState< Record> >({}) const [launchesList, setLaunchesList] = useState< Record> >({}) const [accountSession, setAccountSession] = useState(null) const [accountId, setAccountId] = useState(null) const [accountName, setAccountName] = useState(null) const [accountAdmin, setAccountAdmin] = useState(false) const downloadVersions = useCallback( async ( list: Array<{ id: string type: 0 | 1 | 2 modDownload?: number gameId?: number modId?: number modVersion?: string }> ): Promise => { if (list.length === 0) return setSelectedVersionList([]) const newVersions = list.filter( item => !downloadQueue.includes(item.id) && !downloadProgress.some(d => d.version === item.id) ) if (newVersions.length === 0) return const newDownloads = newVersions.map( item => new DownloadProgress( item.id, 0, 0, false, false, false, false, true, false, 0, 0, 0, false, 0, 0, null, null, null, item.type, item.modDownload ?? null, item.gameId ?? null, item.modId ?? null, item.modVersion ?? null ) ) setDownloadProgress(prev => [...prev, ...newDownloads]) setDownloadQueue(prev => [...prev, ...newVersions.map(v => v.id)]) }, [downloadQueue, downloadProgress] ) useEffect(() => { if (isProcessingQueue || downloadQueue.length === 0) return const processNextDownload = async () => { setIsProcessingQueue(true) const versionId = downloadQueue[0] const downloadInfo = downloadProgress.find(d => d.version == versionId) if (!downloadInfo) { setDownloadProgress(prev => prev.filter(d => d.version !== versionId)) setDownloadQueue(prev => prev.slice(1)) setIsProcessingQueue(false) return } const info = serverVersionList?.versions.find(vf => vf.id == versionId) if (!info) { setDownloadProgress(prev => prev.filter(d => d.version !== versionId)) setDownloadQueue(prev => prev.slice(1)) setIsProcessingQueue(false) return } const gameInfo = serverVersionList?.games.find(vf => vf.id == info.game) if (!gameInfo) { setDownloadProgress(prev => prev.filter(d => d.version !== versionId)) setDownloadQueue(prev => prev.slice(1)) setIsProcessingQueue(false) return } setDownloadProgress(prev => prev.map(d => (d.version === versionId ? { ...d, queued: false } : d)) ) const downloadInfoRequest = await fetch( 'https://games.lncvrt.xyz/api/launcher/download' + (downloadInfo.type == 0 ? '?versionId=' + info.id + '&downloadId=' + info.download : '?downloadId=' + (downloadInfo.type == 1 ? info.modSupportDownload : downloadInfo.modDownload)) + (downloadInfo.type == 2 ? '&modId=' + downloadInfo.modId : ''), { headers: { Requester: 'LncvrtGamesLauncherClient', ClientVersion: await app.getVersion(), ClientPlatform: platform() + '-' + arch() } } ) const signature = downloadInfoRequest.headers.get('x-signature') ?? '' const data = await downloadInfoRequest.json() if ( downloadInfoRequest.status != 200 || !(await verifySignature(JSON.stringify(data), signature)) || !data.success ) { setDownloadProgress(prev => prev.map(d => d.version === versionId ? { ...d, queued: false, failed: true, progress: 0 } : d ) ) await notifyUser( 'Download Failed', `The download for version ${info.displayName} has failed.` ) await getCurrentWindow().requestUserAttention( UserAttentionType.Critical ) return } setDownloadProgress(prev => prev.map(d => d.version === versionId ? { ...d, url: data.data.url, executable: downloadInfo.type == 0 ? info.executable : null, hash: data.data.hash } : d ) ) const res = await invoke('download', { url: data.data.url, name: info.id, hash: data.data.hash, downloadType: downloadInfo.type, modId: String(downloadInfo.modId ?? '') }) if (res === '1') { setDownloadProgress(prev => prev.filter(d => d.version !== versionId)) if (downloadInfo.type != 1) { if (downloadInfo.type == 2) { const currentMods = (await versions?.get>>( 'mods' )) ?? {} await versions?.set('mods', { ...currentMods, [downloadInfo.modGame! + '-' + downloadInfo.modId!]: { [downloadInfo.modVersion!]: Date.now() } }) } else { const currentList = (await versions?.get>('list')) ?? {} await versions?.set('list', { ...currentList, [versionId]: Date.now() }) } } } else if (res == '0') { setDownloadProgress(prev => { const i = prev.findIndex(d => d.version === info.id) if (i === -1) return prev if (prev[i].canceled) { return prev.filter((_, idx) => idx !== i) } const copy = [...prev] copy[i] = { ...copy[i], downloading: false, paused: true, failed: false } return copy }) } else if (res == '-1') { setDownloadProgress(prev => prev.map(d => d.version === versionId ? { ...d, queued: false, failed: true, progress: 0 } : d ) ) await notifyUser( 'Download Failed', `The download for version ${info.displayName} has failed.` ) await getCurrentWindow().requestUserAttention( UserAttentionType.Critical ) } setDownloadQueue(prev => prev.slice(1)) setIsProcessingQueue(false) } processNextDownload() }, [ downloadQueue, isProcessingQueue, downloadProgress, serverVersionList, settings, versions, versionsList, modsList ]) function getSpecialVersionsList (game?: number): GameVersion[] { if (!serverVersionList) return [] return serverVersionList.versions .filter(v => !Object.keys(versionsList).includes(v.id)) .filter(v => { if (platformName == 'linux' && v.wine && !linuxUseWine) return false if (game && v.game != game) return false if (category != -1 && v.category != category) return false if (downloadProgress.length != 0) { return !downloadProgress.some(d => d.version === v.id) } return true }) .sort((a, b) => { if (b.game !== a.game) return a.game - b.game return 0 }) } const closePopup = useCallback(() => { if (popupMode == 0 && selectedGame && pathname === '/main/library') { setSelectedGame(null) setSelectedVersionList([]) } else if (viewingInfoFromDownloads) { setViewingInfoFromDownloads(false) setPopupMode(0) } else if (popupMode == 3 && showModInfo) { setShowModInfo(null) } else if (popupMode == 4) { setPopupMode(2) } else { setFadeOut(true) setTimeout(() => setShowPopup(false), 200) } }, [popupMode, selectedGame, pathname, viewingInfoFromDownloads, showModInfo]) const needsRevisionUpdate = ( lastRevision: number | undefined, version: string ) => { if (!lastRevision) return false return ( lastRevision > 0 && (versionsList == undefined ? 0 : versionsList[version]) / 1000 <= lastRevision ) } const uninstallVersion = async ( version: string, updateList: boolean = true ) => { if (updateList) await versions?.set( 'list', Object.fromEntries( Object.entries(versionsList).filter(([k]) => k !== version) ) ) if ( await exists( (customDataLocation ? customDataLocation + '/' : '') + 'game/' + version, { baseDir: customDataLocation ? undefined : BaseDirectory.AppLocalData } ) ) await remove( (customDataLocation ? customDataLocation + '/' : '') + 'game/' + version, { baseDir: customDataLocation ? undefined : BaseDirectory.AppLocalData, recursive: true } ) } const launchGame = async (versionInfo: GameVersion) => { if (needsRevisionUpdate(versionInfo.lastRevision, versionInfo.id)) { const answer = await ask( 'Before proceeding, if you do not want your installation directory wiped just yet, please backup the files to another directory. When you click "Yes", it will be wiped. Click "No" if you want to open the installation folder instead.', { title: 'Revision Update', kind: 'warning' } ) if (answer) { const answer2 = await ask( 'Are you sure you want to update? If you did not read the last popup, please go back and read it.', { title: 'Revision Update', kind: 'warning' } ) if (!answer2) return //open downloads popup setPopupMode(1) setShowPopup(true) setFadeOut(false) //uninstall await uninstallVersion(versionInfo.id) //reinstall setSelectedVersionList([versionInfo.id]) await downloadVersions([ { id: versionInfo.id, type: 0 } ]) } else { await openFolder(versionInfo.id) } return } await invoke('launch_game', { name: versionInfo.id, executable: versionInfo.executable, displayName: versionInfo.displayName, useWine: !!(platform() == 'linux' && versionInfo.wine && linuxUseWine), wineCommand: linuxWineCommand }) await versions?.set('launches', { ...launchesList, [versionInfo.game]: { ...launchesList[versionInfo.game], [versionInfo.id]: Date.now() } }) } useEffect(() => { const unlisteners: (() => void)[] = [] const setupListeners = async () => { unlisteners.push( await listen('download-size', event => { const [displayName, sizeStr] = event.payload.split(':') const size = Number(sizeStr) setDownloadProgress(prev => { const i = prev.findIndex(d => d.version === displayName) if (i === -1) return prev const copy = [...prev] copy[i] = { ...copy[i], size } return copy }) }) ) unlisteners.push( await listen('download-progress', async event => { const [displayName, progStr, totalSizeStr, speedStr, etaSecsStr] = event.payload.split(':') const prog = Number(progStr) const progBytes = Number(totalSizeStr) const speed = Number(speedStr) const etaSecs = Number(etaSecsStr) setDownloadProgress(prev => { const i = prev.findIndex(d => d.version === displayName) if (i === -1) return prev const copy = [...prev] copy[i] = { ...copy[i], progress: prog, progressBytes: progBytes, speed, etaSecs } return copy }) }) ) unlisteners.push( await listen('download-hash-checking', event => { const displayName = event.payload setDownloadProgress(prev => { const i = prev.findIndex(d => d.version === displayName) if (i === -1) return prev const copy = [...prev] copy[i] = { ...copy[i], hash_checking: true, downloading: false } return copy }) }) ) unlisteners.push( await listen('unzip-start', event => { const displayName = event.payload setDownloadProgress(prev => { const i = prev.findIndex(d => d.version === displayName) if (i === -1) return prev const copy = [...prev] copy[i] = { ...copy[i], hash_checking: false, unzipping: true } return copy }) }) ) unlisteners.push( await listen('unzip-progress', async event => { const [displayName, unzippedStr, unzipTotalStr] = event.payload.split(':') const unzipped = Number(unzippedStr) const unzipTotal = Number(unzipTotalStr) setDownloadProgress(prev => { const i = prev.findIndex(d => d.version === displayName) if (i === -1) return prev const copy = [...prev] copy[i] = { ...copy[i], unzipped, unzipTotal } return copy }) }) ) unlisteners.push( await listen('download-start', event => { const displayName = event.payload setDownloadProgress(prev => { const i = prev.findIndex(d => d.version === displayName) if (i === -1) return prev const copy = [...prev] copy[i] = { ...copy[i], downloading: true, paused: false, failed: false } return copy }) }) ) unlisteners.push( await listen('download-stop', event => { const displayName = event.payload setDownloadProgress(prev => { const i = prev.findIndex(d => d.version === displayName) if (i === -1) return prev const copy = [...prev] copy[i] = { ...copy[i], downloading: false } return copy }) }) ) } setupListeners() return () => { unlisteners.forEach(unlisten => unlisten()) } }, []) useEffect(() => { ;(async () => { setPlatformName(platform()) const client = await app.getVersion() setVersion(client) const legacyOptions = { baseDir: BaseDirectory.AppLocalData } if ( platform() == 'windows' && (await exists('versions.json', legacyOptions)) ) { if ( await exists('versions.json', { baseDir: BaseDirectory.AppConfig }) ) await remove('versions.json', { baseDir: BaseDirectory.AppConfig }) await copyFile('versions.json', 'versions.json', { fromPathBaseDir: BaseDirectory.AppLocalData, toPathBaseDir: BaseDirectory.AppConfig }) await remove('versions.json', legacyOptions) } const settingsLocal = await load('settings.json', { autoSave: true, defaults: { version: client, sidebarAlwaysShowGames: true, linuxUseWine: false, linuxWineCommand: 'wine %path%', theme: 'dark', customDataLocation: '', developerMode: false } }) const versionsLocal = await load('versions.json', { autoSave: true, defaults: { version: client, list: {}, mods: {}, launches: {} } }) const accountLocal = await load('account.json', { autoSave: true, defaults: { version: client, session: null, id: null, name: null, admin: false } }) const cfgVer = (await settingsLocal.get('version')) ?? client const versVer = (await versionsLocal.get('version')) ?? client if (semver.gt(cfgVer, client) || semver.gt(versVer, client)) { exit(1) return } await settingsLocal.set('version', client) await versionsLocal.set('version', client) await accountLocal.set('version', client) if (await exists('config.json', legacyOptions)) { const config = await readTextFile('config.json', legacyOptions) const raw = JSON.parse(config) if ( raw.settings && raw.settings.theme && semver.satisfies(raw.version, '>=1.0.0 <=1.5.4') ) { const parsed = Number(raw.settings.theme) if (parsed == 3) raw.settings.theme = 2 if (parsed == 4) raw.settings.theme = 3 else if (parsed != 0 && parsed != 1) raw.settings.theme = 0 } if (raw.settings.allowNotifications) await settingsLocal?.set( 'notificationsAllowed', Boolean(raw.settings.allowNotifications) ) if (raw.settings.alwaysShowGamesInSidebar) await settingsLocal?.set( 'sidebarAlwaysShowGames', Boolean(raw.settings.alwaysShowGamesInSidebar) ) if (raw.settings.useWineOnUnixWhenNeeded) await settingsLocal?.set( 'linuxUseWine', Boolean(raw.settings.useWineOnUnixWhenNeeded) ) if (raw.settings.wineOnUnixCommand) await settingsLocal?.set( 'linuxWineCommand', String(raw.settings.wineOnUnixCommand) ) if (raw.settings.theme) { const tempTheme = (() => { switch (Number(raw.settings.theme)) { case 1: return 'red' case 2: return 'blue' case 3: return 'purple' default: return 'dark' } })() await settingsLocal?.set('theme', tempTheme) } await remove('config.json', legacyOptions) } setSettings(settingsLocal) setVersions(versionsLocal) setAccount(accountLocal) try { const response = await fetch( 'https://games.lncvrt.xyz/api/launcher/versions', { headers: { Requester: 'LncvrtGamesLauncherClient', ClientVersion: await app.getVersion(), ClientPlatform: platform() + '-' + arch(), Authorization: (await accountLocal.get('session')) ?? '' } } ) const signature = response.headers.get('x-signature') ?? '' const data = await response.json() if ( response.status == 200 && (await verifySignature(JSON.stringify(data), signature)) ) { setServerVersionList(data) } else { await message( 'Failed to get version manifest, please try again later.', { title: 'Error fetching launcher manifest', kind: 'error' } ) await exit(1) return } } catch { await message( 'Failed to get version manifest, please try again later.', { title: 'Error fetching launcher manifest', kind: 'error' } ) await exit(1) return } if (!(await isPermissionGranted())) { await requestPermission() } setLoading(false) const window = getCurrentWindow() await window.show() await window.setFocus() })() }, []) useEffect(() => { if (revisionCheck.current) return if (!serverVersionList) return revisionCheck.current = true ;(async () => { for (const [key, value] of Object.entries(versionsList)) { const verInfo = serverVersionList.versions.find(item => item.id === key) if ( verInfo && verInfo.lastRevision > 0 && value / 1000 <= verInfo.lastRevision ) { await invoke('remove_stale_executable', { version: key, executable: verInfo.executable }) } } })() }, [serverVersionList, versionsList]) useEffect(() => { if ( downloadProgress.length === 0 && downloadQueue.length === 0 && showPopup && popupMode === 1 ) { setTimeout(async () => { await notifyUser('Downloads Complete', 'All downloads finished!') await getCurrentWindow().requestUserAttention( UserAttentionType.Informational ) closePopup() }, 0) } }, [downloadProgress, downloadQueue, showPopup, popupMode, closePopup]) useEffect(() => { if (!settings || !versions) return const unlisteners: Promise<() => void>[] = [] function watchSettings (key: string, fn: (v: T | undefined) => void) { settings!.get(key).then(fn) unlisteners.push(settings!.onKeyChange(key, fn)) } function watchVersions (key: string, fn: (v: T | undefined) => void) { versions!.get(key).then(fn) unlisteners.push(versions!.onKeyChange(key, fn)) } function watchAccount (key: string, fn: (v: T | undefined) => void) { account!.get(key).then(fn) unlisteners.push(account!.onKeyChange(key, fn)) } watchSettings('theme', v => setTheme(v ?? 'dark')) watchSettings('sidebarShowGames', v => setSidebarShowGames(v ?? true) ) watchSettings('linuxUseWine', v => setLinuxUseWine(v ?? false)) watchSettings('linuxWineCommand', v => setLinuxWineCommand(v ?? 'wine %path%') ) watchSettings('customDataLocation', v => setCustomDataLocation(v ?? '') ) watchSettings('developerMode', v => setDeveloperMode(v ?? false)) watchVersions>('list', v => setVersionsList(v ?? {})) watchVersions>>('mods', v => setModsList(v ?? {}) ) watchVersions>>('launches', v => setLaunchesList(v ?? {}) ) watchAccount('session', v => setAccountSession(v ?? null)) watchAccount('id', v => setAccountId(v ?? null)) watchAccount('name', v => setAccountName(v ?? null)) watchAccount('admin', v => setAccountAdmin(v ?? false)) return () => { unlisteners.forEach(u => u.then(fn => fn())) } }, [settings, versions, account]) return ( <> {!loading && (
{ if (showPopup && e.key === 'Escape') closePopup() }} > {platformName == 'windows' && (
)}
{children}
{showPopup && (
) => { if (e.target === e.currentTarget) { if (showModInfo) setShowModInfo(null) if (viewingInfoFromDownloads) { setPopupMode(0) setViewingInfoFromDownloads(false) setManagingVersion(null) setSelectedGame(null) } setFadeOut(true) setTimeout(() => setShowPopup(false), 200) } }} >
{popupMode === 0 && selectedGame ? ( ) : popupMode === 0 && !selectedGame ? ( ) : popupMode === 1 ? ( ) : popupMode === 2 ? ( ) : popupMode === 3 ? ( ) : popupMode === 4 ? ( ) : popupMode === 5 ? ( ) : null}
)}
)} ) }