summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorLawnCable <git@lawncable.net>2021-02-28 17:39:20 +0100
committerLawnCable <git@lawncable.net>2021-02-28 18:17:13 +0100
commit28a45a2a60e0b22db45e6a45f1cd21c7602fc76e (patch)
treea1b4310b18ce8b74e13c6d8500f5038b23875e49 /src
parent47061ed7a78bf19645c29732bd91f1c03f86a618 (diff)
downloadelectron-28a45a2a60e0b22db45e6a45f1cd21c7602fc76e.tar.gz
electron-28a45a2a60e0b22db45e6a45f1cd21c7602fc76e.tar.bz2
electron-28a45a2a60e0b22db45e6a45f1cd21c7602fc76e.tar.xz
electron-28a45a2a60e0b22db45e6a45f1cd21c7602fc76e.zip
apply prettier code formatting
Diffstat (limited to 'src')
-rw-r--r--src/main.ts157
-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
-rw-r--r--src/renderer/customEvents.ts12
-rw-r--r--src/renderer/gameserver/TOSCheck.ts87
-rw-r--r--src/renderer/gameserver/data.ts116
-rw-r--r--src/renderer/gameserver/news.ts71
-rw-r--r--src/renderer/gameserver/onlineCount.ts114
-rw-r--r--src/renderer/gameserver/profile.ts10
-rw-r--r--src/renderer/gameserver/server.ts88
-rw-r--r--src/renderer/gameserver/serverView/controller.ts50
-rw-r--r--src/renderer/gameserver/serverView/info.ts78
-rw-r--r--src/renderer/gameserver/serverView/preferences.ts95
-rw-r--r--src/renderer/gameserver/serverView/screenshots.ts80
-rw-r--r--src/renderer/gameserver/serverView/serverPage.ts19
-rw-r--r--src/renderer/gameserver/socialLink.ts46
-rw-r--r--src/renderer/index.ts35
-rw-r--r--src/renderer/serverView.ts154
24 files changed, 1200 insertions, 1047 deletions
diff --git a/src/main.ts b/src/main.ts
index 9009b6f..2447253 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -1,19 +1,27 @@
-import * as path from 'path';
-import { app, BrowserWindow, ipcMain, remote, Tray, Menu, dialog } from 'electron';
+import * as path from "path";
+import {
+ app,
+ BrowserWindow,
+ ipcMain,
+ remote,
+ Tray,
+ Menu,
+ dialog,
+} from "electron";
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
export let mainWindow: BrowserWindow;
const isSecondInstance = app.makeSingleInstance(() => {
- // Someone tried to run a second instance, we should focus our window.
- if (mainWindow) {
- if (mainWindow.isMinimized()) mainWindow.restore()
- mainWindow.focus()
- }
- })
+ // Someone tried to run a second instance, we should focus our window.
+ if (mainWindow) {
+ if (mainWindow.isMinimized()) mainWindow.restore();
+ mainWindow.focus();
+ }
+});
if (isSecondInstance) {
- app.quit();
+ app.quit();
}
const createWindow = () => {
// Create the browser window.
@@ -23,14 +31,14 @@ const createWindow = () => {
minHeight: 475,
minWidth: 650,
frame: false,
- icon: path.join(__dirname,"../assets/media/icon.ico")
+ icon: path.join(__dirname, "../assets/media/icon.ico"),
});
// and load the index.html of the app.
mainWindow.loadURL(`file://${__dirname}/../assets/index.html`);
// Emitted when the window is closed.
- mainWindow.on('closed', () => {
+ mainWindow.on("closed", () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
@@ -41,18 +49,18 @@ const createWindow = () => {
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
-app.on('ready', createWindow);
+app.on("ready", createWindow);
// Quit when all windows are closed.
-app.on('window-all-closed', () => {
+app.on("window-all-closed", () => {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
- if (process.platform !== 'darwin' && !Status.getStatus().playing) {
+ if (process.platform !== "darwin" && !Status.getStatus().playing) {
app.quit();
}
});
-app.on('activate', () => {
+app.on("activate", () => {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
@@ -60,126 +68,121 @@ app.on('activate', () => {
}
});
-ipcMain.on('quit', (event:any, arg:any)=> {
- mainWindow.close();
+ipcMain.on("quit", (event: any, arg: any) => {
+ mainWindow.close();
});
-ipcMain.on('minimize', (event:any, arg:any)=> {
+ipcMain.on("minimize", (event: any, arg: any) => {
mainWindow.minimize();
});
-ipcMain.on('debug', (event:any, arg:any)=> {
- if(mainWindow.webContents.isDevToolsOpened())
+ipcMain.on("debug", (event: any, arg: any) => {
+ if (mainWindow.webContents.isDevToolsOpened())
mainWindow.webContents.closeDevTools();
- else
- mainWindow.webContents.openDevTools();
+ else mainWindow.webContents.openDevTools();
- Status.setActivity("Debug menue Toggled")
+ Status.setActivity("Debug menue Toggled");
});
-import {Status, EventEmitter} from './main/status';
-
+import { Status, EventEmitter } from "./main/status";
+import { quit as drpcQuit } from "./main/richpresence";
-import {quit as drpcQuit} from './main/richpresence';
-
-app.on('quit', () => {
+app.on("quit", () => {
drpcQuit();
- if (appIcon) appIcon.destroy()
+ if (appIcon) appIcon.destroy();
});
-let appIcon:Tray = null;
+let appIcon: Tray = null;
-EventEmitter.on('openTray',()=>{
- if(!appIcon){
- const iconName = "../assets/media/plushmouboo.png";
- const iconPath = path.join(__dirname, iconName)
- appIcon = new Tray(iconPath)
+EventEmitter.on("openTray", () => {
+ if (!appIcon) {
+ const iconName = "../assets/media/plushmouboo.png";
+ const iconPath = path.join(__dirname, iconName);
+ appIcon = new Tray(iconPath);
- updateTrayIconMenue();
-}
+ updateTrayIconMenue();
+ }
});
-function updateTrayIconMenue(){
- if(appIcon && appIcon!==null){
- let menue:Electron.MenuItemConstructorOptions[] = [];
- if(Status.getStatus().gameRunning){
+function updateTrayIconMenue() {
+ if (appIcon && appIcon !== null) {
+ let menue: Electron.MenuItemConstructorOptions[] = [];
+ if (Status.getStatus().gameRunning) {
menue.push({
- label: 'Open screenshot folder',
+ label: "Open screenshot folder",
click: () => {
- EventEmitter.emit('Mana:openScreenshotDir');
- }
+ EventEmitter.emit("Mana:openScreenshotDir");
+ },
});
menue.push({
- label: 'Kill ManaPlus',
+ label: "Kill ManaPlus",
click: () => {
//TODO Ask the user first to confirm
const options = {
- type: 'warning',
- title: 'Kill ManaPlus',
+ type: "warning",
+ title: "Kill ManaPlus",
message: "Are you sure?",
- buttons: ['Yes', 'No']
- }
+ buttons: ["Yes", "No"],
+ };
dialog.showMessageBox(options, (index) => {
- if(index===0){
- EventEmitter.emit('Mana:killMana');
+ if (index === 0) {
+ EventEmitter.emit("Mana:killMana");
}
- })
- }
+ });
+ },
});
- }else{
+ } else {
menue.push({
- label: 'Close Tray Icon',
+ label: "Close Tray Icon",
click: () => {
- EventEmitter.emit('closeTray');
- }
+ EventEmitter.emit("closeTray");
+ },
});
}
-
- appIcon.setToolTip('LawnCables Mana Launcher');
+ appIcon.setToolTip("LawnCables Mana Launcher");
appIcon.setContextMenu(Menu.buildFromTemplate(menue));
}
}
-EventEmitter.on('status', updateTrayIconMenue);
+EventEmitter.on("status", updateTrayIconMenue);
-EventEmitter.on('closeTray',()=>{
+EventEmitter.on("closeTray", () => {
if (appIcon) {
appIcon.destroy();
appIcon = null;
}
});
-
-import { ManaPlus } from './main/manaplus/manaplus';
+import { ManaPlus } from "./main/manaplus/manaplus";
ManaPlus.init();
-ipcMain.on('play', async (event:any, arg:any) => {
- if(Status.getStatus().playing)return;
- //console.log("play", arg);
- Status.setGameStatus({server: arg.address})
- Status.setPlaying(true);
- await ManaPlus.start(arg);
- //Status.showError("Failed To Launch Mana Plus","Not implemented yet!","Launch Manaplus faild: Not Implemented");
- return false;
+ipcMain.on("play", async (event: any, arg: any) => {
+ if (Status.getStatus().playing) return;
+ //console.log("play", arg);
+ Status.setGameStatus({ server: arg.address });
+ Status.setPlaying(true);
+ await ManaPlus.start(arg);
+ //Status.showError("Failed To Launch Mana Plus","Not implemented yet!","Launch Manaplus faild: Not Implemented");
+ return false;
});
-ipcMain.on('dragFileOut', (event:any, filepath:any) => {
+ipcMain.on("dragFileOut", (event: any, filepath: any) => {
event.sender.startDrag({
file: filepath,
- icon:path.join(__dirname, "../assets/media/screenshot.png")
- })
-})
+ icon: path.join(__dirname, "../assets/media/screenshot.png"),
+ });
+});
-EventEmitter.on('reopenWindow',()=>{
+EventEmitter.on("reopenWindow", () => {
if (mainWindow === null) {
createWindow();
}
});
-EventEmitter.on('closeWindow',()=>{
+EventEmitter.on("closeWindow", () => {
if (mainWindow !== null) {
mainWindow.close();
}
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);
+ });
});
}
diff --git a/src/renderer/customEvents.ts b/src/renderer/customEvents.ts
index 75a1ec5..3cdbf35 100644
--- a/src/renderer/customEvents.ts
+++ b/src/renderer/customEvents.ts
@@ -1,11 +1,13 @@
import { ServerSubPages } from "./gameserver/serverView/controller";
export function switchPage(
- sitetype:"SERVER"|"INTERN",
- page:string,
- subPage?:ServerSubPages
-){
- const event = new CustomEvent('site-changed', { detail:{sitetype, page, subPage} });
+ sitetype: "SERVER" | "INTERN",
+ page: string,
+ subPage?: ServerSubPages
+) {
+ const event = new CustomEvent("site-changed", {
+ detail: { sitetype, page, subPage },
+ });
const elements = document.getElementsByClassName("switch-page-event");
for (let i = 0; i < elements.length; i++) {
elements[i].dispatchEvent(event);
diff --git a/src/renderer/gameserver/TOSCheck.ts b/src/renderer/gameserver/TOSCheck.ts
index e2e4bfc..4744dcd 100644
--- a/src/renderer/gameserver/TOSCheck.ts
+++ b/src/renderer/gameserver/TOSCheck.ts
@@ -1,69 +1,68 @@
-import GameServer from './server';
-import { ipcRenderer } from 'electron';
+import GameServer from "./server";
+import { ipcRenderer } from "electron";
let LAST_TOS = "";
-export default async function CheckNAcceptTOS(server:GameServer):Promise<boolean>{
- try{
+export default async function CheckNAcceptTOS(
+ server: GameServer
+): Promise<boolean> {
+ try {
let thisVersion = await getTOSVersion(server.TOSLink);
- console.log(server.TOSLink,thisVersion);
- LAST_TOS=thisVersion;
- return (localStorage.getItem(server.TOSLink) == thisVersion);
-
+ console.log(server.TOSLink, thisVersion);
+ LAST_TOS = thisVersion;
+ return localStorage.getItem(server.TOSLink) == thisVersion;
} catch (err) {
- console.log("TOS check Error",err);
- return true
+ console.log("TOS check Error", err);
+ return true;
}
-
}
-async function getTOSVersion(address:string):Promise<string>{
+async function getTOSVersion(address: string): Promise<string> {
// Returns date or if not found the hash of the whole page
const PageContent = await request(address);
const date = PageContent.match(/Last Update: \d\d\d\d-\d\d-\d\d/g);
- let hash:string;
- if(!date || date.length > 1){
- hash = HashString(PageContent.replace(/ |\t|\n/g,"").replace(/<.+?>/g, "r")).toString(16);
+ let hash: string;
+ if (!date || date.length > 1) {
+ hash = HashString(
+ PageContent.replace(/ |\t|\n/g, "").replace(/<.+?>/g, "r")
+ ).toString(16);
} else {
- hash = date[0].replace(/ /g,"");
+ hash = date[0].replace(/ /g, "");
}
return hash;
}
-function request(url:string):Promise<string>{
- return new Promise((res, rej)=>{
- var xhr = new XMLHttpRequest();
- xhr.open('GET', url);
- xhr.addEventListener("error", (ev)=>{
- rej(ev);
- });
- xhr.onload = function() {
- if (xhr.status === 200) {
- res(xhr.responseText);
- }
- else {
- rej(new Error(`xhr.status: ${xhr.status} != 200`));
- }
- };
- xhr.send();
+function request(url: string): Promise<string> {
+ return new Promise((res, rej) => {
+ var xhr = new XMLHttpRequest();
+ xhr.open("GET", url);
+ xhr.addEventListener("error", (ev) => {
+ rej(ev);
+ });
+ xhr.onload = function () {
+ if (xhr.status === 200) {
+ res(xhr.responseText);
+ } else {
+ rej(new Error(`xhr.status: ${xhr.status} != 200`));
+ }
+ };
+ xhr.send();
});
}
-
-
// Hash function from http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
-function HashString (s:string){
- let hash = 0;
- if (s.length == 0) return hash;
- for (let i = 0; i < s.length; i++) {
- let char = s.charCodeAt(i);
- hash = ((hash<<5)-hash)+char;
- hash = hash & hash; // Convert to 32bit integer
- }
- return hash;
+function HashString(s: string) {
+ let hash = 0;
+ if (s.length == 0) return hash;
+ for (let i = 0; i < s.length; i++) {
+ let char = s.charCodeAt(i);
+ hash = (hash << 5) - hash + char;
+ hash = hash & hash; // Convert to 32bit integer
+ }
+ return hash;
}
-export function acceptLastTOS(server:GameServer){
+export function acceptLastTOS(server: GameServer) {
localStorage.setItem(server.TOSLink, LAST_TOS);
}
diff --git a/src/renderer/gameserver/data.ts b/src/renderer/gameserver/data.ts
index 421bdff..4ca72d6 100644
--- a/src/renderer/gameserver/data.ts
+++ b/src/renderer/gameserver/data.ts
@@ -1,105 +1,107 @@
// This class returns Data over the gameservers until we find a better solution
-import GameServer from './server';
-import GameServerProfile from './profile';
-import { NewsType } from './news';
-import { OnlineListParser } from './onlineCount';
-import { socialLink } from './socialLink';
-
+import GameServer from "./server";
+import GameServerProfile from "./profile";
+import { NewsType } from "./news";
+import { OnlineListParser } from "./onlineCount";
+import { socialLink } from "./socialLink";
const TMW2 = new GameServer(
- new GameServerProfile(
- "server.tmw2.org",
- 6901,
- "evol2",
- "TMW2"
- ),
+ new GameServerProfile("server.tmw2.org", 6901, "evol2", "TMW2"),
"TMW2",
"TMW2: Moubootaur Legends",
"What happens if you mix TMW with Evol and add many new Ideas",
"https://tmw2.org/news",
- {url:"http://updates.tmw2.org/news.txt",type:NewsType.ManaPlus},
- [{isVideo:false,file:"tmw2/background1.png"}],
+ { url: "http://updates.tmw2.org/news.txt", type: NewsType.ManaPlus },
+ [{ isVideo: false, file: "tmw2/background1.png" }],
"tmw2/icon.png",
[
- new socialLink("fas fa-home","Website","https://moubootaurlegends.org"),
- new socialLink("fab fa-discord","Discord","https://discord.gg/J4gcaqM"),
- new socialLink("fab fa-patreon","Patreon","https://www.patreon.com/TMW2/"),
- new socialLink("fas fa-comments","IRC Chat","http://webchat.freenode.net/?channels=#tmw2"),
- new socialLink("fab fa-youtube","Youtube","https://www.youtube.com/channel/UCiwW5dTmi2xMV_vJfj5Mq5Q"),
- new socialLink("fab fa-steam","Steam Group","http://steamcommunity.com/groups/TheManaWorld2"),
- new socialLink("fab fa-twitter","Twitter","https://twitter.com/TheManaWorld2"),
- new socialLink("fab fa-gitlab","Gitlab","https://gitlab.com/TMW2"),
+ new socialLink("fas fa-home", "Website", "https://moubootaurlegends.org"),
+ new socialLink("fab fa-discord", "Discord", "https://discord.gg/J4gcaqM"),
+ new socialLink(
+ "fab fa-patreon",
+ "Patreon",
+ "https://www.patreon.com/TMW2/"
+ ),
+ new socialLink(
+ "fas fa-comments",
+ "IRC Chat",
+ "http://webchat.freenode.net/?channels=#tmw2"
+ ),
+ new socialLink(
+ "fab fa-youtube",
+ "Youtube",
+ "https://www.youtube.com/channel/UCiwW5dTmi2xMV_vJfj5Mq5Q"
+ ),
+ new socialLink(
+ "fab fa-steam",
+ "Steam Group",
+ "http://steamcommunity.com/groups/TheManaWorld2"
+ ),
+ new socialLink(
+ "fab fa-twitter",
+ "Twitter",
+ "https://twitter.com/TheManaWorld2"
+ ),
+ new socialLink("fab fa-gitlab", "Gitlab", "https://gitlab.com/TMW2"),
],
"https://tmw2.org/legal",
- {parser:OnlineListParser.JSON_ARRAY,url:"https://tmw2.org/online.json"}
+ { parser: OnlineListParser.JSON_ARRAY, url: "https://tmw2.org/online.json" }
);
const Evol = new GameServer(
- new GameServerProfile(
- "world.evolonline.org",
- 6901,
- "evol2"
- ),
+ new GameServerProfile("world.evolonline.org", 6901, "evol2"),
"Evol Online",
"Evol Online",
"[EvolDescription]",
"https://evolonline.org/",
undefined,
- [{isVideo:false,file:"evol/background1.png"}],
+ [{ isVideo: false, file: "evol/background1.png" }],
"evol/icon.png",
- [
- new socialLink("fas fa-home","Website","https://evolonline.org/"),
- ],
+ [new socialLink("fas fa-home", "Website", "https://evolonline.org/")],
"http://wiki.evolonline.org/rules/gamerules",
null
);
const TMW = new GameServer(
- new GameServerProfile(
- "server.themanaworld.org",
- 6901,
- "tmwAthena"
- ),
+ new GameServerProfile("server.themanaworld.org", 6901, "tmwAthena"),
"The Mana World",
"The Mana World",
"The clasic TMW experience. Join adventures with people from all over the world.",
"https://www.themanaworld.org/news",
- {url:"http://themanaworld.github.io/tmwa-server-data/news.txt",type:NewsType.ManaPlus},
- [{isVideo:false,file:"tmw/background1.png"}],
+ {
+ url: "http://themanaworld.github.io/tmwa-server-data/news.txt",
+ type: NewsType.ManaPlus,
+ },
+ [{ isVideo: false, file: "tmw/background1.png" }],
"tmw/icon.png",
[
- new socialLink("fas fa-home","Website","https://www.themanaworld.org/"),
- new socialLink("fas fa-users","Forum","https://forums.themanaworld.org/"),
+ new socialLink("fas fa-home", "Website", "https://www.themanaworld.org/"),
+ new socialLink("fas fa-users", "Forum", "https://forums.themanaworld.org/"),
],
"https://wiki.themanaworld.org/index.php/The_Mana_World:Terms_and_Conditions",
- {parser:OnlineListParser.TMW, url:"https://server.themanaworld.org/"}
+ { parser: OnlineListParser.TMW, url: "https://server.themanaworld.org/" }
);
// https://policies.themanaworld.org/tos is still offline
const noServer = new GameServer(
- new GameServerProfile(
- 'noServer',
- 6901,
- "tmwAthena"
- ),
+ new GameServerProfile("noServer", 6901, "tmwAthena"),
"Mana Plus",
"Open Mana Plus",
"Opens the ManaPlus client",
- 'http://manaplus.org/changelog',
+ "http://manaplus.org/changelog",
undefined,
- [{isVideo:false,file:"noServer/background1.png"}],
+ [{ isVideo: false, file: "noServer/background1.png" }],
"noServer/icon.svg",
[
- new socialLink("fas fa-home","Website","http://manaplus.org/"),
- new socialLink("fab fa-gitlab","Gitlab","https://gitlab.com/manaplus/manaplus/"),
+ new socialLink("fas fa-home", "Website", "http://manaplus.org/"),
+ new socialLink(
+ "fab fa-gitlab",
+ "Gitlab",
+ "https://gitlab.com/manaplus/manaplus/"
+ ),
],
undefined,
null
);
-export const GameServers = [
- TMW2,
- Evol,
- TMW,
- noServer,
-]
+export const GameServers = [TMW2, Evol, TMW, noServer];
diff --git a/src/renderer/gameserver/news.ts b/src/renderer/gameserver/news.ts
index 656238c..34f6995 100644
--- a/src/renderer/gameserver/news.ts
+++ b/src/renderer/gameserver/news.ts
@@ -1,64 +1,67 @@
export enum NewsType {
Markdown, // Without html + yaml
- ManaPlus //update news txt
+ ManaPlus, //update news txt
}
-export namespace News { // Fetches only the most recent entry
- export async function get(url:string,parser:NewsType):Promise<string>{
+export namespace News {
+ // Fetches only the most recent entry
+ export async function get(url: string, parser: NewsType): Promise<string> {
try {
//1. load
const unsafe_content = await request(`${url}?${Math.random()}`);
//2. sanitize
- const content = killHTML( unsafe_content );
+ const content = killHTML(unsafe_content);
//3. parse
- if(parser == NewsType.ManaPlus){
+ if (parser == NewsType.ManaPlus) {
return manaTextParser(content);
- } else if (parser == NewsType.Markdown){
+ } else if (parser == NewsType.Markdown) {
return "Parsing Failed: Markdown Parser is not implemented yet";
}
- } catch (e){
+ } catch (e) {
console.log(e);
return `Failed to get the news, please select the news category on the right to view all news`;
}
}
}
-function request(url:string):Promise<string>{
- return new Promise((res, rej)=>{
- var xhr = new XMLHttpRequest();
- xhr.addEventListener("error", (ev)=>{
- rej(ev);
- });
- xhr.open('GET', url);
- xhr.onload = function() {
- if (xhr.status === 200) {
- res(xhr.responseText);
- }
- else {
- rej(new Error(`xhr.status: ${xhr.status} != 200`));
- }
- };
- xhr.send();
+function request(url: string): Promise<string> {
+ return new Promise((res, rej) => {
+ var xhr = new XMLHttpRequest();
+ xhr.addEventListener("error", (ev) => {
+ rej(ev);
+ });
+ xhr.open("GET", url);
+ xhr.onload = function () {
+ if (xhr.status === 200) {
+ res(xhr.responseText);
+ } else {
+ rej(new Error(`xhr.status: ${xhr.status} != 200`));
+ }
+ };
+ xhr.send();
});
}
-function killHTML(raw:string):string{
- return raw.replace(/<|>/,"⚠️");
+function killHTML(raw: string): string {
+ return raw.replace(/<|>/, "⚠️");
}
-function manaTextParser(input:string){
+function manaTextParser(input: string) {
const tmwLegacy = "##7Legacy Server##0";
let result = input;
- if(result.indexOf(tmwLegacy) !== -1){
+ if (result.indexOf(tmwLegacy) !== -1) {
const i = result.indexOf(tmwLegacy) + tmwLegacy.length;
result = result.slice(0, result.indexOf(tmwLegacy, i));
result = result.replace(/\n \n /, "");
}
- result = result.replace(/\[@@(.+?)\|(.+?)@@\]/g,'<a href="$1">$2</a>')
- .replace(/##B(.+?)##b/g,'<b>$1</b>')
- .replace(/##0 Actual Release: ##1 *(.+)/,'<h2>$1</h2>')
- .replace(/\n/g,"<br>");
- if(result.indexOf(tmwLegacy) === -1)
- result = result.replace(/br>([^]+?)<br></g,'br><p>$1</p><br><').replace(/<br>/g,"");
- return result.replace(/##\d/g,"");
+ result = result
+ .replace(/\[@@(.+?)\|(.+?)@@\]/g, '<a href="$1">$2</a>')
+ .replace(/##B(.+?)##b/g, "<b>$1</b>")
+ .replace(/##0 Actual Release: ##1 *(.+)/, "<h2>$1</h2>")
+ .replace(/\n/g, "<br>");
+ if (result.indexOf(tmwLegacy) === -1)
+ result = result
+ .replace(/br>([^]+?)<br></g, "br><p>$1</p><br><")
+ .replace(/<br>/g, "");
+ return result.replace(/##\d/g, "");
}
diff --git a/src/renderer/gameserver/onlineCount.ts b/src/renderer/gameserver/onlineCount.ts
index cfde7e5..b1c8271 100644
--- a/src/renderer/gameserver/onlineCount.ts
+++ b/src/renderer/gameserver/onlineCount.ts
@@ -1,48 +1,52 @@
-import GameServer from './server';
+import GameServer from "./server";
const MAX_SHOWN_NAMES = 5;
-export async function makeOnlineCounterList(server:GameServer):Promise<HTMLElement>{
-
+export async function makeOnlineCounterList(
+ server: GameServer
+): Promise<HTMLElement> {
try {
const playerList = await fetchOnlineList(server);
return generateHTML(playerList);
} catch (err) {
console.log(err);
- const OnlineCounterContainer = document.createElement('span');
+ const OnlineCounterContainer = document.createElement("span");
OnlineCounterContainer.classList.add("onlineCounter");
OnlineCounterContainer.innerHTML = `<i class="fas fa-times fa-xs"></i>Error:<br>${err}`;
return OnlineCounterContainer;
}
}
-
-function generateHTML(onlinePlayers:string[]):HTMLElement{
- const OnlineCounterContainer = document.createElement('span');
+function generateHTML(onlinePlayers: string[]): HTMLElement {
+ const OnlineCounterContainer = document.createElement("span");
OnlineCounterContainer.classList.add("onlineCounter");
OnlineCounterContainer.innerHTML = `<i class="fas fa-users fa-xs"></i>${onlinePlayers.length} Players online<br>`;
- const PlayerList = document.createElement('span');
+ const PlayerList = document.createElement("span");
PlayerList.classList.add("playerList");
let displayed_players =
- MAX_SHOWN_NAMES < onlinePlayers.length ?
- onlinePlayers.slice(0, MAX_SHOWN_NAMES):onlinePlayers;
-
- displayed_players.forEach(playername => {
- const PlayerItem = document.createElement('span');
- PlayerItem.classList.add("playerItem");
- PlayerItem.innerHTML=`<i class="fas fa-circle fa-xs" data-fa-transform="shrink-8 left-2"></i>${playername}`;
- PlayerList.appendChild(PlayerItem);
- });
-
+ MAX_SHOWN_NAMES < onlinePlayers.length
+ ? onlinePlayers.slice(0, MAX_SHOWN_NAMES)
+ : onlinePlayers;
+
+ displayed_players.forEach((playername) => {
+ const PlayerItem = document.createElement("span");
+ PlayerItem.classList.add("playerItem");
+ PlayerItem.innerHTML = `<i class="fas fa-circle fa-xs" data-fa-transform="shrink-8 left-2"></i>${playername}`;
+ PlayerList.appendChild(PlayerItem);
+ });
- if(MAX_SHOWN_NAMES < onlinePlayers.length){
- const hiddenPlayers = onlinePlayers.filter(playername => displayed_players.indexOf(playername) == -1);
- const MorePlayers = document.createElement('span');
+ if (MAX_SHOWN_NAMES < onlinePlayers.length) {
+ const hiddenPlayers = onlinePlayers.filter(
+ (playername) => displayed_players.indexOf(playername) == -1
+ );
+ const MorePlayers = document.createElement("span");
MorePlayers.classList.add("morePlayers");
- MorePlayers.innerText = ` and ${onlinePlayers.length-MAX_SHOWN_NAMES} more..`;
- MorePlayers.title = hiddenPlayers.join('\n');
+ MorePlayers.innerText = ` and ${
+ onlinePlayers.length - MAX_SHOWN_NAMES
+ } more..`;
+ MorePlayers.title = hiddenPlayers.join("\n");
PlayerList.appendChild(MorePlayers);
}
@@ -56,23 +60,17 @@ export enum OnlineListParser {
TMW,
TMW2API,
EXAMPLE_DATA,
- JSON_ARRAY
-};
-
-async function fetchOnlineList(server:GameServer):Promise<string[]>{
+ JSON_ARRAY,
+}
- if(!server.OnlineList)throw new Error("No Online list was\n specified for this Server");
+async function fetchOnlineList(server: GameServer): Promise<string[]> {
+ if (!server.OnlineList)
+ throw new Error("No Online list was\n specified for this Server");
- if(server.OnlineList.parser && server.OnlineList.url){
- switch(server.OnlineList.parser){
+ if (server.OnlineList.parser && server.OnlineList.url) {
+ switch (server.OnlineList.parser) {
case OnlineListParser.EXAMPLE_DATA:
- return [
- 'LawnCable',
- 'Saulc GM',
- 'Crazyfefe',
- 'Jesus Saves',
- 'DUSTMAN'
- ];
+ return ["LawnCable", "Saulc GM", "Crazyfefe", "Jesus Saves", "DUSTMAN"];
case OnlineListParser.TMW:
return tmwParser(await request(server.OnlineList.url));
case OnlineListParser.JSON_ARRAY:
@@ -85,37 +83,35 @@ async function fetchOnlineList(server:GameServer):Promise<string[]>{
}
}
-
-function tmwParser(rawData:string):string[]{
- let stringArray:string[]=[];
- rawData.replace(/<td>(.+?)<\/td>/g, (x:string, content:string) =>{
+function tmwParser(rawData: string): string[] {
+ let stringArray: string[] = [];
+ rawData.replace(/<td>(.+?)<\/td>/g, (x: string, content: string) => {
stringArray.push(content.replace(/<\/{0,1}.+?>/g, ""));
return "";
});
return stringArray;
}
-function jsonArrayParser(rawData:string):string[]{
+function jsonArrayParser(rawData: string): string[] {
return JSON.parse(rawData);
}
-function request(url:string):Promise<string>{
- return new Promise((res, rej)=>{
- var xhr = new XMLHttpRequest();
- xhr.open('GET', url);
- xhr.addEventListener("error", (ev)=>{
- console.log("Probably a network error:", ev);
+function request(url: string): Promise<string> {
+ return new Promise((res, rej) => {
+ var xhr = new XMLHttpRequest();
+ xhr.open("GET", url);
+ xhr.addEventListener("error", (ev) => {
+ console.log("Probably a network error:", ev);
+ rej(new Error("Probably a network error"));
+ });
+ xhr.onload = function () {
+ if (xhr.status === 200) {
+ res(xhr.responseText);
+ } else {
+ console.log(`xhr.status: ${xhr.status} != 200`);
rej(new Error("Probably a network error"));
- });
- xhr.onload = function() {
- if (xhr.status === 200) {
- res(xhr.responseText);
- }
- else {
- console.log(`xhr.status: ${xhr.status} != 200`);
- rej(new Error("Probably a network error"));
- }
- };
- xhr.send();
+ }
+ };
+ xhr.send();
});
}
diff --git a/src/renderer/gameserver/profile.ts b/src/renderer/gameserver/profile.ts
index 4c99184..c4a6268 100644
--- a/src/renderer/gameserver/profile.ts
+++ b/src/renderer/gameserver/profile.ts
@@ -1,8 +1,8 @@
export default class GameServerProfile {
constructor(
- public address:string,
- public port:number,
- public engine:"tmwAthena"|"hercules"|"evol2",
- public serverID:string = "DEFAULT", // To enable some server specific features
- ){}
+ public address: string,
+ public port: number,
+ public engine: "tmwAthena" | "hercules" | "evol2",
+ public serverID: string = "DEFAULT" // To enable some server specific features
+ ) {}
}
diff --git a/src/renderer/gameserver/server.ts b/src/renderer/gameserver/server.ts
index 9bdfccd..edc7d01 100644
--- a/src/renderer/gameserver/server.ts
+++ b/src/renderer/gameserver/server.ts
@@ -1,58 +1,55 @@
-import GameServerProfile from './profile';
-import { shell, ipcRenderer } from 'electron';
-import { switchPage } from '../customEvents';
-import { NewsType } from './news';
-import { makeOnlineCounterList, OnlineListParser } from './onlineCount';
-import { socialLink } from './socialLink';
-import { PageController } from './serverView/controller';
+import GameServerProfile from "./profile";
+import { shell, ipcRenderer } from "electron";
+import { switchPage } from "../customEvents";
+import { NewsType } from "./news";
+import { makeOnlineCounterList, OnlineListParser } from "./onlineCount";
+import { socialLink } from "./socialLink";
+import { PageController } from "./serverView/controller";
export default class GameServer {
-
- public pageController:PageController;
+ public pageController: PageController;
constructor(
public profile: GameServerProfile,
public menuName: string,
public name: string,
- public shortDescription: string,// the server in 1-2 sentences
+ public shortDescription: string, // the server in 1-2 sentences
public newsPageUrl: string,
- public newsLatestPage: { url: string, type: NewsType },
- public backgrounds: { isVideo: boolean, file: string }[],
+ public newsLatestPage: { url: string; type: NewsType },
+ public backgrounds: { isVideo: boolean; file: string }[],
public icon: string,
public socialLinks: socialLink[],
public TOSLink: string,
- public OnlineList: { parser: OnlineListParser, url: string },
+ public OnlineList: { parser: OnlineListParser; url: string }
) {
this.pageController = new PageController(this);
}
getMenuEntry(): HTMLElement {
- const sidebarItem = document.createElement('div');
+ const sidebarItem = document.createElement("div");
sidebarItem.classList.add("sidebarItem");
//Online counter
- const OnlineCounterContainer = document.createElement('div');
+ const OnlineCounterContainer = document.createElement("div");
//OnlineCounterContainer.appendChild(makeOnlineCounterList(this));
sidebarItem.appendChild(OnlineCounterContainer);
//Title
- const title = document.createElement('div');
+ const title = document.createElement("div");
title.classList.add("title");
- const titleIMG = document.createElement('img');
+ const titleIMG = document.createElement("img");
titleIMG.src = `./media/server/${this.icon}`;
- const titleText = document.createElement('div');
+ const titleText = document.createElement("div");
titleText.innerText = this.menuName;
-
title.appendChild(titleIMG);
title.appendChild(titleText);
-
- title.addEventListener('click', () => {
- switchPage("SERVER", this.name, 'INFO');
+ title.addEventListener("click", () => {
+ switchPage("SERVER", this.name, "INFO");
});
- if (this.profile.address != 'noServer') {
+ if (this.profile.address != "noServer") {
let onlineBoxActive: boolean = false;
let onlineBoxSchouldBeActive: boolean = false;
let updateOnlineContainer = async () => {
@@ -65,11 +62,13 @@ export default class GameServer {
OnlineCounterContainer.appendChild(await makeOnlineCounterList(this));
}
console.log(onlineBoxSchouldBeActive);
- }
+ };
let SetUpdate = (state: boolean) => {
onlineBoxSchouldBeActive = state;
- setTimeout(() => { updateOnlineContainer(); }, 160);
+ setTimeout(() => {
+ updateOnlineContainer();
+ }, 160);
};
title.addEventListener("mouseover", () => {
@@ -92,21 +91,22 @@ export default class GameServer {
sidebarItem.appendChild(title);
//Collapsable
- const container = document.createElement('div');
+ const container = document.createElement("div");
container.classList.add("colapse");
- const info = document.createElement('div');
+ const info = document.createElement("div");
info.innerHTML = '<i class="fas fa-info fa-fw"></i>Information';
container.appendChild(info);
- info.addEventListener('click', () => {
+ info.addEventListener("click", () => {
switchPage("SERVER", this.name, "INFO");
});
- const news = document.createElement('div');
- news.innerHTML = '<i class="far fa-newspaper fa-fw"></i>News <i class="fas fa-external-link-alt" data-fa-transform="shrink-2"></i>';
+ const news = document.createElement("div");
+ news.innerHTML =
+ '<i class="far fa-newspaper fa-fw"></i>News <i class="fas fa-external-link-alt" data-fa-transform="shrink-2"></i>';
if (this.newsPageUrl && this.newsPageUrl !== null) {
- news.addEventListener('click', () => {
+ news.addEventListener("click", () => {
shell.openExternal(this.newsPageUrl);
});
} else {
@@ -115,24 +115,25 @@ export default class GameServer {
container.appendChild(news);
- const screenshots = document.createElement('div');
+ const screenshots = document.createElement("div");
screenshots.innerHTML = '<i class="fas fa-camera fa-fw"></i>Screenshots';
container.appendChild(screenshots);
- screenshots.addEventListener('click', () => {
+ screenshots.addEventListener("click", () => {
switchPage("SERVER", this.name, "SCREENSHOTS");
- })
- const preferences = document.createElement('div');
- if(this.profile.address != 'noServer'){
- preferences.innerHTML = '<i class="fas fa-sliders-h fa-fw"></i>Preferences';
- preferences.addEventListener('click', () => {
+ });
+ const preferences = document.createElement("div");
+ if (this.profile.address != "noServer") {
+ preferences.innerHTML =
+ '<i class="fas fa-sliders-h fa-fw"></i>Preferences';
+ preferences.addEventListener("click", () => {
switchPage("SERVER", this.name, "PREF");
});
container.appendChild(preferences);
}
sidebarItem.appendChild(container);
//event Target / interactivity
- const events = document.createElement('span');
+ const events = document.createElement("span");
events.classList.add("switch-page-event");
events.addEventListener("site-changed", (event: CustomEvent) => {
sidebarItem.classList.remove("selected");
@@ -140,7 +141,10 @@ export default class GameServer {
//news.classList.remove("selected");
screenshots.classList.remove("selected");
preferences.classList.remove("selected");
- if (event.detail.sitetype === "SERVER" && event.detail.page === this.name) {
+ if (
+ event.detail.sitetype === "SERVER" &&
+ event.detail.page === this.name
+ ) {
sidebarItem.classList.add("selected");
// if(event.detail.subPage === "NEWS") {
// news.classList.add("selected");
@@ -163,6 +167,6 @@ export default class GameServer {
const args: any = JSON.parse(JSON.stringify(this.profile));
args.username = localStorage.getItem("2_username_" + this.profile.address);
args.password = localStorage.getItem("2_pin_" + this.profile.address);
- ipcRenderer.send('play', args);
+ ipcRenderer.send("play", args);
}
-} \ No newline at end of file
+}
diff --git a/src/renderer/gameserver/serverView/controller.ts b/src/renderer/gameserver/serverView/controller.ts
index 412033c..5e181ca 100644
--- a/src/renderer/gameserver/serverView/controller.ts
+++ b/src/renderer/gameserver/serverView/controller.ts
@@ -4,33 +4,33 @@ import { ServerInfoPage } from "./info";
import { GameServerPage } from "./serverPage";
import { ServerScreenshotPage } from "./screenshots";
-export type ServerSubPages = 'INFO' | 'SCREENSHOTS' | 'PREF' | 'UNKNOWN';
+export type ServerSubPages = "INFO" | "SCREENSHOTS" | "PREF" | "UNKNOWN";
export class PageController {
- unknownPage: GameServerPage;
- infoPage: ServerInfoPage;
- scrnshtPage: ServerScreenshotPage;
- prefPage: ServerPreferencesPage;
+ unknownPage: GameServerPage;
+ infoPage: ServerInfoPage;
+ scrnshtPage: ServerScreenshotPage;
+ prefPage: ServerPreferencesPage;
- constructor(private server: GameServer) {
- this.unknownPage = new GameServerPage(server);
- this.infoPage = new ServerInfoPage(server);
- this.scrnshtPage = new ServerScreenshotPage(server);
- this.prefPage = new ServerPreferencesPage(server);
- }
+ constructor(private server: GameServer) {
+ this.unknownPage = new GameServerPage(server);
+ this.infoPage = new ServerInfoPage(server);
+ this.scrnshtPage = new ServerScreenshotPage(server);
+ this.prefPage = new ServerPreferencesPage(server);
+ }
- getPage(type: ServerSubPages): HTMLElement {
- let page: GameServerPage = this.unknownPage;
- if (type == "INFO") {
- page = this.infoPage;
- } else if (type == "SCREENSHOTS") {
- page = this.scrnshtPage;
- } else if (type == "PREF") {
- page = this.prefPage;
- }
- const htmlElement = document.createElement('div');
- htmlElement.appendChild(page.getPage());
- updateLoginTextElement(this.server.profile.address);
- return htmlElement;
+ getPage(type: ServerSubPages): HTMLElement {
+ let page: GameServerPage = this.unknownPage;
+ if (type == "INFO") {
+ page = this.infoPage;
+ } else if (type == "SCREENSHOTS") {
+ page = this.scrnshtPage;
+ } else if (type == "PREF") {
+ page = this.prefPage;
}
-} \ No newline at end of file
+ const htmlElement = document.createElement("div");
+ htmlElement.appendChild(page.getPage());
+ updateLoginTextElement(this.server.profile.address);
+ return htmlElement;
+ }
+}
diff --git a/src/renderer/gameserver/serverView/info.ts b/src/renderer/gameserver/serverView/info.ts
index c72286e..40c7e03 100644
--- a/src/renderer/gameserver/serverView/info.ts
+++ b/src/renderer/gameserver/serverView/info.ts
@@ -3,46 +3,48 @@ import { shell } from "electron";
import { GameServerPage } from "./serverPage";
export class ServerInfoPage extends GameServerPage {
+ public getPage(): HTMLElement {
+ const content = document.createElement("div");
+ content.classList.add("infoServerPage");
- public getPage(): HTMLElement {
- const content = document.createElement('div');
- content.classList.add("infoServerPage");
+ const title = document.createElement("div");
+ title.classList.add("title");
+ title.innerText = this.server.name;
+ content.appendChild(title);
- const title = document.createElement('div');
- title.classList.add("title");
- title.innerText = this.server.name;
- content.appendChild(title);
+ const socialContainer = document.createElement("div");
+ socialContainer.classList.add("socialContainer");
+ setTimeout(() => {
+ this.server.socialLinks.forEach((link) => {
+ socialContainer.appendChild(link.getHTML());
+ });
+ }, 5);
+ content.appendChild(socialContainer);
- const socialContainer = document.createElement('div');
- socialContainer.classList.add("socialContainer");
- setTimeout(() => {
- this.server.socialLinks.forEach((link) => {
- socialContainer.appendChild(link.getHTML());
- });
- }, 5);
- content.appendChild(socialContainer);
-
- const shrtDsrption = document.createElement('div');
- shrtDsrption.classList.add("shortDescription");
- shrtDsrption.innerText = this.server.shortDescription;
- content.appendChild(shrtDsrption);
- if (this.server.newsLatestPage && this.server.newsLatestPage != null) {
- const latestNews = document.createElement('div');
- latestNews.classList.add("news");
- content.appendChild(latestNews);
- News.get(this.server.newsLatestPage.url, this.server.newsLatestPage.type).then((result: string) => {
- latestNews.innerHTML = result;
- const aTags = latestNews.getElementsByTagName("a");
- for (var i = 0; i < aTags.length; i++) {
- const href = aTags[i].href.toString();
- aTags[i].addEventListener('click', () => {
- shell.openExternal(href);
- });
- aTags[i].href = "#";
- }
- });
+ const shrtDsrption = document.createElement("div");
+ shrtDsrption.classList.add("shortDescription");
+ shrtDsrption.innerText = this.server.shortDescription;
+ content.appendChild(shrtDsrption);
+ if (this.server.newsLatestPage && this.server.newsLatestPage != null) {
+ const latestNews = document.createElement("div");
+ latestNews.classList.add("news");
+ content.appendChild(latestNews);
+ News.get(
+ this.server.newsLatestPage.url,
+ this.server.newsLatestPage.type
+ ).then((result: string) => {
+ latestNews.innerHTML = result;
+ const aTags = latestNews.getElementsByTagName("a");
+ for (var i = 0; i < aTags.length; i++) {
+ const href = aTags[i].href.toString();
+ aTags[i].addEventListener("click", () => {
+ shell.openExternal(href);
+ });
+ aTags[i].href = "#";
}
-
- return content;
+ });
}
-} \ No newline at end of file
+
+ return content;
+ }
+}
diff --git a/src/renderer/gameserver/serverView/preferences.ts b/src/renderer/gameserver/serverView/preferences.ts
index 4697efe..b7a5255 100644
--- a/src/renderer/gameserver/serverView/preferences.ts
+++ b/src/renderer/gameserver/serverView/preferences.ts
@@ -2,58 +2,65 @@ import GameServerProfile from "../profile";
import { GameServerPage } from "./serverPage";
export class ServerPreferencesPage extends GameServerPage {
+ getPage(): HTMLElement {
+ const content = document.createElement("div");
+ content.classList.add("preferencesServerPage");
- getPage(): HTMLElement {
- const content = document.createElement('div');
- content.classList.add("preferencesServerPage");
+ const title = document.createElement("h2");
+ title.innerText = `Preferences for ${this.server.name}`;
+ content.appendChild(title);
- const title = document.createElement('h2');
- title.innerText = `Preferences for ${this.server.name}`;
- content.appendChild(title);
+ const loginSection = document.createElement("div");
+ loginSection.classList.add("loginSection");
+ content.appendChild(loginSection);
- const loginSection = document.createElement('div');
- loginSection.classList.add("loginSection");
- content.appendChild(loginSection);
+ const loginUsernameLabel = document.createElement("label");
+ loginUsernameLabel.innerText = "Username";
+ const loginUsername = document.createElement("input") as HTMLInputElement;
+ loginUsername.value = localStorage.getItem(
+ "2_username_" + this.server.profile.address
+ );
+ loginUsernameLabel.appendChild(loginUsername);
- const loginUsernameLabel = document.createElement('label');
- loginUsernameLabel.innerText = "Username";
- const loginUsername = document.createElement('input') as HTMLInputElement;
- loginUsername.value = localStorage.getItem("2_username_" + this.server.profile.address);
- loginUsernameLabel.appendChild(loginUsername);
+ const loginPinLabel = document.createElement("label");
+ loginPinLabel.innerText = "Password";
+ const loginPin = document.createElement("input") as HTMLInputElement;
+ loginPin.type = "password";
+ loginPin.value = localStorage.getItem(
+ "2_pin_" + this.server.profile.address
+ );
+ loginPinLabel.appendChild(loginPin);
- const loginPinLabel = document.createElement('label');
- loginPinLabel.innerText = "Password";
- const loginPin = document.createElement('input') as HTMLInputElement;
- loginPin.type = "password";
- loginPin.value = localStorage.getItem("2_pin_" + this.server.profile.address);
- loginPinLabel.appendChild(loginPin);
+ const saveBtn = document.createElement("button") as HTMLButtonElement;
+ saveBtn.innerText = "save";
- const saveBtn = document.createElement('button') as HTMLButtonElement;
- saveBtn.innerText = "save";
+ saveBtn.addEventListener("click", () => {
+ localStorage.setItem(
+ "2_username_" + this.server.profile.address,
+ loginUsername.value
+ );
+ localStorage.setItem(
+ "2_pin_" + this.server.profile.address,
+ loginPin.value
+ );
+ updateLoginTextElement(this.server.profile.address);
+ });
- saveBtn.addEventListener('click', () => {
- localStorage.setItem("2_username_" + this.server.profile.address, loginUsername.value);
- localStorage.setItem("2_pin_" + this.server.profile.address, loginPin.value);
- updateLoginTextElement(this.server.profile.address);
- });
-
-
- loginSection.appendChild(loginUsernameLabel);
- loginSection.appendChild(loginPinLabel);
- loginSection.appendChild(saveBtn);
-
- return content;
- }
+ loginSection.appendChild(loginUsernameLabel);
+ loginSection.appendChild(loginPinLabel);
+ loginSection.appendChild(saveBtn);
+ return content;
+ }
}
export function updateLoginTextElement(serverAddress: string): void {
- const account = localStorage.getItem("2_username_" + serverAddress);
- const pin = localStorage.getItem("2_pin_" + serverAddress);
- const element = document.getElementById('LoginText');
- if (account && pin) {
- element.innerHTML = `Logged in as <b>${account}</b>`;
- } else {
- element.innerHTML = "Automatic login not set up";
- }
-} \ No newline at end of file
+ const account = localStorage.getItem("2_username_" + serverAddress);
+ const pin = localStorage.getItem("2_pin_" + serverAddress);
+ const element = document.getElementById("LoginText");
+ if (account && pin) {
+ element.innerHTML = `Logged in as <b>${account}</b>`;
+ } else {
+ element.innerHTML = "Automatic login not set up";
+ }
+}
diff --git a/src/renderer/gameserver/serverView/screenshots.ts b/src/renderer/gameserver/serverView/screenshots.ts
index 2d6fc62..5af8391 100644
--- a/src/renderer/gameserver/serverView/screenshots.ts
+++ b/src/renderer/gameserver/serverView/screenshots.ts
@@ -2,54 +2,56 @@ import { ipcRenderer, shell } from "electron";
import { GameServerPage } from "./serverPage";
export class ServerScreenshotPage extends GameServerPage {
-
getPage(): HTMLElement {
- const screenshotContainer = document.createElement('div');
+ const screenshotContainer = document.createElement("div");
screenshotContainer.classList.add("screenshotsContainer");
screenshotContainer.id = "screenshots";
- ipcRenderer.send('getScreenshots', this.server.profile.address);
+ ipcRenderer.send("getScreenshots", this.server.profile.address);
return screenshotContainer;
}
}
-ipcRenderer.on('getScreenshots', (event: any, data: { dir: string, screenshots: string[] }) => {
- console.log(data)
- const screenshots = document.getElementById('screenshots');
- if (screenshots) {
- // Display screenshots if that tab is open
- if (data.screenshots.length !== 0) {
- data.screenshots.forEach((fileName: string) => {
- const screenshot = document.createElement("div");
- screenshot.classList.add("screenshot");
- screenshots.appendChild(screenshot);
- const img = document.createElement("img");
- img.src = data.dir + fileName;
- screenshot.appendChild(img);
-
- // const text = document.createElement("span");
- // text.innerText = fileName;
- // screenshot.appendChild(text);
- screenshot.addEventListener('dragstart', (event) => {
- event.preventDefault()
- ipcRenderer.send('dragFileOut', data.dir + fileName)
- })
-
+ipcRenderer.on(
+ "getScreenshots",
+ (event: any, data: { dir: string; screenshots: string[] }) => {
+ console.log(data);
+ const screenshots = document.getElementById("screenshots");
+ if (screenshots) {
+ // Display screenshots if that tab is open
+ if (data.screenshots.length !== 0) {
+ data.screenshots.forEach((fileName: string) => {
+ const screenshot = document.createElement("div");
+ screenshot.classList.add("screenshot");
+ screenshots.appendChild(screenshot);
+ const img = document.createElement("img");
+ img.src = data.dir + fileName;
+ screenshot.appendChild(img);
+
+ // const text = document.createElement("span");
+ // text.innerText = fileName;
+ // screenshot.appendChild(text);
+ screenshot.addEventListener("dragstart", (event) => {
+ event.preventDefault();
+ ipcRenderer.send("dragFileOut", data.dir + fileName);
+ });
+ });
+ } else {
+ const nothingHere = document.createElement("p");
+ nothingHere.classList.add("nothingHere");
+ nothingHere.innerText =
+ "There is nothing here, yet. Make some screenshots in Game and come back here. The default key for snaping screenshots is 'P'.";
+
+ screenshots.appendChild(nothingHere);
+ }
+
+ const openFolderButton = document.createElement("button");
+ openFolderButton.innerText = "Open folder to see all";
+ openFolderButton.addEventListener("click", () => {
+ shell.openItem(data.dir);
});
- } else {
- const nothingHere = document.createElement("p");
- nothingHere.classList.add("nothingHere");
- nothingHere.innerText = "There is nothing here, yet. Make some screenshots in Game and come back here. The default key for snaping screenshots is 'P'."
-
- screenshots.appendChild(nothingHere);
+ screenshots.appendChild(openFolderButton);
}
-
- const openFolderButton = document.createElement('button');
- openFolderButton.innerText = "Open folder to see all";
- openFolderButton.addEventListener('click', () => {
- shell.openItem(data.dir);
- });
- screenshots.appendChild(openFolderButton);
}
-})
+);
diff --git a/src/renderer/gameserver/serverView/serverPage.ts b/src/renderer/gameserver/serverView/serverPage.ts
index 91556b0..622f633 100644
--- a/src/renderer/gameserver/serverView/serverPage.ts
+++ b/src/renderer/gameserver/serverView/serverPage.ts
@@ -1,14 +1,11 @@
import GameServer from "../server";
export class GameServerPage {
-
- constructor(protected server: GameServer) {
-
- }
- getPage(): HTMLElement {
- const content = document.createElement('div');
- content.classList.add("unknownServerPage");
- content.innerText = `Unknown page for${this.server.name}`;
- return content;
- };
-} \ No newline at end of file
+ constructor(protected server: GameServer) {}
+ getPage(): HTMLElement {
+ const content = document.createElement("div");
+ content.classList.add("unknownServerPage");
+ content.innerText = `Unknown page for${this.server.name}`;
+ return content;
+ }
+}
diff --git a/src/renderer/gameserver/socialLink.ts b/src/renderer/gameserver/socialLink.ts
index b56fab0..9c7e353 100644
--- a/src/renderer/gameserver/socialLink.ts
+++ b/src/renderer/gameserver/socialLink.ts
@@ -1,24 +1,28 @@
import { shell } from "electron";
export class socialLink {
- constructor(
- public icon: string,// has to be one from font awesome -https://fontawesome.com/icons
- public tooltip: string,
- public url: string
- ) { }
-
- getHTML(): HTMLElement {
- //<button onclick="sv.openSocialLink(this)" socialLink="abc"><i class="fa fa-user"></i></button><br>
- const element = document.createElement('button');
- element.onclick = () => { this.open() };
- element.innerHTML = `<i class="${this.icon}"></i>`;
- element.title = this.tooltip;
- return element;
- }
-
- open() {
- console.log("A link was clicked!", this.url);
- if (this.url)
- shell.openExternal(this.url.indexOf("://") !== -1 ? this.url : `https://${this.url}`);
- }
- } \ No newline at end of file
+ constructor(
+ public icon: string, // has to be one from font awesome -https://fontawesome.com/icons
+ public tooltip: string,
+ public url: string
+ ) {}
+
+ getHTML(): HTMLElement {
+ //<button onclick="sv.openSocialLink(this)" socialLink="abc"><i class="fa fa-user"></i></button><br>
+ const element = document.createElement("button");
+ element.onclick = () => {
+ this.open();
+ };
+ element.innerHTML = `<i class="${this.icon}"></i>`;
+ element.title = this.tooltip;
+ return element;
+ }
+
+ open() {
+ console.log("A link was clicked!", this.url);
+ if (this.url)
+ shell.openExternal(
+ this.url.indexOf("://") !== -1 ? this.url : `https://${this.url}`
+ );
+ }
+}
diff --git a/src/renderer/index.ts b/src/renderer/index.ts
index f83bd3f..c5729de 100644
--- a/src/renderer/index.ts
+++ b/src/renderer/index.ts
@@ -1,39 +1,36 @@
-import { ipcRenderer } from 'electron';
+import { ipcRenderer } from "electron";
-const quitBtn = document.getElementById('quit');
+const quitBtn = document.getElementById("quit");
-quitBtn.addEventListener('click', () => {
- ipcRenderer.send('quit');
+quitBtn.addEventListener("click", () => {
+ ipcRenderer.send("quit");
});
-const minimizeBtn = document.getElementById('minimize');
+const minimizeBtn = document.getElementById("minimize");
-minimizeBtn.addEventListener('click', () => {
+minimizeBtn.addEventListener("click", () => {
minimizeBtn.blur();
- ipcRenderer.send('minimize');
+ ipcRenderer.send("minimize");
});
document.ondragover = document.ondrop = (event) => {
event.preventDefault();
};
-
-const debugBtn = document.getElementById('debug');
+const debugBtn = document.getElementById("debug");
//debugBtn.hidden = true;
-debugBtn.addEventListener('click', () => {
+debugBtn.addEventListener("click", () => {
debugBtn.blur();
- ipcRenderer.send('debug');
+ ipcRenderer.send("debug");
});
-const activityLabel = document.getElementById('activity');
-const progressBar = document.getElementById('progress') as HTMLProgressElement;
-ipcRenderer.on('status-update', (event:any, status:any) => {
+const activityLabel = document.getElementById("activity");
+const progressBar = document.getElementById("progress") as HTMLProgressElement;
+ipcRenderer.on("status-update", (event: any, status: any) => {
activityLabel.innerText = status.activity;
- if(status.ActivityIsError)
- activityLabel.classList.add("error");
- else
- activityLabel.classList.remove("error");
+ if (status.ActivityIsError) activityLabel.classList.add("error");
+ else activityLabel.classList.remove("error");
progressBar.value = status.progress;
-})
+});
diff --git a/src/renderer/serverView.ts b/src/renderer/serverView.ts
index 04ecde4..d502cc5 100644
--- a/src/renderer/serverView.ts
+++ b/src/renderer/serverView.ts
@@ -1,140 +1,156 @@
-import { ipcRenderer, shell } from 'electron';
-import GameServer from './gameserver/server';
-import { switchPage } from './customEvents';
+import { ipcRenderer, shell } from "electron";
+import GameServer from "./gameserver/server";
+import { switchPage } from "./customEvents";
-import CheckNAcceptTOS from './gameserver/TOSCheck';
-import { acceptLastTOS } from './gameserver/TOSCheck';
+import CheckNAcceptTOS from "./gameserver/TOSCheck";
+import { acceptLastTOS } from "./gameserver/TOSCheck";
-let GameServerList:GameServer[] = null;
-let SelectedGameserver:GameServer = null;
-const playBtn:HTMLButtonElement = document.getElementById('play') as (HTMLButtonElement);
+let GameServerList: GameServer[] = null;
+let SelectedGameserver: GameServer = null;
+const playBtn: HTMLButtonElement = document.getElementById(
+ "play"
+) as HTMLButtonElement;
-const TOSDialog:HTMLDialogElement = document.getElementById('TOSDialog') as (HTMLDialogElement);
+const TOSDialog: HTMLDialogElement = document.getElementById(
+ "TOSDialog"
+) as HTMLDialogElement;
-playBtn.addEventListener('click', async () => {
- if( await CheckNAcceptTOS(SelectedGameserver)){
+playBtn.addEventListener("click", async () => {
+ if (await CheckNAcceptTOS(SelectedGameserver)) {
SelectedGameserver.play();
} else {
//Open Please accept TOS window
TOSDialog.showModal();
}
});
-const TOSCancel:HTMLButtonElement = document.getElementById('TOSCancel') as (HTMLButtonElement);
-TOSCancel.addEventListener('click', function() {
- TOSDialog.close();
+const TOSCancel: HTMLButtonElement = document.getElementById(
+ "TOSCancel"
+) as HTMLButtonElement;
+TOSCancel.addEventListener("click", function () {
+ TOSDialog.close();
});
-const TOSOpen:HTMLButtonElement = document.getElementById('TOSOpen') as (HTMLButtonElement);
-TOSOpen.addEventListener('click', function(e) {
+const TOSOpen: HTMLButtonElement = document.getElementById(
+ "TOSOpen"
+) as HTMLButtonElement;
+TOSOpen.addEventListener("click", function (e) {
e.preventDefault();
shell.openExternal(SelectedGameserver.TOSLink);
});
-const TOSAccept:HTMLButtonElement = document.getElementById('TOSAccept') as (HTMLButtonElement);
-TOSAccept.addEventListener('click', function() {
- acceptLastTOS(SelectedGameserver);
- SelectedGameserver.play();
- TOSDialog.close();
+const TOSAccept: HTMLButtonElement = document.getElementById(
+ "TOSAccept"
+) as HTMLButtonElement;
+TOSAccept.addEventListener("click", function () {
+ acceptLastTOS(SelectedGameserver);
+ SelectedGameserver.play();
+ TOSDialog.close();
});
-const sidebarReference = document.getElementById('sidebar');
-let clickableMenueEntries:HTMLElement[]=[];
-function updateView(){
+const sidebarReference = document.getElementById("sidebar");
+let clickableMenueEntries: HTMLElement[] = [];
+function updateView() {
// This is for updating the ui to new data
-
- if(GameServerList){
+ if (GameServerList) {
// Clear every thing out
while (sidebarReference.firstChild) {
- sidebarReference.removeChild(sidebarReference.firstChild);
+ sidebarReference.removeChild(sidebarReference.firstChild);
}
- GameServerList.forEach((server)=>{
+ GameServerList.forEach((server) => {
sidebarReference.appendChild(server.getMenuEntry());
});
//Switch page according localstorage:
- if(GameServerList.length != 0){
+ if (GameServerList.length != 0) {
const selectedServer = localStorage.getItem("selected_server");
- if(selectedServer && selectedServer !==null ){
- if(GameServerList.filter((server)=>server.name==selectedServer).length == 0){
+ if (selectedServer && selectedServer !== null) {
+ if (
+ GameServerList.filter((server) => server.name == selectedServer)
+ .length == 0
+ ) {
localStorage.removeItem("selected_server");
- switchPage("SERVER", GameServerList[0].name, 'INFO');
- }else{
- switchPage("SERVER", selectedServer, 'INFO');
+ switchPage("SERVER", GameServerList[0].name, "INFO");
+ } else {
+ switchPage("SERVER", selectedServer, "INFO");
}
- }else{
+ } else {
//TODO ask if is on special page like global settings first
- switchPage("SERVER", GameServerList[0].name, 'INFO');
+ switchPage("SERVER", GameServerList[0].name, "INFO");
}
}
}
}
-const serverPage = document.getElementById('serverPage');
-const switchPageEvent = document.createElement('span');
+const serverPage = document.getElementById("serverPage");
+const switchPageEvent = document.createElement("span");
switchPageEvent.classList.add("switch-page-event");
-switchPageEvent.addEventListener("site-changed", (event:CustomEvent)=>{
- if(event.detail.sitetype === "SERVER"){
- SelectedGameserver = GameServerList.filter((server)=>server.name==event.detail.page)[0];
+switchPageEvent.addEventListener("site-changed", (event: CustomEvent) => {
+ if (event.detail.sitetype === "SERVER") {
+ SelectedGameserver = GameServerList.filter(
+ (server) => server.name == event.detail.page
+ )[0];
localStorage.setItem("selected_server", SelectedGameserver.name);
while (serverPage.firstChild) {
- serverPage.removeChild(serverPage.firstChild);
+ serverPage.removeChild(serverPage.firstChild);
}
let page = SelectedGameserver.pageController.getPage(event.detail.subPage);
serverPage.appendChild(page);
// page.classList.add('animated');
// page.classList.add('fadeIn');
- }else{
+ } else {
SelectedGameserver == null;
-
}
- if(typeof(SelectedGameserver) === "undefined" || SelectedGameserver == null){
+ if (typeof SelectedGameserver === "undefined" || SelectedGameserver == null) {
// No gameserver selected
playBtn.hidden = true;
- }else{
+ } else {
// A gameserver is selected
- playBtn.innerText=`Play ${SelectedGameserver.menuName}`;
+ playBtn.innerText = `Play ${SelectedGameserver.menuName}`;
playBtn.hidden = false;
}
setBackground();
});
document.getElementById("topbar").appendChild(switchPageEvent);
-let peviousSelectedGameserver:any=null;
-const contentBackground = document.getElementById('contentBackground');
-function setBackground(){
- if(peviousSelectedGameserver !== SelectedGameserver){
+let peviousSelectedGameserver: any = null;
+const contentBackground = document.getElementById("contentBackground");
+function setBackground() {
+ if (peviousSelectedGameserver !== SelectedGameserver) {
while (contentBackground.firstChild) {
- contentBackground.removeChild(contentBackground.firstChild);
+ contentBackground.removeChild(contentBackground.firstChild);
}
- if(typeof(SelectedGameserver) === "undefined" || SelectedGameserver == null){
- contentBackground.hidden=true;
- contentBackground.classList.add('hidden');
- }else{
- if(SelectedGameserver.backgrounds[0] && !SelectedGameserver.backgrounds[0].isVideo){
- const background1 = document.createElement('img');
+ if (
+ typeof SelectedGameserver === "undefined" ||
+ SelectedGameserver == null
+ ) {
+ contentBackground.hidden = true;
+ contentBackground.classList.add("hidden");
+ } else {
+ if (
+ SelectedGameserver.backgrounds[0] &&
+ !SelectedGameserver.backgrounds[0].isVideo
+ ) {
+ const background1 = document.createElement("img");
background1.src = `./media/server/${SelectedGameserver.backgrounds[0].file}`;
contentBackground.appendChild(background1);
- background1.classList.add('animated');
- background1.classList.add('fadeIn');
+ background1.classList.add("animated");
+ background1.classList.add("fadeIn");
}
- contentBackground.appendChild(document.createElement('div'))
- contentBackground.hidden=false;
- contentBackground.classList.remove('hidden');
+ contentBackground.appendChild(document.createElement("div"));
+ contentBackground.hidden = false;
+ contentBackground.classList.remove("hidden");
}
}
peviousSelectedGameserver = SelectedGameserver;
}
-ipcRenderer.on('status-update', (event:any, status:any) => {
+ipcRenderer.on("status-update", (event: any, status: any) => {
// Everything that isnt server view related is in index.ts
playBtn.disabled = status.playing;
-})
-
-
-
+});
-import { GameServers } from './gameserver/data';
+import { GameServers } from "./gameserver/data";
GameServerList = GameServers;
updateView();