/
Server.ts
412 lines (382 loc) · 16.8 KB
/
Server.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
import { ProgressInfo } from 'builder-util-runtime';
import * as compareVersion from 'compare-versions';
import { autoUpdater, UpdateCheckResult } from 'electron-updater';
import * as fs from 'fs-extra';
import * as moment from 'moment';
import * as path from 'path';
import * as rimraf from 'rimraf';
import { getEnvFolder, isProduction, randomHashedString } from '@models/env';
import { GamesCollection } from '@models/GamesCollection';
import { PlayableGame } from '@models/PlayableGame';
import { GameSource, PotentialGame } from '@models/PotentialGame';
import { getFirstGame, getGameById, searchGame } from './api/igdbWrapper';
import { findSteamData } from './api/SteamDataFinder';
import { getSteamGamePlayTime, getSteamGamesPlayTimes } from './api/SteamPlayTimeWrapper';
import { searchBattleNetGames } from './crawlers/BattleNetCrawler';
import { searchEmulatedGames } from './crawlers/EmulatedCrawler';
import { searchOriginGames } from './crawlers/OriginCrawler';
import { getPlayableGames } from './crawlers/PlayableGamesCrawler';
import { searchSteamGames } from './crawlers/SteamCrawler';
import { launchGame } from './GameLauncher';
import { downloadGamePictures, isAlreadyStored } from './helpers';
import { logger } from './Logger';
import { potentialGamesCacher } from './PotentialGamesCacher';
import { WindowsHandler } from './WindowsHandler';
export class Server {
private readonly windowsHandler: WindowsHandler;
private vitrineConfig: any;
private modulesConfig: any;
private potentialGames: GamesCollection<PotentialGame>;
private playableGames: GamesCollection<PlayableGame>;
private gameLaunched: boolean;
public constructor(config: any, private locales: any[], private vitrineConfigFilePath: string) {
({ modulesConfig: this.modulesConfig, vitrineConfig: this.vitrineConfig } = config);
this.windowsHandler = new WindowsHandler();
this.gameLaunched = false;
this.registerEvents();
}
public run() {
this.windowsHandler.run();
}
public registerEvents() {
this.windowsHandler
.listenToLoader('ready', this.loaderReady.bind(this))
.listenToLoader('launch-client', this.windowsHandler.createClientWindow.bind(this.windowsHandler));
this.windowsHandler
.listenToClient('settings-asked', this.clientSettingsAsked.bind(this))
.listenToClient('ready', this.windowsHandler.clientReady.bind(this.windowsHandler))
.listenToClient('quit-application', this.quitApplication.bind(this))
.listenToClient('fill-igdb-game', this.fillIgdbGame.bind(this))
.listenToClient('search-igdb-games', this.searchIgdbGames.bind(this))
.listenToClient('add-all-games', this.addAllPotentialGames.bind(this))
.listenToClient('add-game', this.addGame.bind(this))
.listenToClient('edit-game', this.editGame.bind(this))
.listenToClient('edit-game-time-played', this.editGameTimePlayed.bind(this))
.listenToClient('launch-game', this.launchGame.bind(this))
.listenToClient('remove-game', this.removeGame.bind(this))
.listenToClient('refresh-potential-games', this.findPotentialGames.bind(this))
.listenToClient('update-settings', this.updateSettings.bind(this));
}
public async loaderReady() {
if (!isProduction()) {
this.windowsHandler.sendToLoader('no-update-found');
return;
}
logger.info('Server', 'Checking for updates.');
autoUpdater.allowPrerelease = true;
autoUpdater.signals.progress((progress: ProgressInfo) => {
this.windowsHandler.sendToLoader('update-progress', Math.round(progress.percent));
});
autoUpdater.signals.updateDownloaded(() => {
autoUpdater.quitAndInstall(true, true);
});
try {
const lastUpdate: UpdateCheckResult = await autoUpdater.checkForUpdates();
if (compareVersion(lastUpdate.updateInfo.version, autoUpdater.currentVersion.version) === 1) {
logger.info('Server', `Update ${lastUpdate.updateInfo.version} found.`);
this.windowsHandler.sendToLoader('update-found', lastUpdate.updateInfo.version);
} else {
logger.info('Server', 'No updates found.');
this.windowsHandler.sendToLoader('no-update-found');
}
} catch (error) {
logger.info('Server', 'Internet is offline, aborting updates checking.');
this.windowsHandler.sendToLoader('no-update-found');
}
}
public async clientSettingsAsked() {
this.potentialGames = new GamesCollection();
this.playableGames = new GamesCollection();
logger.info('Server', 'Sending configuration to client.');
this.windowsHandler.sendToClient('init-settings', this.vitrineConfig, this.modulesConfig, this.locales);
if (!this.vitrineConfig.firstLaunch) {
try {
if (this.vitrineConfig.steam) {
const steamConfig: any = await findSteamData(this.vitrineConfig.steam);
this.vitrineConfig.steam = {
...this.vitrineConfig.steam,
...steamConfig
};
await getSteamGamesPlayTimes(this.vitrineConfig.steam.userId);
}
this.playableGames = await getPlayableGames(this.vitrineConfig.steam);
logger.info('Server', 'Sending playable games to client.');
this.windowsHandler.sendToClient('add-playable-games', this.playableGames.getGames());
this.findPotentialGames();
} catch (error) {
this.throwServerError(error);
}
} else {
logger.info('Server', 'Vitrine first launch.');
}
}
public quitApplication(mustRelaunch?: boolean) {
this.windowsHandler.quitApplication(mustRelaunch);
}
public async fillIgdbGame(gameId: number) {
try {
this.windowsHandler.sendToClient('send-igdb-game', await getGameById(gameId, this.vitrineConfig.lang));
} catch (error) {
this.throwServerError(error);
}
}
public async searchIgdbGames(gameName: string, resultsNb?: number) {
try {
this.windowsHandler.sendToClient('send-igdb-searches', gameName, await searchGame(gameName, resultsNb));
} catch (error) {
this.throwServerError(error);
}
}
public async addAllPotentialGames() {
try {
await Promise.all(
[...this.potentialGames.getGames()].map(async (potentialGame: PotentialGame) => {
const filledGame: any = await getFirstGame(potentialGame.name, this.vitrineConfig.lang);
const [executable, ...args]: string[] = potentialGame.commandLine;
filledGame.executable = executable;
filledGame.arguments = args.join(' ');
console.log(filledGame);
const addedGame: PlayableGame = new PlayableGame(filledGame.name, filledGame);
console.log(addedGame);
addedGame.source = potentialGame.source;
delete filledGame.source;
delete filledGame.id;
const game: PlayableGame = await Server.registerGame(addedGame, filledGame);
logger.info('Server', `Outputting game config file for ${game.name}.`);
const configFilePath: string = path.resolve(path.resolve(getEnvFolder('games'), game.uuid), 'config.json');
await fs.outputJson(configFilePath, game, { spaces: 2 });
logger.info('Server', `Added game ${game.name} sent to client.`);
this.playableGames.addGame(game);
this.playableGames.alphaSort();
this.potentialGames.removeGame(game.uuid);
this.potentialGames.alphaSort();
this.windowsHandler.sendToClient('update-add-all-games-status', this.playableGames.getGames(), this.potentialGames.getGames());
})
);
} catch (error) {
console.log(error);
this.throwServerError(error);
}
}
public async addGame(gameForm: any) {
logger.info('Server', `Adding ${gameForm.name} to Vitrine.`);
const addedGame: PlayableGame = new PlayableGame(gameForm.name, gameForm);
addedGame.source = gameForm.source;
delete gameForm.source;
await this.sendRegisteredGame(await Server.registerGame(addedGame, gameForm));
}
public async editGame(gameUuid: string, gameForm: any) {
logger.info('Server', `Editing ${gameForm.name}.`);
const editedGame: PlayableGame = this.playableGames.getGame(gameUuid);
editedGame.name = gameForm.name;
editedGame.commandLine = [];
const { backgroundScreen, cover } = editedGame.details;
editedGame.details = {
...gameForm,
backgroundScreen,
cover
};
await this.sendRegisteredGame(await Server.registerGame(editedGame, gameForm, true), true);
}
public editGameTimePlayed(gameUuid: string, timePlayed: number) {
const editedGame: PlayableGame = this.playableGames.getGame(gameUuid);
editedGame.timePlayed = timePlayed;
logger.info('Server', `Editing time played for ${editedGame.name} (${timePlayed})`);
this.sendRegisteredGame(editedGame, true);
}
public async launchGame(gameUuid: string) {
if (this.gameLaunched) {
logger.info('Server', 'Trying to launch a game but another one is already running.');
return;
}
const launchingGame: PlayableGame = this.playableGames.getGame(gameUuid);
this.gameLaunched = true;
try {
const secondsPlayed: number = await launchGame(launchingGame);
this.gameLaunched = false;
await launchingGame.addPlayTime(secondsPlayed);
logger.info('Server', `Adding time played ${secondsPlayed} to ${launchingGame.name} (${launchingGame.uuid}).`);
this.windowsHandler.sendToClient('stop-game', gameUuid, launchingGame.timePlayed);
} catch (error) {
this.gameLaunched = false;
this.throwServerError(error);
}
}
public removeGame(gameUuid: string) {
this.playableGames.removeGame(gameUuid);
const gameDirectory: string = path.resolve(getEnvFolder('games'), gameUuid);
rimraf(gameDirectory, () => {
logger.info('Server', `Removing game ${gameUuid} from Vitrine and deleting corresponding directory.`);
this.windowsHandler.sendToClient('remove-playable-game', gameUuid);
this.findPotentialGames();
});
}
public async findPotentialGames() {
try {
logger.info('Server', 'Beginning to search potential games.');
this.windowsHandler.sendToClient('potential-games-search-begin');
this.potentialGames.clear();
await Promise.all([
// TODO: return PotentialGames[] and refactor crawlers
this.searchSteamGames(),
this.searchOriginGames(),
this.searchBattleNetGames(),
this.searchEmulatedGames()
]);
this.potentialGames.alphaSort();
this.potentialGames.setGames(await potentialGamesCacher.cache(this.potentialGames.getGames()));
logger.info('Server', `${this.potentialGames.size()} potential games sent to client.`);
this.windowsHandler.sendToClient('add-potential-games', this.potentialGames.getGames());
} catch (error) {
this.throwServerError(error);
}
}
public async updateSettings(settingsForm: any) {
logger.info('Server', 'Updating global settings.');
const config: any = { ...settingsForm };
let firstTimeSteam: boolean = false;
if (settingsForm.steam && !this.modulesConfig.steam.userId) {
firstTimeSteam = true;
}
try {
await fs.outputJson(this.vitrineConfigFilePath, config, { spaces: 2 });
logger.info('Server', 'Settings outputted to vitrine_config.json.');
this.vitrineConfig = config;
if (firstTimeSteam) {
const steamConfig: any = await findSteamData(this.vitrineConfig.steam);
this.vitrineConfig.steam = {
...this.vitrineConfig.steam,
...steamConfig
};
await getSteamGamesPlayTimes(this.vitrineConfig.steam.userId);
}
this.windowsHandler.sendToClient('settings-updated', this.vitrineConfig);
this.findPotentialGames();
} catch (error) {
this.throwServerError(error);
}
}
private async searchSteamGames() {
if (!this.vitrineConfig.steam) {
return;
}
const games: GamesCollection<PotentialGame> = await searchSteamGames(
{
...this.modulesConfig.steam,
...this.vitrineConfig.steam
},
this.playableGames.getGamesFromSource(GameSource.STEAM)
);
logger.info('Server', 'Adding potential Steam games to potential games list.');
this.potentialGames.addGames(games.getGames());
}
private async searchOriginGames() {
if (!this.vitrineConfig.origin) {
return;
}
const games: GamesCollection<PotentialGame> = await searchOriginGames(
{
...this.modulesConfig.origin,
...this.vitrineConfig.origin
},
this.playableGames.getGamesFromSource(GameSource.ORIGIN)
);
logger.info('Server', 'Adding potential Origin games to potential games list.');
this.potentialGames.addGames(games.getGames());
}
private async searchBattleNetGames() {
if (!this.vitrineConfig.battleNet) {
return;
}
const games: GamesCollection<PotentialGame> = await searchBattleNetGames({
...this.modulesConfig.battleNet,
...this.vitrineConfig.battleNet
});
logger.info('Server', 'Adding potential Battle.net games to potential games list.');
this.potentialGames.addGames(games.getGames());
}
private async searchEmulatedGames() {
if (!this.vitrineConfig.emulated) {
return;
}
const games: GamesCollection<PotentialGame> = await searchEmulatedGames(
{
...this.modulesConfig.emulated,
...this.vitrineConfig.emulated
},
this.playableGames.getGamesFromSource(GameSource.EMULATED)
);
logger.info('Server', 'Adding potential emulated games to potential games list.');
this.potentialGames.addGames(games.getGames());
}
private static async registerGame(game: PlayableGame, gameForm: any, editing: boolean = false) {
game.commandLine = gameForm.arguments ? [gameForm.executable, gameForm.arguments] : [gameForm.executable];
game.details.rating = parseInt(game.details.rating);
if (typeof game.details.genres === 'string') {
game.details.genres = game.details.genres.split(', ');
}
game.details.releaseDate = moment(game.details.date, 'DD/MM/YYYY').unix() * 1000;
if (game.source === GameSource.STEAM) {
game.details.steamId = parseInt(game.commandLine[1].match(/\d+/g)[0]);
}
delete game.details.name;
delete game.details.date;
delete game.details.executable;
delete game.details.arguments;
if (!editing && game.source === GameSource.STEAM) {
game.timePlayed = getSteamGamePlayTime(game.details.steamId);
}
logger.info('Server', `Game form data for ${game.name} being formatted.`);
const gameDirectory: string = path.resolve(getEnvFolder('games'), game.uuid);
const configFilePath: string = path.resolve(gameDirectory, 'config.json');
if (!editing && (await fs.pathExists(configFilePath))) {
return;
}
await fs.ensureDir(gameDirectory);
if (!isAlreadyStored(game.details.backgroundScreen, gameForm.backgroundScreen) || !isAlreadyStored(game.details.cover, gameForm.cover)) {
const gameHash: string = randomHashedString(8);
const backgroundPath: string = path.resolve(gameDirectory, `background.${gameHash}.jpg`);
const coverPath: string = path.resolve(gameDirectory, `cover.${gameHash}.jpg`);
logger.info('Server', `Creating hashed versions for background picture and cover for ${game.name}.`);
const backgroundUrl: string = editing
? gameForm.backgroundScreen
: game.details.backgroundScreen
? game.details.backgroundScreen.replace('t_screenshot_med', 't_screenshot_huge')
: null;
const coverUrl: string = editing ? gameForm.cover : game.details.cover;
const images: any = await downloadGamePictures(game.details, {
backgroundPath,
backgroundUrl,
coverPath,
coverUrl
});
delete game.details.screenshots;
delete game.details.background;
game.details = { ...game.details, ...images };
} else {
logger.info('Server', `Background picture and cover for ${game.name} already stored.`);
}
return game;
}
private async sendRegisteredGame(game: PlayableGame, editing: boolean = false) {
logger.info('Server', `Outputting game config file for ${game.name}.`);
const configFilePath: string = path.resolve(path.resolve(getEnvFolder('games'), game.uuid), 'config.json');
await fs.outputJson(configFilePath, game, { spaces: 2 });
if (!editing) {
logger.info('Server', `Added game ${game.name} sent to client.`);
this.playableGames.addGame(game);
this.windowsHandler.sendToClient('add-playable-game', game);
} else {
logger.info('Server', `Edited game ${game.name} sent to client.`);
this.playableGames.editGame(game);
this.windowsHandler.sendToClient('edit-playable-game', game);
}
if (!editing && game.source !== GameSource.LOCAL) {
this.findPotentialGames();
}
}
private throwServerError(error: Error) {
logger.info('Server', `An error happened: ${error.message}`);
this.windowsHandler.sendToClient('error', error.name, error.stack);
}
}