summaryrefslogtreecommitdiff
path: root/src/main/manaplus/manaplus.ts
blob: 539664927cbea38cad4c90878bb46f16408b207f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
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';

let ManaPlusInstance:ManaPlusApp;

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")
  }

  export function init(){
    if(os.platform() == "win32"){
      ManaPlusInstance = new ManaPlusAppWindows();
      console.log("GameDir:"+ManaPlusInstance.getGameDir());
    }
  }

  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
    };
    let params:string[];
    try {
      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){
      console.log(e);
      Status.showError("Launch Preperation Failed", e.message, "Launch preparation failed")
      return;
    }
    let willUpdate:boolean=false;
    // check if it is installed
    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){
        console.log(e);
        Status.showError("Launch Preperation Failed", e.message, "Launch preparation failed")
        return;
      }
    } else {
      // Not installed will install it
      willUpdate = true;
    }
    // Install/Update the gameclient if needed
    if(willUpdate){
      await update();
    }

    //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);
    // On Close
    Status.setGameRunning(false);
    Status.setPlaying(false);
    Status.removeActivity();
    EventEmitter.emit('reopenWindow');
    EventEmitter.emit('closeTray');
    CurrentServer=null;
  }

}

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)});
    });
});
EventEmitter.on('Mana:openScreenshotDir', ()=>{
  shell.openItem(path.normalize(app.getPath('userData')+`/screenshots/${CurrentServer.address}/`));
});

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){
      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;
}

let manaplusInstance: any=null;

function runManaProgram(parameters: string[],gameExe:string): Promise<any> {
  return new Promise((resolve, reject)=>{
    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', ()=>{
      manaplusInstance = null;
      resolve();
    });
    child.on('error', ()=>{
      manaplusInstance = null;
      resolve();
      //// TODO: Handle Error
    });
    manaplusInstance = child;
  });
}

EventEmitter.on("Mana:killMana",()=>{
  if(manaplusInstance && manaplusInstance !== null)
    manaplusInstance.kill('SIGINT');
});

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;
}

function dialogPromiseWrapper(options:any):Promise<number>{
  return new Promise((res, rej) => {
    dialog.showMessageBox(options, (index) => {
     res(index);
    })
  });
}