247 lines
9.2 KiB
JavaScript
247 lines
9.2 KiB
JavaScript
const { app, BrowserWindow, dialog, ipcMain } = require('electron');
|
|
const path = require('path');
|
|
const fs = require('fs');
|
|
const fsp = fs.promises;
|
|
const { emptyDropStats, mergeDropStatsInto } = require('./lib/dropstats');
|
|
|
|
// Stocké automatiquement dans ~/.config/farm-tracker/ sur Linux (géré par Electron).
|
|
const userDataDir = app.getPath('userData');
|
|
const APP_STATE_FILE = path.join(userDataDir, 'app-state.json');
|
|
const DROPSTATS_FILE = path.join(userDataDir, 'dropstats.json');
|
|
const COMMUNITY_DROPSTATS_FILE = path.join(userDataDir, 'community-dropstats.json');
|
|
const SESSION_HISTORY_FILE = path.join(userDataDir, 'session-history.json');
|
|
|
|
// ---------- Lecture / écriture disque (JSON indenté = facilement lisible) ----------
|
|
|
|
function readJsonSafe(filePath, fallback) {
|
|
try {
|
|
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
} catch (e) {
|
|
return fallback;
|
|
}
|
|
}
|
|
|
|
function writeJsonAtomic(filePath, obj) {
|
|
try {
|
|
if (!fs.existsSync(userDataDir)) fs.mkdirSync(userDataDir, { recursive: true });
|
|
const tmp = filePath + '.tmp';
|
|
fs.writeFileSync(tmp, JSON.stringify(obj, null, 2));
|
|
fs.renameSync(tmp, filePath);
|
|
return true;
|
|
} catch (e) {
|
|
console.error('Erreur de sauvegarde (' + filePath + '):', e);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function loadAppState() { return readJsonSafe(APP_STATE_FILE, null); }
|
|
function saveAppState(obj) { return writeJsonAtomic(APP_STATE_FILE, obj); }
|
|
function loadDropStats() { return readJsonSafe(DROPSTATS_FILE, emptyDropStats()); }
|
|
function saveDropStats(obj) { return writeJsonAtomic(DROPSTATS_FILE, obj); }
|
|
function loadCommunityDropStats() { return readJsonSafe(COMMUNITY_DROPSTATS_FILE, null); }
|
|
function saveCommunityDropStats(obj) { return writeJsonAtomic(COMMUNITY_DROPSTATS_FILE, obj); }
|
|
function loadSessionHistory() { return readJsonSafe(SESSION_HISTORY_FILE, { type: 'farm-tracker-session-history', version: 1, sessions: [] }); }
|
|
function saveSessionHistory(obj) { return writeJsonAtomic(SESSION_HISTORY_FILE, obj); }
|
|
|
|
function resolveLogPath(folderPath) {
|
|
const candidate1 = path.join(folderPath, 'logs', 'latest.log');
|
|
const candidate2 = path.join(folderPath, 'latest.log');
|
|
if (fs.existsSync(candidate1)) return candidate1;
|
|
if (fs.existsSync(candidate2)) return candidate2;
|
|
return null;
|
|
}
|
|
|
|
let mainWindow;
|
|
|
|
function createWindow() {
|
|
mainWindow = new BrowserWindow({
|
|
width: 1180,
|
|
height: 880,
|
|
minWidth: 760,
|
|
minHeight: 600,
|
|
backgroundColor: '#0B0F0C',
|
|
autoHideMenuBar: true,
|
|
webPreferences: {
|
|
preload: path.join(__dirname, 'preload.js'),
|
|
contextIsolation: true,
|
|
nodeIntegration: false
|
|
}
|
|
});
|
|
mainWindow.setMenuBarVisibility(false);
|
|
mainWindow.loadFile(path.join(__dirname, 'renderer', 'index.html'));
|
|
}
|
|
|
|
app.whenReady().then(createWindow);
|
|
app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); });
|
|
app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); });
|
|
|
|
// ---------- IPC : sélection et lecture du dossier Minecraft ----------
|
|
|
|
ipcMain.handle('pick-folder', async () => {
|
|
const result = await dialog.showOpenDialog(mainWindow, {
|
|
properties: ['openDirectory'],
|
|
title: 'Choisis ton dossier .minecraft (ou directement le dossier logs)'
|
|
});
|
|
if (result.canceled || !result.filePaths.length) return { canceled: true };
|
|
const folder = result.filePaths[0];
|
|
const logPath = resolveLogPath(folder);
|
|
if (!logPath) {
|
|
return {
|
|
canceled: false,
|
|
error: 'Impossible de trouver "latest.log" dans ce dossier ni dans son sous-dossier "logs". Sélectionne ton dossier .minecraft, ou le dossier logs directement.'
|
|
};
|
|
}
|
|
return { canceled: false, logPath };
|
|
});
|
|
|
|
ipcMain.handle('check-log-path', async (event, logPath) => {
|
|
try { await fsp.access(logPath, fs.constants.R_OK); return { ok: true }; }
|
|
catch (e) { return { ok: false }; }
|
|
});
|
|
|
|
ipcMain.handle('get-file-size', async (event, logPath) => {
|
|
try { const st = await fsp.stat(logPath); return { size: st.size }; }
|
|
catch (e) { return { size: 0, error: e.message }; }
|
|
});
|
|
|
|
ipcMain.handle('read-chunk', async (event, logPath, start, end) => {
|
|
if (end <= start) return { text: '' };
|
|
let fd;
|
|
try {
|
|
fd = await fsp.open(logPath, 'r');
|
|
const length = end - start;
|
|
const buffer = Buffer.alloc(length);
|
|
await fd.read(buffer, 0, length, start);
|
|
return { text: buffer.toString('utf8') };
|
|
} catch (e) {
|
|
return { text: '', error: e.message };
|
|
} finally {
|
|
if (fd) await fd.close().catch(() => {});
|
|
}
|
|
});
|
|
|
|
// ---------- IPC : état général de l'appli ----------
|
|
|
|
ipcMain.handle('load-app-state', async () => loadAppState());
|
|
ipcMain.handle('save-app-state', async (event, obj) => saveAppState(obj));
|
|
|
|
// ---------- IPC : stats de chance de drop personnelles ----------
|
|
|
|
ipcMain.handle('load-drop-stats', async () => loadDropStats());
|
|
ipcMain.handle('save-drop-stats', async (event, obj) => saveDropStats(obj));
|
|
|
|
ipcMain.handle('export-drop-stats', async () => {
|
|
const current = loadDropStats();
|
|
const defaultName = 'farm-tracker-dropstats-' + new Date().toISOString().slice(0, 10) + '.json';
|
|
const result = await dialog.showSaveDialog(mainWindow, {
|
|
title: 'Exporter mes stats de chance de drop',
|
|
defaultPath: defaultName,
|
|
filters: [{ name: 'JSON', extensions: ['json'] }]
|
|
});
|
|
if (result.canceled || !result.filePath) return { canceled: true };
|
|
fs.writeFileSync(result.filePath, JSON.stringify(current, null, 2));
|
|
return { canceled: false, filePath: result.filePath };
|
|
});
|
|
|
|
ipcMain.handle('import-merge-drop-stats', async () => {
|
|
const result = await dialog.showOpenDialog(mainWindow, {
|
|
title: 'Importer et fusionner des fichiers de stats de drop (plusieurs fichiers possibles)',
|
|
properties: ['openFile', 'multiSelections'],
|
|
filters: [{ name: 'JSON', extensions: ['json'] }]
|
|
});
|
|
if (result.canceled || !result.filePaths.length) return { canceled: true };
|
|
|
|
const current = loadDropStats();
|
|
const details = [];
|
|
let totalAdded = 0;
|
|
|
|
for (const filePath of result.filePaths) {
|
|
try {
|
|
const raw = fs.readFileSync(filePath, 'utf8');
|
|
const data = JSON.parse(raw);
|
|
const added = mergeDropStatsInto(current, data);
|
|
totalAdded += added;
|
|
details.push({ file: path.basename(filePath), addedKills: added, ok: true });
|
|
} catch (e) {
|
|
details.push({ file: path.basename(filePath), ok: false, error: e.message });
|
|
}
|
|
}
|
|
|
|
current.updatedAt = new Date().toISOString();
|
|
saveDropStats(current);
|
|
|
|
return { canceled: false, totalAdded, details, dropStats: current };
|
|
});
|
|
|
|
// ---------- IPC : stats communautaires (reçues du serveur de sync) ----------
|
|
|
|
ipcMain.handle('load-community-drop-stats', async () => loadCommunityDropStats());
|
|
ipcMain.handle('save-community-drop-stats', async (event, obj) => saveCommunityDropStats(obj));
|
|
ipcMain.handle('get-file-paths', () => ({ dropStats: DROPSTATS_FILE, communityDropStats: COMMUNITY_DROPSTATS_FILE }));
|
|
|
|
// ---------- IPC : historique des sessions ----------
|
|
|
|
ipcMain.handle('load-session-history', async () => loadSessionHistory());
|
|
ipcMain.handle('save-session-history', async (event, obj) => saveSessionHistory(obj));
|
|
|
|
// ---------- IPC : sync avec le serveur VPS ----------
|
|
|
|
ipcMain.handle('fetch-community-stats', async (event, { serverUrl }) => {
|
|
return new Promise((resolve) => {
|
|
try {
|
|
const url = new URL('/stats', serverUrl);
|
|
const mod = url.protocol === 'https:' ? require('https') : require('http');
|
|
const req = mod.get({
|
|
hostname: url.hostname,
|
|
port: url.port || (url.protocol === 'https:' ? 443 : 80),
|
|
path: '/stats'
|
|
}, (res) => {
|
|
let data = '';
|
|
res.on('data', chunk => { data += chunk; });
|
|
res.on('end', () => {
|
|
try { resolve({ ok: true, ...JSON.parse(data) }); }
|
|
catch { resolve({ ok: false, error: 'Réponse invalide du serveur' }); }
|
|
});
|
|
});
|
|
req.setTimeout(15000, () => { req.destroy(); resolve({ ok: false, error: 'Timeout (15s)' }); });
|
|
req.on('error', (e) => resolve({ ok: false, error: e.message }));
|
|
} catch (e) {
|
|
resolve({ ok: false, error: e.message });
|
|
}
|
|
});
|
|
});
|
|
|
|
ipcMain.handle('sync-drop-stats', async (event, { serverUrl, clientId, dropStats }) => {
|
|
return new Promise((resolve) => {
|
|
try {
|
|
const url = new URL('/sync', serverUrl);
|
|
const body = JSON.stringify({ clientId, dropStats });
|
|
const mod = url.protocol === 'https:' ? require('https') : require('http');
|
|
const options = {
|
|
hostname: url.hostname,
|
|
port: url.port || (url.protocol === 'https:' ? 443 : 80),
|
|
path: '/sync',
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Content-Length': Buffer.byteLength(body)
|
|
}
|
|
};
|
|
const req = mod.request(options, (res) => {
|
|
let data = '';
|
|
res.on('data', chunk => { data += chunk; });
|
|
res.on('end', () => {
|
|
try { resolve({ ok: true, ...JSON.parse(data) }); }
|
|
catch { resolve({ ok: false, error: 'Réponse invalide du serveur' }); }
|
|
});
|
|
});
|
|
req.setTimeout(15000, () => { req.destroy(); resolve({ ok: false, error: 'Timeout (15s)' }); });
|
|
req.on('error', (e) => resolve({ ok: false, error: e.message }));
|
|
req.write(body);
|
|
req.end();
|
|
} catch (e) {
|
|
resolve({ ok: false, error: e.message });
|
|
}
|
|
});
|
|
});
|