Skip to content

Commit

Permalink
Fixed 2 Critical bugs
Browse files Browse the repository at this point in the history
- Fixed issues with file deletion
- Fixed Issues with files downloading
  • Loading branch information
LeMocha committed Jun 29, 2024
1 parent 48cb14e commit 9290d2a
Show file tree
Hide file tree
Showing 3 changed files with 221 additions and 1 deletion.
9 changes: 9 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,15 @@ jobs:
run: npm ci
shell: bash

- name: Customise Dependancies file
run: |
if [[ "$RUNNER_OS" == "Windows" ]]; then
copy customised_downloader.js node_modules/minecraft-java-core/build/utils/Downloader.js
else
cp customised_downloader.js node_modules/minecraft-java-core/build/utils/Downloader.js
fi
shell: bash

- name: Build
env:
GH_TOKEN: ${{ secrets.github_token }}
Expand Down
189 changes: 189 additions & 0 deletions customised_downloader.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
"use strict";
/**
* @author Luuxis
* @license CC-BY-NC 4.0 - https://creativecommons.org/licenses/by-nc/4.0/
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(require("fs"));
const node_fetch_1 = __importDefault(require("node-fetch"));
const events_1 = require("events");

class download {
constructor() {
this.on = events_1.EventEmitter.prototype.on;
this.emit = events_1.EventEmitter.prototype.emit;
}

async downloadFile(url, path, fileName, retries = 300) {
const attemptDownload = async (attempt) => {
if (!fs_1.default.existsSync(path))
fs_1.default.mkdirSync(path, { recursive: true });

const writer = fs_1.default.createWriteStream(path + '/' + fileName);
try {
const response = await (0, node_fetch_1.default)(url);
let size = response.headers.get('content-length');
let downloaded = 0;

return new Promise((resolve, reject) => {
response.body.on('data', (chunk) => {
downloaded += chunk.length;
this.emit('progress', downloaded, size);
writer.write(chunk);
});

response.body.on('end', () => {
writer.end();
resolve();
});

response.body.on('error', async (err) => {
this.emit('error', err);
writer.end();
if (attempt < retries) {
console.log(`Retrying download (${attempt + 1}/${retries})...`);
setTimeout(() => attemptDownload(attempt + 1).then(resolve).catch(reject), 2000);
} else {
reject(err);
}
});
});
} catch (error) {
this.emit('error', error);
if (attempt < retries) {
console.log(`Retrying download (${attempt + 1}/${retries})...`);
setTimeout(() => attemptDownload(attempt + 1), 2000);
} else {
throw error;
}
}
};

return attemptDownload(0);
}

async downloadFileMultiple(files, size, limit = 1, timeout = 10000, retries = 300) {
if (limit > files.length)
limit = files.length;

let completed = 0;
let downloaded = 0;
let queued = 0;
let start = new Date().getTime();
let before = 0;
let speeds = [];
let estimated = setInterval(() => {
let duration = (new Date().getTime() - start) / 1000;
let loaded = (downloaded - before) * 8;
if (speeds.length >= 5)
speeds = speeds.slice(1);
speeds.push((loaded / duration) / 8);
let speed = 0;
for (let s of speeds)
speed += s;
speed /= speeds.length;
this.emit("speed", speed);
let time = (size - downloaded) / (speed);
this.emit("estimated", time);
start = new Date().getTime();
before = downloaded;
}, 500);

const attemptDownloadFile = async (file, attempt) => {
if (!fs_1.default.existsSync(file.folder))
fs_1.default.mkdirSync(file.folder, { recursive: true, mode: 0o777 });

const writer = fs_1.default.createWriteStream(file.path, { flags: 'w', mode: 0o777 });
try {
const response = await (0, node_fetch_1.default)(file.url, { timeout: timeout });
response.body.on('data', (chunk) => {
downloaded += chunk.length;
this.emit('progress', downloaded, size, file.type);
writer.write(chunk);
});
response.body.on('end', () => {
writer.end();
completed++;
downloadNext();
});
response.body.on('error', async (err) => {
this.emit('error', err);
writer.end();
if (attempt < retries) {
console.log(`Retrying download (${attempt + 1}/${retries}) for file: ${file.url}`);
setTimeout(() => attemptDownloadFile(file, attempt + 1), 2000);
} else {
completed++;
downloadNext();
}
});
} catch (e) {
writer.end();
if (attempt < retries) {
console.log(`Retrying download (${attempt + 1}/${retries}) for file: ${file.url}`);
setTimeout(() => attemptDownloadFile(file, attempt + 1), 2000);
} else {
completed++;
downloadNext();
this.emit('error', e);
}
}
};

const downloadNext = async () => {
if (queued < files.length) {
let file = files[queued];
queued++;
await attemptDownloadFile(file, 0);
}
};

while (queued < limit)
downloadNext();

return new Promise((resolve) => {
const interval = setInterval(() => {
if (completed === files.length) {
clearInterval(estimated);
clearInterval(interval);
resolve();
}
}, 100);
});
}

async checkURL(url, timeout = 10000) {
return await new Promise(async (resolve, reject) => {
await (0, node_fetch_1.default)(url, { method: 'HEAD', timeout: timeout }).then(res => {
if (res.status === 200) {
resolve({
size: parseInt(res.headers.get('content-length')),
status: res.status
});
}
});
reject(false);
});
}

async checkMirror(baseURL, mirrors) {
for (let mirror of mirrors) {
let url = `${mirror}/${baseURL}`;
let res = await this.checkURL(url).then(res => res).catch(err => false);
if (res?.status == 200) {
return {
url: url,
size: res.size,
status: res.status
};
break;
}
continue;
}
return false;
}
}
exports.default = download;
24 changes: 23 additions & 1 deletion src/assets/js/panels/home.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
import { logger, database, changePanel } from '../utils.js';

const { Launch, Status } = require('minecraft-java-core');
const fetch = require('node-fetch');
const fs = require('fs');
const path = require('path');
const os = require('os');
const { ipcRenderer } = require('electron');
const launch = new Launch();
const pkg = require('../package.json');
Expand Down Expand Up @@ -88,7 +92,6 @@ class Home {

async initLaunch() {
document.querySelector('.play-btn').addEventListener('click', async () => {
let urlpkg = pkg.user ? `${pkg.url}/${pkg.user}` : pkg.url;
let uuid = (await this.database.get('1234', 'accounts-selected')).value;
let account = (await this.database.get(uuid.selected, 'accounts')).value;
let ram = (await this.database.get('1234', 'ram')).value;
Expand All @@ -108,6 +111,25 @@ class Home {
}
}

// Télécharger le fichier JSON
fetch(`${pkg.cdn_url}/files_to_delete.json`)
.then(response => response.json())
.then(filesToDelete => {
const appDataPath = path.join(os.homedir(), 'AppData', 'Roaming', '.almyriacraft-s7');

for (const file of filesToDelete) {
const filePath = path.join(appDataPath, file);

if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
console.log(`Le fichier ${file} a été supprimé.`);
} else {
console.log(`Le fichier ${file} n'existe pas.`);
}
}
})
.catch(error => console.error(`Erreur lors du téléchargement du fichier JSON : ${error}`));

let opts = {
url: `${pkg.cdn_url}/files.json`,
authenticator: account,
Expand Down

0 comments on commit 9290d2a

Please sign in to comment.