Compare commits

...

14 Commits

Author SHA1 Message Date
Tianpao
9afbc993ba feat:hash优化筛选模组 2025-09-07 17:42:56 +08:00
Tianpao
f65dea29f5 feat:使用mcim镜像源 统一UA 2025-08-14 13:44:53 +08:00
Tianpao
9d77fa53c7 feat:fabric启动脚本,垃圾回收,rubbish改名 fix:json解析失败崩溃 2025-07-26 16:27:14 +08:00
Tianpao
d8d8c4051a feat:更新fabric安装器 2025-07-26 15:11:44 +08:00
Tianpao
32f7473533 fix:DEP无法正常抛出错误 2025-07-26 13:29:47 +08:00
Tianpao
9f9cfc3e17 feat:检测是否安装Java fix:修复彩色字体无法显示 2025-07-24 11:22:01 +08:00
Tianpao
777d8e43aa 0 2025-07-24 02:40:23 +08:00
Tianpao
5ddcaf9b45 feat:修复TOML 重构DeEarth(未) 2025-07-24 02:40:20 +08:00
Tianpao
40492b8bd0 fix:DeEarth unzip出错时无法处理 refactor:支持从MCIM获取head 2025-07-10 13:46:05 +08:00
Tianpao
bb860b2c4a feat:同步DeEarth上游分支 2025-07-10 09:48:56 +08:00
Tianpao
9dcc4e6c83 fix:DeEarth无法识别NeoForge 2025-07-09 21:47:01 +08:00
Tianpao
cfa97c8715 fix:neoforge无法安装 2025-07-09 21:44:04 +08:00
Tianpao
0acd64ae86 fix:neoforge无法使用 2025-07-09 20:44:54 +08:00
Tianpao
2f518e4487 refactor:优化 2025-07-09 19:15:59 +08:00
12 changed files with 554 additions and 256 deletions

15
Untitled-2.js Normal file
View File

@@ -0,0 +1,15 @@
import got from 'got';
const res = await got.post('https://api.modrinth.com/v2/version_files', {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0',
},
json: {
hashes: [
"ea0f38408102e4d2efd53c2cc11b88b711996b48d8922f76ea6abf731219c5bd1efe39ddf9cce77c54d49a62ff10fb685c00d2e4c524ab99d20f6296677ab2c4",
"925a5c4899affa4098d997dfa4a4cb52c636d539e94bc489d1fa034218cb96819a70eb8b01647a39316a59fcfe223c1a8c05ed2e2ae5f4c1e75fa48f6af1c961"
],
algorithm: 'sha512',
}
}).json()
console.log(res)

35
package-lock.json generated
View File

@@ -10,7 +10,6 @@
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"adm-zip": "^0.5.16", "adm-zip": "^0.5.16",
"chalk": "^5.4.1",
"cli-progress": "^3.12.0", "cli-progress": "^3.12.0",
"dotenv": "^17.0.1", "dotenv": "^17.0.1",
"fs-extra": "^11.3.0", "fs-extra": "^11.3.0",
@@ -18,7 +17,8 @@
"inquirer": "^12.6.3", "inquirer": "^12.6.3",
"p-map": "^7.0.3", "p-map": "^7.0.3",
"p-retry": "^6.2.1", "p-retry": "^6.2.1",
"toml": "^3.0.0", "picocolors": "^1.1.1",
"smol-toml": "^1.4.1",
"yauzl": "^3.2.0" "yauzl": "^3.2.0"
}, },
"devDependencies": { "devDependencies": {
@@ -1937,18 +1937,6 @@
"node": ">=4" "node": ">=4"
} }
}, },
"node_modules/chalk": {
"version": "5.4.1",
"resolved": "https://registry.npmmirror.com/chalk/-/chalk-5.4.1.tgz",
"integrity": "sha512-zgVZuo2WcZgfUEmsn6eO3kINexW8RAE4maiQ8QNs8CtpPCSyMiYsULR3HQYkm3w8FIA3SberyMJMSldGsW+U3w==",
"license": "MIT",
"engines": {
"node": "^12.17.0 || ^14.13 || >=16.0.0"
},
"funding": {
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
"node_modules/chardet": { "node_modules/chardet": {
"version": "0.7.0", "version": "0.7.0",
"resolved": "https://registry.npmmirror.com/chardet/-/chardet-0.7.0.tgz", "resolved": "https://registry.npmmirror.com/chardet/-/chardet-0.7.0.tgz",
@@ -4873,7 +4861,6 @@
"version": "1.1.1", "version": "1.1.1",
"resolved": "https://registry.npmmirror.com/picocolors/-/picocolors-1.1.1.tgz", "resolved": "https://registry.npmmirror.com/picocolors/-/picocolors-1.1.1.tgz",
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
"dev": true,
"license": "ISC" "license": "ISC"
}, },
"node_modules/picomatch": { "node_modules/picomatch": {
@@ -5482,6 +5469,18 @@
"node": ">=8" "node": ">=8"
} }
}, },
"node_modules/smol-toml": {
"version": "1.4.1",
"resolved": "https://registry.npmmirror.com/smol-toml/-/smol-toml-1.4.1.tgz",
"integrity": "sha512-CxdwHXyYTONGHThDbq5XdwbFsuY4wlClRGejfE2NtwUtiHYsP1QtNsHb/hnj31jKYSchztJsaA8pSQoVzkfCFg==",
"license": "BSD-3-Clause",
"engines": {
"node": ">= 18"
},
"funding": {
"url": "https://github.com/sponsors/cyyynthia"
}
},
"node_modules/sort-keys": { "node_modules/sort-keys": {
"version": "1.1.2", "version": "1.1.2",
"resolved": "https://registry.npmmirror.com/sort-keys/-/sort-keys-1.1.2.tgz", "resolved": "https://registry.npmmirror.com/sort-keys/-/sort-keys-1.1.2.tgz",
@@ -5838,12 +5837,6 @@
"node": ">=8.0" "node": ">=8.0"
} }
}, },
"node_modules/toml": {
"version": "3.0.0",
"resolved": "https://registry.npmmirror.com/toml/-/toml-3.0.0.tgz",
"integrity": "sha512-y/mWCZinnvxjTKYhJ+pYxwD0mRLVvOtdS2Awbgxln6iEnt4rk0yBxeSBHkGJcPucRiG0e55mwWp+g/05rsrd6w==",
"license": "MIT"
},
"node_modules/trim-repeated": { "node_modules/trim-repeated": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmmirror.com/trim-repeated/-/trim-repeated-1.0.0.tgz", "resolved": "https://registry.npmmirror.com/trim-repeated/-/trim-repeated-1.0.0.tgz",

View File

@@ -16,7 +16,6 @@
}, },
"dependencies": { "dependencies": {
"adm-zip": "^0.5.16", "adm-zip": "^0.5.16",
"chalk": "^5.4.1",
"cli-progress": "^3.12.0", "cli-progress": "^3.12.0",
"dotenv": "^17.0.1", "dotenv": "^17.0.1",
"fs-extra": "^11.3.0", "fs-extra": "^11.3.0",
@@ -24,7 +23,8 @@
"inquirer": "^12.6.3", "inquirer": "^12.6.3",
"p-map": "^7.0.3", "p-map": "^7.0.3",
"p-retry": "^6.2.1", "p-retry": "^6.2.1",
"toml": "^3.0.0", "picocolors": "^1.1.1",
"smol-toml": "^1.4.1",
"yauzl": "^3.2.0" "yauzl": "^3.2.0"
}, },
"devDependencies": { "devDependencies": {

167
src/main copy.ts Normal file
View File

@@ -0,0 +1,167 @@
import inquirer from "inquirer";
import yauzl, { Entry, ZipFile } from "yauzl";
import process, { emit } from "node:process";
import fs from "node:fs";
import fse from "fs-extra";
import { exec } from "node:child_process";
import { join, basename, dirname } from "node:path";
import { platform, what_platform } from "./platform/index.js";
import { isDevelopment, readzipentry } from "./utils/utils.js";
import fabric from "./ml_install/fabric.js";
import forge from "./ml_install/forge.js";
import neoforge from "./ml_install/neoforge.js";
import { DeEarthMain } from "./utils/DeEarth.js";
import { LOGGER } from "./utils/logger.js";
import { fileURLToPath } from "node:url";
interface Answers {
modpack_path: string | undefined;
}
let unzip_path: string = "";
if (isDevelopment) {
unzip_path = join("./", "instance/");
} else {
unzip_path = join(getCurrnetDir().replace("dist", ""), "instance");
}
let zipnamew: string = "";
const argv = process.argv.slice(2)[0];
if (!argv) {
const answer: Answers = await inquirer.prompt([
{ type: "input", name: "modpack_path", message: "请输入整合包路径" },
]);
if (answer.modpack_path) {
initdir();
await main(answer.modpack_path);
}
} else {
initdir();
await main(argv);
}
function initdir() {
if (!fs.existsSync(unzip_path)) {
fse.ensureDirSync(join(unzip_path, "rubbish"));
}
}
async function main(modpack_path: string) {
const zipname = basename(modpack_path)
.replace(".zip", "")
.replace(".mrpack", "");
zipnamew = zipname;
let dud_files: Array<string> = [];
let pack_info: object | undefined = undefined;
let entry_arr: Entry[] = [];
//unzip
const zipfile: ZipFile = await new Promise((resolve, reject) => {
yauzl.open(modpack_path, { lazyEntries: true }, (err, zipfile) => {
if (err) {
reject(err);
}
resolve(zipfile);
});
});
zipfile.readEntry(); //首次读取
zipfile.on("entry", (entry) => {
entry_arr.push(entry);
zipfile.readEntry();
});
await new Promise((resolve) => zipfile.on("end", async () => resolve));
for (let i = 0; i < entry_arr.length; i++) {
const entry = entry_arr[i];
const name: string = entry.fileName;
if (/\/$/.test(name)) {
continue;
} else if (name.includes("overrides/")) {
const zipfilex = join(
unzip_path,
zipname,
name.replace("overrides/", "")
);
if (!fs.existsSync(zipfilex)) {
zipfile.openReadStream(entry, (err, stream) => {
//读取overrides文件夹下的所有文件和文件夹
const dir = dirname(zipfilex);
fse.ensureDirSync(dir);
console.log(zipfilex);
stream.pipe(fse.createWriteStream(zipfilex));
});
}
} else if (name.endsWith(".json") || name.includes("mcbbs.packmeta")) {
dud_files.push(name);
if (
name.includes("manifest.json") ||
name.includes("modrinth.index.json")
) {
pack_info = JSON.parse((await readzipentry(zipfile, entry)).toString());
}
}
}
//zipfile.on("end", async () => {
//zip
//try {
const dirx = join(unzip_path, zipname);
const plat = platform(what_platform(dud_files));
if (typeof pack_info !== "object") throw new Error("未找到manifest.json");
const info = await plat.getinfo(pack_info);
await plat.downloadfile(pack_info, dirx);
await DeEarthMain(join(dirx, "mods"), join(unzip_path, "rubbish"));
await install(info.loader, info.minecraft, info.loader_version, dirx);
fs.writeFileSync(
join(dirx, "eula.txt"),
"#By changing the setting below to TRUE you are indicating your agreement to our EULA (https://aka.ms/MinecraftEULA).\n#This serverpack created by DeEarthX(QQ_Group:559349662)\neula=true"
);
LOGGER.info("DeEarthX已将服务端制作完成");
zipfile.close();
//} catch (e) {
//LOGGER.error(e);
//}
//});
//});
//})
}
async function install(
type: string,
minecraft: string,
loaderver: string,
path: string
) {
if (await checkJava()) {
LOGGER.error(
"未安装Java或系统环境变量不存在Java已跳过自动安装模组加载器服务端"
);
return;
}
switch (type) {
case "fabric":
await fabric(minecraft, loaderver, path);
break;
case "fabric-loader":
await fabric(minecraft, loaderver, path);
break;
case "forge":
await forge(minecraft, loaderver, path);
break;
case "neoforge":
await neoforge(minecraft, loaderver, path);
break;
}
}
function checkJava() {
return new Promise((resolve) => {
exec("java -version", (err) => {
if (err) {
resolve(false);
} else {
resolve(true);
}
});
});
}
function getCurrnetDir() {
const url = new URL(".", import.meta.url);
return fileURLToPath(url);
}

View File

@@ -5,7 +5,7 @@ import fs from "node:fs";
import fse from "fs-extra"; import fse from "fs-extra";
import { join, basename, dirname } from "node:path"; import { join, basename, dirname } from "node:path";
import { platform, what_platform } from "./platform/index.js"; import { platform, what_platform } from "./platform/index.js";
import { isDevelopment, readzipentry } from "./utils/utils.js"; import { type ForgeInfo, isDevelopment, isInstallJava, readzipentry } from "./utils/utils.js";
import fabric from "./ml_install/fabric.js"; import fabric from "./ml_install/fabric.js";
import forge from "./ml_install/forge.js"; import forge from "./ml_install/forge.js";
import neoforge from "./ml_install/neoforge.js"; import neoforge from "./ml_install/neoforge.js";
@@ -39,7 +39,7 @@ if (!argv) {
function initdir() { function initdir() {
if (!fs.existsSync(unzip_path)) { if (!fs.existsSync(unzip_path)) {
fse.ensureDirSync(join(unzip_path, "rubbish")); fse.ensureDirSync(join(unzip_path, ".rubbish"));
} }
} }
@@ -54,12 +54,14 @@ async function main(modpack_path: string) {
yauzl.open(modpack_path, { lazyEntries: true }, (err, zipfile) => { yauzl.open(modpack_path, { lazyEntries: true }, (err, zipfile) => {
zipfile.readEntry(); //首次读取 zipfile.readEntry(); //首次读取
zipfile.on("entry", async (entry) => { zipfile.on("entry", async (entry) => {
if (/\/$/.test(entry.fileName)) {
} else if (entry.fileName.includes("overrides/")) { const name: string = entry.fileName;
if (/\/$/.test(name)) {
} else if (name.includes("overrides/")) {
const zipfilex = join( const zipfilex = join(
unzip_path, unzip_path,
zipname, zipname,
entry.fileName.replace("overrides/", "") name.replace("overrides/", "")
); );
if (!fs.existsSync(zipfilex)) { if (!fs.existsSync(zipfilex)) {
zipfile.openReadStream(entry, (err, stream) => { zipfile.openReadStream(entry, (err, stream) => {
@@ -69,18 +71,16 @@ async function main(modpack_path: string) {
console.log(zipfilex); console.log(zipfilex);
stream.pipe(fse.createWriteStream(zipfilex)); stream.pipe(fse.createWriteStream(zipfilex));
}); });
//console.log(entry.fileName)
} }
} else { } else if (name.endsWith(".json")||name.endsWith("mcbbs.packmeta")) {
const name: string = entry.fileName; dud_files.push(name);
dud_files.push(name);
if (name.endsWith(".json")) {
//console.log((await readzipentry(zipfile, entry))) //console.log((await readzipentry(zipfile, entry)))
pack_info = JSON.parse( if(name.endsWith("modrinth.index.json")|| name.endsWith("manifest.json")){
(await readzipentry(zipfile, entry)).toString() pack_info = JSON.parse(
); (await readzipentry(zipfile, entry)).toString()
);
}
} }
}
zipfile.readEntry(); zipfile.readEntry();
}); });
zipfile.on("end", async () => { zipfile.on("end", async () => {
@@ -89,12 +89,13 @@ async function main(modpack_path: string) {
const plat = platform(what_platform(dud_files)); const plat = platform(what_platform(dud_files));
const info = await plat.getinfo(pack_info); const info = await plat.getinfo(pack_info);
await plat.downloadfile(pack_info, dirx); await plat.downloadfile(pack_info, dirx);
await DeEarthMain(join(dirx, "mods"), join(unzip_path, "rubbish")); await DeEarthMain(join(dirx, "mods"), join(unzip_path, ".rubbish"));
await install(info.loader, info.minecraft, info.loader_version, dirx); await install(info.loader, info.minecraft, info.loader_version, dirx);
fs.writeFileSync( fs.writeFileSync(
join(dirx, "instance.zip"), join(dirx, "eula.txt"),
"#By changing the setting below to TRUE you are indicating your agreement to our EULA (https://aka.ms/MinecraftEULA).\n#This serverpack created by DeEarthX\neula=true" "#By changing the setting below to TRUE you are indicating your agreement to our EULA (https://aka.ms/MinecraftEULA).\n#This serverpack created by DeEarthX(QQ_Group:559349662)\neula=true"
); );
await garcol(dirx,{minecraft_verison: info.minecraft, forge_verison: info.loader_version}).catch((e)=>{});
LOGGER.info("DeEarthX已将服务端制作完成"); LOGGER.info("DeEarthX已将服务端制作完成");
zipfile.close(); zipfile.close();
}); });
@@ -107,12 +108,19 @@ async function install(
loaderver: string, loaderver: string,
path: string path: string
) { ) {
if (!(await isInstallJava)){
LOGGER.error("请先安装Java")
return;
}
switch (type) { switch (type) {
case "fabric": case "fabric":
await fabric(minecraft, loaderver, path); await fabric(minecraft, loaderver, path);
break; break;
case "fabric-loader": case "fabric-loader":
await fabric(minecraft, loaderver, path); await fabric(minecraft, loaderver, path);
const com = "java -jar fabric-server-launch.jar"
fs.writeFileSync(join(path,'run.bat'),com)
fs.writeFileSync(join(path,'run.sh'),com)
break; break;
case "forge": case "forge":
await forge(minecraft, loaderver, path); await forge(minecraft, loaderver, path);
@@ -123,6 +131,24 @@ async function install(
} }
} }
async function garcol(p:string,fi:ForgeInfo): Promise<void> {
return new Promise((resolve,reject)=>{
try{
LOGGER.info("正在删除垃圾文件......")
const x = [`Forge-${fi.minecraft_verison}-${fi.forge_verison}.jar`,`installer.log`,`installer.jar`,`fabric-installer-1.0.3.jar`,`options.txt`,`shaderpacks/`,`resourcepacks/`,'essential/']
for (let i=0;i<x.length;i++){
try{
fs.rmSync(join(p, x[i]),{recursive: true, force: true})
}catch(e){}
}
resolve()
}catch(err){
reject(err)
}
})
}
function getCurrnetDir() { function getCurrnetDir() {
const url = new URL(".", import.meta.url); const url = new URL(".", import.meta.url);
return fileURLToPath(url); return fileURLToPath(url);

View File

@@ -1,6 +1,7 @@
import cp from "child_process"; import cp from "child_process";
import fsExtra from "fs-extra"; import fsExtra from "fs-extra";
import got from "got"; import got from "got";
import { usemirror } from "../utils/utils.js";
export default async function install( export default async function install(
mcver: string, mcver: string,
fabricver: string, fabricver: string,
@@ -8,12 +9,12 @@ export default async function install(
) { ) {
const data = ( const data = (
await got.get( await got.get(
`https://maven.fabricmc.net/net/fabricmc/fabric-installer/1.0.1/fabric-installer-1.0.1.jar` `https://maven.fabricmc.net/net/fabricmc/fabric-installer/1.0.3/fabric-installer-1.0.3.jar`
) )
).rawBody; ).rawBody;
fsExtra.outputFileSync(path+"/fabric-installer-1.0.1.jar", data); fsExtra.outputFileSync(path+"/fabric-installer-1.0.3.jar", data);
cp.execSync( cp.execSync(
`java -jar fabric-installer-1.0.1.jar server -mcver ${mcver} -loader ${fabricver}`, `java -jar fabric-installer-1.0.3.jar server -mcver ${mcver} -loader ${fabricver}`,
{ cwd: path, stdio: "ignore" } { cwd: path, stdio: "ignore" }
); );
} }

View File

@@ -9,7 +9,7 @@ import { LOGGER } from "../utils/logger.js";
const gotx = got.extend({ const gotx = got.extend({
prefixUrl: "https://bmclapi2.bangbang93.com", prefixUrl: "https://bmclapi2.bangbang93.com",
headers: { "User-Agent": "DeEarthX V2" }, headers: { "User-Agent": "DeEarthX" },
}); });
interface mcinfoX { interface mcinfoX {
@@ -24,12 +24,12 @@ export default async function install(
) { ) {
//instance //instance
const mcinfo = (await gotx const mcinfo = (await gotx
.get(`version/${minecraftversion}/json`) .get(`version/${minecraftversion}/json`,{ headers: { "User-Agent": "DeEarthX" } })
.json()) as mcinfoX; //获取Minecraft版本JSON .json()) as mcinfoX; //获取Minecraft版本JSON
const forgepath = path; const forgepath = path;
const forgedata = ( const forgedata = (
await gotx.get( await gotx.get(
`forge/download?mcversion=${minecraftversion}&version=${loaderversion}&category=installer&format=jar` `forge/download?mcversion=${minecraftversion}&version=${loaderversion}&category=installer&format=jar`,
) )
).rawBody; ).rawBody;
fse.outputFileSync( fse.outputFileSync(

View File

@@ -6,7 +6,7 @@ import { LOGGER } from "../utils/logger.js";
import cp from "child_process"; import cp from "child_process";
const got = gotx.extend({ const got = gotx.extend({
prefixUrl: "https://bmclapi2.bangbang93.com", prefixUrl: "https://bmclapi2.bangbang93.com",
headers: { "User-Agent": "DeEarthX V2" }, headers: { "User-Agent": "DeEarthX" },
}); });
interface mcinfoX { interface mcinfoX {
@@ -19,7 +19,7 @@ export default async function install(
neoforge: string, neoforge: string,
path: string path: string
) { ) {
const mcinfo = (await gotx const mcinfo = (await got
.get(`version/${minecraft}/json`) .get(`version/${minecraft}/json`)
.json()) as mcinfoX; //获取Minecraft版本JSON .json()) as mcinfoX; //获取Minecraft版本JSON
const installer = ( const installer = (
@@ -35,7 +35,7 @@ export default async function install(
//下载依赖1 //下载依赖1
const t = fvdata[c].downloads.artifact; const t = fvdata[c].downloads.artifact;
await xfastdownload( await xfastdownload(
`maven${new URL(t.url).pathname}`, `https://bmclapi2.bangbang93.com/maven${new URL(t.url).pathname.replace("/releases","")}`,
`${path}/libraries/${t.path}`, `${path}/libraries/${t.path}`,
16 16
); );
@@ -47,7 +47,7 @@ export default async function install(
//下载依赖2 //下载依赖2
const t = fvdata[c].downloads.artifact; const t = fvdata[c].downloads.artifact;
await xfastdownload( await xfastdownload(
`maven${new URL(t.url).pathname}`, `https://bmclapi2.bangbang93.com/maven${new URL(t.url).pathname.replace("/releases","")}`,
`${path}/libraries/${t.path}`, `${path}/libraries/${t.path}`,
16 16
); );
@@ -57,13 +57,13 @@ export default async function install(
for (let d = 0; d < mcinfo.libraries.length; d++) { for (let d = 0; d < mcinfo.libraries.length; d++) {
const g = mcinfo.libraries[d].downloads.artifact; const g = mcinfo.libraries[d].downloads.artifact;
await xfastdownload( await xfastdownload(
`maven${new URL(g.url).pathname}`, `https://bmclapi2.bangbang93.com/maven${new URL(g.url).pathname}`,
`${path}/libraries/${g.path}`, `${path}/libraries/${g.path}`,
16 16
); );
} }
await xfastdownload( await xfastdownload(
`version/${minecraft}/server`, `https://bmclapi2.bangbang93.com/version/${minecraft}/server`,
`${path}/libraries/net/minecraft/server/${minecraft}/server-${minecraft}.jar`, `${path}/libraries/net/minecraft/server/${minecraft}/server-${minecraft}.jar`,
1 1
); );

View File

@@ -46,6 +46,7 @@ export class CurseForge implements XPlatform {
"Content-Type": "application/json", "Content-Type": "application/json",
"x-api-key": "x-api-key":
"$2a$10$ydk0TLDG/Gc6uPMdz7mad.iisj2TaMDytVcIW4gcVP231VKngLBKy", "$2a$10$ydk0TLDG/Gc6uPMdz7mad.iisj2TaMDytVcIW4gcVP231VKngLBKy",
"User-Agent": "DeEarthX",
}, },
}) })
.json() .json()

View File

@@ -1,25 +1,27 @@
/* Power by.Tianpao /* Power by.Tianpao
* 本工具可能会判断失误,但也能为您节省不少时间! * 本工具可能会判断失误,但也能为您节省不少时间!
* DeEarth V2 From StarNet.X * DeEarth V2 From StarNet.X
* Writing in 03.29.2025(latest) * Writing in 07.10.2025(latest)
* ©2024-2025 * ©2024-2025
*/ */
import AdmZip from "adm-zip"; import AdmZip from "adm-zip";
import got from "got"; import got from "got";
import fs from "fs"; import fs from "fs";
import toml from 'toml'; import crypto from "crypto";
import toml from 'smol-toml'
import path from 'path'; import path from 'path';
import pMap from "p-map"; import pMap from "p-map";
import { usemirror } from "./utils.js";
import { LOGGER } from "./logger.js"; import { LOGGER } from "./logger.js";
import { MultiBar } from "cli-progress"; import { MultiBar } from "cli-progress";
export async function DeEarthMain(modspath: string, movepath: any) { export async function DeEarthMain(modspath: string, movepath: any) {
if(!fs.existsSync(movepath)){ if (!fs.existsSync(movepath)) {
fs.mkdirSync(movepath) fs.mkdirSync(movepath)
} }
LOGGER.info(`DeEarth V1.0.0`) LOGGER.info(`DeEarth V1.0.0`)
LOGGER.info(`如有无法筛选的mods请前往 https://dearth.0771010.xyz/ 提交未成功筛选的模组的modid`) LOGGER.info(`如有无法筛选的mods请前往 https://dearth.0771010.xyz/ 提交未成功筛选的模组的modid`)
LOGGER.info(`Probejs 7.0.0以上版本为非客户端mod如rubbish中有请自行添加回去`) LOGGER.info(`Probejs 7.0.0以上版本为非客户端mod.rubbish中有请自行添加回去`)
const resaddr = fs.readdirSync(modspath) const resaddr = fs.readdirSync(modspath)
LOGGER.info(`获取目录列表,一共${resaddr.length}个jar文件。`) LOGGER.info(`获取目录列表,一共${resaddr.length}个jar文件。`)
const totalBar = multibar.create(resaddr.length, 0, { filename: '总文件数' }) const totalBar = multibar.create(resaddr.length, 0, { filename: '总文件数' })
@@ -35,93 +37,113 @@ fs.mkdirSync(movepath)
} }
export async function DeEarth(modpath: string, movepath: string) { export async function DeEarth(modpath: string, movepath: string) {
const zip = new AdmZip(modpath).getEntries(); let mrurl = "https://api.modrinth.com"
//for (let i = 0; i < zip.length; i++) { if (usemirror){
//const e = zip[i] mrurl = "https://mod.mcimirror.top/modrinth"
}
let pid:string|undefined = undefined
try {
const data = fs.readFileSync(modpath)
const hash = crypto.createHash('sha1').update(data).digest('hex')
const pjson = await got.get(`${mrurl}/v2/version_file/${hash}?algorithm=sha1`,{
headers:{
"User-Agent": "DeEarth"
}
}).json<{project_id:string}>()
pid = pjson.project_id
//console.log("哈希命中成功正在查询Modrinth")
}catch(e){}
const zipinfo = ZipInfo(modpath)
let modid:string = ""
if(zipinfo){
if(zipinfo.modinfo.type === "forge"){
modid = zipinfo.modinfo.data.mods[0].modId
}else if(zipinfo.modinfo.type === "fabric"){
modid = zipinfo.modinfo.data.id
}
try { //Modrinth try { //Modrinth
for (let i = 0; i < zip.length; i++) { let body:any
const e = zip[i] if (pid){
if (e.entryName == "META-INF/mods.toml") { //Forge,NeoForge body = JSON.parse(await FastGot(`${mrurl}/v2/project/${pid}`))
const modid = toml.parse(e.getData().toString('utf-8')).mods[0].modId }else{
//const body = await got.get(`https://api.modrinth.com/v2/project/${modid}`, { headers: { "User-Agent": "DeEarth" } }).json() body = JSON.parse(await FastGot(`${mrurl}/v2/project/${modid}`))
const body = JSON.parse(await FastGot(`https://api.modrinth.com/v2/project/${modid}`)) }
if (body.client_side == "required" && body.server_side == "unsupported") { if(body.client_side == "required" && body.server_side !== "required"){
fs.renameSync(modpath, `${movepath}/${path.basename(modpath)}`) fs.renameSync(modpath, `${movepath}/${path.basename(modpath)}`)
} }
} else if (e.entryName == "fabric.mod.json") { //Fabric } catch (error) { //DeEarthPublic
const modid = JSON.parse(e.getData().toString('utf-8')).id try {
//const body = await got.get(`https://api.modrinth.com/v2/project/${modid}`, { headers: { "User-Agent": "DeEarth" } }).json() if (JSON.parse(await FastGot(`https://dearth.0771010.xyz/api/modid?modid=${modid}`)).isClient) {
const body = JSON.parse(await FastGot(`https://api.modrinth.com/v2/project/${modid}`)) fs.renameSync(modpath, `${movepath}/${path.basename(modpath)}`)
if (body.client_side == "required" && body.server_side == "unsupported") { }else{
fs.renameSync(modpath, `${movepath}/${path.basename(modpath)}`) throw new Error("DeEarthPublic Not Found This Mod")
}
}
} }
} catch (error) { //mods.toml或fabric.mod.json判断 } catch (error) { //mods.toml或fabric.mod.json判断
try{//DeEarthPublic try{
for (let i = 0; i < zip.length; i++) { if(zipinfo.modinfo.type === "forge"){
const e = zip[i] const mcside = zipinfo.modinfo.data.dependencies[modid].find((mod: { modId: string; }) => mod.modId === "minecraft").side //Minecraft
if (e.entryName == "META-INF/mods.toml") { //Forge,Neoforge if (mcside == "CLIENT") {
const modid = toml.parse(e.getData().toString('utf-8')).mods[0].modId fs.renameSync(modpath, `${movepath}/${path.basename(modpath)}`)
const body = JSON.parse(await FastGot(`https://dearth.0771010.xyz/api/modid?modid=${modid}`))
if (body.isClient) {
fs.renameSync(modpath, `${movepath}/${path.basename(modpath)}`)
}
} else if (e.entryName == "fabric.mod.json") { //Fabric
const modid = JSON.parse(e.getData().toString('utf-8')).id
const body = JSON.parse(await FastGot(`https://dearth.0771010.xyz/api/modid?modid=${modid}`))
if (body.isClient) {
fs.renameSync(modpath, `${movepath}/${path.basename(modpath)}`)
}
}
} }
}catch(errorr){ const forgeside = zipinfo.modinfo.data.dependencies[modid].find((mod: { modId: string; }) => mod.modId === "forge").side //Forge
for (let i = 0; i < zip.length; i++) { if (forgeside == "CLIENT") {
const e = zip[i] fs.renameSync(modpath, `${movepath}/${path.basename(modpath)}`)
try { }
if (e.entryName == "META-INF/mods.toml") { //Forge,Neoforge const neoside = zipinfo.modinfo.data.dependencies[modid].find((mod: { modId: string; }) => mod.modId === "neoforge").side //NeoForge
const tr = toml.parse(e.getData().toString('utf-8')) if (neoside == "CLIENT") {
const mcside = tr.dependencies[tr.mods[0].modId].find((mod: { modId: string; }) => mod.modId === "minecraft").side fs.renameSync(modpath, `${movepath}/${path.basename(modpath)}`)
if (mcside == "CLIENT"){ //从Minecraft判断 }
fs.renameSync(modpath, `${movepath}/${path.basename(modpath)}`) }else if(zipinfo.modinfo.type === "fabric"){ //Fabric
} const fmj = zipinfo.modinfo.data.environment
const forgeside = tr.dependencies[tr.mods[0].modId].find((mod: { modId: string; }) => mod.modId === "forge").side if (fmj == "client") {
if (forgeside == "CLIENT") { //从Forge判断 fs.renameSync(modpath, `${movepath}/${path.basename(modpath)}`)
fs.renameSync(modpath, `${movepath}/${path.basename(modpath)}`)
}
} else if (e.entryName == "fabric.mod.json") { //Fabric
const fmj = JSON.parse(e.getData().toString('utf-8')).environment
if (fmj == "client") {
fs.renameSync(modpath, `${movepath}/${path.basename(modpath)}`)
}
}
} catch (erro) {//从Mixin判断 但是可能为不准确
for (let i = 0; i < zip.length; i++) {
const e = zip[i]
try {
if (!e.entryName.includes("/") && e.entryName.endsWith(".json") && !e.entryName.endsWith("refmap.json") && !e.entryName.endsWith("mod.json")) {
LOGGER.info(e.entryName)
const resx = JSON.parse(e.getData().toString('utf-8'))
if (e.entryName.includes("common.mixins.json")) { //第一步从common mixins文件判断判断失败后再使用modid.mixins.json进行判断
if (resx.mixins == null || Object.keys(resx.mixins).length == 0 && Object.keys(resx.client).length !== 0) {
fs.renameSync(modpath, `${movepath}/${path.basename(modpath)}`)
}
} else {
if (resx.mixins == null || Object.keys(resx.mixins).length == 0 && Object.keys(resx.client).length !== 0) {
fs.renameSync(modpath, `${movepath}/${path.basename(modpath)}`)
}
}
}
} catch (err:any) {//避免有傻逼JSON写注释虽然GSON可以这样 但是这样一点也不人道)
if (err.errno !== -4058) {
LOGGER.error(`大天才JSON写注释了估计模组路径:${modpath},过滤失败`)
}
}
}
} }
} }
}catch(error){
try{
for (let i = 0; i < zipinfo.mixins.length; i++) {
const e = zipinfo.mixins[i]
const info = JSON.parse(e.info)
if (isMixin(info)) {
fs.renameSync(modpath, `${movepath}/${path.basename(modpath)}`)
}
}
}catch(error){
LOGGER.error(`大天才JSON写注释了估计模组路径:${modpath},过滤失败`)
}
}
} }
} }
}
}
function ZipInfo(modpath: string) {
interface ZipInfo {
mixins: { filename: string, info: string }[]
modinfo: {type:string,data:any};
}
try{
let zipinfo: ZipInfo = { mixins: [], modinfo: {type: "",data: {}} }
const zip = new AdmZip(modpath).getEntries();
for (let i = 0; i < zip.length; i++) {
const e = zip[i]
if (isMixinFile(e.entryName)) {
zipinfo.mixins.push({ filename: e.entryName, info: e.getData().toString('utf-8') })
} else if (isForge(e.entryName)) {
zipinfo.modinfo.type = "forge"
zipinfo.modinfo.data = toml.parse(e.getData().toString('utf-8'))
} else if (e.entryName.endsWith("fabric.mod.json")) {
zipinfo.modinfo.type = "fabric"
zipinfo.modinfo.data = JSON.parse(e.getData().toString('utf-8'))
}
}
return zipinfo;
}catch(error){
LOGGER.error(error)
}
} }
async function FastGot(url: string) { async function FastGot(url: string) {
@@ -131,7 +153,7 @@ async function FastGot(url: string) {
try { try {
if (e[0] !== null) { //防止URL为空 if (e[0] !== null) { //防止URL为空
//if(isChinaIpAddress((await got.get("https://4.ipw.cn/")).body)){ //if(isChinaIpAddress((await got.get("https://4.ipw.cn/")).body)){
return (await got.get(e[0], { headers: { "User-Agent": "DeEarth" } })).body return (await got.get(e[0], { headers: { "User-Agent": "DeEarthX" } })).body
//}else{ //}else{
//return (await got.get(`https://mod.mcimirror.top/modrinth/${new URL(e[0]).pathname}`, { headers: { "User-Agent": "DeEarth" } })).body //MCIM源 //return (await got.get(`https://mod.mcimirror.top/modrinth/${new URL(e[0]).pathname}`, { headers: { "User-Agent": "DeEarth" } })).body //MCIM源
//} //}
@@ -148,7 +170,7 @@ async function FastGot(url: string) {
}) })
if (fastgot[0] !== undefined) { if (fastgot[0] !== undefined) {
return fastgot[0] return fastgot[0]
}else{ } else {
return "null" return "null"
} }
} }
@@ -156,9 +178,21 @@ async function FastGot(url: string) {
const multibar = new MultiBar({ const multibar = new MultiBar({
format: ' {bar} | {filename} | {value}/{total}', format: ' {bar} | {filename} | {value}/{total}',
noTTYOutput: true, noTTYOutput: true,
notTTYSchedule: 10*1000, notTTYSchedule: 10 * 1000,
}) })
function isMixin(resx: { mixins: {} | null; client: {}; }) {
return resx.mixins == null || Object.keys(resx.mixins).length == 0 && Object.keys(resx.client).length !== 0
}
function isForge(name: string): boolean {
return name.endsWith("mods.toml") || name.endsWith("neoforge.mod.toml")
}
function isMixinFile(name: string): boolean {
return !name.includes("/") && name.endsWith(".json") && !name.endsWith("refmap.json") && !name.endsWith("mod.json")
}
function isChinaIpAddress(ipAddress: string) { function isChinaIpAddress(ipAddress: string) {
const chinaRegex = /^((?:(?:1(?:0|1|2[0-7]|[3-9][0-9])|2(?:[0-4][0-9]|5[0-5])|[3-9][0-9]{2})\.){3}(?:(?:1(?:0|1|2[0-7]|[3-9][0-9])|2(?:[0-4][0-9]|5[0-5])|[3-9][0-9]{2})))$/; const chinaRegex = /^((?:(?:1(?:0|1|2[0-7]|[3-9][0-9])|2(?:[0-4][0-9]|5[0-5])|[3-9][0-9]{2})\.){3}(?:(?:1(?:0|1|2[0-7]|[3-9][0-9])|2(?:[0-4][0-9]|5[0-5])|[3-9][0-9]{2})))$/;
return chinaRegex.test(ipAddress); return chinaRegex.test(ipAddress);

View File

@@ -1,4 +1,4 @@
import chalk from "chalk"; import pc from "picocolors"
export const LOGGER = { export const LOGGER = {
info(text: string) { info(text: string) {
info(text); info(text);
@@ -6,39 +6,39 @@ export const LOGGER = {
warn(text: string) { warn(text: string) {
warn(text); warn(text);
}, },
error(text: string | object) { error(text: string | object | unknown) {
error(text); error(text);
}, },
}; };
function info(text: string) { function info(text: string) {
console.log( console.log(
`[${chalk.blue( `[${pc.blue(
new Date().toLocaleDateString() + " " + new Date().toLocaleTimeString() new Date().toLocaleDateString() + " " + new Date().toLocaleTimeString()
)}](${process.pid})[${chalk.green("INFO")}]:${chalk.cyan(text)}` )}](${process.pid})[${pc.green("INFO")}]:${pc.cyan(text)}`
); );
} }
function warn(text: string) { function warn(text: string) {
console.log( console.log(
`[${chalk.blue( `[${pc.blue(
new Date().toLocaleDateString() + " " + new Date().toLocaleTimeString() new Date().toLocaleDateString() + " " + new Date().toLocaleTimeString()
)}](${process.pid})[${chalk.yellowBright("WARN")}]:${chalk.yellowBright( )}](${process.pid})[${pc.yellowBright("WARN")}]:${pc.yellowBright(
text text
)}` )}`
); );
} }
function error(error: object | string) { function error(error: object | string | unknown) {
if (typeof error === "object") { if (typeof error === "object") {
console.log( console.log(
`[${chalk.blue( `[${pc.blue(
new Date().toLocaleDateString() + " " + new Date().toLocaleTimeString() new Date().toLocaleDateString() + " " + new Date().toLocaleTimeString()
)}](${process.pid})[${chalk.red("ERROR")}:${JSON.stringify(error)}` )}](${process.pid})[${pc.red("ERROR")}:${JSON.stringify(error)}`
); );
} else { } else {
console.log( console.log(
`[${chalk.blue( `[${pc.blue(
new Date().toLocaleDateString() + " " + new Date().toLocaleTimeString() new Date().toLocaleDateString() + " " + new Date().toLocaleTimeString()
)}](${process.pid})[${chalk.red("ERROR")}:${error}` )}](${process.pid})[${pc.red("ERROR")}:${error}`
); );
} }
} }

View File

@@ -1,22 +1,31 @@
import pMap from "p-map"; import pMap from "p-map";
import pRetry from "p-retry"; import pRetry from "p-retry";
import fs from "node:fs" import fs from "node:fs";
import fse from "fs-extra" import fse from "fs-extra";
import yauzl from "yauzl"; import yauzl from "yauzl";
import got from "got"; import got from "got";
import env from "dotenv" import env from "dotenv";
import { MultiBar } from "cli-progress"; import { MultiBar } from "cli-progress";
import {URL, fileURLToPath } from "node:url"; import { URL, fileURLToPath } from "node:url";
import { LOGGER } from "./logger.js"; import { LOGGER } from "./logger.js";
import { exec } from "node:child_process";
export async function readzipentry(zipfile: yauzl.ZipFile, entry: yauzl.Entry):Promise<string> { export interface ForgeInfo{
minecraft_verison: string,
forge_verison: string
}
export async function readzipentry(
zipfile: yauzl.ZipFile,
entry: yauzl.Entry
): Promise<string> {
const data: Buffer<ArrayBufferLike>[] = []; const data: Buffer<ArrayBufferLike>[] = [];
return await new Promise((reslove, reject) => { return await new Promise((reslove, reject) => {
zipfile.openReadStream(entry, (err, e) => { zipfile.openReadStream(entry, (err, e) => {
e.on("data", (chunk: Buffer) => { e.on("data", (chunk: Buffer) => {
data.push(chunk); data.push(chunk);
}).on("end", () => { }).on("end", () => {
if (data.length !== 0&&typeof data !== "string"){ if (data.length !== 0 && typeof data !== "string") {
reslove(Buffer.concat(data).toString()); reslove(Buffer.concat(data).toString());
} }
}); });
@@ -24,119 +33,171 @@ export async function readzipentry(zipfile: yauzl.ZipFile, entry: yauzl.Entry):P
}); });
} }
export async function fastdownload(data:[string,string]){ export async function fastdownload(data: [string, string]) {
const multibar = new MultiBar({ const multibar = new MultiBar({
format: ' {bar} | {filename} | {value}/{total}', format: " {bar} | {filename} | {value}/{total}",
noTTYOutput: true, noTTYOutput: true,
notTTYSchedule: 10*1000, notTTYSchedule: 10 * 1000,
}) });
const totalBar = multibar.create(data.length, 0, {filename: '总文件数'}) const totalBar = multibar.create(data.length, 0, { filename: "总文件数" });
return await pMap(data,async(e)=>{ return await pMap(
const size:number = await (async()=>{const head = (await got.head(e[0].replace("https://mod.mcimirror.top","https://edge.forgecdn.net"))).headers['content-length'];if(head){return Number(head)}else{return 0}})() data,
const bar = multibar.create(size, 0, {filename: e[1]}) async (e) => {
try{ const size: number = await (async () => {
await pRetry(async()=>{ const head = (
if(!fs.existsSync(e[1])){ await got.head(
await got.get(e[0],{ e[0] /*.replace("https://mod.mcimirror.top","https://edge.forgecdn.net")*/,
responseType:"buffer", { headers: { "user-agent": "DeEarthX" } }
}).on('downloadProgress',(progress)=>{ )
bar.update(progress.transferred) ).headers["content-length"];
}).then((res)=>{ if (head) {
fse.outputFileSync(e[1],res.rawBody) return Number(head);
}) } else {
} return 0;
},{retries:3}) }
}catch(e){ })();
LOGGER.error({err:e}) const bar = multibar.create(size, 0, { filename: e[1] });
}finally{ try {
bar.stop() await pRetry(
totalBar.increment() async () => {
multibar.remove(bar) if (!fs.existsSync(e[1])) {
await got
.get(e[0], {
responseType: "buffer",
headers: {
"user-agent": "DeEarthX",
},
})
.on("downloadProgress", (progress) => {
bar.update(progress.transferred);
})
.then((res) => {
fse.outputFileSync(e[1], res.rawBody);
});
}
},
{ retries: 3 }
);
} catch (e) {
LOGGER.error({ err: e });
} finally {
bar.stop();
totalBar.increment();
multibar.remove(bar);
} }
},{concurrency:16}) },
{ concurrency: 16 }
);
} }
export async function mr_fastdownload(data:[string,string,string]){ export async function mr_fastdownload(data: [string, string, string]) {
const multibar = new MultiBar({ const multibar = new MultiBar({
format: ' {bar} | {filename} | {value}/{total}', format: " {bar} | {filename} | {value}/{total}",
noTTYOutput: true, noTTYOutput: true,
notTTYSchedule: 10*1000, notTTYSchedule: 10 * 1000,
}); });
const totalBar = multibar.create(data.length, 0, { filename: '总文件数' }); const totalBar = multibar.create(data.length, 0, { filename: "总文件数" });
return await pMap(data, async (e) => { return await pMap(
data,
async (e) => {
const bar = multibar.create(Number(e[2]), 0, { filename: e[1] }); const bar = multibar.create(Number(e[2]), 0, { filename: e[1] });
try { try {
await pRetry(async () => { await pRetry(
if (!fse.existsSync(e[1])) { async () => {
await got.get(e[0], { if (!fse.existsSync(e[1])) {
responseType: "buffer", await got
}).on('downloadProgress', (progress) => { .get(e[0], {
bar.update(progress.transferred); responseType: "buffer",
}).then((res) => { headers: {
fse.outputFileSync(e[1], res.rawBody); "user-agent": "DeEarthX",
}); },
} })
}, { retries: 3 }); .on("downloadProgress", (progress) => {
bar.update(progress.transferred);
})
.then((res) => {
fse.outputFileSync(e[1], res.rawBody);
});
}
},
{ retries: 3 }
);
} catch (e) {
LOGGER.error({ err: e });
} finally {
bar.stop();
totalBar.increment();
multibar.remove(bar);
} }
catch (e) { },
LOGGER.error({ err: e }); { concurrency: 16 }
} );
finally {
bar.stop();
totalBar.increment();
multibar.remove(bar);
}
}, { concurrency: 16 });
} }
export async function xfastdownload( export async function xfastdownload(
url: string, url: string,
path: string, path: string,
concurrency: number = 1 concurrency: number = 1
) { ) {
let e = []; let e = [];
e.push([url, path]); e.push([url, path]);
await pMap( await pMap(
e, e,
async (e) => { async (e) => {
try { try {
return await pRetry( return await pRetry(
async () => { async () => {
if ( if (
url !== null && url !== null &&
url !== "" && url !== "" &&
path !== null && path !== null &&
!fs.existsSync(e[1]) !fs.existsSync(e[1])
) { ) {
const res = (await got.get(e[0])).rawBody; //下载文件 const res = (await got.get(e[0],{
await fse.outputFile(e[1], res); //保存文件 headers: {
} "user-agent": "DeEarthX"
}, }
{ })).rawBody; //下载文件
retries: 2, await fse.outputFile(e[1], res); //保存文件
} }
); },
} catch (error) { {
LOGGER.error({ err: error }); retries: 2,
} }
}, );
{ } catch (error) {
concurrency: concurrency, LOGGER.error({ err: error });
} }
); },
} {
concurrency: concurrency,
export const usemirror = (()=>{
env.config({debug:false})
const mirror = process.env.MIRROR
if(mirror){
return false
}else{
return true
} }
})() );
}
export const isDevelopment = (()=>{ export const usemirror = (() => {
env.config() env.config({ debug: false });
return process.env.DEVELOPMENT const mirror = process.env.MIRROR;
})() if (mirror) {
return false;
} else {
return true;
}
})();
export const isDevelopment = (() => {
env.config();
return process.env.DEVELOPMENT;
})();
export const isInstallJava:Promise<boolean> = (() => {
return new Promise((resolve) => {
exec("java -version", (err) => {
if (err) {
resolve(false);
} else {
resolve(true);
}
});
});
})();