Compare commits
17 Commits
v1.0.0
...
a5688f124c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a5688f124c | ||
|
|
cf43ada948 | ||
|
|
4ce8b41a4c | ||
|
|
0562b326c8 | ||
|
|
857a8477d7 | ||
|
|
fdbf57a6d6 | ||
|
|
4f7aab646b | ||
|
|
35481fe7d7 | ||
|
|
26b70d29c4 | ||
|
|
c94cdf679a | ||
|
|
a5d1725ee7 | ||
|
|
23662003da | ||
|
|
34ed92a647 | ||
|
|
2760ab4897 | ||
|
|
6e306a9bed | ||
|
|
13a5ede027 | ||
|
|
2a66dd7174 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -22,5 +22,8 @@ Thumbs.db
|
||||
.vscode/
|
||||
.idea/
|
||||
|
||||
# Token local (jamais commité)
|
||||
.gitea-token
|
||||
|
||||
# Claude Code
|
||||
.claude/
|
||||
|
||||
@@ -1,37 +1,46 @@
|
||||
#!/usr/bin/env bash
|
||||
# Installe (ou met à jour) l'entrée de menu "Farm Tracker" pointant vers l'AppImage déjà construit.
|
||||
set -e
|
||||
# Installation initiale de Farm Tracker (AppImage + entrée de menu).
|
||||
# À lancer une seule fois. Les mises à jour suivantes sont automatiques.
|
||||
set -euo pipefail
|
||||
|
||||
APPDIR="/home/shamiiow/GitHub/farm-tracker-app/dist"
|
||||
APPIMAGE=$(ls "$APPDIR"/*.AppImage 2>/dev/null | head -n1)
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
DIST_DIR="$SCRIPT_DIR/dist"
|
||||
|
||||
if [ -z "$APPIMAGE" ]; then
|
||||
echo "Aucun fichier .AppImage trouvé dans : $APPDIR"
|
||||
echo "Lance d'abord (depuis le dossier du projet) : npm run dist"
|
||||
# Trouve l'AppImage dans dist/
|
||||
APPIMAGE_SRC=$(ls "$DIST_DIR"/*.AppImage 2>/dev/null | head -n1)
|
||||
if [ -z "$APPIMAGE_SRC" ]; then
|
||||
echo "Aucun .AppImage trouvé dans dist/. Lance d'abord : npm run dist"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
chmod +x "$APPIMAGE"
|
||||
# Chemin stable — indépendant de la version
|
||||
INSTALL_DIR="$HOME/.local/bin"
|
||||
STABLE_PATH="$INSTALL_DIR/farm-tracker.AppImage"
|
||||
|
||||
mkdir -p "$INSTALL_DIR"
|
||||
cp "$APPIMAGE_SRC" "$STABLE_PATH"
|
||||
chmod +x "$STABLE_PATH"
|
||||
|
||||
# Entrée de menu
|
||||
DESKTOP_DIR="$HOME/.local/share/applications"
|
||||
mkdir -p "$DESKTOP_DIR"
|
||||
DESKTOP_FILE="$DESKTOP_DIR/farm-tracker.desktop"
|
||||
|
||||
cat > "$DESKTOP_FILE" << INNEREOF
|
||||
cat > "$DESKTOP_DIR/farm-tracker.desktop" << EOF
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Farm Tracker
|
||||
Comment=Suivi de loot Minecraft en direct
|
||||
Exec="$APPIMAGE" %U
|
||||
Exec="$STABLE_PATH" %U
|
||||
Icon=applications-games
|
||||
Terminal=false
|
||||
Categories=Game;Utility;
|
||||
StartupWMClass=farm-tracker
|
||||
INNEREOF
|
||||
EOF
|
||||
|
||||
chmod +x "$DESKTOP_FILE"
|
||||
chmod +x "$DESKTOP_DIR/farm-tracker.desktop"
|
||||
update-desktop-database "$DESKTOP_DIR" >/dev/null 2>&1 || true
|
||||
|
||||
echo "Entrée installée : $DESKTOP_FILE"
|
||||
echo "AppImage détecté : $APPIMAGE"
|
||||
echo "Cherche \"Farm Tracker\" dans ton menu d'applications (déconnexion/reconnexion parfois nécessaire selon le bureau)."
|
||||
echo "Installé dans : $STABLE_PATH"
|
||||
echo "Entrée de menu : $DESKTOP_DIR/farm-tracker.desktop"
|
||||
echo ""
|
||||
echo "Les prochaines mises à jour s'installeront automatiquement sans rien retoucher."
|
||||
|
||||
@@ -21,12 +21,14 @@ function mergeDropStatsInto(target, source) {
|
||||
|
||||
for (const [mobName, mobData] of Object.entries(sourceMobs)) {
|
||||
if (!mobName) continue;
|
||||
if (!target.mobs[mobName]) target.mobs[mobName] = { kills: 0, items: {} };
|
||||
if (!target.mobs[mobName]) target.mobs[mobName] = { kills: 0, totalExp: 0, totalCols: 0, items: {} };
|
||||
const t = target.mobs[mobName];
|
||||
|
||||
const kills = Number(mobData.kills) || 0;
|
||||
t.kills += kills;
|
||||
addedKills += kills;
|
||||
t.totalExp = (t.totalExp || 0) + (Number(mobData.totalExp) || 0);
|
||||
t.totalCols = (t.totalCols || 0) + (Number(mobData.totalCols) || 0);
|
||||
|
||||
const items = mobData.items || {};
|
||||
for (const [key, item] of Object.entries(items)) {
|
||||
|
||||
389
main.js
389
main.js
@@ -4,24 +4,25 @@ 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');
|
||||
|
||||
// Fichiers globaux (non liés à un profil)
|
||||
const COMMUNITY_DROPSTATS_FILE = path.join(userDataDir, 'community-dropstats.json');
|
||||
const SESSION_HISTORY_FILE = path.join(userDataDir, 'session-history.json');
|
||||
const UPDATE_PREFS_FILE = path.join(userDataDir, 'update-prefs.json');
|
||||
const UPDATE_PREFS_FILE = path.join(userDataDir, 'update-prefs.json');
|
||||
const PROFILES_FILE = path.join(userDataDir, 'profiles.json');
|
||||
|
||||
// Fichiers legacy (profil "default")
|
||||
const LEGACY_APP_STATE_FILE = path.join(userDataDir, 'app-state.json');
|
||||
const LEGACY_DROPSTATS_FILE = path.join(userDataDir, 'dropstats.json');
|
||||
const LEGACY_SESSION_HISTORY_FILE= path.join(userDataDir, 'session-history.json');
|
||||
|
||||
const RELEASES_API = 'https://git.shamiiow.com/api/v1/repos/shamiiow/farm-tracker-sao/releases/latest';
|
||||
|
||||
// ---------- Lecture / écriture disque (JSON indenté = facilement lisible) ----------
|
||||
// ---------- Lecture / écriture disque ----------
|
||||
|
||||
function readJsonSafe(filePath, fallback) {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
||||
} catch (e) {
|
||||
return fallback;
|
||||
}
|
||||
try { return JSON.parse(fs.readFileSync(filePath, 'utf8')); }
|
||||
catch { return fallback; }
|
||||
}
|
||||
|
||||
function writeJsonAtomic(filePath, obj) {
|
||||
@@ -37,22 +38,82 @@ function writeJsonAtomic(filePath, obj) {
|
||||
}
|
||||
}
|
||||
|
||||
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 tryUnlink(filePath) { try { fs.unlinkSync(filePath); } catch (_) {} }
|
||||
|
||||
function generateId() {
|
||||
return Math.random().toString(36).slice(2, 10) + Date.now().toString(36);
|
||||
}
|
||||
|
||||
// ---------- Profils ----------
|
||||
|
||||
function emptyProfilesData() {
|
||||
return {
|
||||
activeProfileId: 'default',
|
||||
profiles: [{
|
||||
id: 'default',
|
||||
name: 'Défaut',
|
||||
dropStatsMode: 'private',
|
||||
createdAt: new Date().toISOString()
|
||||
}]
|
||||
};
|
||||
}
|
||||
|
||||
function loadProfilesData() {
|
||||
const data = readJsonSafe(PROFILES_FILE, null);
|
||||
if (!data) {
|
||||
const def = emptyProfilesData();
|
||||
writeJsonAtomic(PROFILES_FILE, def);
|
||||
return def;
|
||||
}
|
||||
// compat : s'assurer que le profil default existe toujours
|
||||
if (!data.profiles.find(p => p.id === 'default')) {
|
||||
data.profiles.unshift({ id: 'default', name: 'Défaut', dropStatsMode: 'private', createdAt: new Date().toISOString() });
|
||||
writeJsonAtomic(PROFILES_FILE, data);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
function getActiveProfile() {
|
||||
const data = loadProfilesData();
|
||||
return data.profiles.find(p => p.id === data.activeProfileId) || data.profiles[0];
|
||||
}
|
||||
|
||||
// ---------- Chemins de fichiers dynamiques selon profil ----------
|
||||
|
||||
function profileAppStateFile(p) {
|
||||
if (!p || p.id === 'default') return LEGACY_APP_STATE_FILE;
|
||||
return path.join(userDataDir, `app-state-${p.id}.json`);
|
||||
}
|
||||
|
||||
function profileDropStatsFile(p) {
|
||||
if (!p || p.id === 'default') return LEGACY_DROPSTATS_FILE;
|
||||
if (p.dropStatsMode === 'shared') return path.join(userDataDir, 'dropstats-shared.json');
|
||||
return path.join(userDataDir, `dropstats-${p.id}.json`);
|
||||
}
|
||||
|
||||
function profileSessionHistoryFile(p) {
|
||||
if (!p || p.id === 'default') return LEGACY_SESSION_HISTORY_FILE;
|
||||
return path.join(userDataDir, `session-history-${p.id}.json`);
|
||||
}
|
||||
|
||||
// ---------- Load / save avec profil actif ----------
|
||||
|
||||
function loadAppState() { return readJsonSafe(profileAppStateFile(getActiveProfile()), null); }
|
||||
function saveAppState(obj) { return writeJsonAtomic(profileAppStateFile(getActiveProfile()), obj); }
|
||||
function loadDropStats() { return readJsonSafe(profileDropStatsFile(getActiveProfile()), emptyDropStats()); }
|
||||
function saveDropStats(obj) { return writeJsonAtomic(profileDropStatsFile(getActiveProfile()), obj); }
|
||||
function loadSessionHistory() { return readJsonSafe(profileSessionHistoryFile(getActiveProfile()), { type: 'farm-tracker-session-history', version: 1, sessions: [] }); }
|
||||
function saveSessionHistory(o) { return writeJsonAtomic(profileSessionHistoryFile(getActiveProfile()), o); }
|
||||
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 loadUpdatePrefs() { return readJsonSafe(UPDATE_PREFS_FILE, { snoozedUntil: null }); }
|
||||
function saveUpdatePrefs(obj) { return writeJsonAtomic(UPDATE_PREFS_FILE, obj); }
|
||||
function loadUpdatePrefs() { return readJsonSafe(UPDATE_PREFS_FILE, { snoozedUntil: null }); }
|
||||
function saveUpdatePrefs(obj) { return writeJsonAtomic(UPDATE_PREFS_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;
|
||||
const c1 = path.join(folderPath, 'logs', 'latest.log');
|
||||
const c2 = path.join(folderPath, 'latest.log');
|
||||
if (fs.existsSync(c1)) return c1;
|
||||
if (fs.existsSync(c2)) return c2;
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -103,47 +164,90 @@ function resolveAssetUrl(release) {
|
||||
return asset ? asset.browser_download_url : null;
|
||||
}
|
||||
|
||||
function sendUpdateProgress(percent, status, error) {
|
||||
if (mainWindow && !mainWindow.isDestroyed())
|
||||
mainWindow.webContents.send('update-progress', { percent, status, error });
|
||||
}
|
||||
|
||||
function downloadFileWithProgress(url, destPath, onProgress) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const follow = (currentUrl, redirects) => {
|
||||
if (redirects > 5) return reject(new Error('Trop de redirections'));
|
||||
const mod = currentUrl.startsWith('https') ? require('https') : require('http');
|
||||
const req = mod.get(currentUrl, { timeout: 120000, headers: { 'User-Agent': 'farm-tracker-updater' } }, (res) => {
|
||||
if ([301, 302, 307, 308].includes(res.statusCode))
|
||||
return follow(res.headers.location, redirects + 1);
|
||||
if (res.statusCode !== 200)
|
||||
return reject(new Error(`HTTP ${res.statusCode}`));
|
||||
const total = parseInt(res.headers['content-length'] || '0', 10);
|
||||
let downloaded = 0;
|
||||
const file = fs.createWriteStream(destPath);
|
||||
res.on('data', chunk => {
|
||||
downloaded += chunk.length;
|
||||
file.write(chunk);
|
||||
if (total > 0 && onProgress) onProgress(Math.round(downloaded / total * 100));
|
||||
});
|
||||
res.on('end', () => file.close(() => resolve(destPath)));
|
||||
res.on('error', err => { file.close(); try { fs.unlinkSync(destPath); } catch (_) {} reject(err); });
|
||||
});
|
||||
req.on('error', reject);
|
||||
req.on('timeout', () => { req.destroy(); reject(new Error('Timeout')); });
|
||||
};
|
||||
follow(url, 0);
|
||||
});
|
||||
}
|
||||
|
||||
async function downloadAndInstall(downloadUrl, version) {
|
||||
if (!app.isPackaged) {
|
||||
dialog.showMessageBox(mainWindow, { type: 'info', title: 'Mode développement', message: 'Auto-install non disponible en mode dev.', buttons: ['OK'] });
|
||||
return;
|
||||
}
|
||||
const ext = process.platform === 'win32' ? '.exe' : '.AppImage';
|
||||
const tmpPath = path.join(app.getPath('temp'), `farm-tracker-${version}${ext}`);
|
||||
try {
|
||||
sendUpdateProgress(0, 'downloading');
|
||||
await downloadFileWithProgress(downloadUrl, tmpPath, pct => sendUpdateProgress(pct, 'downloading'));
|
||||
sendUpdateProgress(100, 'installing');
|
||||
if (process.platform === 'linux') {
|
||||
fs.chmodSync(tmpPath, 0o755);
|
||||
const { spawn } = require('child_process');
|
||||
spawn(tmpPath, [], { detached: true, stdio: 'ignore' }).unref();
|
||||
app.quit();
|
||||
} else if (process.platform === 'win32') {
|
||||
const { spawn } = require('child_process');
|
||||
spawn(tmpPath, ['/S'], { detached: true, stdio: 'ignore' }).unref();
|
||||
app.quit();
|
||||
}
|
||||
} catch (e) {
|
||||
sendUpdateProgress(0, 'error', e.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function showUpdateDialog(version, downloadUrl, ignoreSnooze = false) {
|
||||
const current = app.getVersion();
|
||||
if (!isNewerVersion(version, current)) return false;
|
||||
|
||||
if (!ignoreSnooze) {
|
||||
const prefs = loadUpdatePrefs();
|
||||
if (prefs.snoozedUntil === 'indefinite') return false;
|
||||
if (prefs.snoozedUntil && new Date(prefs.snoozedUntil) > new Date()) return false;
|
||||
}
|
||||
|
||||
const { response } = await dialog.showMessageBox(mainWindow, {
|
||||
type: 'info',
|
||||
title: 'Mise à jour disponible',
|
||||
message: `Version ${version} disponible`,
|
||||
detail: `Version actuelle : ${current}`,
|
||||
buttons: ['Télécharger', 'Me rappeler dans...'],
|
||||
defaultId: 0,
|
||||
cancelId: 1
|
||||
type: 'info', title: 'Mise à jour disponible', message: `Version ${version} disponible`,
|
||||
detail: `Version actuelle : ${current}\nL'application se relancera automatiquement après la mise à jour.`,
|
||||
buttons: ['Installer maintenant', 'Me rappeler dans...'], defaultId: 0, cancelId: 1
|
||||
});
|
||||
|
||||
if (response === 0) {
|
||||
shell.openExternal(downloadUrl);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (response === 0) { downloadAndInstall(downloadUrl, version); return true; }
|
||||
const { response: snoozeResponse } = await dialog.showMessageBox(mainWindow, {
|
||||
type: 'question',
|
||||
title: 'Me rappeler dans...',
|
||||
type: 'question', title: 'Me rappeler dans...',
|
||||
message: 'Ne plus afficher cette mise à jour pendant :',
|
||||
buttons: SNOOZE_OPTIONS.map(o => o.label),
|
||||
defaultId: 0,
|
||||
cancelId: SNOOZE_OPTIONS.length - 1
|
||||
buttons: SNOOZE_OPTIONS.map(o => o.label), defaultId: 0, cancelId: SNOOZE_OPTIONS.length - 1
|
||||
});
|
||||
|
||||
const chosen = SNOOZE_OPTIONS[snoozeResponse];
|
||||
if (chosen.days === -1) return false;
|
||||
if (chosen.days === null) {
|
||||
saveUpdatePrefs({ snoozedUntil: 'indefinite' });
|
||||
} else {
|
||||
const until = new Date();
|
||||
until.setDate(until.getDate() + chosen.days);
|
||||
const until = new Date(); until.setDate(until.getDate() + chosen.days);
|
||||
saveUpdatePrefs({ snoozedUntil: until.toISOString() });
|
||||
}
|
||||
return false;
|
||||
@@ -156,39 +260,46 @@ async function checkForUpdates(ignoreSnooze = false) {
|
||||
const downloadUrl = resolveAssetUrl(release);
|
||||
if (!version || !downloadUrl) return false;
|
||||
return await showUpdateDialog(version, downloadUrl, ignoreSnooze);
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
} catch (_) { return false; }
|
||||
}
|
||||
|
||||
let mainWindow;
|
||||
|
||||
function createWindow() {
|
||||
mainWindow = new BrowserWindow({
|
||||
width: 1180,
|
||||
height: 880,
|
||||
minWidth: 760,
|
||||
minHeight: 600,
|
||||
backgroundColor: '#0B0F0C',
|
||||
autoHideMenuBar: true,
|
||||
width: 1180, height: 880, minWidth: 760, minHeight: 600,
|
||||
backgroundColor: '#0B0F0C', autoHideMenuBar: true,
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, 'preload.js'),
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false
|
||||
contextIsolation: true, nodeIntegration: false
|
||||
}
|
||||
});
|
||||
mainWindow.setMenuBarVisibility(false);
|
||||
mainWindow.loadFile(path.join(__dirname, 'renderer', 'index.html'));
|
||||
}
|
||||
|
||||
function selfInstallLinux() {
|
||||
if (process.platform !== 'linux' || !app.isPackaged) return;
|
||||
const appImagePath = process.env.APPIMAGE;
|
||||
if (!appImagePath) return;
|
||||
const stablePath = path.join(require('os').homedir(), '.local', 'bin', 'farm-tracker.AppImage');
|
||||
if (appImagePath === stablePath) return;
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(stablePath), { recursive: true });
|
||||
fs.copyFileSync(appImagePath, stablePath);
|
||||
fs.chmodSync(stablePath, 0o755);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
app.whenReady().then(() => {
|
||||
selfInstallLinux();
|
||||
createWindow();
|
||||
setTimeout(() => checkForUpdates(false), 5000);
|
||||
});
|
||||
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 ----------
|
||||
// ---------- IPC : dossier Minecraft ----------
|
||||
|
||||
ipcMain.handle('pick-folder', async () => {
|
||||
const result = await dialog.showOpenDialog(mainWindow, {
|
||||
@@ -198,18 +309,13 @@ ipcMain.handle('pick-folder', async () => {
|
||||
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.'
|
||||
};
|
||||
}
|
||||
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 }; }
|
||||
catch { return { ok: false }; }
|
||||
});
|
||||
|
||||
ipcMain.handle('get-file-size', async (event, logPath) => {
|
||||
@@ -226,52 +332,38 @@ ipcMain.handle('read-chunk', async (event, logPath, start, end) => {
|
||||
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(() => {});
|
||||
}
|
||||
} catch (e) { return { text: '', error: e.message }; }
|
||||
finally { if (fd) await fd.close().catch(() => {}); }
|
||||
});
|
||||
|
||||
// ---------- IPC : état général de l'appli ----------
|
||||
// ---------- IPC : état application (par profil) ----------
|
||||
|
||||
ipcMain.handle('load-app-state', async () => loadAppState());
|
||||
ipcMain.handle('save-app-state', async (event, obj) => saveAppState(obj));
|
||||
ipcMain.handle('load-app-state', async () => loadAppState());
|
||||
ipcMain.handle('save-app-state', async (_, obj) => saveAppState(obj));
|
||||
|
||||
// ---------- IPC : stats de chance de drop personnelles ----------
|
||||
// ---------- IPC : drop stats (par profil) ----------
|
||||
|
||||
ipcMain.handle('load-drop-stats', async () => loadDropStats());
|
||||
ipcMain.handle('save-drop-stats', async (event, obj) => saveDropStats(obj));
|
||||
ipcMain.handle('save-drop-stats', async (_, 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'] }]
|
||||
});
|
||||
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'] }]
|
||||
});
|
||||
const result = await dialog.showOpenDialog(mainWindow, { title: 'Importer et fusionner des fichiers de stats de drop', 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 data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
||||
const added = mergeDropStatsInto(current, data);
|
||||
totalAdded += added;
|
||||
details.push({ file: path.basename(filePath), addedKills: added, ok: true });
|
||||
@@ -279,23 +371,82 @@ ipcMain.handle('import-merge-drop-stats', async () => {
|
||||
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) ----------
|
||||
// ---------- IPC : stats communautaires (globales) ----------
|
||||
|
||||
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 }));
|
||||
ipcMain.handle('load-community-drop-stats', async () => loadCommunityDropStats());
|
||||
ipcMain.handle('save-community-drop-stats', async (_, obj) => saveCommunityDropStats(obj));
|
||||
ipcMain.handle('get-file-paths', () => ({
|
||||
dropStats: profileDropStatsFile(getActiveProfile()),
|
||||
communityDropStats: COMMUNITY_DROPSTATS_FILE
|
||||
}));
|
||||
|
||||
// ---------- IPC : historique des sessions ----------
|
||||
// ---------- IPC : historique des sessions (par profil) ----------
|
||||
|
||||
ipcMain.handle('load-session-history', async () => loadSessionHistory());
|
||||
ipcMain.handle('save-session-history', async (event, obj) => saveSessionHistory(obj));
|
||||
ipcMain.handle('save-session-history', async (_, obj) => saveSessionHistory(obj));
|
||||
|
||||
// ---------- IPC : profils ----------
|
||||
|
||||
ipcMain.handle('get-profiles', () => loadProfilesData());
|
||||
|
||||
ipcMain.handle('create-profile', (_, { name, dropStatsMode }) => {
|
||||
const data = loadProfilesData();
|
||||
const newProfile = {
|
||||
id: generateId(),
|
||||
name: (name || 'Nouveau profil').trim().slice(0, 40),
|
||||
dropStatsMode: dropStatsMode === 'shared' ? 'shared' : 'private',
|
||||
createdAt: new Date().toISOString()
|
||||
};
|
||||
data.profiles.push(newProfile);
|
||||
writeJsonAtomic(PROFILES_FILE, data);
|
||||
return data;
|
||||
});
|
||||
|
||||
ipcMain.handle('switch-profile', (_, id) => {
|
||||
const data = loadProfilesData();
|
||||
if (!data.profiles.find(p => p.id === id)) return { ok: false, error: 'Profil introuvable' };
|
||||
data.activeProfileId = id;
|
||||
writeJsonAtomic(PROFILES_FILE, data);
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
ipcMain.handle('rename-profile', (_, { id, name }) => {
|
||||
const data = loadProfilesData();
|
||||
const profile = data.profiles.find(p => p.id === id);
|
||||
if (!profile) return { ok: false };
|
||||
profile.name = (name || '').trim().slice(0, 40) || profile.name;
|
||||
writeJsonAtomic(PROFILES_FILE, data);
|
||||
return { ok: true, profile };
|
||||
});
|
||||
|
||||
ipcMain.handle('delete-profile', (_, id) => {
|
||||
if (id === 'default') return { ok: false, error: 'Le profil Défaut ne peut pas être supprimé.' };
|
||||
const data = loadProfilesData();
|
||||
const profile = data.profiles.find(p => p.id === id);
|
||||
if (!profile) return { ok: false, error: 'Profil introuvable' };
|
||||
data.profiles = data.profiles.filter(p => p.id !== id);
|
||||
if (data.activeProfileId === id) data.activeProfileId = 'default';
|
||||
// supprimer les fichiers du profil
|
||||
tryUnlink(path.join(userDataDir, `app-state-${id}.json`));
|
||||
tryUnlink(path.join(userDataDir, `dropstats-${id}.json`));
|
||||
tryUnlink(path.join(userDataDir, `session-history-${id}.json`));
|
||||
writeJsonAtomic(PROFILES_FILE, data);
|
||||
return { ok: true, newActiveId: data.activeProfileId };
|
||||
});
|
||||
|
||||
ipcMain.handle('set-drop-stats-mode', (_, { id, mode }) => {
|
||||
const data = loadProfilesData();
|
||||
const profile = data.profiles.find(p => p.id === id);
|
||||
if (!profile) return { ok: false };
|
||||
profile.dropStatsMode = mode === 'shared' ? 'shared' : 'private';
|
||||
writeJsonAtomic(PROFILES_FILE, data);
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
// ---------- IPC : mise à jour ----------
|
||||
|
||||
@@ -305,28 +456,20 @@ ipcMain.handle('check-update-manual', async () => {
|
||||
const version = (release.tag_name || '').replace(/^v/, '');
|
||||
const downloadUrl = resolveAssetUrl(release);
|
||||
const current = app.getVersion();
|
||||
if (!version || !downloadUrl || !isNewerVersion(version, current)) {
|
||||
return { checked: true, hasUpdate: false, current };
|
||||
}
|
||||
if (!version || !downloadUrl || !isNewerVersion(version, current)) return { checked: true, hasUpdate: false, current };
|
||||
await showUpdateDialog(version, downloadUrl, true);
|
||||
return { checked: true, hasUpdate: true };
|
||||
} catch (e) {
|
||||
return { checked: false, error: e.message };
|
||||
}
|
||||
} catch (e) { return { checked: false, error: e.message }; }
|
||||
});
|
||||
|
||||
// ---------- IPC : sync avec le serveur VPS ----------
|
||||
// ---------- IPC : sync VPS ----------
|
||||
|
||||
ipcMain.handle('fetch-community-stats', async (event, { serverUrl }) => {
|
||||
ipcMain.handle('fetch-community-stats', async (_, { 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) => {
|
||||
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', () => {
|
||||
@@ -336,27 +479,20 @@ ipcMain.handle('fetch-community-stats', async (event, { serverUrl }) => {
|
||||
});
|
||||
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 });
|
||||
}
|
||||
} catch (e) { resolve({ ok: false, error: e.message }); }
|
||||
});
|
||||
});
|
||||
|
||||
ipcMain.handle('sync-drop-stats', async (event, { serverUrl, clientId, dropStats }) => {
|
||||
ipcMain.handle('sync-drop-stats', async (_, { 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)
|
||||
}
|
||||
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 = '';
|
||||
@@ -368,10 +504,7 @@ ipcMain.handle('sync-drop-stats', async (event, { serverUrl, clientId, dropStats
|
||||
});
|
||||
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 });
|
||||
}
|
||||
req.write(body); req.end();
|
||||
} catch (e) { resolve({ ok: false, error: e.message }); }
|
||||
});
|
||||
});
|
||||
|
||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "farm-tracker",
|
||||
"version": "1.0.0",
|
||||
"version": "1.0.3",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "farm-tracker",
|
||||
"version": "1.0.0",
|
||||
"version": "1.0.3",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"dist": "^0.1.2",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "farm-tracker",
|
||||
"version": "1.0.0",
|
||||
"version": "1.1.0",
|
||||
"description": "Suivi de loot Minecraft en direct, avec sauvegarde automatique des stats et des chances de drop.",
|
||||
"main": "main.js",
|
||||
"scripts": {
|
||||
|
||||
10
preload.js
10
preload.js
@@ -24,5 +24,13 @@ contextBridge.exposeInMainWorld('api', {
|
||||
loadSessionHistory: () => ipcRenderer.invoke('load-session-history'),
|
||||
saveSessionHistory: (obj) => ipcRenderer.invoke('save-session-history', obj),
|
||||
|
||||
checkUpdateManual: () => ipcRenderer.invoke('check-update-manual')
|
||||
checkUpdateManual: () => ipcRenderer.invoke('check-update-manual'),
|
||||
onUpdateProgress: (cb) => ipcRenderer.on('update-progress', (_, data) => cb(data)),
|
||||
|
||||
getProfiles: () => ipcRenderer.invoke('get-profiles'),
|
||||
createProfile: (name, mode) => ipcRenderer.invoke('create-profile', { name, dropStatsMode: mode }),
|
||||
switchProfile: (id) => ipcRenderer.invoke('switch-profile', id),
|
||||
renameProfile: (id, name) => ipcRenderer.invoke('rename-profile', { id, name }),
|
||||
deleteProfile: (id) => ipcRenderer.invoke('delete-profile', id),
|
||||
setDropStatsMode: (id, mode) => ipcRenderer.invoke('set-drop-stats-mode', { id, mode }),
|
||||
});
|
||||
|
||||
1160
renderer/index.html
1160
renderer/index.html
File diff suppressed because it is too large
Load Diff
BIN
renderer/levelup.ogg
Normal file
BIN
renderer/levelup.ogg
Normal file
Binary file not shown.
@@ -21,7 +21,9 @@ const VERSION = pkg.version;
|
||||
const TAG = `v${VERSION}`;
|
||||
|
||||
const DIST = path.join(__dirname, '..', 'dist');
|
||||
const ASSETS = fs.readdirSync(DIST).filter(f => f.endsWith('.AppImage') || (f.endsWith('.exe') && !f.endsWith('.blockmap')));
|
||||
const ASSETS = fs.readdirSync(DIST).filter(f =>
|
||||
(f.endsWith('.AppImage') || (f.endsWith('.exe') && !f.endsWith('.blockmap'))) && f.includes(VERSION)
|
||||
);
|
||||
|
||||
if (!ASSETS.length) {
|
||||
console.error('Aucun binaire trouvé dans dist/. Lance "npm run dist" et "npm run dist:win" d\'abord.');
|
||||
|
||||
56
tools/release.sh
Executable file
56
tools/release.sh
Executable file
@@ -0,0 +1,56 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
# ---------- Token ----------
|
||||
TOKEN="${GITEA_TOKEN:-}"
|
||||
if [ -z "$TOKEN" ] && [ -f ".gitea-token" ]; then
|
||||
TOKEN=$(tr -d '[:space:]' < .gitea-token)
|
||||
fi
|
||||
if [ -z "$TOKEN" ]; then
|
||||
read -rsp "Token Gitea : " TOKEN
|
||||
echo
|
||||
fi
|
||||
|
||||
# ---------- Version ----------
|
||||
CURRENT=$(node -p "require('./package.json').version")
|
||||
if [ -n "${1:-}" ]; then
|
||||
VERSION="$1"
|
||||
else
|
||||
echo "Version actuelle : v$CURRENT"
|
||||
read -rp "Nouvelle version [patch / minor / major / X.Y.Z] : " VERSION
|
||||
fi
|
||||
|
||||
npm version "$VERSION" --no-git-tag-version --silent
|
||||
NEW=$(node -p "require('./package.json').version")
|
||||
echo "→ v$NEW"
|
||||
|
||||
# ---------- Build ----------
|
||||
echo ""
|
||||
echo "Nettoyage des anciens binaires..."
|
||||
find dist -maxdepth 1 \( -name "*.AppImage" -o -name "*.exe" -o -name "*.blockmap" \) -delete 2>/dev/null || true
|
||||
|
||||
echo "Build Linux (AppImage)..."
|
||||
npm run dist --silent
|
||||
|
||||
if command -v wine &>/dev/null; then
|
||||
echo "Build Windows (exe)..."
|
||||
npm run dist:win --silent
|
||||
else
|
||||
echo "(Wine non trouvé — build Windows ignoré)"
|
||||
fi
|
||||
|
||||
# ---------- Release Gitea ----------
|
||||
echo ""
|
||||
GITEA_TOKEN="$TOKEN" node tools/release.js
|
||||
|
||||
# ---------- Git ----------
|
||||
git add package.json package-lock.json
|
||||
git commit -m "chore: release v$NEW" --quiet
|
||||
git remote set-url origin "https://shamiiow:${TOKEN}@git.shamiiow.com/shamiiow/farm-tracker-sao.git"
|
||||
git push --quiet
|
||||
git remote set-url origin "https://git.shamiiow.com/shamiiow/farm-tracker-sao.git"
|
||||
|
||||
echo ""
|
||||
echo "Release v$NEW publiée."
|
||||
Reference in New Issue
Block a user