-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathmain.ts
208 lines (182 loc) · 5.5 KB
/
main.ts
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
/* eslint-disable no-console */
/// <reference types="vite/client" />
import { spawn } from "cross-spawn";
import { app, BrowserWindow, dialog, ipcMain } from "electron";
import * as fs from "fs";
import * as path from "path";
let mainWindow;
let apiProcess: any;
const isDevelopment = process.env.NODE_ENV === "development";
interface AppConfig {
apiPort: string;
dbPath: string;
logsPath: string;
}
// Function to read the configuration file. If it does not exist, create it with default values.
function readOrCreateAppConfig() {
const userDataPath = app.getPath("userData");
const configPath = path.join(userDataPath, "config.json");
const defaultConfig: AppConfig = {
apiPort: "35427",
dbPath: path.join(userDataPath, "witsml-explorer-db.db"),
logsPath: path.join(userDataPath, "logs")
};
let config: AppConfig;
let existingConfig: AppConfig;
try {
const configData = fs.readFileSync(configPath, "utf-8");
existingConfig = JSON.parse(configData);
// Merge the configs to ensure that new properties are added to the existing config.
config = { ...defaultConfig, ...existingConfig };
} catch (err) {
config = defaultConfig;
}
if (
!!JSON.stringify(existingConfig) &&
JSON.stringify(existingConfig) !== JSON.stringify(config)
) {
try {
fs.writeFileSync(configPath, JSON.stringify(config, null, 4), "utf-8");
console.log("Config created/updated:", configPath);
} catch (error) {
console.error("Failed to write configuration:", error);
showErrorAndQuit(
`Failed to write configuration file: ${configPath}. ${error}`
);
}
}
console.log("Using configuration:\n", config);
return config;
}
function showErrorAndQuit(message: string) {
dialog.showMessageBoxSync(this, {
type: "error",
buttons: ["OK"],
title: "Confirm",
message
});
app.quit();
}
interface Deferred<T> {
promise: Promise<T>;
resolve: (value?: T | PromiseLike<T>) => void;
reject: (reason?: any) => void;
}
// Function to manually control a Promise
export function deferred<T>(): Deferred<T> {
let resolve: (value?: T | PromiseLike<T>) => void;
let reject: (reason?: any) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
function getProductionPath(
relativePath: string,
isAsarUnpacked: boolean = false
) {
if (isAsarUnpacked) {
const asarUnpackedPath = __dirname.replace(
/\.asar([\\/])/,
".asar.unpacked$1"
);
return path.join(asarUnpackedPath, "../", relativePath);
} else {
return path.join(__dirname, "../", relativePath);
}
}
async function startApi(appConfig: AppConfig) {
if (isDevelopment) {
const basePath = app.getAppPath();
const env = {
...process.env,
"CONFIG_PATH": path.join(basePath, "api.config.json"),
"ASPNETCORE_URLS": `http://localhost:${appConfig.apiPort}`,
"ASPNETCORE_ENVIRONMENT": "Development",
"Serilog:WriteTo:1:Args:path": path.join(
appConfig.logsPath,
"witsml-explorer-api-.log"
),
"LiteDB:Name": appConfig.dbPath
};
apiProcess = spawn(
"dotnet",
[
"run",
"--project",
path.join(basePath, "../WitsmlExplorer.Api/WitsmlExplorer.Api.csproj"),
"--no-launch-profile"
],
{ env }
);
} else {
const env = {
...process.env,
"ASPNETCORE_URLS": `http://localhost:${appConfig.apiPort}`,
"CONFIG_PATH": "./api.config.json",
"Serilog:WriteTo:1:Args:path": path.join(
appConfig.logsPath,
"witsml-explorer-api-.log"
),
"LiteDB:Name": appConfig.dbPath
};
const apiPath = getProductionPath("api/", true);
apiProcess = spawn(path.join(apiPath, "WitsmlExplorer.Api"), [], {
env,
cwd: apiPath
});
}
// Promise that is manually resolved when the API has started.
const { promise, resolve, reject } = deferred();
// The app will wait 30 seconds for the API to start, if not it will be forced quit.
setTimeout(() => {
reject();
}, 60000);
// Log messages from the API to the console
apiProcess.stdout.setEncoding("utf8");
apiProcess.stdout.on("data", (data: string) => {
console.log(`API: ${data}`);
if (data.includes("Application started")) resolve();
});
await promise.catch(() => {
showErrorAndQuit(
"API was not able to run, the application will be forced quit!"
);
});
}
function createWindow() {
mainWindow = new BrowserWindow({
width: 1920,
height: 1080,
webPreferences: {
preload: path.join(__dirname, "../preload/preload.js")
}
});
mainWindow.setMenuBarVisibility(false);
if (isDevelopment) {
mainWindow.loadURL(process.env["ELECTRON_RENDERER_URL"]);
} else {
mainWindow.loadFile(path.join(__dirname, "../renderer/index.html"));
}
mainWindow.on("closed", (): void => (mainWindow = null));
}
app.whenReady().then(async () => {
const appConfig = readOrCreateAppConfig();
await startApi(appConfig);
ipcMain.handle("getConfig", () => appConfig);
createWindow();
// From Electron docs: macOS apps generally continue running even without any windows open, and activating the app when no windows are available should open a new one.
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("before-quit", () => {
apiProcess?.kill();
apiProcess = null;
});