aboutsummaryrefslogtreecommitdiff
path: root/src/utils.js
blob: 5ba98e6ccfefbd3667cdece3fa2a8d5a5703bbb8 (plain)
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
const path = require("path");
const fs = require("fs-extra");
const { dialog, ipcMain, Notification } = require("electron");

const Emitter = require("events");
const events = new Emitter();

const cli = require("./cli");
const lang = require("./lang");
const json = require("./modules/json");
const version = require("./modules/version");
const settings = require("./modules/settings");
const requests = require("./modules/requests");
const findgame = require("./modules/findgame");

const unzip = require("unzipper");
const exec = require("child_process").exec;
const { https } = require("follow-redirects");

// Logs into the dev tools of the renderer
function winLog(msg) {
	ipcMain.emit("win-log", msg, msg);
}

// Sends an alert to the renderer
function winAlert(msg) {
	ipcMain.emit("win-alert", msg, msg);
}

// A simple function that checks if the game is running, which we use to
// not update Northstar when it is running.
async function isGameRunning() {
	return new Promise(resolve => {
		let procs = ["Titanfall2.exe", "Titanfall2-unpacked.exe", "NorthstarLauncher.exe"];
		// While we could use a Node module to do this instead, I
		// decided not to do so. As this achieves exactly the same
		// thing. And it's not much more clunky.
		let cmd = (() => {
			switch (process.platform) {
				case "linux": return "ps -A";
				case "win32": return "tasklist";
			}
		})();

		exec(cmd, (err, stdout) => {
			for (let i = 0; i < procs.length; i++) {
				if (stdout.includes(procs[i])) {
					resolve(true);
					break
				}

				if (i == procs.length - 1) {resolve(false)}
			}
		});
	});
}

// checks if any origin processes are running
async function isOriginRunning() {
	return new Promise(resolve => {
		let procs = ["Origin.exe", "OriginClientService.exe"];
		let cmd = (() => {
			switch (process.platform) {
				case "linux": return "ps -A";
				case "win32": return "tasklist";
			}
		})();

		exec(cmd, (err, stdout) => {
			procs.forEach(proc => {
				if (stdout.includes(proc)) {
					resolve(true);
					return;
				}
				resolve(false);
			});
		});
	});
}

// kill origin processes
async function killOrigin() {
	return new Promise(resolve => {
		let proc = "Origin.exe"; //I'm pretty sure we only have to kill this one
		let cmd = (() => {
			switch (process.platform) {
				case "linux": return "killall " + proc;
				case "win32": return "taskkill /IM " + proc + " /F";
			}
		})();

		exec(cmd, (err, stdout) => {
			// just try and fail silently if we don't find it w/e
			resolve(true);
		});
	});
}

// Handles auto updating Northstar.
//
// It uses isGameRunning() to ensure it doesn't run while the game is
// running, as that may have all kinds of issues.
function handleNorthstarUpdating() {
	if (! settings.nsupdate || ! fs.existsSync("viper.json") || settings.gamepath.length === 0) {
		return;
	}

	async function _checkForUpdates() {
		let localVersion = version.northstar();
		let distantVersion = await requests.getLatestNsVersion();
		if (distantVersion == false) { return; }
		console.log(lang("cli.autoupdates.checking"));

		// Checks if NS is outdated
		if (localVersion !== distantVersion) {
			console.log(lang("cli.autoupdates.available"));
			if (await isGameRunning()) {
				console.log(lang("cli.autoupdates.gamerunning"));
				new Notification({
					title: lang("gui.nsupdate.gaming.title"),
					body: lang("gui.nsupdate.gaming.body")
				}).show();
			} else {
				console.log(lang("cli.autoupdates.updatingns"));
				updateNorthstar();
			}
		} else {
			console.log(lang("cli.autoupdates.noupdate"));
		}

		setTimeout(
			_checkForUpdates,
			15 * 60 * 1000
			// interval in between each update check
			// by default 15 minutes.
		);
	}

	_checkForUpdates();
}


// Requests to set the game path
//
// If running with CLI it takes in the --setpath argument otherwise it
// open the systems file browser for the user to select a path.
async function setpath(win, forcedialog) {
	function setGamepath(folder) {
		settings.gamepath = folder;
		settings.zip = path.join(settings.gamepath + "/northstar.zip");
		settings.save();
		win.webContents.send("newpath", settings.gamepath);
		ipcMain.emit("newpath", null, settings.gamepath);

		modpath = path.join(settings.gamepath, "R2Northstar/mods");
	}

	if (! win) { // CLI
		setGamepath(cli.param("setpath"));
	} else { // GUI
		if (! forcedialog) {
			function setGamepath(folder, forcedialog) {
				settings.gamepath = folder;
				settings.zip = path.join(settings.gamepath + "/northstar.zip");
				settings.save();
				win.webContents.send("newpath", settings.gamepath);
				ipcMain.emit("newpath", null, settings.gamepath);
			}

			let gamepath = await findgame();
			if (gamepath) {
				setGamepath(gamepath);
				return;
			}

			winAlert(lang("general.missingpath"));
		}

		// Fallback to manual selection
		dialog.showOpenDialog({properties: ["openDirectory"]}).then(res => {
			if (res.canceled) {
				ipcMain.emit("newpath", null, false);
				return;
			}
			if (! fs.existsSync(path.join(res.filePaths[0], "Titanfall2.exe"))) {
				ipcMain.emit("wrong-path");
				return;
			}

			setGamepath(res.filePaths[0]);

			cli.exit();
			return;
		}).catch(err => {console.error(err)})
	}
}

// Renames excluded files to their original name
function restoreExcludedFiles() {
	for (let i = 0; i < settings.excludes.length; i++) {
		let exclude = path.join(settings.gamepath + "/" + settings.excludes[i]);
		if (fs.existsSync(exclude + ".excluded")) {
			fs.renameSync(exclude + ".excluded", exclude);
		}
	}
}
// At start, restore excluded files who might have been created by an incomplete update process.
restoreExcludedFiles();

// Installs/Updates Northstar
//
// If Northstar is already installed it'll be an update, otherwise it'll
// install it. It simply downloads the Northstar archive from GitHub, if
// it's outdated, then extracts it into the game path.
//
// As to handle not overwriting files we rename certain files to
// <file>.excluded, then rename them back after the extraction. The
// unzip module does not support excluding files directly.
async function updateNorthstar() {
	if (! gamepathExists()) {return}

	ipcMain.emit("ns-update-event", "cli.update.checking");
	console.log(lang("cli.update.checking"));
	var ns_version = version.northstar();

	const latestAvailableVersion = await requests.getLatestNsVersion();
	console.log(latestAvailableVersion)
	if (latestAvailableVersion == false) {
		ipcMain.emit("ns-update-event", "cli.update.noInternet");
		return;
	}

	// Makes sure it is not already the latest version
	if (ns_version === latestAvailableVersion) {
		ipcMain.emit("ns-update-event", "cli.update.uptodate.short");
		console.log(lang("cli.update.uptodate"), ns_version);

		winLog(lang("gui.update.uptodate"));
		cli.exit();
		return;
	} else {
		if (ns_version != "unknown") {
			console.log(lang("cli.update.current"), ns_version);
		};
		console.log(lang("cli.update.downloading") + ":", latestAvailableVersion);
		ipcMain.emit("ns-update-event", "cli.update.downloading");
	}

	// Renames excluded files to <file>.excluded
	for (let i = 0; i < settings.excludes.length; i++) {
		let exclude = path.join(settings.gamepath + "/" + settings.excludes[i]);
		if (fs.existsSync(exclude)) {
			fs.renameSync(exclude, exclude + ".excluded");
		}
	}

	// Start the download of the zip
	https.get(requests.getLatestNsVersionLink(), (res) => {
		let stream = fs.createWriteStream(settings.zip);
		res.pipe(stream);

		let received = 0;
		// Progress messages, we should probably switch this to
		// percentage instead of how much is downloaded.
		res.on("data", (chunk) => {
			received += chunk.length;
			ipcMain.emit("ns-update-event", lang("gui.update.downloading") + " " + (received / 1024 / 1024).toFixed(1) + "mb");
		})

		stream.on("finish", () => {
			stream.close();
			let extract = fs.createReadStream(settings.zip);

			winLog(lang("gui.update.extracting"));
			ipcMain.emit("ns-update-event", "gui.update.extracting");
			console.log(lang("cli.update.downloaddone"));
			// Extracts the zip, this is the part where we're actually
			// installing Northstar.
			extract.pipe(unzip.Extract({path: settings.gamepath}))

			let max = received;
			received = 0;

			extract.on("data", (chunk) => {
				received += chunk.length;
				let percent = Math.floor(received / max * 100);
				ipcMain.emit("ns-update-event", lang("gui.update.extracting") + " " + percent + "%");
			})

			extract.on("end", () => {
				extract.close();
				ipcMain.emit("getversion");

				restoreExcludedFiles();

				ipcMain.emit("gui-getmods");
				ipcMain.emit("get-version");
				ipcMain.emit("ns-update-event", "cli.update.uptodate.short");
				winLog(lang("gui.update.finished"));
				console.log(lang("cli.update.finished"));
				cli.exit();
			})
		})
	})
}

// Updates Viper itself
//
// This uses electron updater to easily update and publish releases, it
// simply fetches it from GitHub and updates if it's outdated, very
// useful. Not much we have to do on our side.
function updateViper(autoinstall) {
	const { autoUpdater } = require("electron-updater");

	if (! autoUpdater.isUpdaterActive()) {
		if (settings.nsupdate) {
			handleNorthstarUpdating();
		}
		return cli.exit();
	}

	if (autoinstall) {
		autoUpdater.on("update-downloaded", (info) => {
			autoUpdater.quitAndInstall();
		});
	}

	autoUpdater.on("error", (info) => {cli.exit(1)});
	autoUpdater.on("update-not-available", (info) => {
		// only check for NS updates if Viper itself has no updates and
		// if NS auto updates is enabled.
		if (settings.nsupdate || cli.hasArgs()) {
			handleNorthstarUpdating();
		}
		cli.exit();
	});

	autoUpdater.checkForUpdatesAndNotify();
}

// Launches the game
//
// Either Northstar or Vanilla. Linux support is not currently a thing,
// however it'll be added at some point.
function launch(game_version) {
	if (process.platform == "linux") {
		winAlert(lang("cli.launch.linuxerror"));
		console.error("error:", lang("cli.launch.linuxerror"));
		cli.exit(1);
		return;
	}

	process.chdir(settings.gamepath);
	switch(game_version) {
		case "vanilla":
			console.log(lang("general.launching"), "Vanilla...");
			exec("Titanfall2.exe", {cwd: settings.gamepath});
			break;
		default:
			console.log(lang("general.launching"), "Northstar...");
			exec("NorthstarLauncher.exe", {cwd: settings.gamepath});
			break;
	}
}

// Returns true/false depending on if the gamepath currently exists/is
// mounted, used to avoid issues...
function gamepathExists() {
	return fs.existsSync(settings.gamepath);
}

setInterval(() => {
	if (gamepathExists()) {
		ipcMain.emit("gui-getmods");
	} else {
		if (fs.existsSync("viper.json")) {
			if (settings.gamepath != "") {
				ipcMain.emit("gamepath-lost");
			}
		}
	}
}, 1500)

module.exports = {
	winLog,

	updateViper,
	updateNorthstar,
	handleNorthstarUpdating,

	launch,
	killOrigin,
	isGameRunning,
	isOriginRunning,

	setpath,
	gamepathExists,

	lang,
	setlang: (lang) => {
		settings.lang = lang;
		settings.save();
	},
}