Skip to content

Commit

Permalink
EditorHome.vueとpreload.tsで使われているfs、pathモジュールをメインに移してnodeitegrationをfa…
Browse files Browse the repository at this point in the history
…lseに (#1042)

close #1017
  • Loading branch information
madosuki authored Dec 18, 2022
1 parent 86364fe commit c4ce68d
Show file tree
Hide file tree
Showing 7 changed files with 91 additions and 37 deletions.
23 changes: 22 additions & 1 deletion src/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import {
EngineInfo,
ElectronStoreType,
EngineDirValidationResult,
SystemError,
} from "./type/preload";

import log from "electron-log";
Expand Down Expand Up @@ -1000,7 +1001,7 @@ async function createWindow() {
show: false,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
nodeIntegration: true,
nodeIntegration: false,
contextIsolation: true,
sandbox: false, // TODO: 外しても問題ないか検証して外す
},
Expand Down Expand Up @@ -1393,6 +1394,26 @@ ipcMainHandle("RESTART_APP", async (_, { isSafeMode }) => {
win.close();
});

ipcMainHandle("WRITE_FILE", (_, { filePath, buffer }) => {
try {
fs.writeFileSync(filePath, new DataView(buffer));
} catch (e) {
// throwだと`.code`の情報が消えるのでreturn
const a = e as SystemError;
return { code: a.code, message: a.message };
}

return undefined;
});

ipcMainHandle("JOIN_PATH", (_, { pathArray }) => {
return path.join(...pathArray);
});

ipcMainHandle("READ_FILE", (_, { filePath }) => {
return fs.promises.readFile(filePath);
});

// app callback
app.on("web-contents-created", (e, contents) => {
// リンククリック時はブラウザを開く
Expand Down
45 changes: 18 additions & 27 deletions src/electron/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,8 @@ import {
IpcRenderer,
IpcRendererEvent,
} from "electron";
import fs from "fs";
import path from "path";

import { Sandbox, SystemError, ElectronStoreType } from "@/type/preload";
import { Sandbox, ElectronStoreType } from "@/type/preload";
import { IpcIHData, IpcSOData } from "@/type/ipc";

function ipcRendererInvoke<T extends keyof IpcIHData>(
Expand Down Expand Up @@ -72,27 +70,28 @@ const api: Sandbox = {
if (!tempDir) {
tempDir = await ipcRendererInvoke("GET_TEMP_DIR");
}
fs.writeFileSync(path.join(tempDir, relativePath), new DataView(buffer));
const tempFilePath = await ipcRendererInvoke("JOIN_PATH", {
pathArray: [tempDir, relativePath],
});
await ipcRendererInvoke("WRITE_FILE", {
filePath: tempFilePath,
buffer: buffer,
});
},

loadTempFile: async () => {
if (!tempDir) {
tempDir = await ipcRendererInvoke("GET_TEMP_DIR");
}
const buf = fs.readFileSync(path.join(tempDir, "hoge.txt"));
const tempFilePath = await ipcRendererInvoke("JOIN_PATH", {
pathArray: [tempDir, "hoge.txt"],
});
const buf = await ipcRendererInvoke("READ_FILE", {
filePath: tempFilePath,
});
return new TextDecoder().decode(buf);
},

getBaseName: ({ filePath }) => {
/**
* filePathから拡張子を含むファイル名を取り出す。
* vueファイルから直接pathモジュールを読み込むことは出来るが、
* その中のbasename関数は上手く動作しない(POSIX pathとして処理される)。
* この関数を呼び出せばWindows pathが正しく処理される。
*/
return path.basename(filePath);
},

showAudioSaveDialog: ({ title, defaultPath }) => {
return ipcRendererInvoke("SHOW_AUDIO_SAVE_DIALOG", { title, defaultPath });
},
Expand Down Expand Up @@ -138,20 +137,12 @@ const api: Sandbox = {
return ipcRendererInvoke("SHOW_IMPORT_FILE_DIALOG", { title });
},

writeFile: ({ filePath, buffer }) => {
try {
// throwだと`.code`の情報が消えるのでreturn
fs.writeFileSync(filePath, new DataView(buffer));
} catch (e) {
const a = e as SystemError;
return { code: a.code, message: a.message };
}

return undefined;
writeFile: async ({ filePath, buffer }) => {
return await ipcRendererInvoke("WRITE_FILE", { filePath, buffer });
},

readFile: ({ filePath }) => {
return fs.promises.readFile(filePath);
readFile: async ({ filePath }) => {
return await ipcRendererInvoke("READ_FILE", { filePath });
},

openTextEditContextMenu: () => {
Expand Down
6 changes: 3 additions & 3 deletions src/store/audio.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1151,7 +1151,7 @@ export const audioStore = createPartialStore<AudioStoreTypes>({
}
}

let writeFileResult = window.electron.writeFile({
let writeFileResult = await window.electron.writeFile({
filePath,
buffer: await blob.arrayBuffer(),
}); // 失敗した場合、WriteFileErrorResultオブジェクトが返り、成功時はundefinedが反る
Expand All @@ -1178,7 +1178,7 @@ export const audioStore = createPartialStore<AudioStoreTypes>({
type: "text/plain;charset=UTF-8",
});

writeFileResult = window.electron.writeFile({
writeFileResult = await window.electron.writeFile({
filePath: filePath.replace(/\.wav$/, ".lab"),
buffer: await labBlob.arrayBuffer(),
});
Expand Down Expand Up @@ -1209,7 +1209,7 @@ export const audioStore = createPartialStore<AudioStoreTypes>({
});
})();

writeFileResult = window.electron.writeFile({
writeFileResult = await window.electron.writeFile({
filePath: filePath.replace(/\.wav$/, ".txt"),
buffer: await textBlob.arrayBuffer(),
});
Expand Down
8 changes: 4 additions & 4 deletions src/store/project.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createUILockAction } from "@/store/ui";
import { AudioItem, ProjectStoreState, ProjectStoreTypes } from "@/store/type";
import semver from "semver";
import { buildProjectFileName } from "./utility";
import { buildProjectFileName, getBaseName } from "./utility";
import { createPartialStore } from "./vuex";

import Ajv, { JTDDataType } from "ajv/dist/jtd";
Expand All @@ -16,8 +16,8 @@ export const projectStoreState: ProjectStoreState = {
export const projectStore = createPartialStore<ProjectStoreTypes>({
PROJECT_NAME: {
getter(state) {
return state.projectFilePath !== undefined
? window.electron.getBaseName({ filePath: state.projectFilePath })
return state.projectFilePath
? getBaseName(state.projectFilePath)
: undefined;
},
},
Expand Down Expand Up @@ -347,7 +347,7 @@ export const projectStore = createPartialStore<ProjectStoreTypes>({
const buf = new TextEncoder().encode(
JSON.stringify(projectData)
).buffer;
window.electron.writeFile({ filePath, buffer: buf });
await window.electron.writeFile({ filePath, buffer: buf });
context.commit("SET_PROJECT_FILEPATH", { filePath });
context.commit(
"SET_SAVED_LAST_COMMAND_UNIX_MILLISEC",
Expand Down
27 changes: 27 additions & 0 deletions src/store/utility.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { State } from "@/store/type";
import { ToolbarButtonTagType } from "@/type/preload";
import path from "path";
import { Platform } from "quasar";

export function sanitizeFileName(fileName: string): string {
// \x00 - \x1f: ASCII 制御文字
Expand Down Expand Up @@ -166,3 +168,28 @@ export const convertLongVowel = (text: string): string => {
.replace(/(?<=[ン]ー*)ー/g, "ン")
.replace(/(?<=[ッ]ー*)ー/g, "ッ");
};

// based on https://github.com/BBWeb/path-browserify/blob/win-version/index.js
export const getBaseName = (filePath: string) => {
if (!Platform.is.win) return path.basename(filePath);

const splitDeviceRegex =
/^([a-zA-Z]:|[\\/]{2}[^\\/]+[\\/]+[^\\/]+)?([\\/])?([\s\S]*?)$/;
const splitTailRegex =
/^([\s\S]*?)((?:\.{1,2}|[^\\/]+?|)(\.[^./\\]*|))(?:[\\/]*)$/;

const resultOfSplitDeviceRegex = splitDeviceRegex.exec(filePath);
if (
resultOfSplitDeviceRegex == undefined ||
resultOfSplitDeviceRegex.length < 3
)
return "";
const tail = resultOfSplitDeviceRegex[3] || "";

const resultOfSplitTailRegex = splitTailRegex.exec(tail);
if (resultOfSplitTailRegex == undefined || resultOfSplitTailRegex.length < 2)
return "";
const basename = resultOfSplitTailRegex[2] || "";

return basename;
};
16 changes: 16 additions & 0 deletions src/type/ipc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
ThemeSetting,
ToolbarSetting,
UpdateInfo,
WriteFileErrorResult,
} from "@/type/preload";

/**
Expand Down Expand Up @@ -269,6 +270,21 @@ export type IpcIHData = {
args: [obj: { isSafeMode: boolean }];
return: void;
};

JOIN_PATH: {
args: [obj: { pathArray: string[] }];
return: string;
};

WRITE_FILE: {
args: [obj: { filePath: string; buffer: ArrayBuffer }];
return: WriteFileErrorResult | undefined;
};

READ_FILE: {
args: [obj: { filePath: string }];
return: ArrayBuffer;
};
};

/**
Expand Down
3 changes: 1 addition & 2 deletions src/type/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ export interface Sandbox {
getPrivacyPolicyText(): Promise<string>;
saveTempAudioFile(obj: { relativePath: string; buffer: ArrayBuffer }): void;
loadTempFile(): Promise<string>;
getBaseName(obj: { filePath: string }): string;
showAudioSaveDialog(obj: {
title: string;
defaultPath?: string;
Expand Down Expand Up @@ -68,7 +67,7 @@ export interface Sandbox {
writeFile(obj: {
filePath: string;
buffer: ArrayBuffer;
}): WriteFileErrorResult | undefined;
}): Promise<WriteFileErrorResult | undefined>;
readFile(obj: { filePath: string }): Promise<ArrayBuffer>;
openTextEditContextMenu(): Promise<void>;
isAvailableGPUMode(): Promise<boolean>;
Expand Down

0 comments on commit c4ce68d

Please sign in to comment.