summaryrefslogtreecommitdiff
path: root/src/main
diff options
context:
space:
mode:
Diffstat (limited to 'src/main')
-rw-r--r--src/main/manaplus/manaApp/linux.ts246
-rw-r--r--src/main/manaplus/manaApp/manaApp.interface.ts12
-rw-r--r--src/main/manaplus/manaApp/windows.ts156
-rw-r--r--src/main/manaplus/manaplus.ts323
-rw-r--r--src/main/richpresence.ts88
-rw-r--r--src/main/status.ts105
-rw-r--r--src/main/util/downloader.ts44
-rw-r--r--src/main/util/webrequest.ts61
8 files changed, 577 insertions, 458 deletions
diff --git a/src/main/manaplus/manaApp/linux.ts b/src/main/manaplus/manaApp/linux.ts
index 6c804d5..da37de0 100644
--- a/src/main/manaplus/manaApp/linux.ts
+++ b/src/main/manaplus/manaApp/linux.ts
@@ -1,124 +1,160 @@
import { ManaPlusApp } from "./manaApp.interface";
import { app } from "electron";
-import * as fs from 'fs-extra';
+import * as fs from "fs-extra";
import { getRequest } from "../../util/webrequest";
import { Status } from "../../status";
import { download, Progress as ProgressType } from "../../util/downloader";
import { promisify } from "util";
export class ManaPlusAppLinux implements ManaPlusApp {
- private path: string;
- startCommand: string;
- versionRegEx: RegExp = /.*ManaPlus ([\d.]+) Linux.*/g;//TODO
- constructor() {
- const ManaPath = app.getPath('userData') + "/manaplus";
- fs.existsSync(ManaPath) || fs.mkdirSync(ManaPath);
- fs.existsSync(app.getPath('userData') + "/temp") || fs.mkdirSync(app.getPath('userData') + "/temp");
- this.path = ManaPath;
- this.startCommand = ManaPath + '/Mana.AppImage'
- }
- getGameDir(): string {
- throw new Error("getGameDir() is windows only!");
- }
- getVersion(): Promise<string> {
- return new Promise((res, rej) => {
- let output: string;
- const child = require('child_process').execFile(this.startCommand, ['-v'], function (err: Error, data: any) {
- output = data.toString();
- });
- child.on('close', () => {
- output = output.replace(this.versionRegEx, "$1");
- res(output);
- });
- child.on('error', () => {
- rej(new Error("Version check failed"));
- });
- });
- }
- isInstalled(): boolean {
- return fs.existsSync(this.path + '/Mana.AppImage');
- }
- async updateAvailable(): Promise<{ isNewVersion: boolean; newestVersion: string; }> {
- try {
- let versions = await getRequest("https://tmw2.org/manalauncher/versions.json?" + Date.now());
- let currect_version = await this.isInstalled ? await this.getVersion() : "-";
- return {
- isNewVersion: currect_version.indexOf(versions.AppImage.version) === -1,
- newestVersion: versions.AppImage.version
- };
- } catch (e) {
- throw e;
+ private path: string;
+ startCommand: string;
+ versionRegEx: RegExp = /.*ManaPlus ([\d.]+) Linux.*/g; //TODO
+ constructor() {
+ const ManaPath = app.getPath("userData") + "/manaplus";
+ fs.existsSync(ManaPath) || fs.mkdirSync(ManaPath);
+ fs.existsSync(app.getPath("userData") + "/temp") ||
+ fs.mkdirSync(app.getPath("userData") + "/temp");
+ this.path = ManaPath;
+ this.startCommand = ManaPath + "/Mana.AppImage";
+ }
+ getGameDir(): string {
+ throw new Error("getGameDir() is windows only!");
+ }
+ getVersion(): Promise<string> {
+ return new Promise((res, rej) => {
+ let output: string;
+ const child = require("child_process").execFile(
+ this.startCommand,
+ ["-v"],
+ function (err: Error, data: any) {
+ output = data.toString();
}
+ );
+ child.on("close", () => {
+ output = output.replace(this.versionRegEx, "$1");
+ res(output);
+ });
+ child.on("error", () => {
+ rej(new Error("Version check failed"));
+ });
+ });
+ }
+ isInstalled(): boolean {
+ return fs.existsSync(this.path + "/Mana.AppImage");
+ }
+ async updateAvailable(): Promise<{
+ isNewVersion: boolean;
+ newestVersion: string;
+ }> {
+ try {
+ let versions = await getRequest(
+ "https://tmw2.org/manalauncher/versions.json?" + Date.now()
+ );
+ let currect_version = (await this.isInstalled)
+ ? await this.getVersion()
+ : "-";
+ return {
+ isNewVersion: currect_version.indexOf(versions.AppImage.version) === -1,
+ newestVersion: versions.AppImage.version,
+ };
+ } catch (e) {
+ throw e;
}
- async update(): Promise<any> {
- fs.existsSync(app.getPath('userData') + "/temp") || fs.mkdirSync(app.getPath('userData') + "/temp");
- // Get Update URL
- Status.setProgress(500);
- Status.setProgress(-1);
- Status.setActivity("Fetching Download URL");
- let downloadURL;
- try {
- let versions = await getRequest("https://tmw2.org/manalauncher/versions.json?" + Date.now());
- downloadURL = versions.AppImage.file;
- } catch (e) {
- console.log(e);
- Status.showError("Download Url fetching error", e.message, `Download Url fetching error: ${e.message}`);
- throw new Error("Download Url fetching error");
- }
- Status.setProgress(-1);
+ }
+ async update(): Promise<any> {
+ fs.existsSync(app.getPath("userData") + "/temp") ||
+ fs.mkdirSync(app.getPath("userData") + "/temp");
+ // Get Update URL
+ Status.setProgress(500);
+ Status.setProgress(-1);
+ Status.setActivity("Fetching Download URL");
+ let downloadURL;
+ try {
+ let versions = await getRequest(
+ "https://tmw2.org/manalauncher/versions.json?" + Date.now()
+ );
+ downloadURL = versions.AppImage.file;
+ } catch (e) {
+ console.log(e);
+ Status.showError(
+ "Download Url fetching error",
+ e.message,
+ `Download Url fetching error: ${e.message}`
+ );
+ throw new Error("Download Url fetching error");
+ }
+ Status.setProgress(-1);
- const updateDestination: string = `${app.getPath('userData')}/temp/update.AppImage`;
+ const updateDestination: string = `${app.getPath(
+ "userData"
+ )}/temp/update.AppImage`;
- try {
- await download(downloadURL, updateDestination, (state: ProgressType) => {
- Status.setProgress(Math.floor(state.percent * 100));
- const speed = Math.floor(Math.floor(state.speed) / 1024);
- Status.setActivity(`Downloading ManaPlus... ${speed} KiB/s`);
- console.log(state);
- });
- } catch (e) {
- console.log(e);
- Status.showError("Download error", e.message, `Download error: ${e.message}`);
- throw new Error("Download error");
- }
- Status.setProgress(500);
+ try {
+ await download(downloadURL, updateDestination, (state: ProgressType) => {
+ Status.setProgress(Math.floor(state.percent * 100));
+ const speed = Math.floor(Math.floor(state.speed) / 1024);
+ Status.setActivity(`Downloading ManaPlus... ${speed} KiB/s`);
+ console.log(state);
+ });
+ } catch (e) {
+ console.log(e);
+ Status.showError(
+ "Download error",
+ e.message,
+ `Download error: ${e.message}`
+ );
+ throw new Error("Download error");
+ }
+ Status.setProgress(500);
- //IDEA: Check Integrity of the download
+ //IDEA: Check Integrity of the download
- // Backup old files
- Status.setActivity(`Backup Old version`);
- try {
- await fs.remove(this.path + '/Mana2.AppImage')
- if (fs.existsSync(this.path + '/Mana.AppImage'))
- await fs.move(this.path + '/Mana.AppImage', this.path + '/Mana2.AppImage');
- console.log("Backup old version done.");
- } catch (err) {
- Status.showError("Backup old version Failed", err.message, `Backup old version Failed: ${err.message}`);
- throw new Error("Backup error");
- }
+ // Backup old files
+ Status.setActivity(`Backup Old version`);
+ try {
+ await fs.remove(this.path + "/Mana2.AppImage");
+ if (fs.existsSync(this.path + "/Mana.AppImage"))
+ await fs.move(
+ this.path + "/Mana.AppImage",
+ this.path + "/Mana2.AppImage"
+ );
+ console.log("Backup old version done.");
+ } catch (err) {
+ Status.showError(
+ "Backup old version Failed",
+ err.message,
+ `Backup old version Failed: ${err.message}`
+ );
+ throw new Error("Backup error");
+ }
- Status.setProgress(500);
- Status.setActivity(`ManaPlus download completed. Instaling..`);
- try {
- console.log('Use chmod');
- const chmod = promisify(fs.chmod);
- await chmod(updateDestination, '755');
-
- console.log('Now move the thing!');
- await fs.move(updateDestination, this.path + '/Mana.AppImage');
- //await chmod(this.path + '/Mana.AppImage', '744');
- } catch (err) {
- console.log('Instalation error', err);
- Status.showError("Instalation failed", err ? err.message : 'undefined', `Instalation Failed: ${err ? err.message : 'undefined'}`);
- throw new Error("Instalation error");
- }
+ Status.setProgress(500);
+ Status.setActivity(`ManaPlus download completed. Instaling..`);
+ try {
+ console.log("Use chmod");
+ const chmod = promisify(fs.chmod);
+ await chmod(updateDestination, "755");
- Status.setActivity('Instalation completed');
+ console.log("Now move the thing!");
+ await fs.move(updateDestination, this.path + "/Mana.AppImage");
+ //await chmod(this.path + '/Mana.AppImage', '744');
+ } catch (err) {
+ console.log("Instalation error", err);
+ Status.showError(
+ "Instalation failed",
+ err ? err.message : "undefined",
+ `Instalation Failed: ${err ? err.message : "undefined"}`
+ );
+ throw new Error("Instalation error");
+ }
- //IDEA: Check Integrity of gamefiles
+ Status.setActivity("Instalation completed");
- Status.setActivity('Update successfull');
+ //IDEA: Check Integrity of gamefiles
- return 0;
- }
-} \ No newline at end of file
+ Status.setActivity("Update successfull");
+
+ return 0;
+ }
+}
diff --git a/src/main/manaplus/manaApp/manaApp.interface.ts b/src/main/manaplus/manaApp/manaApp.interface.ts
index a4fa795..c576f47 100644
--- a/src/main/manaplus/manaApp/manaApp.interface.ts
+++ b/src/main/manaplus/manaApp/manaApp.interface.ts
@@ -1,8 +1,8 @@
export interface ManaPlusApp {
- readonly startCommand:string,
- getGameDir():string,
- getVersion():Promise<string>,
- isInstalled():boolean,
- updateAvailable():Promise<{isNewVersion:boolean, newestVersion:string}>,
- update():Promise<any>
+ readonly startCommand: string;
+ getGameDir(): string;
+ getVersion(): Promise<string>;
+ isInstalled(): boolean;
+ updateAvailable(): Promise<{ isNewVersion: boolean; newestVersion: string }>;
+ update(): Promise<any>;
}
diff --git a/src/main/manaplus/manaApp/windows.ts b/src/main/manaplus/manaApp/windows.ts
index 293fc72..ed9e70c 100644
--- a/src/main/manaplus/manaApp/windows.ts
+++ b/src/main/manaplus/manaApp/windows.ts
@@ -1,70 +1,79 @@
-import { ManaPlusApp } from './manaApp.interface';
-import { app } from 'electron';
-import * as fs from 'fs-extra';
-import { Status } from '../../status';
-import {download, Progress as ProgressType} from '../../util/downloader';
-import * as extract from 'extract-zip';
-import { getRequest } from '../../util/webrequest';
-
+import { ManaPlusApp } from "./manaApp.interface";
+import { app } from "electron";
+import * as fs from "fs-extra";
+import { Status } from "../../status";
+import { download, Progress as ProgressType } from "../../util/downloader";
+import * as extract from "extract-zip";
+import { getRequest } from "../../util/webrequest";
export class ManaPlusAppWindows implements ManaPlusApp {
- private path:string;
- public readonly startCommand:string;
- versionRegEx:RegExp = /.*ManaPlus ([\d.]+) Windows.*/g;
- constructor(){
- const ManaPath = app.getPath('userData')+"\\manaplus";
+ private path: string;
+ public readonly startCommand: string;
+ versionRegEx: RegExp = /.*ManaPlus ([\d.]+) Windows.*/g;
+ constructor() {
+ const ManaPath = app.getPath("userData") + "\\manaplus";
fs.existsSync(ManaPath) || fs.mkdirSync(ManaPath);
- fs.existsSync(app.getPath('userData')+"\\temp") || fs.mkdirSync(app.getPath('userData')+"\\temp");
+ fs.existsSync(app.getPath("userData") + "\\temp") ||
+ fs.mkdirSync(app.getPath("userData") + "\\temp");
this.path = ManaPath;
- this.startCommand = this.path + "\\Mana\\manaplus.exe"
+ this.startCommand = this.path + "\\Mana\\manaplus.exe";
}
- getGameDir(): string {
- return this.path+"\\Mana\\";
- }
- getVersion(): Promise<string> {
+ getGameDir(): string {
+ return this.path + "\\Mana\\";
+ }
+ getVersion(): Promise<string> {
return new Promise((res, rej) => {
- let output:string;
- const child = require('child_process').execFile(this.startCommand, ['-v'], function(err:Error, data:any) {
- output = data.toString();
- });
- child.on('close', ()=>{
+ let output: string;
+ const child = require("child_process").execFile(
+ this.startCommand,
+ ["-v"],
+ function (err: Error, data: any) {
+ output = data.toString();
+ }
+ );
+ child.on("close", () => {
output = output.replace(this.versionRegEx, "$1");
res(output);
});
- child.on('error', ()=>{
+ child.on("error", () => {
rej(new Error("Version check failed"));
});
});
- }
+ }
isInstalled(): boolean {
- return fs.existsSync(this.path+"\\Mana\\manaplus.exe");
- }
+ return fs.existsSync(this.path + "\\Mana\\manaplus.exe");
+ }
async update() {
- fs.existsSync(app.getPath('userData')+"\\temp") || fs.mkdirSync(app.getPath('userData')+"\\temp");
- // Get Update URL
+ fs.existsSync(app.getPath("userData") + "\\temp") ||
+ fs.mkdirSync(app.getPath("userData") + "\\temp");
+ // Get Update URL
Status.setProgress(500);
Status.setActivity("Fetching Download URL");
let downloadURL;
try {
- let versions = await getRequest("https://tmw2.org/manalauncher/versions.json?"+Date.now());
+ let versions = await getRequest(
+ "https://tmw2.org/manalauncher/versions.json?" + Date.now()
+ );
downloadURL = versions.windows64.file;
- } catch (e){
+ } catch (e) {
console.log(e);
throw new Error("Download Url fetching error");
}
Status.setProgress(-1);
- const updateDestination:string = `${app.getPath('userData')}\\temp\\update.zip`;
+ const updateDestination: string = `${app.getPath(
+ "userData"
+ )}\\temp\\update.zip`;
try {
- await download(downloadURL, updateDestination, (state:ProgressType) => {
- Status.setProgress(Math.floor(state.percent*100));
- const speed = Math.floor(Math.floor(state.speed)/1024);
+ await download(downloadURL, updateDestination, (state: ProgressType) => {
+ Status.setProgress(Math.floor(state.percent * 100));
+ const speed = Math.floor(Math.floor(state.speed) / 1024);
Status.setActivity(`Downloading ManaPlus... ${speed} KiB/s`);
console.log(state);
});
- } catch (e){
+ } catch (e) {
console.log(e);
throw new Error("Download error");
}
@@ -74,22 +83,30 @@ export class ManaPlusAppWindows implements ManaPlusApp {
// Backup old files
Status.setActivity(`Backup Old version`);
try {
- await fs.remove(this.path+'\\Mana2')
- if(fs.existsSync(this.path+'\\Mana'))
- await fs.move(this.path+'\\Mana', this.path+'\\Mana2');
+ await fs.remove(this.path + "\\Mana2");
+ if (fs.existsSync(this.path + "\\Mana"))
+ await fs.move(this.path + "\\Mana", this.path + "\\Mana2");
console.log("Backup old version done.");
} catch (err) {
- Status.showError("Backup old version Failed", err.message, `Backup old version Failed: ${err.message}`);
+ Status.showError(
+ "Backup old version Failed",
+ err.message,
+ `Backup old version Failed: ${err.message}`
+ );
throw new Error("Backup error");
}
Status.setProgress(500);
Status.setActivity(`ManaPlus download completed. Unziping..`);
- const extraction = new Promise((resolve, reject)=>{
- extract(updateDestination, {dir: this.path }, function (err) {
- if(err){
+ const extraction = new Promise((resolve, reject) => {
+ extract(updateDestination, { dir: this.path }, function (err) {
+ if (err) {
console.log(err);
- Status.showError("ManaPlus unziping failed", err.message, `Unzip Failed: ${err.message}`);
+ Status.showError(
+ "ManaPlus unziping failed",
+ err.message,
+ `Unzip Failed: ${err.message}`
+ );
reject(new Error("Extraction Error"));
}
resolve();
@@ -97,38 +114,53 @@ export class ManaPlusAppWindows implements ManaPlusApp {
});
await extraction;
- Status.setActivity('Unziping completed');
+ Status.setActivity("Unziping completed");
//IDEA: Check Integrity of gamefiles
-
// DELETE Old File and remove update file
- Status.setActivity('Cleaning up (Deleting update files)');
+ Status.setActivity("Cleaning up (Deleting update files)");
try {
- await fs.remove(this.path+'\\Mana2')
- await fs.remove(updateDestination)
- console.log('Cleanup done');
+ await fs.remove(this.path + "\\Mana2");
+ await fs.remove(updateDestination);
+ console.log("Cleanup done");
} catch (err) {
console.error(err);
- Status.showError("Clean up Failed", "Please remove '"+updateDestination+"' and '"+'this.path'+'\\Mana2'+"' manualy", `Unzip Failed: ${err.message}`);
+ Status.showError(
+ "Clean up Failed",
+ "Please remove '" +
+ updateDestination +
+ "' and '" +
+ "this.path" +
+ "\\Mana2" +
+ "' manualy",
+ `Unzip Failed: ${err.message}`
+ );
}
Status.setProgress(-1);
//Status.showError("Unziping isn't implemented yet", "WIP", "not further implemented")
- Status.setActivity('Update successfull');
+ Status.setActivity("Update successfull");
return 0;
- }
- async updateAvailable(): Promise<{ isNewVersion: boolean; newestVersion: string; }> {
+ }
+ async updateAvailable(): Promise<{
+ isNewVersion: boolean;
+ newestVersion: string;
+ }> {
try {
- let versions = await getRequest("https://tmw2.org/manalauncher/versions.json?"+Date.now());
- let currect_version = await this.isInstalled ? await this.getVersion(): "-";
+ let versions = await getRequest(
+ "https://tmw2.org/manalauncher/versions.json?" + Date.now()
+ );
+ let currect_version = (await this.isInstalled)
+ ? await this.getVersion()
+ : "-";
return {
- isNewVersion:currect_version.indexOf(versions.windows64.version) === -1,
- newestVersion:versions.windows64.version
+ isNewVersion:
+ currect_version.indexOf(versions.windows64.version) === -1,
+ newestVersion: versions.windows64.version,
};
- }catch (e){
+ } catch (e) {
throw e;
}
-
- }
+ }
}
diff --git a/src/main/manaplus/manaplus.ts b/src/main/manaplus/manaplus.ts
index 7573c84..981c7d5 100644
--- a/src/main/manaplus/manaplus.ts
+++ b/src/main/manaplus/manaplus.ts
@@ -1,68 +1,82 @@
-import { ManaPlusApp } from './manaApp/manaApp.interface';
-import { ManaPlusAppWindows } from './manaApp/windows';
-import * as os from 'os';
-import * as path from 'path';
-import * as fs from 'fs-extra';
-import { app, ipcMain, shell, dialog } from 'electron';
-import { Status, EventEmitter } from '../status';
-import { ManaPlusAppLinux } from './manaApp/linux';
+import { ManaPlusApp } from "./manaApp/manaApp.interface";
+import { ManaPlusAppWindows } from "./manaApp/windows";
+import * as os from "os";
+import * as path from "path";
+import * as fs from "fs-extra";
+import { app, ipcMain, shell, dialog } from "electron";
+import { Status, EventEmitter } from "../status";
+import { ManaPlusAppLinux } from "./manaApp/linux";
-let ManaPlusInstance:ManaPlusApp;
+let ManaPlusInstance: ManaPlusApp;
-let CurrentServer:{serverID:string,address:string}=null;
-
-export namespace ManaPlus{
+let CurrentServer: { serverID: string; address: string } = null;
+export namespace ManaPlus {
export const ERRORS = {
- NOT_INITILIZED_YET_ERROR:new Error("The ManaPlus updater wasn't initilized")
- }
+ NOT_INITILIZED_YET_ERROR: new Error(
+ "The ManaPlus updater wasn't initilized"
+ ),
+ };
- export function init(){
- if(os.platform() == "win32"){
+ export function init() {
+ if (os.platform() == "win32") {
ManaPlusInstance = new ManaPlusAppWindows();
- console.log("GameDir:"+ManaPlusInstance.getGameDir());
+ console.log("GameDir:" + ManaPlusInstance.getGameDir());
}
- if(os.platform() == "linux"){
+ if (os.platform() == "linux") {
ManaPlusInstance = new ManaPlusAppLinux();
- console.log("startCommand:"+ManaPlusInstance.startCommand);
+ console.log("startCommand:" + ManaPlusInstance.startCommand);
}
}
- export async function update(){
- if(!wasInitilized())throw ERRORS.NOT_INITILIZED_YET_ERROR;
+ export async function update() {
+ if (!wasInitilized()) throw ERRORS.NOT_INITILIZED_YET_ERROR;
return await ManaPlusInstance.update();
}
-
-
- export async function start(args: any){
- CurrentServer={
- serverID:args.serverID,
- address:args.address
+ export async function start(args: any) {
+ CurrentServer = {
+ serverID: args.serverID,
+ address: args.address,
};
- let params:string[];
+ let params: string[];
try {
- params = await makeParams(args.address,args.port,args.engine,args.username,args.password);
+ params = await makeParams(
+ args.address,
+ args.port,
+ args.engine,
+ args.username,
+ args.password
+ );
//params = ['-v'];// DEBUG: This option is to disable manaplus for testing (open it just for getting the version)
- } catch (e){
+ } catch (e) {
console.log(e);
- Status.showError("Launch Preperation Failed (LPF_PARMS)", e.message, "Launch preparation failed");
+ Status.showError(
+ "Launch Preperation Failed (LPF_PARMS)",
+ e.message,
+ "Launch preparation failed"
+ );
Status.setPlaying(false);
return;
}
- let willUpdate:boolean=false;
+ let willUpdate: boolean = false;
// check if it is installed
- if(ManaPlusInstance.isInstalled()){
+ if (ManaPlusInstance.isInstalled()) {
// Check if update is available and ask if the user wants to update
try {
let version = await ManaPlusInstance.updateAvailable();
- willUpdate = (version.isNewVersion && await updateDialog(version.newestVersion));
- } catch (e){
+ willUpdate =
+ version.isNewVersion && (await updateDialog(version.newestVersion));
+ } catch (e) {
console.log(e);
- Status.showError("Launch Preperation Failed (LPF_Update): This error can also mean that you are offline, \
-please check you network connection first.", e.message, "Launch preparation failed")
+ Status.showError(
+ "Launch Preperation Failed (LPF_Update): This error can also mean that you are offline, \
+please check you network connection first.",
+ e.message,
+ "Launch preparation failed"
+ );
Status.setPlaying(false);
return;
}
@@ -71,109 +85,127 @@ please check you network connection first.", e.message, "Launch preparation fail
willUpdate = true;
}
// Install/Update the gameclient if needed
- if(willUpdate){
+ if (willUpdate) {
try {
await update();
} catch (error) {
Status.setPlaying(false);
throw error;
}
-
}
//IDEA have client data updated here to, if needed
-
// Run it
Status.setGameRunning(true);
- EventEmitter.emit('closeWindow');
- EventEmitter.emit('openTray');
- await runManaProgram(params,ManaPlusInstance.startCommand,args.address);
+ EventEmitter.emit("closeWindow");
+ EventEmitter.emit("openTray");
+ await runManaProgram(params, ManaPlusInstance.startCommand, args.address);
// On Close
- Status.setGameStatus({server: "Launcher"})
+ Status.setGameStatus({ server: "Launcher" });
Status.setGameRunning(false);
Status.setPlaying(false);
Status.removeActivity();
- EventEmitter.emit('reopenWindow');
- EventEmitter.emit('closeTray');
- CurrentServer=null;
+ EventEmitter.emit("reopenWindow");
+ EventEmitter.emit("closeTray");
+ CurrentServer = null;
}
-
}
-ipcMain.on('getScreenshots', (event:any, arg:string)=> {
- const screenshotsDir = path.normalize(app.getPath('userData')+`/screenshots/${arg}/`);
+ipcMain.on("getScreenshots", (event: any, arg: string) => {
+ const screenshotsDir = path.normalize(
+ app.getPath("userData") + `/screenshots/${arg}/`
+ );
fs.existsSync(screenshotsDir) || fs.mkdirSync(screenshotsDir);
- fs.readdir(screenshotsDir, (err, dir) => {
- let screenshots:string[]=[];
- for (var i = 0, path; path = dir[i]; i++) {
- screenshots.push(path);
- }
- event.sender.send('getScreenshots', {dir:screenshotsDir, screenshots:screenshots.reverse().slice(0, 24)});
+ fs.readdir(screenshotsDir, (err, dir) => {
+ let screenshots: string[] = [];
+ for (var i = 0, path; (path = dir[i]); i++) {
+ screenshots.push(path);
+ }
+ event.sender.send("getScreenshots", {
+ dir: screenshotsDir,
+ screenshots: screenshots.reverse().slice(0, 24),
});
+ });
});
-EventEmitter.on('Mana:openScreenshotDir', ()=>{
- shell.openItem(path.normalize(app.getPath('userData')+`/screenshots/${CurrentServer.address}/`));
+EventEmitter.on("Mana:openScreenshotDir", () => {
+ shell.openItem(
+ path.normalize(
+ app.getPath("userData") + `/screenshots/${CurrentServer.address}/`
+ )
+ );
});
-function wasInitilized(){
- return typeof(ManaPlusInstance) !== "undefined" && typeof(ManaPlusInstance) !== "undefined";
+function wasInitilized() {
+ return (
+ typeof ManaPlusInstance !== "undefined" &&
+ typeof ManaPlusInstance !== "undefined"
+ );
}
-async function makeParams(server: any,port: any,engine: any,username?: any,password?: any):Promise<string[]>{
- let parameters:string[] = [];
- if(server && engine && port && server != 'noServer'){
- parameters.push(...[
- "-s", server,
- "-y", engine,
- "-p", port
- ]);
- if(username && password){
- parameters.push(...[
- "-U", username,
- "-P", password
- ]);
- }
+async function makeParams(
+ server: any,
+ port: any,
+ engine: any,
+ username?: any,
+ password?: any
+): Promise<string[]> {
+ let parameters: string[] = [];
+ if (server && engine && port && server != "noServer") {
+ parameters.push(...["-s", server, "-y", engine, "-p", port]);
+ if (username && password) {
+ parameters.push(...["-U", username, "-P", password]);
}
- // Setup Paths and stuff
- const configDir = path.normalize(app.getPath('userData')+"/mana_config");
- const localDataDir = path.normalize(app.getPath('userData')+"/mana_local_data");
- const screenshotsDir = path.normalize(app.getPath('userData')+`/screenshots/${server}`);
- await fs.ensureDir(configDir);
- await fs.ensureDir(localDataDir);
- await fs.ensureDir(screenshotsDir);
- parameters.push(...[
- "-C", configDir,
- "-L", localDataDir,
- "--screenshot-dir", screenshotsDir,
- ]);
- //console.log(parameters);
-
- return parameters;
+ }
+ // Setup Paths and stuff
+ const configDir = path.normalize(app.getPath("userData") + "/mana_config");
+ const localDataDir = path.normalize(
+ app.getPath("userData") + "/mana_local_data"
+ );
+ const screenshotsDir = path.normalize(
+ app.getPath("userData") + `/screenshots/${server}`
+ );
+ await fs.ensureDir(configDir);
+ await fs.ensureDir(localDataDir);
+ await fs.ensureDir(screenshotsDir);
+ parameters.push(
+ ...["-C", configDir, "-L", localDataDir, "--screenshot-dir", screenshotsDir]
+ );
+ //console.log(parameters);
+
+ return parameters;
}
-let manaplusInstance: any=null;
+let manaplusInstance: any = null;
-function runManaProgram(parameters: string[],gameExe:string,server?:string): Promise<any> {
- return new Promise(async(resolve, reject)=>{
- if(server){
+function runManaProgram(
+ parameters: string[],
+ gameExe: string,
+ server?: string
+): Promise<any> {
+ return new Promise(async (resolve, reject) => {
+ if (server) {
Status.setActivity(`Preparing Launch`);
await setSkipUpdateWindows(server);
}
Status.setActivity(`Starting ManaPlus`);
//console.log(gameExe, parameters);
- const child = require('child_process').execFile(gameExe, parameters, function(err:Error, data:any) {
- console.log(err);
- console.log(data.toString());
- Status.setActivity(`ManaPlus is running`);
- });
- child.on('close', ()=>{
+ const child = require("child_process").execFile(
+ gameExe,
+ parameters,
+ function (err: Error, data: any) {
+ console.log(err);
+ console.log(data.toString());
+ Status.setActivity(`ManaPlus is running`);
+ }
+ );
+ child.on("close", () => {
manaplusInstance = null;
resolve();
});
- child.on('error', ()=>{
+ child.on("error", () => {
manaplusInstance = null;
resolve();
//// TODO: Handle Error
@@ -182,51 +214,55 @@ function runManaProgram(parameters: string[],gameExe:string,server?:string): Pro
});
}
-EventEmitter.on("Mana:killMana",()=>{
- if(manaplusInstance && manaplusInstance !== null)
- manaplusInstance.kill('SIGINT');
+EventEmitter.on("Mana:killMana", () => {
+ if (manaplusInstance && manaplusInstance !== null)
+ manaplusInstance.kill("SIGINT");
});
-async function updateDialog(newestVersion:string):Promise<boolean>{
+async function updateDialog(newestVersion: string): Promise<boolean> {
const options = {
- type: 'info',
- title: `ManaPlus Update available: ${newestVersion}`,
- message: "Do you want to update now? Please note that you'll have to update eventually to ensure further compability with the servers",
- buttons: ['Nah, LATER', 'Update NOW']
- }
- let dialog = await dialogPromiseWrapper(options);
- console.log("....",dialog);
- return dialog === 1;
+ type: "info",
+ title: `ManaPlus Update available: ${newestVersion}`,
+ message:
+ "Do you want to update now? Please note that you'll have to update eventually to ensure further compability with the servers",
+ buttons: ["Nah, LATER", "Update NOW"],
+ };
+ let dialog = await dialogPromiseWrapper(options);
+ console.log("....", dialog);
+ return dialog === 1;
}
-function dialogPromiseWrapper(options:any):Promise<number>{
+function dialogPromiseWrapper(options: any): Promise<number> {
return new Promise((res, rej) => {
dialog.showMessageBox(options, (index) => {
- res(index);
- })
+ res(index);
+ });
});
}
-const default_server_config = '<?xml version="1.0"?>\
+const default_server_config =
+ '<?xml version="1.0"?>\
<configuration>\
<option name="updateType" value="1"/>\
<list name="player"/>\
</configuration>';
-const parseString = require('xml2js').parseString, xml2js = require('xml2js');
-async function setSkipUpdateWindows(server:string){
- const serverConfigXML = path.normalize(app.getPath('userData')+`/mana_config/${server}/config.xml`);
-
- if(fs.existsSync(serverConfigXML)){
+const parseString = require("xml2js").parseString,
+ xml2js = require("xml2js");
+async function setSkipUpdateWindows(server: string) {
+ const serverConfigXML = path.normalize(
+ app.getPath("userData") + `/mana_config/${server}/config.xml`
+ );
+
+ if (fs.existsSync(serverConfigXML)) {
//add to this file
- try{
- let data = await fs.readFile(serverConfigXML, 'utf8');
+ try {
+ let data = await fs.readFile(serverConfigXML, "utf8");
data = await editXML(data);
await fs.outputFile(serverConfigXML, data);
- } catch (err){
+ } catch (err) {
console.log(err);
}
-
- }else{
+ } else {
//create the file
fs.outputFile(serverConfigXML, default_server_config);
}
@@ -234,25 +270,26 @@ async function setSkipUpdateWindows(server:string){
return;
}
-function editXML(xml:string):Promise<string>{
- return new Promise((res, rej)=>{
- parseString(xml, function(err:any, result:any){
- if(err) console.log(err);
-
- var json = result;
- const updaterVar = json.configuration.option.find((item:any)=>item.$.name=="updateType");
- if(updaterVar){
- if(updaterVar.$.value === 1){
- return rej(new Error("Has allready the right value"));
- }
- updaterVar.$.value = 1;
- }else{
- json.configuration.option.push({$:{name:"updateType",value:1}});
+function editXML(xml: string): Promise<string> {
+ return new Promise((res, rej) => {
+ parseString(xml, function (err: any, result: any) {
+ if (err) console.log(err);
+
+ var json = result;
+ const updaterVar = json.configuration.option.find(
+ (item: any) => item.$.name == "updateType"
+ );
+ if (updaterVar) {
+ if (updaterVar.$.value === 1) {
+ return rej(new Error("Has allready the right value"));
}
+ updaterVar.$.value = 1;
+ } else {
+ json.configuration.option.push({ $: { name: "updateType", value: 1 } });
+ }
- var builder = new xml2js.Builder();
- res(builder.buildObject(json));
-
+ var builder = new xml2js.Builder();
+ res(builder.buildObject(json));
});
});
}
diff --git a/src/main/richpresence.ts b/src/main/richpresence.ts
index 93d9f9a..75acfdf 100644
--- a/src/main/richpresence.ts
+++ b/src/main/richpresence.ts
@@ -1,46 +1,50 @@
-import {Status} from './status';
+import { Status } from "./status";
// Only for testing as of right now -> Experimental
-const ClientId = '551884486351126528';
-const DiscordRPC = require('discord-rich-presence')(ClientId);
+const ClientId = "551884486351126528";
+const DiscordRPC = require("discord-rich-presence")(ClientId);
const slogans = [
- 'free OpenSource 2D MMORPG',
- 'Community made',
- 'Join a Server or start your own'
-]
-const dataSet:
-{[key:string]:{name:string, logo:string, description:string}} = {
- 'server.tmw2.org':{
- name: 'Moubootaur Legends',
- logo: 'tmw2',
- description: 'Playing on Moubootaur Legends ⎛tmw2.org⎠'
- },
- 'world.evolonline.org':{
- name: 'Evol Online',
- logo: 'evol',
- description: 'Playing on Evol Online ⎛evolonline.org⎠'
- },
- 'server.themanaworld.org':{
- name: 'The Mana World',
- logo: 'tmw',
- description: 'Playing on The Mana World ⎛themanaworld.org⎠'
- },
- 'noServer':{
- name: 'Manaplus',
- logo: 'manaplus',
- description: 'Playing on any of the M+ servers'
- }
- }
+ "free OpenSource 2D MMORPG",
+ "Community made",
+ "Join a Server or start your own",
+];
+const dataSet: {
+ [key: string]: { name: string; logo: string; description: string };
+} = {
+ "server.tmw2.org": {
+ name: "Moubootaur Legends",
+ logo: "tmw2",
+ description: "Playing on Moubootaur Legends ⎛tmw2.org⎠",
+ },
+ "world.evolonline.org": {
+ name: "Evol Online",
+ logo: "evol",
+ description: "Playing on Evol Online ⎛evolonline.org⎠",
+ },
+ "server.themanaworld.org": {
+ name: "The Mana World",
+ logo: "tmw",
+ description: "Playing on The Mana World ⎛themanaworld.org⎠",
+ },
+ noServer: {
+ name: "Manaplus",
+ logo: "manaplus",
+ description: "Playing on any of the M+ servers",
+ },
+};
async function setActivity() {
- const status = Status.getStatus()
+ const status = Status.getStatus();
- const slogan = slogans[Math.floor(Math.random() * slogans.length)]
+ const slogan = slogans[Math.floor(Math.random() * slogans.length)];
- const data = dataSet[status.gameStatus.server]
+ const data = dataSet[status.gameStatus.server];
- const details = status.gameStatus.server === 'Launcher' ? 'in Launcher Menu' : `🎮 ${data.name} 🎮`
- const logo = data && data.logo
+ const details =
+ status.gameStatus.server === "Launcher"
+ ? "in Launcher Menu"
+ : `🎮 ${data.name} 🎮`;
+ const logo = data && data.logo;
DiscordRPC.updatePresence({
state: `»${slogan}«`,
@@ -59,7 +63,7 @@ async function setActivity() {
});
}
-DiscordRPC.on('connected', () => {
+DiscordRPC.on("connected", () => {
setActivity();
// activity can only be set every 15 seconds
@@ -70,12 +74,12 @@ DiscordRPC.on('connected', () => {
DiscordRPC.on("error", console.log);
-DiscordRPC.on('join', (secret:string) => {
- console.log('we should join with', secret);
+DiscordRPC.on("join", (secret: string) => {
+ console.log("we should join with", secret);
});
-DiscordRPC.on('spectate', (secret:string) => {
- console.log('we should spectate with', secret);
+DiscordRPC.on("spectate", (secret: string) => {
+ console.log("we should spectate with", secret);
});
// DiscordRPC.on('joinRequest', (user) => {
@@ -86,9 +90,9 @@ DiscordRPC.on('spectate', (secret:string) => {
// }
// });
-export function quit(){
+export function quit() {
DiscordRPC.disconnect();
console.log("Shutting down Discord RPC integration");
}
-process.on('unhandledRejection', console.error); \ No newline at end of file
+process.on("unhandledRejection", console.error);
diff --git a/src/main/status.ts b/src/main/status.ts
index 2e59d0f..d58ebc6 100644
--- a/src/main/status.ts
+++ b/src/main/status.ts
@@ -1,86 +1,89 @@
-import { mainWindow } from '../main';
-import { dialog } from 'electron';
+import { mainWindow } from "../main";
+import { dialog } from "electron";
type STATUS = {
- progress:number,
- activity:string,
- ActivityIsError:boolean,
- playing:boolean,
- gameRunning:boolean,
- gameStatus:{
- server: string
- }
-}
+ progress: number;
+ activity: string;
+ ActivityIsError: boolean;
+ playing: boolean;
+ gameRunning: boolean;
+ gameStatus: {
+ server: string;
+ };
+};
-const status:STATUS = {
- progress:null,
- activity:null,
- playing:false, //Is manaplus starting or started
- ActivityIsError:false,
- gameRunning:false,
+const status: STATUS = {
+ progress: null,
+ activity: null,
+ playing: false, //Is manaplus starting or started
+ ActivityIsError: false,
+ gameRunning: false,
gameStatus: {
- server: "Launcher"
- }
-}
+ server: "Launcher",
+ },
+};
export namespace Status {
- export function setGameRunning(value: boolean){
- status.gameRunning=value;
+ export function setGameRunning(value: boolean) {
+ status.gameRunning = value;
updateStatus();
}
- export function setProgress(value: number){
- status.progress=value;
+ export function setProgress(value: number) {
+ status.progress = value;
updateStatus();
}
- export function removeProgress(){
- status.progress=null;
+ export function removeProgress() {
+ status.progress = null;
updateStatus();
}
- export function setActivity(value: string){
- status.activity=value;
- status.ActivityIsError=false;
+ export function setActivity(value: string) {
+ status.activity = value;
+ status.ActivityIsError = false;
updateStatus();
}
- export function removeActivity(){
- status.activity=null;
- status.ActivityIsError=false;
+ export function removeActivity() {
+ status.activity = null;
+ status.ActivityIsError = false;
updateStatus();
}
- export function showError(title:string, message:string, activityMsg:string=message){
+ export function showError(
+ title: string,
+ message: string,
+ activityMsg: string = message
+ ) {
status.activity = activityMsg;
status.ActivityIsError = true;
updateStatus();
- setTimeout(()=>{dialog.showErrorBox(title, message);},300);
+ setTimeout(() => {
+ dialog.showErrorBox(title, message);
+ }, 300);
}
- export function setPlaying(playing: boolean){
- status.playing=playing;
+ export function setPlaying(playing: boolean) {
+ status.playing = playing;
updateStatus();
}
- export function setGameStatus(gameStatus:{ server: string }){
- status.gameStatus=gameStatus;
+ export function setGameStatus(gameStatus: { server: string }) {
+ status.gameStatus = gameStatus;
updateStatus();
}
- export function getStatus():STATUS{
+ export function getStatus(): STATUS {
return status;
}
}
-function updateStatus(){
- if(mainWindow && mainWindow!== null){
-
- if(status.progress==null || status.progress<0)
- mainWindow.setProgressBar(-1);
- else if(status.progress>100)
- mainWindow.setProgressBar(2);
- else
- mainWindow.setProgressBar(status.progress/100);
+function updateStatus() {
+ if (mainWindow && mainWindow !== null) {
+ if (status.progress == null || status.progress < 0)
+ mainWindow.setProgressBar(-1);
+ else if (status.progress > 100) mainWindow.setProgressBar(2);
+ else mainWindow.setProgressBar(status.progress / 100);
- mainWindow.webContents.send('status-update', status);
+ mainWindow.webContents.send("status-update", status);
}
- EventEmitter.emit('status', status);
+ EventEmitter.emit("status", status);
}
-import * as events from 'events';
+import * as events from "events";
class MyEmitter extends events {}
diff --git a/src/main/util/downloader.ts b/src/main/util/downloader.ts
index 075097d..2a25b52 100644
--- a/src/main/util/downloader.ts
+++ b/src/main/util/downloader.ts
@@ -1,28 +1,32 @@
-var fs = require('fs');
-var request = require('request');
-var progress = require('request-progress');
+var fs = require("fs");
+var request = require("request");
+var progress = require("request-progress");
export type Progress = {
- percent:number,
- speed:number,
- size:{
- total:number,
- transfered:number
- },
- time:{
- elapsed:number,
- remaining:number
- }
+ percent: number;
+ speed: number;
+ size: {
+ total: number;
+ transfered: number;
+ };
+ time: {
+ elapsed: number;
+ remaining: number;
+ };
};
-export function download(url:string,targetLocation:string,onprogress: (state:Progress)=>void):Promise<any>{
- return new Promise((resolve:any,reject:any)=>{
+export function download(
+ url: string,
+ targetLocation: string,
+ onprogress: (state: Progress) => void
+): Promise<any> {
+ return new Promise((resolve: any, reject: any) => {
progress(request(url), {
- throttle: 500
+ throttle: 500,
})
- .on('progress', onprogress)
- .on('error', reject)
- .on('end', resolve)
- .pipe(fs.createWriteStream(targetLocation));
+ .on("progress", onprogress)
+ .on("error", reject)
+ .on("end", resolve)
+ .pipe(fs.createWriteStream(targetLocation));
});
}
diff --git a/src/main/util/webrequest.ts b/src/main/util/webrequest.ts
index aba8bfd..8fb0408 100644
--- a/src/main/util/webrequest.ts
+++ b/src/main/util/webrequest.ts
@@ -1,35 +1,38 @@
-import * as https from 'https';
-import * as http from 'http';
+import * as https from "https";
+import * as http from "http";
-export function getRequest(url:string):Promise<any> {
- const webrequest:any = url.indexOf('https') !== -1 ? https:http;
+export function getRequest(url: string): Promise<any> {
+ const webrequest: any = url.indexOf("https") !== -1 ? https : http;
const t1 = Date.now();
return new Promise((resolve, reject) => {
- webrequest.get(url, (res:any) => {
- const { statusCode } = res;
+ webrequest
+ .get(url, (res: any) => {
+ const { statusCode } = res;
- let error;
- if (statusCode !== 200) {
- error = new Error('Request Failed.\n' +
- `Status Code: ${statusCode}`);
- }
- if (error) {
- res.resume();
- reject(error);
- } else {
- res.setEncoding('utf8');
- let rawData = '';
- res.on('data', (chunk:any) => { rawData += chunk; });
- res.on('end', () => {
- try {
- resolve(JSON.parse(rawData));
- } catch (e) {
- reject(e);
- }
- });
- }
- }).on('error', (e:Error) => {
- reject(e);
- });
+ let error;
+ if (statusCode !== 200) {
+ error = new Error("Request Failed.\n" + `Status Code: ${statusCode}`);
+ }
+ if (error) {
+ res.resume();
+ reject(error);
+ } else {
+ res.setEncoding("utf8");
+ let rawData = "";
+ res.on("data", (chunk: any) => {
+ rawData += chunk;
+ });
+ res.on("end", () => {
+ try {
+ resolve(JSON.parse(rawData));
+ } catch (e) {
+ reject(e);
+ }
+ });
+ }
+ })
+ .on("error", (e: Error) => {
+ reject(e);
+ });
});
}