Run prettier formatter

This commit is contained in:
Brian Bowman
2022-07-19 04:37:38 -05:00
parent e9df0f17db
commit eb9aa34323
67 changed files with 1157 additions and 1071 deletions

View File

@@ -3,8 +3,7 @@ import { dataDir } from '@tauri-apps/api/path'
let configFilePath: string
let defaultConfig: Configuration
(async() => {
;(async () => {
defaultConfig = {
toggle_grasscutter: false,
game_install_path: 'C:\\Program Files\\Genshin Impact\\Genshin Impact game\\GenshinImpact.exe',
@@ -57,8 +56,8 @@ export interface Configuration {
export async function setConfigOption<K extends keyof Configuration>(key: K, value: Configuration[K]): Promise<void> {
const config = await getConfig()
config[key] = value
await saveConfig(<Configuration> config)
await saveConfig(<Configuration>config)
}
export async function getConfigOption<K extends keyof Configuration>(key: K): Promise<Configuration[K]> {
@@ -71,13 +70,13 @@ export async function getConfigOption<K extends keyof Configuration>(key: K): Pr
export async function getConfig() {
const raw = await readConfigFile()
let parsed: Configuration = defaultConfig
try {
parsed = <Configuration> JSON.parse(raw)
} catch(e) {
parsed = <Configuration>JSON.parse(raw)
} catch (e) {
// We could not open the file
console.log(e)
// TODO: Create a popup saying the config file is corrupted.
}
@@ -100,7 +99,7 @@ async function readConfigFile() {
if (!dirs.find((fileOrDir) => fileOrDir?.name === 'cultivation')) {
// Create dir
await fs.createDir(local + 'cultivation').catch(e => console.log(e))
await fs.createDir(local + 'cultivation').catch((e) => console.log(e))
}
const innerDirs = await fs.readDir(local + '/cultivation')
@@ -108,7 +107,7 @@ async function readConfigFile() {
// Create grasscutter dir for potential installation
if (!innerDirs.find((fileOrDir) => fileOrDir?.name === 'grasscutter')) {
// Create dir
await fs.createDir(local + 'cultivation/grasscutter').catch(e => console.log(e))
await fs.createDir(local + 'cultivation/grasscutter').catch((e) => console.log(e))
}
const dataFiles = await fs.readDir(local + 'cultivation')
@@ -118,13 +117,13 @@ async function readConfigFile() {
// Create config file
const file: fs.FsTextFileOption = {
path: configFilePath,
contents: JSON.stringify(defaultConfig)
contents: JSON.stringify(defaultConfig),
}
await fs.writeFile(file)
}
// Finally, read the file
// Finally, read the file
return await fs.readTextFile(configFilePath)
}
@@ -132,6 +131,6 @@ async function writeConfigFile(raw: string) {
// All external config functions call readConfigFile, which ensure files exists
await fs.writeFile({
path: configFilePath,
contents: raw
contents: raw,
})
}

View File

@@ -4,15 +4,15 @@ import { byteToString } from './string'
export default class DownloadHandler {
downloads: {
path: string,
progress: number,
total: number,
total_downloaded: number,
status: string,
startTime: number,
error?: string,
speed?: string,
onFinish?: () => void,
path: string
progress: number
total: number
total_downloaded: number
status: string
startTime: number
error?: string
speed?: string
onFinish?: () => void
}[]
// Pass tauri invoke function
@@ -22,13 +22,13 @@ export default class DownloadHandler {
listen('download_progress', ({ payload }) => {
// @ts-expect-error Payload may be unknown but backend always returns this object
const obj: {
downloaded: string,
total: string,
path: string,
total_downloaded: string,
downloaded: string
total: string
path: string
total_downloaded: string
} = payload
const index = this.downloads.findIndex(download => download.path === obj.path)
const index = this.downloads.findIndex((download) => download.path === obj.path)
this.downloads[index].progress = parseInt(obj.downloaded, 10)
this.downloads[index].total = parseInt(obj.total, 10)
this.downloads[index].total_downloaded = parseInt(obj.total_downloaded, 10)
@@ -52,7 +52,7 @@ export default class DownloadHandler {
const filename = payload
// set status to finished
const index = this.downloads.findIndex(download => download.path === filename)
const index = this.downloads.findIndex((download) => download.path === filename)
this.downloads[index].status = 'finished'
// Call onFinish callback
@@ -65,12 +65,12 @@ export default class DownloadHandler {
listen('download_error', ({ payload }) => {
// @ts-expect-error shut up typescript
const errorData: {
path: string,
error: string,
path: string
error: string
} = payload
// Set download to error
const index = this.downloads.findIndex(download => download.path === errorData.path)
const index = this.downloads.findIndex((download) => download.path === errorData.path)
this.downloads[index].status = 'error'
this.downloads[index].error = errorData.error
})
@@ -78,13 +78,13 @@ export default class DownloadHandler {
// Extraction events
listen('extract_start', ({ payload }) => {
// Find the download that is no extracting and set it's status as such
const index = this.downloads.findIndex(download => download.path === payload)
const index = this.downloads.findIndex((download) => download.path === payload)
this.downloads[index].status = 'extracting'
})
listen('extract_end', ({ payload }) => {
// Find the download that is no extracting and set it's status as such
const index = this.downloads.findIndex(download => download.path === payload)
const index = this.downloads.findIndex((download) => download.path === payload)
this.downloads[index].status = 'finished'
})
}
@@ -95,16 +95,16 @@ export default class DownloadHandler {
downloadingJar() {
// Kinda hacky but it works
return this.downloads.some(d => d.path.includes('grasscutter.zip'))
return this.downloads.some((d) => d.path.includes('grasscutter.zip'))
}
downloadingResources() {
// Kinda hacky but it works
return this.downloads.some(d => d.path.includes('resources'))
return this.downloads.some((d) => d.path.includes('resources'))
}
downloadingRepo() {
return this.downloads.some(d => d.path.includes('grasscutter_repo.zip'))
return this.downloads.some((d) => d.path.includes('grasscutter_repo.zip'))
}
addDownload(url: string, path: string, onFinish?: () => void) {
@@ -128,24 +128,24 @@ export default class DownloadHandler {
invoke('stop_download', { path })
// Remove from list
const index = this.downloads.findIndex(download => download.path === path)
const index = this.downloads.findIndex((download) => download.path === path)
this.downloads.splice(index, 1)
}
getDownloadProgress(path: string) {
const index = this.downloads.findIndex(download => download.path === path)
const index = this.downloads.findIndex((download) => download.path === path)
return this.downloads[index] || null
}
getDownloadSize(path: string) {
const index = this.downloads.findIndex(download => download.path === path)
const index = this.downloads.findIndex((download) => download.path === path)
return byteToString(this.downloads[index].total) || null
}
getTotalAverage() {
const files = this.downloads.filter(d => d.status === 'downloading')
const files = this.downloads.filter((d) => d.status === 'downloading')
const total = files.reduce((acc, d) => acc + d.total, 0)
const progress = files.reduce((acc, d) => d.progress !== 0 ? acc + d.progress : acc + d.total_downloaded, 0)
const progress = files.reduce((acc, d) => (d.progress !== 0 ? acc + d.progress : acc + d.total_downloaded), 0)
let speedStr = '0 B/s'
// Get download speed based on startTimes
@@ -158,10 +158,10 @@ export default class DownloadHandler {
return {
average: (progress / total) * 100 || 0,
files: this.downloads.filter(d => d.status === 'downloading').length,
extracting: this.downloads.filter(d => d.status === 'extracting').length,
files: this.downloads.filter((d) => d.status === 'downloading').length,
extracting: this.downloads.filter((d) => d.status === 'extracting').length,
totalSize: total,
speed: speedStr
speed: speedStr,
}
}
}
}

View File

@@ -3,7 +3,7 @@ import { getConfig } from './configuration'
export async function getGameExecutable() {
const config = await getConfig()
if(!config.game_install_path) {
if (!config.game_install_path) {
return null
}
@@ -14,7 +14,7 @@ export async function getGameExecutable() {
export async function getGameFolder() {
const config = await getConfig()
if(!config.game_install_path) {
if (!config.game_install_path) {
return null
}
@@ -24,4 +24,4 @@ export async function getGameFolder() {
const path = pathArr.join('/')
return path
}
}

View File

@@ -3,12 +3,12 @@ import React from 'react'
import { getConfigOption } from './configuration'
interface IProps {
text: string;
text: string
}
interface IState {
language: string;
translated_text: string;
language: string
translated_text: string
}
export default class Tr extends React.Component<IProps, IState> {
@@ -28,7 +28,7 @@ export default class Tr extends React.Component<IProps, IState> {
if (!language) language = 'en'
invoke('get_lang', { lang: language }).then((response) => {
const translation_obj = JSON.parse(response as string || '{}')
const translation_obj = JSON.parse((response as string) || '{}')
// Traversal
if (text.includes('.')) {
@@ -39,7 +39,7 @@ export default class Tr extends React.Component<IProps, IState> {
if (!translation) {
translation = ''
} else {
translation = typeof translation !== 'string' ? translation[keys[i]] : translation as string
translation = typeof translation !== 'string' ? translation[keys[i]] : (translation as string)
}
}
@@ -48,7 +48,7 @@ export default class Tr extends React.Component<IProps, IState> {
})
} else {
this.setState({
translated_text: translation_obj[text] || ''
translated_text: translation_obj[text] || '',
})
}
})
@@ -62,13 +62,13 @@ export default class Tr extends React.Component<IProps, IState> {
export async function getLanguages() {
const resp: {
[key: string]: string;
[key: string]: string
} = await invoke('get_languages')
const lang_list: {
[key: string]: string;
[key: string]: string
}[] = []
Object.keys(resp).forEach(k => {
Object.keys(resp).forEach((k) => {
const parsed = JSON.parse(resp[k])
if (parsed.lang_name) {
@@ -80,9 +80,9 @@ export async function getLanguages() {
}
export async function translate(text: string) {
const language = await getConfigOption('language') || 'en'
const translation_json = JSON.parse(await invoke('get_lang', { lang: language }) || '{}')
const language = (await getConfigOption('language')) || 'en'
const translation_json = JSON.parse((await invoke('get_lang', { lang: language })) || '{}')
// Traversal
if (text.includes('.')) {
const keys = text.split('.')
@@ -92,7 +92,7 @@ export async function translate(text: string) {
if (!translation) {
translation = ''
} else {
translation = typeof translation !== 'string' ? translation[keys[i]] : translation as string
translation = typeof translation !== 'string' ? translation[keys[i]] : (translation as string)
}
}
@@ -100,4 +100,4 @@ export async function translate(text: string) {
} else {
return translation_json[text] || ''
}
}
}

View File

@@ -5,7 +5,7 @@ import { getGameExecutable, getGameFolder } from './game'
export async function patchMetadata() {
const metadataExists = await invoke('dir_exists', {
path: await getGameMetadataPath() + '\\global-metadata.dat'
path: (await getGameMetadataPath()) + '\\global-metadata.dat',
})
if (!metadataExists) {
@@ -16,9 +16,9 @@ export async function patchMetadata() {
// Copy unpatched metadata to backup location
const copiedMeta = await invoke('copy_file_with_new_name', {
path: await getGameMetadataPath() + '\\global-metadata.dat',
path: (await getGameMetadataPath()) + '\\global-metadata.dat',
newPath: await getBackupMetadataPath(),
newName: 'global-metadata-unpatched.dat'
newName: 'global-metadata-unpatched.dat',
})
if (!copiedMeta) {
@@ -42,9 +42,9 @@ export async function patchMetadata() {
console.log('Replacing unpatched game metadata with patched metadata')
const replacedMeta = await invoke('copy_file_with_new_name', {
path: await getBackupMetadataPath() + '\\global-metadata-patched.dat',
path: (await getBackupMetadataPath()) + '\\global-metadata-patched.dat',
newPath: await getGameMetadataPath(),
newName: 'global-metadata.dat'
newName: 'global-metadata.dat',
})
if (!replacedMeta) {
@@ -58,7 +58,7 @@ export async function patchMetadata() {
export async function patchGame() {
const backupExists = await invoke('dir_exists', {
path: await getBackupMetadataPath() + '\\global-metadata-unpatched.dat'
path: (await getBackupMetadataPath()) + '\\global-metadata-unpatched.dat',
})
if (!backupExists) {
@@ -72,7 +72,7 @@ export async function patchGame() {
// Do we have a patch already?
const patchedExists = await invoke('dir_exists', {
path: await getBackupMetadataPath() + '\\global-metadata-patched.dat'
path: (await getBackupMetadataPath()) + '\\global-metadata-patched.dat',
})
if (!patchedExists) {
@@ -82,12 +82,12 @@ export async function patchGame() {
if (!patched) {
return false
}
}
}
// Are we already patched? If so, that's fine, just continue as normal
const gameIsPatched = await invoke('are_files_identical', {
path1: await getBackupMetadataPath() + '\\global-metadata-patched.dat',
path2: await getGameMetadataPath() + '\\global-metadata.dat'
path1: (await getBackupMetadataPath()) + '\\global-metadata-patched.dat',
path2: (await getGameMetadataPath()) + '\\global-metadata.dat',
})
if (gameIsPatched) {
@@ -96,17 +96,17 @@ export async function patchGame() {
// Is the current backup the same as the games current metadata?
const backupIsCurrent = await invoke('are_files_identical', {
path1: await getBackupMetadataPath() + '\\global-metadata-unpatched.dat',
path2: await getGameMetadataPath() + '\\global-metadata.dat'
})
path1: (await getBackupMetadataPath()) + '\\global-metadata-unpatched.dat',
path2: (await getGameMetadataPath()) + '\\global-metadata.dat',
})
// Game has probably been updated. We need to repatch the game...
if (!backupIsCurrent) {
const deletedOldBackup = await invoke('delete_file', {
path: await getBackupMetadataPath() + '\\global-metadata-unpatched.dat'
path: (await getBackupMetadataPath()) + '\\global-metadata-unpatched.dat',
})
const deletedOldPatched = await invoke('delete_file', {
path: await getBackupMetadataPath() + '\\global-metadata-patched.dat'
path: (await getBackupMetadataPath()) + '\\global-metadata-patched.dat',
})
// It's fine if these deletes fail. The game will be replaced anyway.
@@ -134,9 +134,9 @@ export async function patchGame() {
// Finally, replace the unpatched metadata with the patched one
const replaced = await invoke('copy_file_with_new_name', {
path: await getBackupMetadataPath() + '\\global-metadata-patched.dat',
path: (await getBackupMetadataPath()) + '\\global-metadata-patched.dat',
newPath: await getGameMetadataPath(),
newName: 'global-metadata.dat'
newName: 'global-metadata.dat',
})
if (!replaced) {
@@ -148,7 +148,7 @@ export async function patchGame() {
export async function unpatchGame() {
const backupExists = await invoke('dir_exists', {
path: await getBackupMetadataPath() + '\\global-metadata-unpatched.dat'
path: (await getBackupMetadataPath()) + '\\global-metadata-unpatched.dat',
})
if (!backupExists) {
@@ -157,9 +157,9 @@ export async function unpatchGame() {
}
const replaced = await invoke('copy_file_with_new_name', {
path: await getBackupMetadataPath() + '\\global-metadata-unpatched.dat',
path: (await getBackupMetadataPath()) + '\\global-metadata-unpatched.dat',
newPath: await getGameMetadataPath(),
newName: 'global-metadata.dat'
newName: 'global-metadata.dat',
})
return replaced
@@ -172,21 +172,27 @@ export async function getGameMetadataPath() {
return null
}
return (await getGameFolder() + '\\' + gameExec.replace('.exe', '_Data') + '\\Managed\\Metadata').replace(/\\/g, '/')
return ((await getGameFolder()) + '\\' + gameExec.replace('.exe', '_Data') + '\\Managed\\Metadata').replace(
/\\/g,
'/'
)
}
export async function getBackupMetadataPath() {
return await dataDir() + 'cultivation\\metadata'
return (await dataDir()) + 'cultivation\\metadata'
}
export async function globalMetadataLink() {
const versionAPIUrl = 'https://sdk-os-static.mihoyo.com/hk4e_global/mdk/launcher/api/resource?channel_id=1&key=gcStgarh&launcher_id=10&sub_channel_id=0'
const versionAPIUrl =
'https://sdk-os-static.mihoyo.com/hk4e_global/mdk/launcher/api/resource?channel_id=1&key=gcStgarh&launcher_id=10&sub_channel_id=0'
// Get versions from API
const versions = JSON.parse(await invoke('web_get', {
url: versionAPIUrl
}))
const versions = JSON.parse(
await invoke('web_get', {
url: versionAPIUrl,
})
)
if (!versions || versions.retcode !== 0) {
console.log('Failed to get versions from API')
return null
@@ -195,7 +201,7 @@ export async function globalMetadataLink() {
// Get latest version
const latest = versions.data.game.latest
return latest.decompressed_path as string + '/GenshinImpact_Data/Managed/Metadata/global-metadata.dat'
return (latest.decompressed_path as string) + '/GenshinImpact_Data/Managed/Metadata/global-metadata.dat'
}
export async function restoreMetadata(manager: DownloadHandler) {
@@ -208,16 +214,16 @@ export async function restoreMetadata(manager: DownloadHandler) {
// Should make sure metadata path exists since the user may have deleted it
await invoke('dir_create', {
path: await getBackupMetadataPath()
path: await getBackupMetadataPath(),
})
// It is possible the unpatched backup is mistakenly patched
await invoke('delete_file', {
path: await getBackupMetadataPath() + '\\global-metadata-unpatched.dat'
path: (await getBackupMetadataPath()) + '\\global-metadata-unpatched.dat',
})
// Download the file
manager.addDownload(metaLink, await getBackupMetadataPath() + '\\global-metadata-unpatched.dat', () => {
manager.addDownload(metaLink, (await getBackupMetadataPath()) + '\\global-metadata-unpatched.dat', () => {
unpatchGame()
})
console.log('Restoring backedup metadata')

View File

@@ -4,10 +4,12 @@ export async function toggleEncryption(path: string) {
let serverConf
try {
serverConf = JSON.parse(await invoke('read_file', {
path,
}))
} catch(e) {
serverConf = JSON.parse(
await invoke('read_file', {
path,
})
)
} catch (e) {
console.log(`Server config at ${path} not found or invalid`)
return
}
@@ -28,13 +30,15 @@ export async function encryptionEnabled(path: string) {
let serverConf
try {
serverConf = JSON.parse(await invoke('read_file', {
path,
}))
} catch(e) {
serverConf = JSON.parse(
await invoke('read_file', {
path,
})
)
} catch (e) {
console.log(`Server config at ${path} not found or invalid`)
return false
}
return serverConf.server.http.encryption.useEncryption
}
}

View File

@@ -8,4 +8,4 @@ export function byteToString(bytes: number) {
const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)).toString(), 10)
if (i === 0) return `${bytes} ${sizes[i]}`
return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${sizes[i]}`
}
}

View File

@@ -33,15 +33,15 @@ const defaultTheme = {
description: 'Default theme',
includes: {
css: [],
js: []
js: [],
},
path: 'default'
path: 'default',
}
export async function getThemeList() {
// Do some invoke to backend to get the theme list
const themes = await invoke('get_theme_list', {
dataDir: `${await dataDir()}/cultivation`
}) as BackendThemeList[]
const themes = (await invoke('get_theme_list', {
dataDir: `${await dataDir()}/cultivation`,
})) as BackendThemeList[]
const list: ThemeList[] = [
// ALWAYS include default theme
{
@@ -50,13 +50,13 @@ export async function getThemeList() {
description: 'Default theme',
includes: {
css: [],
js: []
js: [],
},
path: 'default'
}
path: 'default',
},
]
themes.forEach(t => {
themes.forEach((t) => {
let obj
try {
@@ -74,7 +74,7 @@ export async function getThemeList() {
export async function getTheme(name: string) {
const themes = await getThemeList()
return themes.find(t => t.name === name) || defaultTheme
return themes.find((t) => t.name === name) || defaultTheme
}
export async function loadTheme(theme: ThemeList, document: Document) {
@@ -89,7 +89,7 @@ export async function loadTheme(theme: ThemeList, document: Document) {
const jsIncludes = theme.includes.js
// Load CSS files
cssIncludes.forEach(css => {
cssIncludes.forEach((css) => {
if (!css) return
const link = document.createElement('link')
@@ -100,7 +100,7 @@ export async function loadTheme(theme: ThemeList, document: Document) {
})
// Load JS files
jsIncludes.forEach(js => {
jsIncludes.forEach((js) => {
if (!js) return
const script = document.createElement('script')
@@ -125,7 +125,7 @@ export async function loadTheme(theme: ThemeList, document: Document) {
// Save the background to our data dir
await invoke('copy_file', {
path: theme.path + '/' + theme.customBackgroundPath,
newPath: bgPath
newPath: bgPath,
})
// Set the background
@@ -139,4 +139,4 @@ export async function loadTheme(theme: ThemeList, document: Document) {
await setConfigOption('customBackground', config.customBackground)
return
}
}

View File

@@ -7,9 +7,9 @@ export function unzip(file: string, dest: string, onFinish?: () => void) {
destpath: dest,
})
listen('extract_end', ({payload}) => {
listen('extract_end', ({ payload }) => {
if (payload === file && onFinish) {
onFinish()
}
})
}
}