Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent chain files from being saved in install directory #2835

Merged
merged 9 commits into from
May 8, 2024
90 changes: 71 additions & 19 deletions src/main/gui/main-window.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import os from 'os';
import path from 'path';
import { v4 as uuid4 } from 'uuid';
import { BackendEventMap } from '../../common/Backend';
import { Version } from '../../common/common-types';
import { FileSaveResult, Version } from '../../common/common-types';
import { log } from '../../common/log';
import { ChainnerSettings } from '../../common/settings/settings';
import { CriticalError } from '../../common/ui/error';
Expand All @@ -24,13 +24,41 @@ import { BackendProcess } from '../backend/process';
import { setupBackend } from '../backend/setup';
import { isArmMac, isMac } from '../env';
import { addBrowserWindow, addFile, addFiles, removeFile, removeFiles } from '../fileWatcher';
import { getRootDir } from '../platform';
import { getIsPortableSync, getRootDir, installDir } from '../platform';
import { BrowserWindowWithSafeIpc, ipcMain } from '../safeIpc';
import { SaveFile, openSaveFile } from '../SaveFile';
import { SaveData, SaveFile, openSaveFile } from '../SaveFile';
import { writeSettings } from '../setting-storage';
import { getAllFiles } from '../util';
import { MenuData, setMainMenu } from './menu';

const version = app.getVersion() as Version;
const documentsDir = app.getPath('documents');

const askSaveLocation = async (
mainWindow: BrowserWindowWithSafeIpc,
saveData: SaveData,
defaultPath: string | undefined
): Promise<FileSaveResult> => {
const { canceled, filePath } = await dialog.showSaveDialog(mainWindow, {
title: 'Save Chain File',
filters: [{ name: 'Chain File', extensions: ['chn'] }],
defaultPath: defaultPath ?? documentsDir,
});
if (!canceled && filePath) {
if (filePath.startsWith(installDir)) {
dialog.showMessageBoxSync({
type: 'error',
title: 'Cannot save in install directory',
message: `Cannot save chain files in chaiNNer's install directory. Please choose a different location.`,
buttons: ['OK'],
});
return askSaveLocation(mainWindow, saveData, defaultPath);
}
await SaveFile.write(filePath, saveData, version);
return { kind: 'Success', path: filePath };
}
return { kind: 'Canceled' };
};

const registerEventHandlerPreSetup = (
mainWindow: BrowserWindowWithSafeIpc,
Expand Down Expand Up @@ -92,24 +120,17 @@ const registerEventHandlerPreSetup = (
);

// file IO
ipcMain.handle('file-save-as-json', async (event, saveData, defaultPath) => {
try {
const documentsDir = app.getPath('documents');
const { canceled, filePath } = await dialog.showSaveDialog(mainWindow, {
title: 'Save Chain File',
filters: [{ name: 'Chain File', extensions: ['chn'] }],
defaultPath: defaultPath ?? documentsDir,
});
if (!canceled && filePath) {
await SaveFile.write(filePath, saveData, version);
return { kind: 'Success', path: filePath };
ipcMain.handle(
'file-save-as-json',
async (event, saveData, defaultPath): Promise<FileSaveResult> => {
try {
return await askSaveLocation(mainWindow, saveData, defaultPath);
} catch (error) {
log.error(error);
throw error;
}
return { kind: 'Canceled' };
} catch (error) {
log.error(error);
throw error;
}
});
);

ipcMain.handle('file-save-json', async (event, saveData, savePath) => {
try {
Expand Down Expand Up @@ -493,6 +514,35 @@ const setupProgressListeners = (
});
};

const checkForChainFilesInInstallDir = async () => {
if (getIsPortableSync()) {
return;
}
// Scan install dir for chain files and warn user if they are found
const chainFiles = await getAllFiles(installDir);
const chainFilesFiltered = chainFiles.filter((f) => f.endsWith('.chn'));
if (chainFilesFiltered.length > 0) {
const result = dialog.showMessageBoxSync({
type: 'warning',
title: 'Found chain files in install directory',
message: `Found ${chainFilesFiltered.length} chain (.chn) file${
chainFilesFiltered.length === 1 ? '' : 's'
} in chaiNNer's install directory.`,
detail: `Please move them to a different location.\n\nChain files stored inside chaiNNer's install directory might be deleted *permanently* when chaiNNer is updated, re-installed, or uninstalled.\n\nStore chain files in a directory you control, for example your documents folder or your desktop.\n\nFiles:\n- ${chainFilesFiltered
.slice(0, 5)
.join('\n- ')}${
chainFilesFiltered.length > 5
? `\n- ...and ${chainFilesFiltered.length - 5} more.`
: ''
}`,
buttons: ['Ignore', 'Open install folder'],
});
if (result === 1) {
await shell.openPath(installDir);
}
}
};

export const createMainWindow = async (args: OpenArguments, settings: ChainnerSettings) => {
// Create the browser window.
const mainWindow = new BrowserWindow({
Expand Down Expand Up @@ -574,6 +624,8 @@ export const createMainWindow = async (args: OpenArguments, settings: ChainnerSe
path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`)
);
}

await checkForChainFilesInInstallDir();
} catch (error) {
if (error instanceof CriticalError) {
await progressController.submitInterrupt(error.interrupt);
Expand Down
4 changes: 4 additions & 0 deletions src/main/platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,7 @@ export const getLogsFolder = lazy((): string => {
export const getBackendStorageFolder = lazy((): string => {
return path.join(getRootDir(), 'backend-storage');
});

export const installDir = getIsPortableSync()
? path.dirname(app.getPath('exe'))
: path.join(path.dirname(app.getPath('exe')), '..');
20 changes: 20 additions & 0 deletions src/main/util.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,28 @@
import { constants } from 'fs';
import fs from 'fs/promises';
import path from 'path';

export const checkFileExists = (file: string): Promise<boolean> =>
fs.access(file, constants.F_OK).then(
() => true,
() => false
);

export const getAllFiles = async (dirPath: string, fileList: string[] = []) => {
const files = await fs.readdir(dirPath);

await Promise.all(
files.map(async (file) => {
const filePath = path.join(dirPath, file);
const stat = await fs.stat(filePath);

if (stat.isDirectory()) {
await getAllFiles(filePath, fileList);
} else {
fileList.push(filePath);
}
})
);

return fileList;
};
Loading