feat:首次提交(无法使用)

This commit is contained in:
Tianpao
2025-07-02 19:52:56 +08:00
parent fc20a736c4
commit 839d208029
15 changed files with 772 additions and 35 deletions

59
src/main.ts Normal file
View File

@@ -0,0 +1,59 @@
import inquirer from "inquirer";
import yauzl from "yauzl";
import process from "node:process";
import { join, basename } from "node:path";
import { platform, what_platform } from "./platform/index.js";
import { readzipentry } from "./utils/utils.js";
interface Answers {
modpack_path: string | undefined;
}
const unzip_path = "./instance";
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) {
await main(answer.modpack_path);
}
} else {
await main(argv);
}
async function main(modpack_path: string) {
const zipname = basename(modpack_path)
.replace(".zip", "")
.replace(".mrpack", "");
let dud_files: Array<string> = [];
let pack_info: object;
//unzip
yauzl.open(modpack_path, { lazyEntries: true }, (err, zipfile) => {
zipfile.readEntry(); //首次读取
zipfile.on("entry", async (entry) => {
if (/\/$/.test(entry.fileName)) {
} else if (entry.fileName.includes("overrides/")) {
/*zipfile.openReadStream(entry,(err,stream)=>{ //读取overrides文件夹下的所有文件和文件夹
})*/
//console.log(entry.fileName)
} else {
const name: string = entry.fileName;
dud_files.push(name);
if (name && name.endsWith(".json")) {
pack_info = JSON.parse(
(await readzipentry(zipfile, entry)).toString()
);
}
console.log(name);
}
zipfile.readEntry();
});
zipfile.on("end", () => {
//zip
platform(what_platform(dud_files));
//console.log(dud_files)
zipfile.close();
});
});
}

0
src/ml_install/fabric.ts Normal file
View File

0
src/ml_install/forge.ts Normal file
View File

View File

View File

@@ -0,0 +1,28 @@
import { fastdownload } from "../utils/utils.js";
import { modpack_info, XPlatform } from "./index.js";
export interface CurseForgeManifest {
minecraft: {
version: string;
modLoaders: Array<{ id: string }>;
};
}
export class CurseForge implements XPlatform {
async getinfo(manifest: object): Promise<modpack_info> {
let result: modpack_info = Object.create({});
const local_manifest = manifest as CurseForgeManifest;
if (result && local_manifest)
result.minecraft = local_manifest.minecraft.version;
const loader_all = local_manifest.minecraft.modLoaders[0].id.match(
/(.*)-/
) as RegExpMatchArray;
result.loader = loader_all[1];
result.loader_version = loader_all[0];
return result;
}
async downloadfile(urls: [string, string]): Promise<void> {
await fastdownload(urls);
}
}

42
src/platform/index.ts Normal file
View File

@@ -0,0 +1,42 @@
import { CurseForge } from "./curseforge.js";
import { MCBBS } from "./mcbbs.js";
import { Modrinth } from "./modrinth.js";
export interface XPlatform {
getinfo(manifest: object): Promise<modpack_info>;
downloadfile(
urls: [string, string] | [string, string, string]
): Promise<void>;
}
export interface modpack_info {
minecraft: string;
loader: string;
loader_version: string;
}
export function platform(plat: string | undefined): XPlatform {
let platform: XPlatform = Object.create({});
switch (plat) {
case "curseforge":
platform = new CurseForge();
break;
case "modrinth":
platform = new Modrinth();
case "mcbbs":
platform = new MCBBS();
}
return platform;
}
export function what_platform(dud_files: Array<string>) {
if (dud_files.includes("mcbbs.packmeta")) {
return "mcbbs";
} else if (dud_files.includes("manifest.json")) {
return "curseforge";
} else if (dud_files.includes("modrinth.index.json")) {
return "modrinth";
} else {
return undefined;
}
}

21
src/platform/mcbbs.ts Normal file
View File

@@ -0,0 +1,21 @@
import { CurseForgeManifest } from "./curseforge.js";
import { modpack_info, XPlatform } from "./index.js";
interface MCBBSManifest extends CurseForgeManifest {}
export class MCBBS implements XPlatform {
async getinfo(manifest: object): Promise<modpack_info> {
const result: modpack_info = Object.create({});
const local_manifest = manifest as MCBBSManifest;
if (result && local_manifest)
result.minecraft = local_manifest.minecraft.version;
const loader_all = local_manifest.minecraft.modLoaders[0].id.match(
/(.*)-/
) as RegExpMatchArray;
result.loader = loader_all[1];
result.loader_version = loader_all[0];
return result;
}
async downloadfile(urls: [string, string]): Promise<void> {}
}

33
src/platform/modrinth.ts Normal file
View File

@@ -0,0 +1,33 @@
import { mr_fastdownload } from "../utils/utils.js";
import { modpack_info, XPlatform } from "./index.js";
interface ModrinthManifest {
dependencies: {
minecraft: string;
forge: string;
neoforge: string;
"fabric-loader": string;
[key: string]: string;
};
}
export class Modrinth implements XPlatform {
async getinfo(manifest: object): Promise<modpack_info> {
let result: modpack_info = Object.create({});
const local_manifest = manifest as ModrinthManifest;
const depkey = Object.keys(local_manifest.dependencies);
const loader = ["forge", "neoforge", "fabric-loader"];
result.minecraft = local_manifest.dependencies.minecraft;
for (let i = 0; i < depkey.length; i++) {
const key = depkey[i];
if (key !== "minecraft" && loader.includes(key)) {
result.loader = key;
result.loader_version = local_manifest.dependencies[key];
}
}
return result;
}
async downloadfile(urls: [string, string, string]): Promise<void> {
await mr_fastdownload(urls);
}
}

145
src/utils/DeEarth.ts Normal file
View File

@@ -0,0 +1,145 @@
/* Power by.Tianpao
* 本工具可能会判断失误,但也能为您节省不少时间!
* DeEarth V2 From StarNet.X
* Writing in 03.29.2025(latest)
* ©2024-2025
*/
import AdmZip from "adm-zip";
import got from "got";
import fs from "fs";
import toml from 'toml';
import path from 'path';
import pMap from "p-map";
import { LOGGER } from "./logger.js";
import { MultiBar } from "cli-progress";
export async function DeEarthMain(modspath: string, movepath: any) {
if(!fs.existsSync(movepath)){
fs.mkdirSync(movepath)
}
LOGGER.info(`DeEarth V1.0.0`)
const resaddr = fs.readdirSync(modspath)
LOGGER.info(`获取目录列表,一共${resaddr.length}个jar文件。`)
const totalBar = multibar.create(resaddr.length, 0, { filename: '总文件数' })
for (let i = 0; i < resaddr.length; i++) {
const e = `${modspath}/${resaddr[i]}`
if (e.endsWith(".jar") && fs.statSync(e).isFile()) { //判断是否以.jar结尾并且是文件
//console.log(e)
await DeEarth(e, movepath) //使用DeEarth进行审查mod并移动
totalBar.increment()
}
}
multibar.stop()
}
export async function DeEarth(modpath: string, movepath: string) {
const zip = new AdmZip(modpath).getEntries();
//for (let i = 0; i < zip.length; i++) {
//const e = zip[i]
try { //Modrinth
for (let i = 0; i < zip.length; i++) {
const e = zip[i]
if (e.entryName == "META-INF/mods.toml") { //Forge,NeoForge
const modid = toml.parse(e.getData().toString('utf-8')).mods[0].modId
//const body = await got.get(`https://api.modrinth.com/v2/project/${modid}`, { headers: { "User-Agent": "DeEarth" } }).json()
const body = JSON.parse(await FastGot(`https://api.modrinth.com/v2/project/${modid}`))
if (body.client_side == "required" && body.server_side == "unsupported") {
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 = await got.get(`https://api.modrinth.com/v2/project/${modid}`, { headers: { "User-Agent": "DeEarth" } }).json()
const body = JSON.parse(await FastGot(`https://api.modrinth.com/v2/project/${modid}`))
if (body.client_side == "required" && body.server_side == "unsupported") {
fs.renameSync(modpath, `${movepath}/${path.basename(modpath)}`)
}
}
}
} catch (error) { //mods.toml或fabric.mod.json判断
for (let i = 0; i < zip.length; i++) {
const e = zip[i]
try {
if (e.entryName == "META-INF/mods.toml") { //Forge,Neoforge
const tr = toml.parse(e.getData().toString('utf-8'))
const mcside = tr.dependencies[tr.mods[0].modId].find((mod: { modId: string; }) => mod.modId === "minecraft").side
if (mcside == "CLIENT"){ //从Minecraft判断
fs.renameSync(modpath, `${movepath}/${path.basename(modpath)}`)
}
const forgeside = tr.dependencies[tr.mods[0].modId].find((mod: { modId: string; }) => mod.modId === "forge").side
if (forgeside == "CLIENT") { //从Forge判断
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},过滤失败`)
}
}
}
}
}
}
//}
}
async function FastGot(url: string) {
let e = []
e.push([url])
const fastgot = await pMap(e, async (e: any[]) => {
try {
if (e[0] !== null) { //防止URL为空
//if(isChinaIpAddress((await got.get("https://4.ipw.cn/")).body)){
return (await got.get(e[0], { headers: { "User-Agent": "DeEarth" } })).body
//}else{
//return (await got.get(`https://mod.mcimirror.top/modrinth/${new URL(e[0]).pathname}`, { headers: { "User-Agent": "DeEarth" } })).body //MCIM源
//}
}
} catch (error: any) {
if (error.message !== "Response code 404 (Not Found)") {
LOGGER.error({ err: error })
} else {
throw new Error(error)
}
}
}, {
concurrency: 48
})
if (fastgot[0] !== undefined) {
return fastgot[0]
}else{
return "null"
}
}
const multibar = new MultiBar({
format: ' {bar} | {filename} | {value}/{total}',
noTTYOutput: true,
notTTYSchedule: 10*1000,
})
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})))$/;
return chinaRegex.test(ipAddress);
}

44
src/utils/logger.ts Normal file
View File

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

85
src/utils/utils.ts Normal file
View File

@@ -0,0 +1,85 @@
import pMap from "p-map";
import pRetry from "p-retry";
import fse from "fs-extra"
import yauzl from "yauzl";
import got from "got";
import { MultiBar } from "cli-progress";
import { LOGGER } from "./logger.js";
export async function readzipentry(zipfile: yauzl.ZipFile, entry: yauzl.Entry):Promise<string|Buffer> {
const data: Buffer<ArrayBufferLike>[] = [];
return await new Promise((reslove, reject) => {
zipfile.openReadStream(entry, (err, e) => {
e.on("data", (chunk: Buffer) => {
data.push(chunk);
}).on("end", () => {
reslove(data.toString());
});
});
});
}
export async function fastdownload(data:[string,string]){
const multibar = new MultiBar({
format: ' {bar} | {filename} | {value}/{total}',
noTTYOutput: true,
notTTYSchedule: 10*1000,
})
const totalBar = multibar.create(data.length, 0, {filename: '总文件数'})
return await pMap(data,async(e)=>{
const size:number = await (async()=>{const head = (await got.head(e[0])).headers['content-length'];if(head){return Number(head)}else{return 0}})()
const bar = multibar.create(size, 0, {filename: e[1]})
try{
await pRetry(async()=>{
if(!fse.existsSync(e[1])){
await got.get(e[0],{
responseType:"buffer",
}).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})
}
export async function mr_fastdownload(data:[string,string,string]){
const multibar = new MultiBar({
format: ' {bar} | {filename} | {value}/{total}',
noTTYOutput: true,
notTTYSchedule: 10*1000,
});
const totalBar = multibar.create(data.length, 0, { filename: '总文件数' });
return await pMap(data, async (e) => {
const bar = multibar.create(Number(e[2]), 0, { filename: e[1] });
try {
await pRetry(async () => {
if (!fse.existsSync(e[1])) {
await got.get(e[0], {
responseType: "buffer",
}).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 });
}