commit 4654f36202c8c7d5a90fa948aeda7d82c2a83899
Author: 15736060610 <15736060610@139.com>
Date: Sat Mar 14 21:11:59 2026 +0800
项目迁移
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
new file mode 100644
index 0000000..b7d817c
--- /dev/null
+++ b/.github/workflows/build.yml
@@ -0,0 +1,106 @@
+name: CI/CD
+
+on:
+ push:
+ branches:
+ - main
+ tags:
+ - 'v*'
+
+jobs:
+ check:
+ name: Code Check
+ runs-on: windows-latest
+
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
+
+ - name: Setup pnpm
+ uses: pnpm/action-setup@v4
+ with:
+ version: 9
+
+ - name: Setup Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: '24.14.0'
+ cache: 'pnpm'
+
+ - name: Install dependencies
+ run: pnpm install
+
+ - name: Type check backend
+ run: |
+ cd backend
+ pnpm exec tsc --noEmit
+
+ - name: Type check frontend
+ run: |
+ cd front
+ pnpm exec vue-tsc --noEmit
+
+ build:
+ name: Build Windows
+ runs-on: windows-latest
+ if: startsWith(github.ref, 'refs/tags/v')
+ permissions:
+ contents: write
+
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+
+ - name: Setup pnpm
+ uses: pnpm/action-setup@v4
+ with:
+ version: 9
+
+ - name: Setup Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: '24.14.0'
+ cache: 'pnpm'
+
+ - name: Setup Rust
+ uses: dtolnay/rust-toolchain@stable
+
+ - name: Install dependencies
+ run: pnpm install
+
+ - name: Build backend
+ run: pnpm run backend
+
+ - name: Compress with UPX
+ run: pnpm run upx
+
+ - name: Copy backend to frontend
+ run: pnpm run back2front
+
+ - name: Build frontend
+ run: pnpm run tauri
+
+ - name: Move build to root
+ run: pnpm run build2root
+
+ - name: Upload artifacts
+ uses: actions/upload-artifact@v4
+ with:
+ name: DeEarthX-V3-${{ github.ref_name }}-windows
+ path: |
+ DeEarthX-V3_x64-setup.exe
+ DeEarthX-V3_x64-setup.zip
+
+ - name: Create Release
+ uses: softprops/action-gh-release@v2
+ with:
+ files: |
+ DeEarthX-V3_x64-setup.exe
+ DeEarthX-V3_x64-setup.zip
+ draft: false
+ prerelease: false
+ generate_release_notes: true
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..febec3c
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,34 @@
+# Logs
+logs
+*.log
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+pnpm-debug.log*
+lerna-debug.log*
+
+node_modules
+dist
+dist-ssr
+*.local
+
+# Editor directories and files
+.vscode/*
+!.vscode/extensions.json
+.idea
+.DS_Store
+*.suo
+*.ntvs*
+*.njsproj
+*.sln
+*.sw?
+*.zip
+Dex-v3-core.exe
+core-x86_64-pc-windows-msvc.exe
+config.json
+*.exe
+*.jar
+instance
+*.mrpack
+templates/
+package-lock.json
diff --git a/.trae/documents/deearthx_improvement_plan.md b/.trae/documents/deearthx_improvement_plan.md
new file mode 100644
index 0000000..b4b960d
--- /dev/null
+++ b/.trae/documents/deearthx_improvement_plan.md
@@ -0,0 +1,133 @@
+# DeEarthX-CE - 改进计划
+
+## 项目分析
+
+DeEarthX-CE 是一个与 Minecraft 相关的工具,包含以下组件:
+- **后端**:TypeScript + Express 构建,提供模组检测、过滤、平台集成等功能
+- **前端**:Vue 3 + Ant Design Vue + Tauri 构建的桌面应用
+- **文档**:VitePress 构建的文档网站
+
+## 改进任务列表
+
+### [ ] 任务 1:代码质量检查与优化
+- **Priority**:P1
+- **Depends On**:None
+- **Description**:
+ - 检查并清理未使用的依赖
+ - 统一代码风格和命名规范
+ - 优化错误处理机制
+ - 提高代码可读性和可维护性
+- **Success Criteria**:
+ - 所有依赖都是必要的
+ - 代码风格统一
+ - 错误处理完善
+- **Test Requirements**:
+ - `programmatic` TR-1.1:运行 `npm run build` 无错误
+ - `programmatic` TR-1.2:运行代码检查工具无严重警告
+ - `human-judgement` TR-1.3:代码结构清晰,注释完善
+
+### [ ] 任务 2:性能优化
+- **Priority**:P2
+- **Depends On**:任务 1
+- **Description**:
+ - 优化文件操作性能
+ - 优化网络请求和响应
+ - 减少不必要的计算和重复操作
+ - 提高模组处理速度
+- **Success Criteria**:
+ - 文件操作速度提升
+ - 网络请求响应时间减少
+ - 模组处理效率提高
+- **Test Requirements**:
+ - `programmatic` TR-2.1:模组处理时间减少 20%
+ - `programmatic` TR-2.2:内存使用降低 15%
+ - `human-judgement` TR-2.3:用户操作响应更流畅
+
+### [ ] 任务 3:安全性增强
+- **Priority**:P1
+- **Depends On**:任务 1
+- **Description**:
+ - 检查并修复安全漏洞
+ - 加强输入验证
+ - 优化文件操作安全性
+ - 检查依赖的安全状态
+- **Success Criteria**:
+ - 无安全漏洞
+ - 输入验证完善
+ - 依赖无安全问题
+- **Test Requirements**:
+ - `programmatic` TR-3.1:运行安全扫描工具无严重漏洞
+ - `programmatic` TR-3.2:所有输入都经过验证
+ - `human-judgement` TR-3.3:安全措施到位
+
+### [ ] 任务 4:功能增强
+- **Priority**:P2
+- **Depends On**:任务 1, 任务 3
+- **Description**:
+ - 完善用户界面交互
+ - 增加更多模组平台支持
+ - 优化模板管理功能
+ - 增强多语言支持
+- **Success Criteria**:
+ - 用户界面更友好
+ - 支持更多模组平台
+ - 模板管理更便捷
+ - 多语言支持更完善
+- **Test Requirements**:
+ - `programmatic` TR-4.1:所有新增功能正常工作
+ - `human-judgement` TR-4.2:用户界面美观易用
+ - `human-judgement` TR-4.3:多语言支持准确
+
+### [ ] 任务 5:构建和部署优化
+- **Priority**:P2
+- **Depends On**:任务 1, 任务 2
+- **Description**:
+ - 优化构建流程
+ - 减少构建时间
+ - 优化打包大小
+ - 完善部署文档
+- **Success Criteria**:
+ - 构建流程更高效
+ - 构建时间减少
+ - 打包大小优化
+ - 部署文档完善
+- **Test Requirements**:
+ - `programmatic` TR-5.1:构建时间减少 25%
+ - `programmatic` TR-5.2:打包大小减少 20%
+ - `human-judgement` TR-5.3:部署文档清晰完整
+
+### [ ] 任务 6:测试覆盖度提升
+- **Priority**:P3
+- **Depends On**:任务 1
+- **Description**:
+ - 增加单元测试
+ - 增加集成测试
+ - 提高测试覆盖度
+ - 建立测试自动化流程
+- **Success Criteria**:
+ - 测试覆盖度达到 80% 以上
+ - 关键功能有测试用例
+ - 测试自动化流程建立
+- **Test Requirements**:
+ - `programmatic` TR-6.1:测试覆盖度达到 80% 以上
+ - `programmatic` TR-6.2:所有测试用例通过
+ - `human-judgement` TR-6.3:测试用例设计合理
+
+## 实施步骤
+
+1. 首先进行代码质量检查与优化(任务 1)
+2. 然后进行安全性增强(任务 3)
+3. 接着进行性能优化(任务 2)
+4. 之后进行功能增强(任务 4)
+5. 然后进行构建和部署优化(任务 5)
+6. 最后进行测试覆盖度提升(任务 6)
+
+## 预期成果
+
+通过以上改进,DeEarthX-CE 项目将:
+- 代码质量更高,更易维护
+- 性能更优,响应更快
+- 安全性更强,更可靠
+- 功能更完善,用户体验更好
+- 构建和部署更高效
+- 测试覆盖更全面,质量更有保障
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..0ad25db
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,661 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published
+ by the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..af9b188
--- /dev/null
+++ b/README.md
@@ -0,0 +1,87 @@
+# DeEarthX V3
+
+## 项目概述
+
+DeEarthX V3 是一个 Minecraft 整合包服务端制作工具,帮你快速把客户端整合包转换成可运行的服务端,同时提供模板管理功能。
+
+QQ群:1090666196
+
+## 核心功能
+
+### 整合包支持
+- CurseForge
+- Modrinth
+- MCBBS
+
+### 模组处理
+自动区分客户端和服务端模组,保留服务端需要的,剔除客户端专用的(光影、材质包等)。
+
+### 工作模式
+- **开服模式**:下载服务端和模组加载器,完整生成服务端
+- **上传模式**:只做模组筛选,不下载服务端文件
+
+### 模组加载器
+- Forge
+- NeoForge
+- Fabric
+
+### 版本支持
+支持 1.16.5 到最新版本。
+
+### 模板管理
+- 创建、编辑、删除本地模板
+- 导入/导出模板
+- 模板商店,支持从远程下载模板
+- 智能下载速度测试,选择最快的下载链接
+
+## 技术架构
+
+### 后端
+TypeScript + Node.js,Express 提供 Web 服务,WebSocket 实时通信,使用 Node.js SEA 打包为独立 exe。
+
+### 前端
+Vue 3 + TypeScript,Tauri 2 桌面框架,Ant Design Vue UI 组件,Tailwind CSS 样式。
+
+## 使用流程
+
+1. 准备整合包文件
+2. 选择模式(开服/上传)
+3. 上传文件
+4. 等待处理完成
+5. 下载服务端
+
+## 模板管理流程
+
+1. 进入模板管理页面
+2. 选择本地模板或模板商店
+3. 本地模板:创建、编辑、删除、导出模板
+4. 模板商店:浏览并下载模板
+
+## 项目特色
+
+- 上传即用,无需配置
+- 实时进度显示
+- 内置 BMCLAPI 和 MCIM 镜像源加速下载
+- 支持多语言
+- 智能模板管理系统
+- 模板商店提供丰富的预设模板
+
+> [!WARNING]
+> 模组可能过滤不干净,且制作的服务端禁止用于售卖!
+
+## 安装说明
+
+直接下载安装包安装即可使用。
+
+**注意**:建议不要安装在 C 盘,避免权限问题。
+
+## 系统要求
+
+- 操作系统:Windows
+- 开服模式需要 Java 环境
+- 上传模式不需要 Java
+
+## 开发团队
+
+- **Tianpao**:核心开发
+- **XCC**:功能优化
diff --git a/b2f.js b/b2f.js
new file mode 100644
index 0000000..82b7687
--- /dev/null
+++ b/b2f.js
@@ -0,0 +1,68 @@
+import fs from "node:fs";
+import archiver from "archiver";
+import path from "node:path";
+
+const args = process.argv.slice(2);
+
+if (args.length !== 1) {
+ console.error("使用方法: node b2f.js ");
+ process.exit(1);
+}
+
+switch (args[0]) {
+ case "b2f": //backend to frontend
+ const sourcePath = "./backend/dist/core.exe";
+ const destPath = "./front/src-tauri/binaries/core-x86_64-pc-windows-msvc.exe";
+
+ if (!fs.existsSync(sourcePath)) {
+ console.error(`错误: 源文件不存在: ${sourcePath}`);
+ console.error("请先运行 'npm run backend' 构建后端");
+ process.exit(1);
+ }
+
+ // 确保目标目录存在
+ const destDir = path.dirname(destPath);
+ if (!fs.existsSync(destDir)) {
+ fs.mkdirSync(destDir, { recursive: true });
+ console.log(`创建目录: ${destDir}`);
+ }
+
+ // 复制文件
+ fs.copyFileSync(sourcePath, destPath);
+ console.log(`成功复制: ${sourcePath} -> ${destPath}`);
+ break;
+ case "b2r": //build to root
+ const exePath = "./front/src-tauri/target/release/bundle/nsis/DeEarthX-V3_1.0.0_x64-setup.exe";
+ const rootExePath = "./DeEarthX-V3_x64-setup.exe";
+ const zipPath = "./DeEarthX-V3_x64-setup.zip";
+
+ if (!fs.existsSync(exePath)) {
+ console.error(`错误: 源文件不存在: ${exePath}`);
+ console.error("请先运行 'npm run tauri' 构建前端");
+ process.exit(1);
+ }
+
+ // 移动 exe 到根目录
+ fs.renameSync(exePath, rootExePath);
+ console.log(`移动文件: ${exePath} -> ${rootExePath}`);
+
+ // 打包成 zip
+ const output = fs.createWriteStream(zipPath);
+ const archive = archiver("zip", {
+ zlib: { level: 9 } // 最高压缩级别
+ });
+
+ output.on('close', () => {
+ console.log(`打包完成: ${zipPath} (${archive.pointer()} 字节)`);
+ });
+
+ archive.pipe(output);
+ archive.file(rootExePath, { name: path.basename(rootExePath) });
+ await archive.finalize();
+
+ break;
+ default:
+ console.error(`错误: 未知参数 '${args[0]}'`);
+ console.error("有效参数: b2f, b2r");
+ process.exit(1);
+}
diff --git a/backend/config1.json b/backend/config1.json
new file mode 100644
index 0000000..c02a410
--- /dev/null
+++ b/backend/config1.json
@@ -0,0 +1,14 @@
+{
+ "mirror": {
+ "bmclapi": true,
+ "mcimirror": true
+ },
+ "filter": {
+ "hashes": true,
+ "dexpub": true,
+ "mixins": true
+ },
+ "oaf": true,
+ "port": 37019,
+ "host": "localhost"
+}
\ No newline at end of file
diff --git a/backend/package.json b/backend/package.json
new file mode 100644
index 0000000..35d6a2b
--- /dev/null
+++ b/backend/package.json
@@ -0,0 +1,54 @@
+{
+ "name": "dex-v3-core",
+ "version": "1.0.0",
+ "description": "",
+ "license": "MIT",
+ "author": "Tianpao",
+ "type": "module",
+ "main": "dist/bundle.js",
+ "bin": "dist/bundle.js",
+ "scripts": {
+ "test": "set \"DEBUG=true\"&&tsc&&node dist/main.js",
+ "rollup": "rollup -c rollup.config.js",
+ "sea": "node --experimental-sea-config sea-config.json",
+ "sea:build": "node -e \"require('fs').copyFileSync(process.execPath, './dist/core.exe')\" && npx postject ./dist/core.exe NODE_SEA_BLOB ./dist/sea-prep.blob --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2",
+ "build": "npm run rollup && npm run sea && npm run sea:build"
+ },
+ "devDependencies": {
+ "@rollup/plugin-commonjs": "^28.0.6",
+ "@rollup/plugin-json": "^6.1.0",
+ "@rollup/plugin-node-resolve": "^16.0.1",
+ "@rollup/plugin-terser": "^0.4.4",
+ "@rollup/plugin-typescript": "^12.1.4",
+ "@types/adm-zip": "^0.5.7",
+ "@types/archiver": "^7.0.0",
+ "@types/cors": "^2.8.19",
+ "@types/express": "^5.0.3",
+ "@types/fs-extra": "^11.0.4",
+ "@types/jest": "^30.0.0",
+ "@types/multer": "^2.0.0",
+ "@types/ws": "^8.18.1",
+ "@types/yauzl": "^2.10.3",
+ "jest": "^30.2.0",
+ "postject": "^1.0.0-alpha.6",
+ "rollup": "^4.50.1",
+ "ts-jest": "^29.4.6",
+ "typescript": "^5.9.2"
+ },
+ "dependencies": {
+ "@types/yazl": "^3.3.0",
+ "adm-zip": "^0.5.16",
+ "cors": "^2.8.5",
+ "express": "^5.1.0",
+ "fs-extra": "^11.3.1",
+ "got": "^14.4.8",
+ "multer": "^2.0.2",
+ "p-map": "^7.0.3",
+ "p-retry": "^7.0.0",
+ "picocolors": "^1.1.1",
+ "smol-toml": "^1.6.0",
+ "ws": "^8.18.3",
+ "yauzl": "^3.2.0",
+ "yazl": "^3.3.1"
+ }
+}
diff --git a/backend/rollup.config.js b/backend/rollup.config.js
new file mode 100644
index 0000000..fee42a5
--- /dev/null
+++ b/backend/rollup.config.js
@@ -0,0 +1,45 @@
+import typescript from '@rollup/plugin-typescript'
+import resolve from '@rollup/plugin-node-resolve';
+import commonjs from '@rollup/plugin-commonjs'
+import json from '@rollup/plugin-json';
+import terser from '@rollup/plugin-terser';
+
+export default {
+ input: 'src/main.ts',
+ output: {
+ file: 'dist/bundle.js',
+ format: 'cjs',
+ inlineDynamicImports: true,
+ sourcemap: false
+ },
+ plugins: [
+ typescript({
+ tsconfig: './tsconfig.json',
+ module: 'Node16',
+ compilerOptions: {
+ module: 'Node16'
+ }
+ }),
+ resolve({
+ preferBuiltins: true,
+ browser: false,
+ extensions: ['.ts', '.js', '.json'],
+ dedupe: ['tslib']
+ }),
+ commonjs({
+ transformMixedEsModules: true
+ }),
+ json(),
+ terser({
+ compress: true,
+ mangle: false
+ })
+ ],
+ onwarn: (warning, warn) => {
+ if (warning.code === 'CIRCULAR_DEPENDENCY') return;
+ if (warning.code === 'THIS_IS_UNDEFINED') return;
+ if (warning.code === 'MODULE_LEVEL_DIRECTIVE') return;
+ if (warning.code === 'UNRESOLVED_IMPORT') return;
+ warn(warning);
+ }
+};
diff --git a/backend/sea-config.json b/backend/sea-config.json
new file mode 100644
index 0000000..626cdde
--- /dev/null
+++ b/backend/sea-config.json
@@ -0,0 +1,7 @@
+{
+ "main": "./dist/bundle.js",
+ "output": "./dist/sea-prep.blob",
+ "disableExperimentalSEAWarning": true,
+ "useSnapshot": false,
+ "useCodeCache": true
+}
\ No newline at end of file
diff --git a/backend/src/Dex.ts b/backend/src/Dex.ts
new file mode 100644
index 0000000..7e2f196
--- /dev/null
+++ b/backend/src/Dex.ts
@@ -0,0 +1,365 @@
+import fs from "node:fs";
+import p from "node:path";
+import websocket, { WebSocketServer } from "ws";
+import { pipeline } from "node:stream/promises";
+import { platform, what_platform } from "./platform/index.js";
+import { ModFilterService } from "./dearth/index.js";
+import { dinstall, mlsetup } from "./modloader/index.js";
+import { Config } from "./utils/config.js";
+import { execPromise, getAppDir } from "./utils/utils.js";
+import { MessageWS } from "./utils/ws.js";
+import { logger } from "./utils/logger.js";
+import { yauzl_promise } from "./utils/ziplib.js";
+import yauzl from "yauzl";
+import archiver from "archiver";
+
+export class Dex {
+ wsx!: WebSocketServer;
+ message!: MessageWS;
+
+ constructor(ws: WebSocketServer) {
+ this.wsx = ws;
+ this.wsx.on("connection", (e) => {
+ this.message = new MessageWS(e);
+ });
+ }
+
+ public async Main(buffer: Buffer, dser: boolean, filename?: string, template?: string) {
+ try {
+ const first = Date.now();
+ await this.processModpack(buffer, filename, first, dser, template);
+ } catch (e) {
+ const err = e as Error;
+ logger.error("主流程执行失败", err);
+ this.message.handleError(err);
+ }
+ }
+
+ private async processModpack(buffer: Buffer, filename: string | undefined, startTime: number, isServerMode: boolean, template?: string) {
+ const processedBuffer = await this._processModpack(buffer, filename);
+ const zps = await this._zips(processedBuffer);
+ const { contain, info } = await zps._getinfo();
+
+ if (!contain || !info) {
+ logger.error("整合包信息为空");
+ this.message.handleError(new Error("该整合包似乎不是有效的整合包。"));
+ return;
+ }
+
+ const plat = what_platform(contain);
+ logger.debug("检测到平台", { 平台: plat });
+ logger.debug("整合包信息", info);
+
+ const mpname = info.name;
+ const unpath = p.join(getAppDir(), "instance", mpname);
+
+ await this.parallelTasks(zps, mpname, plat, info, unpath);
+ await this.filterMods(unpath, mpname);
+ await this.installModLoader(plat, info, unpath, isServerMode, template);
+ await this.completeTask(startTime, unpath, mpname, isServerMode);
+ }
+
+ private async parallelTasks(zps: any, mpname: string, plat: string | undefined, info: any, unpath: string) {
+ await Promise.all([
+ zps._unzip(mpname),
+ platform(plat).downloadfile(info, unpath, this.message)
+ ]).catch(e => {
+ logger.error("并行任务执行异常", e);
+ });
+ this.message.statusChange();
+ }
+
+ private async filterMods(unpath: string, mpname: string) {
+ const config = Config.getConfig();
+ await new ModFilterService(p.join(unpath, "mods"), p.join(getAppDir(), ".rubbish", mpname), config.filter, this.message).filter();
+ this.message.statusChange();
+ }
+
+ private async installModLoader(plat: string | undefined, info: any, unpath: string, isServerMode: boolean, template?: string) {
+ const mlinfo = await platform(plat).getinfo(info);
+ if (isServerMode) {
+ await mlsetup(
+ mlinfo.loader,
+ mlinfo.minecraft,
+ mlinfo.loader_version,
+ unpath,
+ this.message,
+ template
+ )
+ } else {
+ dinstall(
+ mlinfo.loader,
+ mlinfo.minecraft,
+ mlinfo.loader_version,
+ unpath
+ );
+ }
+ }
+
+ private async completeTask(startTime: number, unpath: string, mpname: string, isServerMode: boolean) {
+ const config = Config.getConfig();
+ const latest = Date.now();
+ const duration = latest - startTime;
+
+ if (isServerMode) {
+ this.message.serverInstallComplete(unpath, duration);
+ } else {
+ this.message.finish(startTime, latest);
+ }
+
+ if (!isServerMode && config.autoZip) {
+ await this._createZip(unpath, mpname);
+ }
+
+ if (config.oaf) {
+ await execPromise(`start ${p.join(getAppDir(), "instance")}`);
+ }
+
+ logger.info(`任务完成,耗时 ${duration}ms`);
+ }
+
+ private async _processModpack(buffer: Buffer, filename?: string): Promise {
+ if (!filename || !filename.endsWith('.zip')) {
+ logger.debug("文件名无效或非 ZIP 格式,直接返回原始缓冲区", { 文件名: filename });
+ return buffer;
+ }
+
+ const startTime = Date.now();
+ const bufferSize = buffer.length;
+ logger.info("开始处理整合包", { 文件名: filename, 文件大小: `${(bufferSize / 1024 / 1024).toFixed(2)} MB` });
+
+ try {
+ const zip = await (new Promise((resolve, reject) => {
+ yauzl.fromBuffer(buffer, { lazyEntries: true, strictFileNames: true }, (err, zipfile) => {
+ if (err) {
+ logger.error("解析 ZIP 文件失败", { 文件名: filename, 错误: err.message });
+ reject(err);
+ return;
+ }
+ logger.debug("ZIP 文件解析成功", { 文件名: filename });
+ resolve(zipfile);
+ });
+ }));
+
+ logger.info("检测到 PCL 整合包格式,尝试提取 modpack.mrpack 文件");
+
+ return new Promise((resolve, reject) => {
+ let mrpackBuffer: Buffer | null = null;
+ let hasProcessed = false;
+ let entryCount = 0;
+
+ zip.on('entry', (entry: yauzl.Entry) => {
+ entryCount++;
+
+ if (hasProcessed) {
+ zip.readEntry();
+ return;
+ }
+
+ if (entry.fileName === 'modpack.mrpack') {
+ logger.info("找到 modpack.mrpack 文件,开始读取", { 文件大小: `${(entry.uncompressedSize / 1024).toFixed(2)} KB` });
+ hasProcessed = true;
+ zip.openReadStream(entry, (err, stream) => {
+ if (err) {
+ logger.error("打开 modpack.mrpack 读取流失败", { 错误: err.message });
+ zip.close();
+ reject(err);
+ return;
+ }
+
+ const chunks: Buffer[] = [];
+ let bytesRead = 0;
+
+ stream.on('data', (chunk) => {
+ bytesRead += chunk.length;
+ chunks.push(chunk);
+ });
+
+ stream.on('end', () => {
+ mrpackBuffer = Buffer.concat(chunks);
+ const duration = Date.now() - startTime;
+ logger.info("modpack.mrpack 提取成功", {
+ 原始大小: `${(bufferSize / 1024 / 1024).toFixed(2)} MB`,
+ 提取大小: `${(mrpackBuffer.length / 1024).toFixed(2)} KB`,
+ 耗时: `${duration}ms`
+ });
+ zip.close();
+ resolve(mrpackBuffer);
+ });
+
+ stream.on('error', (err) => {
+ logger.error("读取 modpack.mrpack 数据失败", { 错误: err.message });
+ zip.close();
+ reject(err);
+ });
+ });
+ } else {
+ zip.readEntry();
+ }
+ });
+
+ zip.on('end', () => {
+ if (!hasProcessed) {
+ const duration = Date.now() - startTime;
+ logger.warn("未找到 modpack.mrpack 文件,使用原始缓冲区", {
+ 扫描条目数: entryCount,
+ 耗时: `${duration}ms`
+ });
+ zip.close();
+ resolve(buffer);
+ }
+ });
+
+ zip.on('error', (err) => {
+ logger.error("ZIP 文件处理异常", { 错误: err.message });
+ zip.close();
+ reject(err);
+ });
+
+ zip.readEntry();
+ });
+ } catch (e) {
+ const err = e as Error;
+ const duration = Date.now() - startTime;
+ logger.error("处理整合包失败,使用原始缓冲区", {
+ 文件名: filename,
+ 错误: err.message,
+ 耗时: `${duration}ms`
+ });
+ return buffer;
+ }
+ }
+
+ private async _zips(buffer: Buffer) {
+ if (buffer.length === 0) {
+ throw new Error("zip 数据为空");
+ }
+ const zip = await yauzl_promise(buffer);
+ let index = 0;
+ const _getinfo = async () => {
+ const importantFiles = ["manifest.json", "modrinth.index.json"];
+ for await (const entry of zip) {
+ if (importantFiles.includes(entry.fileName)) {
+ const content = await entry.ReadEntry;
+ const info = JSON.parse(content.toString());
+ logger.debug("找到关键文件", { fileName: entry.fileName, info });
+ return { contain: entry.fileName, info };
+ }
+ index++;
+ }
+ throw new Error("整合包中未找到清单文件");
+ }
+ if (index === zip.length) {
+ throw new Error("整合包中未找到清单文件");
+ }
+ const _unzip = async (instancename: string) => {
+ logger.info("开始解压流程", { 实例名称: instancename });
+ const instancePath = p.join(getAppDir(), "instance", instancename);
+ let index = 1;
+ for await (const entry of zip) {
+ const isDir = entry.fileName.endsWith("/");
+ logger.info(`进度: ${index}/${zip.length}, 文件: ${entry.fileName}`);
+
+ if (!entry.fileName.startsWith("overrides/")) {
+ logger.info("跳过非 overrides 文件", entry.fileName);
+ this.message.unzip(entry.fileName, zip.length, index);
+ index++;
+ continue;
+ }
+
+ if (entry.fileName === "overrides/") {
+ logger.info("跳过 overrides 目录", entry.fileName);
+ this.message.unzip(entry.fileName, zip.length, index);
+ index++;
+ continue;
+ }
+
+ if (this._ublack(entry.fileName)) {
+ logger.info("跳过黑名单文件", entry.fileName);
+ this.message.unzip(entry.fileName, zip.length, index);
+ index++;
+ continue;
+ }
+
+ if (isDir) {
+ let targetPath = entry.fileName.replace("overrides/", "");
+ await fs.promises.mkdir(p.join(instancePath, targetPath), {
+ recursive: true,
+ });
+ } else {
+ let targetPath = entry.fileName.replace("overrides/", "");
+
+ const dirPath = p.join(instancePath, targetPath.substring(0, targetPath.lastIndexOf("/")));
+ await fs.promises.mkdir(dirPath, { recursive: true });
+
+ const fullPath = p.join(instancePath, targetPath);
+ if (fs.existsSync(fullPath)) {
+ logger.info("文件已存在,跳过解压", targetPath);
+ } else {
+ const stream = await entry.openReadStream;
+ const write = fs.createWriteStream(fullPath);
+ await pipeline(stream, write);
+ }
+ }
+ this.message.unzip(entry.fileName, zip.length, index);
+ index++;
+ }
+ logger.info("解压流程完成", { 实例名称: instancename, 总文件数: zip.length });
+ }
+ return { _getinfo, _unzip };
+ }
+
+ private _ublack(filename: string): boolean {
+ const blacklist = [
+ "overrides/options.txt",
+ "overrides/shaderpacks",
+ "overrides/essential",
+ "overrides/resourcepacks",
+ "overrides/PCL",
+ "overrides/CustomSkinLoader"
+ ];
+
+ if (filename === "overrides/" || filename === "overrides") {
+ return true;
+ }
+
+ return blacklist.some(item => {
+ const normalizedItem = item.endsWith("/") ? item : item + "/";
+ const normalizedFilename = filename.endsWith("/") ? filename : filename + "/";
+ return normalizedFilename === normalizedItem || normalizedFilename.startsWith(normalizedItem);
+ });
+ }
+
+ private async _createZip(sourcePath: string, mpname: string): Promise {
+ return new Promise((resolve, reject) => {
+ const outputPath = p.join(getAppDir(), "instance", `${mpname}.zip`);
+ const output = fs.createWriteStream(outputPath);
+ const archive = archiver('zip', {
+ zlib: { level: 9 }
+ });
+
+ output.on('close', () => {
+ logger.info(`打包成功: ${outputPath} (${archive.pointer()} 字节)`);
+ this.message.info(`服务端已打包: ${mpname}.zip`);
+ resolve();
+ });
+
+ archive.on('error', (err: Error) => {
+ logger.error('打包失败', err);
+ reject(err);
+ });
+
+ archive.on('warning', (err: NodeJS.ErrnoException) => {
+ if (err.code === 'ENOENT') {
+ logger.warn('打包警告', err);
+ } else {
+ reject(err);
+ }
+ });
+
+ archive.pipe(output);
+ archive.directory(sourcePath, false);
+ archive.finalize();
+ });
+ }
+}
diff --git a/backend/src/core.ts b/backend/src/core.ts
new file mode 100644
index 0000000..7e12eb0
--- /dev/null
+++ b/backend/src/core.ts
@@ -0,0 +1,755 @@
+import express, { Application } from "express";
+import multer from "multer";
+import cors from "cors"
+import websocket, { WebSocketServer } from "ws"
+import { createServer, Server } from "node:http";
+import { Config, IConfig } from "./utils/config.js";
+import { Dex } from "./Dex.js";
+import { logger } from "./utils/logger.js";
+import { checkJava, JavaCheckResult, detectJavaPaths } from "./utils/utils.js";
+import { Galaxy } from "./galaxy.js";
+import fs from "node:fs";
+
+export class Core {
+ private config: IConfig;
+ private readonly app: Application;
+ private readonly server: Server;
+ public ws!: WebSocketServer;
+ private wsx!: websocket;
+ private readonly upload: multer.Multer;
+ dex: Dex;
+ galaxy: Galaxy;
+
+ constructor(config: IConfig) {
+ this.config = config
+ this.app = express();
+ this.server = createServer(this.app);
+ this.ws = new WebSocketServer({ server: this.server })
+ this.ws.on("connection",(e)=>{
+ this.wsx = e
+ })
+ this.dex = new Dex(this.ws)
+ this.galaxy = new Galaxy()
+ const storage = multer.memoryStorage();
+ this.upload = multer({
+ storage: storage,
+ limits: {
+ fileSize: 2 * 1024 * 1024 * 1024,
+ files: 10
+ }
+ });
+ }
+
+ private async javachecker() {
+ try {
+ const result: JavaCheckResult = await checkJava();
+
+ if (result.exists && result.version) {
+ logger.info(`检测到 Java: ${result.version.fullVersion} (${result.version.vendor})`);
+
+ if (this.wsx) {
+ this.wsx.send(JSON.stringify({
+ type: "info",
+ message: `检测到 Java: ${result.version.fullVersion} (${result.version.vendor})`,
+ data: result.version
+ }));
+ }
+ } else {
+ logger.error("Java 检查失败", result.error);
+
+ if (this.wsx) {
+ this.wsx.send(JSON.stringify({
+ type: "error",
+ message: result.error || "未找到 Java 或版本检查失败",
+ data: result
+ }));
+ }
+ }
+ } catch (error) {
+ logger.error("Java 检查异常", error as Error);
+
+ if (this.wsx) {
+ this.wsx.send(JSON.stringify({
+ type: "error",
+ message: "Java 检查遇到异常"
+ }));
+ }
+ }
+ }
+
+ private setupExpressRoutes() {
+ this.setupMiddleware();
+ this.setupHealthRoutes();
+ this.setupTaskRoutes();
+ this.setupConfigRoutes();
+ this.setupModCheckRoutes();
+ this.setupGalaxyRoutes();
+ this.setupJavaRoutes();
+ this.setupTemplateRoutes();
+ }
+
+ private setupMiddleware() {
+ this.app.use(cors());
+ this.app.use(express.json({ limit: '2gb' }));
+ this.app.use(express.urlencoded({ extended: true, limit: '2gb' }));
+
+ // 全局错误处理中间件
+ this.app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
+ logger.error("全局错误捕获", err);
+ res.status(err.status || 500).json({
+ status: err.status || 500,
+ message: err.message || "服务器内部错误",
+ stack: process.env.NODE_ENV === 'development' ? err.stack : undefined
+ });
+ });
+ }
+
+ private setupHealthRoutes() {
+ // 健康检查路由(ping 接口)
+ this.app.get('/', (req, res) => {
+ const pingTime = new Date().toISOString();
+ logger.debug("收到 Ping 请求", { time: pingTime, ip: req.ip });
+ res.json({
+ status: 200,
+ by: "DeEarthX.Core",
+ qqg: "559349662",
+ bilibili: "https://space.bilibili.com/1728953419 ",
+ ping: pingTime
+ });
+ });
+
+ // 版本信息路由
+ this.app.get('/version', (req, res) => {
+ logger.debug("请求版本信息", { ip: req.ip });
+ res.json({
+ status: 200,
+ version: "1.0.0",
+ name: "DeEarthX.Core",
+ buildTime: new Date().toISOString()
+ });
+ });
+ }
+
+ private setupTaskRoutes() {
+ // 启动任务路由
+ this.app.post("/start", this.upload.single("file"), (req, res) => {
+ try {
+ if (!req.file) {
+ return res.status(400).json({ status: 400, message: "未上传文件" });
+ }
+ if (!req.query.mode) {
+ return res.status(400).json({ status: 400, message: "缺少 mode 参数" });
+ }
+
+ // 文件类型检查
+ const allowedExtensions = ['.zip', '.mrpack'];
+ const fileExtension = req.file.originalname.toLowerCase().substring(req.file.originalname.lastIndexOf('.'));
+ if (!allowedExtensions.includes(fileExtension)) {
+ return res.status(400).json({ status: 400, message: "只支持 .zip 和 .mrpack 文件" });
+ }
+
+ const isServerMode = req.query.mode === "server";
+ const template = req.query.template as string || "";
+ logger.info("正在启动任务", { 是否服务端模式: isServerMode, 文件名: req.file.originalname, 文件大小: req.file.size, 模板: template || "官方模组加载器" });
+
+ // 非阻塞执行主要任务
+ this.dex.Main(req.file.buffer, isServerMode, req.file.originalname, template).catch(err => {
+ logger.error("任务执行失败", err);
+ });
+
+ res.json({ status: 200, message: "任务已提交,正在处理中" });
+ } catch (err) {
+ const error = err as Error;
+ logger.error("/start 路由错误", error);
+ res.status(500).json({ status: 500, message: "服务器内部错误" });
+ }
+ });
+ }
+
+ private setupConfigRoutes() {
+ // 获取配置路由
+ this.app.get('/config/get', (req, res) => {
+ try {
+ this.config = Config.getConfig();
+ res.json(this.config);
+ } catch (err) {
+ const error = err as Error;
+ logger.error("/config/get 路由错误", error);
+ res.status(500).json({ status: 500, message: "获取配置失败" });
+ }
+ });
+
+ // 更新配置路由
+ this.app.post('/config/post', (req, res) => {
+ try {
+ Config.writeConfig(req.body);
+ this.config = req.body;
+ Config.clearCache();
+ logger.info("配置已更新");
+ res.json({ status: 200 });
+ } catch (err) {
+ const error = err as Error;
+ logger.error("/config/post 路由错误", error);
+ res.status(500).json({ status: 500, message: "更新配置失败" });
+ }
+ });
+ }
+
+ private setupModCheckRoutes() {
+ // 模组检查路由 - 通过路径检查
+ this.app.get('/modcheck', async (req, res) => {
+ try {
+ const modsPath = req.query.path as string;
+ if (!modsPath) {
+ return res.status(400).json({ status: 400, message: "缺少 path 参数" });
+ }
+
+ const { ModCheckService } = await import('./dearth/index.js');
+ const checkService = new ModCheckService(modsPath);
+ const results = await checkService.checkMods();
+
+ res.json(results);
+ } catch (err) {
+ const error = err as Error;
+ logger.error("/modcheck 路由错误", error);
+ res.status(500).json({ status: 500, message: "模组检查失败" });
+ }
+ });
+
+
+
+ // 模组检查路由 - 通过文件夹路径和整合包名字检查
+ this.app.post('/modcheck/folder', async (req, res) => {
+ try {
+ const { folderPath, bundleName } = req.body;
+
+ if (!folderPath) {
+ logger.warn("请求中缺少文件夹路径");
+ return res.status(400).json({ status: 400, message: "缺少文件夹路径" });
+ }
+
+ if (!bundleName || !bundleName.trim()) {
+ logger.warn("请求中缺少整合包名字");
+ return res.status(400).json({ status: 400, message: "缺少整合包名字" });
+ }
+
+ logger.info("收到模组检查文件夹请求", {
+ folderPath,
+ bundleName: bundleName.trim()
+ });
+
+ const { ModCheckService } = await import('./dearth/index.js');
+ const checkService = new ModCheckService(folderPath);
+ const results = await checkService.checkModsWithBundle(bundleName.trim());
+
+ logger.info("模组检查完成", { resultsCount: results.length });
+ res.json(results);
+ } catch (err) {
+ const error = err as Error;
+ logger.error("/modcheck/folder 路由错误", error);
+ res.status(500).json({ status: 500, message: "模组检查失败: " + error.message });
+ }
+ });
+ }
+
+ private setupGalaxyRoutes() {
+ this.app.use("/galaxy", this.galaxy.getRouter());
+ }
+
+ private setupJavaRoutes() {
+ // 检查Java版本
+ this.app.get('/java/check', async (req, res) => {
+ try {
+ const javaPath = req.query.path as string;
+ const result: JavaCheckResult = await checkJava(javaPath);
+
+ res.json({
+ status: 200,
+ data: result
+ });
+ } catch (err) {
+ const error = err as Error;
+ logger.error("/java/check 路由错误", error);
+ res.status(500).json({ status: 500, message: "Java检查失败" });
+ }
+ });
+
+ // 自动检测Java路径
+ this.app.get('/java/detect', async (req, res) => {
+ try {
+ const paths = await detectJavaPaths();
+
+ res.json({
+ status: 200,
+ data: paths
+ });
+ } catch (err) {
+ const error = err as Error;
+ logger.error("/java/detect 路由错误", error);
+ res.status(500).json({ status: 500, message: "Java路径检测失败" });
+ }
+ });
+ }
+
+ private setupTemplateRoutes() {
+ // 获取模板列表
+ this.app.get('/templates', async (req, res) => {
+ try {
+ const templateModule = await import('./template/index.js');
+ const TemplateManager = (templateModule as any).TemplateManager;
+ const templateManager = new TemplateManager();
+ const templates = await templateManager.getTemplates();
+
+ res.json({
+ status: 200,
+ data: templates
+ });
+ } catch (err) {
+ const error = err as Error;
+ logger.error("/templates 路由错误", error);
+ res.status(500).json({ status: 500, message: "获取模板列表失败" });
+ }
+ });
+
+ // 创建模板
+ this.app.post('/templates', async (req, res) => {
+ try {
+ const { name, version, description, author } = req.body;
+
+ if (!name) {
+ res.status(400).json({ status: 400, message: "模板名称不能为空" });
+ return;
+ }
+
+ const templateModule = await import('./template/index.js');
+ const TemplateManager = (templateModule as any).TemplateManager;
+ const templateManager = new TemplateManager();
+
+ const templateId = `template-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
+
+ await templateManager.createTemplate(templateId, {
+ name,
+ version: version || '1.0.0',
+ description: description || '',
+ author: author || '',
+ created: new Date().toISOString().split("T")[0],
+ type: 'template'
+ });
+
+ res.json({
+ status: 200,
+ message: "模板创建成功",
+ data: { id: templateId }
+ });
+ } catch (err) {
+ const error = err as Error;
+ logger.error("/templates POST 路由错误", error);
+ res.status(500).json({ status: 500, message: "创建模板失败" });
+ }
+ });
+
+ // 删除模板
+ this.app.delete('/templates/:id', async (req, res) => {
+ try {
+ const { id } = req.params;
+
+ const templateModule = await import('./template/index.js');
+ const TemplateService = (templateModule as any).TemplateService;
+ const templateService = new TemplateService();
+
+ const success = await templateService.deleteTemplate(id);
+
+ if (success) {
+ res.json({
+ status: 200,
+ message: "模板删除成功"
+ });
+ } else {
+ res.status(404).json({ status: 404, message: "模板不存在" });
+ }
+ } catch (err) {
+ const error = err as Error;
+ logger.error(`/templates/${req.params.id} DELETE 路由错误`, error);
+ res.status(500).json({ status: 500, message: "删除模板失败" });
+ }
+ });
+
+ // 修改模板信息
+ this.app.put('/templates/:id', async (req, res) => {
+ try {
+ const { id } = req.params;
+ const { name, version, description, author } = req.body;
+
+ if (!name) {
+ res.status(400).json({ status: 400, message: "模板名称不能为空" });
+ return;
+ }
+
+ const templateModule = await import('./template/index.js');
+ const TemplateManager = (templateModule as any).TemplateManager;
+ const templateManager = new TemplateManager();
+
+ await templateManager.updateTemplate(id, {
+ name,
+ version: version || '1.0.0',
+ description: description || '',
+ author: author || '',
+ type: 'template'
+ });
+
+ res.json({
+ status: 200,
+ message: "模板更新成功"
+ });
+ } catch (err) {
+ const error = err as Error;
+ logger.error(`/templates/${req.params.id} PUT 路由错误`, error);
+ res.status(500).json({ status: 500, message: "更新模板失败" });
+ }
+ });
+
+ // 打开模板文件夹
+ this.app.get('/templates/:id/path', async (req, res) => {
+ try {
+ const { id } = req.params;
+ const path = await import('path');
+ const { exec } = await import('child_process');
+ const templateModule = await import('./template/index.js');
+ const TemplateManager = (templateModule as any).TemplateManager;
+
+ const templateManager = new TemplateManager();
+ const templatesPath = (templateManager as any).templatesPath;
+ const templatePath = path.resolve(templatesPath, id);
+
+ const platform = process.platform;
+ let command: string;
+
+ if (platform === 'win32') {
+ command = `explorer "${templatePath}"`;
+ } else if (platform === 'darwin') {
+ command = `open "${templatePath}"`;
+ } else {
+ command = `xdg-open "${templatePath}"`;
+ }
+
+ exec(command, (error) => {
+ res.json({
+ status: 200,
+ message: "文件夹已打开"
+ });
+ });
+ } catch (err) {
+ const error = err as Error;
+ logger.error(`/templates/${req.params.id}/path 路由错误`, error);
+ res.status(500).json({ status: 500, message: "打开文件夹失败" });
+ }
+ });
+
+ // 导出模板
+ this.app.get('/templates/:id/export', async (req, res) => {
+ try {
+ const { id } = req.params;
+ const templateModule = await import('./template/index.js');
+ const TemplateManager = (templateModule as any).TemplateManager;
+ const templateManager = new TemplateManager();
+
+ // 生成临时文件路径
+ const os = await import('os');
+ const path = await import('path');
+ const tempDir = os.tmpdir();
+ const outputPath = path.join(tempDir, `template-${id}.zip`);
+
+ // 导出模板
+ await templateManager.exportTemplate(id, outputPath);
+
+ // 发送文件
+ res.download(outputPath, `template-${id}.zip`, (err) => {
+ // 下载完成后删除临时文件
+ fs.unlink(outputPath, () => {});
+ if (err) {
+ logger.error(`导出模板失败: ${err.message}`);
+ res.status(500).json({ status: 500, message: "导出模板失败" });
+ }
+ });
+ } catch (err) {
+ const error = err as Error;
+ logger.error(`/templates/${req.params.id}/export 路由错误`, error);
+ res.status(500).json({ status: 500, message: "导出模板失败" });
+ }
+ });
+
+ // 导入模板
+ this.app.post('/templates/import', this.upload.single('file'), async (req, res) => {
+ try {
+ if (!req.file) {
+ return res.status(400).json({ status: 400, message: "未上传文件" });
+ }
+
+ // 文件类型检查
+ const fileExtension = req.file.originalname.toLowerCase().substring(req.file.originalname.lastIndexOf('.'));
+ if (fileExtension !== '.zip') {
+ return res.status(400).json({ status: 400, message: "只支持 .zip 文件" });
+ }
+
+ const templateModule = await import('./template/index.js');
+ const TemplateManager = (templateModule as any).TemplateManager;
+ const templateManager = new TemplateManager();
+
+ // 导入模板
+ const templateId = await templateManager.importTemplate(req.file.buffer);
+
+ res.json({
+ status: 200,
+ message: "模板导入成功",
+ data: { id: templateId }
+ });
+ } catch (err) {
+ const error = err as Error;
+ logger.error("/templates/import 路由错误", error);
+ res.status(500).json({ status: 500, message: "导入模板失败" });
+ }
+ });
+
+ // 存储SSE连接
+ const sseConnections = new Map();
+
+ // 存储下载状态
+ const downloadStates = new Map();
+
+ // 从URL安装模板 - POST请求启动下载
+ this.app.post('/templates/install-from-url', async (req, res) => {
+ try {
+ const { url, requestId, resumeFrom = 0 } = req.body;
+
+ if (!url) {
+ return res.status(400).json({ status: 400, message: "缺少 url 参数" });
+ }
+
+ // 下载文件并流式处理
+ const { default: got } = await import('got');
+ const { createWriteStream, readFileSync, statSync, unlinkSync } = await import('fs');
+ const { tmpdir } = await import('os');
+ const { join } = await import('path');
+
+ // 创建临时文件
+ const tempFilePath = join(tmpdir(), `template-${Date.now()}.zip`);
+ const writeStream = createWriteStream(tempFilePath, {
+ flags: resumeFrom > 0 ? 'a' : 'w' // 支持断点续传
+ });
+
+ // 构建请求选项
+ const requestOptions = {
+ headers: {} as Record
+ };
+
+ // 如果是续传,设置Range头
+ if (resumeFrom > 0) {
+ requestOptions.headers['Range'] = `bytes=${resumeFrom}-`;
+ }
+
+ // 流式下载(支持分块)
+ const request = await got.stream(url, requestOptions);
+
+ let totalSize = 0;
+ let downloadedSize = resumeFrom;
+
+ // 获取文件大小(如果可用)
+ request.on('response', (response) => {
+ // 检查是否支持分块下载
+ const acceptRanges = response.headers['accept-ranges'];
+ console.log(`服务器支持分块下载: ${acceptRanges}`);
+
+ // 获取文件大小
+ let contentLength = response.headers['content-length'];
+ if (!contentLength) {
+ // 如果没有content-length,尝试从content-range获取
+ const contentRange = response.headers['content-range'];
+ if (contentRange) {
+ const matches = contentRange.match(/bytes \d+-\d+\/(\d+)/);
+ if (matches && matches[1]) {
+ contentLength = matches[1];
+ }
+ }
+ }
+
+ if (contentLength) {
+ totalSize = parseInt(contentLength);
+ // 发送初始化信息,包含文件大小
+ if (sseConnections.has(requestId)) {
+ const sseRes = sseConnections.get(requestId);
+ sseRes.write(`data: ${JSON.stringify({
+ type: 'init',
+ totalSize,
+ resumeFrom
+ })}\n\n`);
+ }
+ }
+ });
+
+ // 监听数据传输,计算进度
+ request.on('data', (chunk) => {
+ downloadedSize += chunk.length;
+ if (totalSize > 0) {
+ const progress = Math.round((downloadedSize / totalSize) * 100);
+ // 向后端日志输出进度
+ console.log(`下载进度: ${progress}%`);
+ // 发送进度信息到SSE连接
+ if (sseConnections.has(requestId)) {
+ const sseRes = sseConnections.get(requestId);
+ sseRes.write(`data: ${JSON.stringify({
+ type: 'progress',
+ progress,
+ downloadedSize,
+ totalSize
+ })}\n\n`);
+ }
+ } else {
+ // 无法计算总大小时,发送假进度
+ const progress = Math.min(90, Math.round((downloadedSize / 1024 / 1024) * 10));
+ if (sseConnections.has(requestId)) {
+ const sseRes = sseConnections.get(requestId);
+ sseRes.write(`data: ${JSON.stringify({
+ type: 'progress',
+ progress,
+ downloadedSize
+ })}\n\n`);
+ }
+ }
+ });
+
+ // 管道到临时文件
+ await new Promise((resolve, reject) => {
+ request.pipe(writeStream)
+ .on('finish', resolve)
+ .on('error', reject);
+ });
+
+ // 读取临时文件
+ const buffer = readFileSync(tempFilePath);
+
+ // 清理临时文件
+ unlinkSync(tempFilePath);
+
+ // 导入模板
+ const templateModule = await import('./template/index.js');
+ const TemplateManager = (templateModule as any).TemplateManager;
+ const templateManager = new TemplateManager();
+
+ const templateId = await templateManager.importTemplate(buffer);
+
+ // 发送完成响应到SSE连接
+ if (sseConnections.has(requestId)) {
+ const sseRes = sseConnections.get(requestId);
+ sseRes.write(`data: ${JSON.stringify({
+ type: 'complete',
+ status: 200,
+ message: "模板安装成功",
+ data: { id: templateId }
+ })}\n\n`);
+ sseRes.end();
+ sseConnections.delete(requestId);
+ }
+
+ // 清理下载状态
+ downloadStates.delete(requestId);
+
+ // 发送POST响应
+ res.json({
+ status: 200,
+ message: "模板安装成功",
+ data: { id: templateId }
+ });
+ } catch (err) {
+ const error = err as Error;
+ const { requestId } = req.body;
+ logger.error("/templates/install-from-url 路由错误", error);
+
+ // 发送错误信息到SSE连接
+ if (sseConnections.has(requestId)) {
+ const sseRes = sseConnections.get(requestId);
+ sseRes.write(`data: ${JSON.stringify({
+ type: 'error',
+ status: 500,
+ message: "安装模板失败"
+ })}\n\n`);
+ sseRes.end();
+ sseConnections.delete(requestId);
+ }
+
+ // 清理下载状态
+ downloadStates.delete(requestId);
+
+ res.status(500).json({ status: 500, message: "安装模板失败" });
+ }
+ });
+
+ // SSE连接 - GET请求
+ this.app.get('/templates/install-from-url', (req, res) => {
+ const { requestId } = req.query;
+
+ if (!requestId) {
+ return res.status(400).json({ status: 400, message: "缺少 requestId 参数" });
+ }
+
+ // 设置SSE响应头
+ res.setHeader('Content-Type', 'text/event-stream');
+ res.setHeader('Cache-Control', 'no-cache');
+ res.setHeader('Connection', 'keep-alive');
+ res.setHeader('Access-Control-Allow-Origin', '*');
+
+ // 存储连接
+ sseConnections.set(requestId, res);
+
+ // 发送初始信息
+ res.write(`data: ${JSON.stringify({ type: 'init' })}\n\n`);
+
+ // 处理连接关闭
+ req.on('close', () => {
+ sseConnections.delete(requestId);
+ console.log(`SSE连接已关闭: ${requestId}`);
+ });
+ });
+
+ // 获取模板商店数据
+ this.app.get('/templates/store', async (req, res) => {
+ try {
+ const { default: got } = await import('got');
+
+ // 从指定URL获取模板商店数据
+ const response = await got('http://dex.xcclyc.cn/template/template_stor.json');
+ const data = JSON.parse(response.body);
+
+ // 确保返回的数据结构符合前端预期
+ if (!data.templates) {
+ return res.json({
+ status: 200,
+ data: { templates: [] }
+ });
+ }
+
+ res.json({
+ status: 200,
+ data: data
+ });
+ } catch (err) {
+ const error = err as Error;
+ logger.error("/templates/store 路由错误", error);
+ res.status(500).json({ status: 500, message: "获取模板商店数据失败" });
+ }
+ });
+ }
+ public async start() {
+
+ this.setupExpressRoutes();
+ const port = this.config.port || 37019;
+ const host = this.config.host || 'localhost';
+ this.server.listen(port, host, async () => {
+ logger.info(`服务器正在运行于 http://${host}:${port}`);
+ await this.javachecker();
+ });
+
+ this.server.on('error', (err) => {
+ logger.error("服务器错误", err);
+ });
+ }
+}
\ No newline at end of file
diff --git a/backend/src/dearth/ModCheckService.ts b/backend/src/dearth/ModCheckService.ts
new file mode 100644
index 0000000..6ace7f5
--- /dev/null
+++ b/backend/src/dearth/ModCheckService.ts
@@ -0,0 +1,571 @@
+import { FileExtractor } from "./utils/FileExtractor.js";
+import { HashFilter } from "./strategies/HashFilter.js";
+import { MixinFilter } from "./strategies/MixinFilter.js";
+import { DexpubFilter } from "./strategies/DexpubFilter.js";
+import { ModrinthFilter } from "./strategies/ModrinthFilter.js";
+import { IModCheckResult, IModCheckConfig, IFileInfo, ModSide } from "./types.js";
+import { JarParser } from "../utils/jar-parser.js";
+import { logger } from "../utils/logger.js";
+import * as fs from "fs";
+import * as path from "path";
+import crypto from "node:crypto";
+
+const DEFAULT_CONFIG: IModCheckConfig = {
+ enableDexpub: true,
+ enableModrinth: true,
+ enableMixin: true,
+ enableHash: true,
+ timeout: 30000,
+};
+
+export class ModCheckService {
+ private readonly extractor: FileExtractor;
+ private readonly config: IModCheckConfig;
+
+ constructor(modsDir: string, config?: Partial) {
+ this.extractor = new FileExtractor(modsDir);
+ this.config = { ...DEFAULT_CONFIG, ...config };
+ }
+
+ async checkMods(): Promise {
+ logger.info("开始模组检查流程");
+ const files = await this.extractor.extractFilesInfo();
+ const results: IModCheckResult[] = [];
+
+ for (const file of files) {
+ const result = await this.checkSingleFile(file);
+ results.push(result);
+ }
+
+ logger.info("模组检查流程完成", { 总模组数: results.length });
+ return results;
+ }
+
+ async checkModsWithBundle(bundleName: string): Promise {
+ logger.info("开始模组检查流程(带整合包)", { bundleName });
+ const files = await this.extractor.extractFilesInfo();
+ const results: IModCheckResult[] = [];
+
+ const clientMods = await this.identifyClientSideMods(files);
+
+ for (const file of files) {
+ const filename = file.filename;
+ const isClient = clientMods.includes(filename);
+
+ results.push({
+ filename: path.basename(filename),
+ filePath: filename,
+ clientSide: isClient ? 'required' : 'unknown',
+ serverSide: isClient ? 'unsupported' : 'unknown',
+ source: isClient ? 'Multiple' : 'none',
+ checked: isClient,
+ allResults: isClient ? [{
+ source: 'Multiple',
+ clientSide: 'required',
+ serverSide: 'unsupported',
+ checked: true
+ }] : []
+ });
+ }
+
+ if (clientMods.length > 0) {
+ await this.moveClientMods(clientMods, bundleName);
+ logger.info(`已移动 ${clientMods.length} 个客户端模组到 .rubbish/${bundleName}`);
+ }
+
+ logger.info("模组检查流程完成", { 总模组数: results.length, 客户端模组数: clientMods.length });
+ return results;
+ }
+
+ private async identifyClientSideMods(files: IFileInfo[]): Promise {
+ const clientMods: string[] = [];
+ const processedFiles = new Set();
+
+ if (this.config.enableDexpub) {
+ logger.info("开始 Galaxy Square (dexpub) 检查客户端模组");
+ const dexpubStrategy = new DexpubFilter();
+ const dexpubMods = await dexpubStrategy.filter(files);
+ const serverModsListSet = new Set(await dexpubStrategy.getServerMods(files));
+
+ dexpubMods.forEach(mod => processedFiles.add(mod));
+ serverModsListSet.forEach(mod => processedFiles.add(mod));
+ clientMods.push(...dexpubMods);
+ }
+
+ if (this.config.enableModrinth) {
+ logger.info("开始 Modrinth API 检查客户端模组");
+
+ let serverModsSet = new Set();
+ if (this.config.enableDexpub) {
+ const dexpubStrategy = new DexpubFilter();
+ serverModsSet = new Set(await dexpubStrategy.getServerMods(files));
+ }
+
+ const unprocessedFiles = files.filter(f => !processedFiles.has(f.filename));
+ const modrinthMods = await new ModrinthFilter().filter(unprocessedFiles);
+
+ modrinthMods.forEach(mod => processedFiles.add(mod));
+ clientMods.push(...modrinthMods);
+ }
+
+ if (this.config.enableMixin) {
+ logger.info("开始 Mixin 检查客户端模组");
+
+ const unprocessedFiles = files.filter(f => !processedFiles.has(f.filename));
+ const mixinMods = await new MixinFilter().filter(unprocessedFiles);
+
+ mixinMods.forEach(mod => processedFiles.add(mod));
+ clientMods.push(...mixinMods);
+ }
+
+ if (this.config.enableHash) {
+ logger.info("开始 Hash 检查客户端模组");
+
+ const unprocessedFiles = files.filter(f => !processedFiles.has(f.filename));
+ const hashMods = await new HashFilter().filter(unprocessedFiles);
+
+ clientMods.push(...hashMods);
+ }
+
+ const uniqueMods = [...new Set(clientMods)];
+ logger.info("识别到客户端模组", { 数量: uniqueMods.length });
+
+ return uniqueMods;
+ }
+
+ private async moveClientMods(clientModFilePaths: string[], bundleName: string): Promise {
+ const rubbishDir = path.join('.rubbish', bundleName);
+
+ try {
+ await fs.promises.mkdir(rubbishDir, { recursive: true });
+ logger.info(`创建目录: ${rubbishDir}`);
+ } catch (error: any) {
+ logger.error(`创建目录失败: ${rubbishDir}`, error);
+ throw error;
+ }
+
+ for (const filePath of clientModFilePaths) {
+ const filename = path.basename(filePath);
+ const destPath = path.join(rubbishDir, filename);
+
+ try {
+ await fs.promises.rename(filePath, destPath);
+ logger.debug(`移动模组: ${filename} -> ${destPath}`);
+ } catch (error: any) {
+ logger.error(`移动模组失败: ${filename}`, error);
+ }
+ }
+ }
+
+ async checkUploadedFiles(uploadedFiles: Array<{ originalname: string; buffer: Buffer }>): Promise {
+ logger.info("开始检查上传文件", { 文件数量: uploadedFiles.length });
+ const results: IModCheckResult[] = [];
+
+ for (const uploadedFile of uploadedFiles) {
+ try {
+ const fileData = uploadedFile.buffer;
+ const mixins = await JarParser.extractMixins(fileData);
+ const infos = await JarParser.extractModInfo(fileData);
+
+ const fileInfo: IFileInfo = {
+ filename: uploadedFile.originalname,
+ hash: crypto.createHash('sha1').update(fileData).digest('hex'),
+ mixins,
+ infos,
+ fileData,
+ };
+
+ const result = await this.checkSingleFile(fileInfo);
+ results.push(result);
+ } catch (error: any) {
+ logger.error("处理上传文件时出错", { 文件名: uploadedFile.originalname, 错误: error.message });
+ results.push({
+ filename: uploadedFile.originalname,
+ filePath: uploadedFile.originalname,
+ clientSide: "unknown",
+ serverSide: "unknown",
+ source: "none",
+ checked: false,
+ errors: [error.message],
+ allResults: [],
+ });
+ }
+ }
+
+ logger.info("上传文件模组检查完成", { 总模组数: results.length });
+ return results;
+ }
+
+ async checkSingleMod(filePath: string): Promise {
+ const filename = path.basename(filePath);
+ const hash = await this.calculateHash(filePath);
+ const extractor = new FileExtractor(path.dirname(filePath));
+ const files = await extractor.extractFilesInfo();
+ const fileInfo = files.find(f => f.filename === filename);
+
+ if (!fileInfo) {
+ return {
+ filename,
+ filePath,
+ clientSide: "unknown",
+ serverSide: "unknown",
+ source: "none",
+ checked: false,
+ errors: ["文件未找到或无法提取"],
+ allResults: [],
+ };
+ }
+
+ return this.checkSingleFile(fileInfo);
+ }
+
+ private async checkSingleFile(file: IFileInfo): Promise {
+ const result: IModCheckResult = {
+ filename: file.filename,
+ filePath: file.filename,
+ clientSide: "unknown",
+ serverSide: "unknown",
+ source: "none",
+ checked: false,
+ errors: [],
+ allResults: [],
+ };
+
+ const allResults = await this.collectAllResultsParallel(file);
+ result.allResults = allResults;
+
+ const bestResult = this.mergeResults(allResults);
+
+ result.clientSide = bestResult.clientSide;
+ result.serverSide = bestResult.serverSide;
+ result.source = bestResult.source;
+ result.checked = bestResult.checked;
+ result.errors = bestResult.errors;
+
+ const modInfo = await this.extractModInfoDetails(file);
+ if (modInfo) {
+ result.modId = modInfo.id;
+ result.iconUrl = modInfo.iconUrl;
+ result.description = modInfo.description;
+ result.author = modInfo.author;
+ }
+
+ return result;
+ }
+
+ private async collectAllResultsParallel(file: IFileInfo): Promise> {
+ const checkPromises: Promise<{
+ clientSide: ModSide;
+ serverSide: ModSide;
+ source: string;
+ checked: boolean;
+ error?: string;
+ }>[] = [];
+
+ if (this.config.enableDexpub) {
+ checkPromises.push(this.runCheckWithTimeout(this.checkDexpub, file, "Dexpub"));
+ }
+
+ if (this.config.enableModrinth) {
+ checkPromises.push(this.runCheckWithTimeout(this.checkModrinth, file, "Modrinth"));
+ }
+
+ if (this.config.enableMixin) {
+ checkPromises.push(this.runCheckWithTimeout(this.checkMixin, file, "Mixin"));
+ }
+
+ if (this.config.enableHash) {
+ checkPromises.push(this.runCheckWithTimeout(this.checkHash, file, "Hash"));
+ }
+
+ return Promise.all(checkPromises);
+ }
+
+ private async runCheckWithTimeout(
+ checkFn: (file: IFileInfo) => Promise<{ clientSide: ModSide; serverSide: ModSide } | null>,
+ file: IFileInfo,
+ source: string
+ ): Promise<{
+ clientSide: ModSide;
+ serverSide: ModSide;
+ source: string;
+ checked: boolean;
+ error?: string;
+ }> {
+ return this.runWithTimeout(
+ checkFn(file),
+ `${source} 检查超时: ${file.filename}`
+ ).then(result => {
+ if (result) {
+ return {
+ clientSide: result.clientSide,
+ serverSide: result.serverSide,
+ source,
+ checked: true,
+ };
+ }
+ return {
+ clientSide: "unknown" as ModSide,
+ serverSide: "unknown" as ModSide,
+ source,
+ checked: false,
+ };
+ }).catch((error: any) => {
+ logger.warn(`${file.filename} 的 ${source} 检查失败`, { 错误: error.message });
+ return {
+ clientSide: "unknown" as ModSide,
+ serverSide: "unknown" as ModSide,
+ source,
+ checked: false,
+ error: error.message,
+ };
+ });
+ }
+
+ private mergeResults(results: Array<{
+ clientSide: ModSide;
+ serverSide: ModSide;
+ source: string;
+ checked: boolean;
+ error?: string;
+ }>): {
+ clientSide: ModSide;
+ serverSide: ModSide;
+ source: string;
+ checked: boolean;
+ errors: string[];
+ } {
+ const errors: string[] = [];
+ const successfulResults = results.filter(r => r.checked);
+
+ for (const r of results) {
+ if (r.error) {
+ errors.push(`${r.source}: ${r.error}`);
+ }
+ }
+
+ if (successfulResults.length === 0) {
+ return {
+ clientSide: "unknown",
+ serverSide: "unknown",
+ source: "none",
+ checked: false,
+ errors,
+ };
+ }
+
+ const priority: { [key: string]: number } = {
+ "Dexpub": 1,
+ "Modrinth": 2,
+ "Mixin": 3,
+ "Hash": 4,
+ };
+
+ successfulResults.sort((a, b) => priority[a.source] - priority[b.source]);
+ const best = successfulResults[0];
+
+ return {
+ clientSide: best.clientSide,
+ serverSide: best.serverSide,
+ source: best.source,
+ checked: true,
+ errors,
+ };
+ }
+
+ private async checkDexpub(file: IFileInfo): Promise<{ clientSide: ModSide; serverSide: ModSide } | null> {
+ const strategy = new DexpubFilter();
+ const files = [file];
+
+ const clientMods = await strategy.filter(files);
+ const serverMods = await strategy.getServerMods(files);
+ const filename = path.basename(file.filename);
+
+ if (clientMods.some(f => path.basename(f) === filename)) {
+ return { clientSide: "required", serverSide: "unsupported" };
+ } else if (serverMods.some(f => path.basename(f) === filename)) {
+ return { clientSide: "unsupported", serverSide: "required" };
+ }
+
+ return null;
+ }
+
+ private async checkModrinth(file: IFileInfo): Promise<{ clientSide: ModSide; serverSide: ModSide } | null> {
+ const strategy = new ModrinthFilter();
+ const files = [file];
+ const clientMods = await strategy.filter(files);
+ const filename = path.basename(file.filename);
+
+ if (clientMods.some(f => path.basename(f) === filename)) {
+ return { clientSide: "required", serverSide: "unsupported" };
+ }
+
+ for (const info of file.infos) {
+ if (info.name === "modrinth.index.json" || info.name === "modrinth.json") {
+ try {
+ const data = JSON.parse(info.data);
+ const clientSide = this.mapClientSide(data.client_side);
+ const serverSide = this.mapServerSide(data.server_side);
+ return { clientSide, serverSide };
+ } catch {
+ continue;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ private async checkMixin(file: IFileInfo): Promise<{ clientSide: ModSide; serverSide: ModSide } | null> {
+ for (const mixin of file.mixins) {
+ try {
+ const config = JSON.parse(mixin.data);
+ if (!config.mixins?.length && config.client?.length > 0 && !file.filename.includes("lib")) {
+ return { clientSide: "required", serverSide: "unsupported" };
+ }
+ } catch {
+ continue;
+ }
+ }
+ return null;
+ }
+
+ private async checkHash(file: IFileInfo): Promise<{ clientSide: ModSide; serverSide: ModSide } | null> {
+ const strategy = new HashFilter();
+ const files = [file];
+ const clientMods = await strategy.filter(files);
+ const filename = path.basename(file.filename);
+
+ if (clientMods.some(f => path.basename(f) === filename)) {
+ return { clientSide: "required", serverSide: "unsupported" };
+ }
+
+ return null;
+ }
+
+ private mapClientSide(value: string | undefined): ModSide {
+ if (value === "required") return "required";
+ if (value === "optional") return "optional";
+ if (value === "unsupported") return "unsupported";
+ return "unknown";
+ }
+
+ private mapServerSide(value: string | undefined): ModSide {
+ if (value === "required") return "required";
+ if (value === "optional") return "optional";
+ if (value === "unsupported") return "unsupported";
+ return "unknown";
+ }
+
+ private async runWithTimeout(promise: Promise, timeoutMessage: string): Promise {
+ let timeoutId: NodeJS.Timeout;
+
+ const timeoutPromise = new Promise((_, reject) => {
+ timeoutId = setTimeout(() => {
+ reject(new Error(timeoutMessage));
+ }, this.config.timeout);
+ });
+
+ try {
+ const result = await Promise.race([promise, timeoutPromise]);
+ clearTimeout(timeoutId!);
+ return result;
+ } catch (error) {
+ clearTimeout(timeoutId!);
+ throw error;
+ }
+ }
+
+ private async calculateHash(filePath: string): Promise {
+ const fileData = fs.readFileSync(filePath);
+ return crypto.createHash('sha1').update(fileData).digest('hex');
+ }
+
+ private async extractModInfoDetails(file: IFileInfo): Promise<{
+ id?: string;
+ iconUrl?: string;
+ description?: string;
+ author?: string;
+ } | null> {
+ for (const info of file.infos) {
+ try {
+ if (info.name.endsWith("mods.toml") || info.name.endsWith("neoforge.mods.toml")) {
+ const { default: toml } = await import("smol-toml");
+ const data = toml.parse(info.data) as any;
+
+ if (data.mods && Array.isArray(data.mods) && data.mods.length > 0) {
+ const mod = data.mods[0] as any;
+ let iconUrl: string | undefined;
+
+ if (mod.logoFile) {
+ iconUrl = await this.extractIconFile(file, mod.logoFile);
+ }
+
+ return {
+ id: mod.modId || mod.modid,
+ iconUrl,
+ description: mod.description,
+ author: mod.authors || mod.author,
+ };
+ }
+ } else if (info.name.endsWith("fabric.mod.json")) {
+ const data = JSON.parse(info.data);
+
+ return {
+ id: data.id,
+ iconUrl: data.icon,
+ description: data.description,
+ author: data.authors?.join(", ") || data.author,
+ };
+ } else if (info.name === "modrinth.index.json" || info.name === "modrinth.json") {
+ const data = JSON.parse(info.data);
+
+ return {
+ id: data.project_id || data.id,
+ description: data.summary || data.description,
+ };
+ }
+ } catch (error: any) {
+ logger.debug(`解析 ${info.name} 失败:`, error.message);
+ continue;
+ }
+ }
+
+ return null;
+ }
+
+ private async extractIconFile(file: IFileInfo, iconPath: string): Promise {
+ try {
+ let jarData: Buffer;
+
+ if (file.fileData) {
+ jarData = file.fileData;
+ } else {
+ jarData = fs.readFileSync(file.filename);
+ }
+
+ const { Azip } = await import("../utils/ziplib.js");
+ const zipEntries = Azip(jarData);
+
+ for (const entry of zipEntries) {
+ if (entry.entryName === iconPath || entry.entryName.endsWith(iconPath)) {
+ const data = await entry.getData();
+ const ext = iconPath.split('.').pop()?.toLowerCase();
+ const mimeType = ext === 'png' ? 'png' : 'jpeg';
+
+ return `data:image/${mimeType};base64,${data.toString('base64')}`;
+ }
+ }
+ } catch (error: any) {
+ logger.debug(`提取图标文件 ${iconPath} 失败:`, error.message);
+ }
+
+ return undefined;
+ }
+}
diff --git a/backend/src/dearth/ModFilterService.ts b/backend/src/dearth/ModFilterService.ts
new file mode 100644
index 0000000..fd0d84c
--- /dev/null
+++ b/backend/src/dearth/ModFilterService.ts
@@ -0,0 +1,134 @@
+import { FileExtractor } from "./utils/FileExtractor.js";
+import { FileOperator } from "./utils/FileOperator.js";
+import { HashFilter } from "./strategies/HashFilter.js";
+import { MixinFilter } from "./strategies/MixinFilter.js";
+import { DexpubFilter } from "./strategies/DexpubFilter.js";
+import { ModrinthFilter } from "./strategies/ModrinthFilter.js";
+import { IFilterConfig } from "./types.js";
+import { logger } from "../utils/logger.js";
+import { MessageWS } from "../utils/ws.js";
+import path from "node:path";
+
+export class ModFilterService {
+ private readonly extractor: FileExtractor;
+ private readonly operator: FileOperator;
+ private readonly config: IFilterConfig;
+ private messageWS?: MessageWS;
+
+ constructor(modsPath: string, movePath: string, config: IFilterConfig, messageWS?: MessageWS) {
+ this.extractor = new FileExtractor(modsPath);
+ this.operator = new FileOperator(movePath);
+ this.config = config;
+ this.messageWS = messageWS;
+ }
+
+ async filter(): Promise {
+ logger.info("开始模组筛选流程");
+ const startTime = Date.now();
+
+ try {
+ const files = await this.extractor.extractFilesInfo();
+
+ if (this.messageWS) {
+ this.messageWS.filterModsStart(files.length);
+ }
+
+ const clientMods = await this.identifyClientSideMods(files);
+ const result = await this.operator.moveClientSideMods(clientMods);
+
+ const duration = Date.now() - startTime;
+
+ if (this.messageWS) {
+ this.messageWS.filterModsComplete(clientMods.length, result.success, duration);
+ }
+
+ logger.info("模组筛选流程完成", {
+ 识别到的客户端模组: clientMods.length,
+ 成功移动: result.success,
+ 跳过: result.skipped,
+ 失败: result.error
+ });
+ } catch (error) {
+ if (this.messageWS) {
+ this.messageWS.filterModsError(error instanceof Error ? error.message : String(error));
+ }
+ throw error;
+ }
+ }
+
+ private async identifyClientSideMods(files: Array<{ filename: string; hash: string; mixins: any[]; infos: any[] }>): Promise {
+ const clientMods: string[] = [];
+ const processedFiles = new Set();
+
+ if (this.config.dexpub) {
+ logger.info("开始 Galaxy Square (dexpub) 检查客户端模组");
+ const dexpubStrategy = new DexpubFilter();
+ const dexpubMods = await dexpubStrategy.filter(files);
+ const serverModsListSet = new Set(await dexpubStrategy.getServerMods(files));
+
+ dexpubMods.forEach(mod => processedFiles.add(mod));
+ serverModsListSet.forEach(mod => processedFiles.add(mod));
+ clientMods.push(...dexpubMods);
+
+ if (this.messageWS) {
+ this.messageWS.filterModsProgress(processedFiles.size, files.length, "Galaxy Square (dexpub) 检查");
+ }
+ }
+
+ if (this.config.modrinth) {
+ logger.info("开始 Modrinth API 检查客户端模组");
+
+ let serverModsSet = new Set();
+ if (this.config.dexpub) {
+ const dexpubStrategy = new DexpubFilter();
+ serverModsSet = new Set(await dexpubStrategy.getServerMods(files));
+ }
+
+ const unprocessedFiles = files.filter(f => !processedFiles.has(f.filename));
+ const modrinthMods = await new ModrinthFilter().filter(unprocessedFiles);
+
+ modrinthMods.forEach(mod => processedFiles.add(mod));
+ clientMods.push(...modrinthMods);
+
+ if (this.messageWS) {
+ this.messageWS.filterModsProgress(processedFiles.size, files.length, "Modrinth API 检查");
+ }
+ }
+
+ if (this.config.mixins) {
+ logger.info("开始 Mixin 检查客户端模组");
+
+ const unprocessedFiles = files.filter(f => !processedFiles.has(f.filename));
+ const mixinMods = await new MixinFilter().filter(unprocessedFiles);
+
+ mixinMods.forEach(mod => processedFiles.add(mod));
+ clientMods.push(...mixinMods);
+
+ if (this.messageWS) {
+ this.messageWS.filterModsProgress(processedFiles.size, files.length, "Mixin 检查");
+ }
+ }
+
+ if (this.config.hashes) {
+ logger.info("开始 Hash 检查客户端模组");
+
+ const unprocessedFiles = files.filter(f => !processedFiles.has(f.filename));
+ const hashMods = await new HashFilter().filter(unprocessedFiles);
+
+ clientMods.push(...hashMods);
+
+ if (this.messageWS) {
+ this.messageWS.filterModsProgress(processedFiles.size, files.length, "Hash 检查");
+ }
+ }
+
+ const uniqueMods = [...new Set(clientMods)];
+ logger.info("识别到客户端模组", { 数量: uniqueMods.length, 模组: uniqueMods });
+
+ if (uniqueMods.length > 0) {
+ logger.debug("第一个模组路径", { 原始路径: uniqueMods[0], 绝对路径: path.resolve(uniqueMods[0]), cwd: process.cwd() });
+ }
+
+ return uniqueMods;
+ }
+}
diff --git a/backend/src/dearth/index.ts b/backend/src/dearth/index.ts
new file mode 100644
index 0000000..7270d5f
--- /dev/null
+++ b/backend/src/dearth/index.ts
@@ -0,0 +1,25 @@
+export { ModFilterService } from "./ModFilterService.js";
+export { FileExtractor } from "./utils/FileExtractor.js";
+export { FileOperator } from "./utils/FileOperator.js";
+export { ModCheckService } from "./ModCheckService.js";
+
+export type {
+ IFileInfo,
+ IInfoFile,
+ IMixinFile,
+ IHashResponse,
+ IProjectInfo,
+ IDexpubCheckResult,
+ IFilterStrategy,
+ IFilterConfig,
+ IModCheckResult,
+ IModCheckConfig,
+ ModSide
+} from "./types.js";
+
+export {
+ HashFilter,
+ MixinFilter,
+ DexpubFilter,
+ ModrinthFilter
+} from "./strategies/index.js";
diff --git a/backend/src/dearth/strategies/DexpubFilter.ts b/backend/src/dearth/strategies/DexpubFilter.ts
new file mode 100644
index 0000000..1863244
--- /dev/null
+++ b/backend/src/dearth/strategies/DexpubFilter.ts
@@ -0,0 +1,80 @@
+import got, { Got } from "got";
+import { logger } from "../../utils/logger.js";
+import { IFilterStrategy, IFileInfo, IDexpubCheckResult } from "../types.js";
+
+export class DexpubFilter implements IFilterStrategy {
+ name = "DexpubFilter";
+ private got: Got;
+
+ constructor() {
+ this.got = got.extend({
+ prefixUrl: "https://galaxy.tianpao.top/",
+ headers: {
+ "User-Agent": "DeEarthX",
+ },
+ responseType: "json",
+ });
+ }
+
+ async filter(files: IFileInfo[]): Promise {
+ const result = await this.checkDexpubForClientMods(files);
+ logger.info("Galaxy Square 检查完成", { 服务端模组: result.serverMods, 客户端模组: result.clientMods });
+ return result.clientMods;
+ }
+
+ private async checkDexpubForClientMods(files: IFileInfo[]): Promise {
+ const clientMods: string[] = [];
+ const serverMods: string[] = [];
+ const modIds: string[] = [];
+ const map: Map = new Map();
+
+ try {
+ for (const file of files) {
+ for (const info of file.infos) {
+ try {
+ const config = JSON.parse(info.data);
+ const keys = Object.keys(config);
+
+ if (keys.includes("id")) {
+ modIds.push(config.id);
+ map.set(config.id, file.filename);
+ } else if (keys.includes("mods")) {
+ modIds.push(config.mods[0].modId);
+ map.set(config.mods[0].modId, file.filename);
+ }
+ } catch (error: any) {
+ logger.error("检查模组信息文件失败,文件名: " + file.filename, error);
+ }
+ }
+ }
+
+ const modIdToIsTypeMod = await this.got.post(`api/mod/check`, {
+ json: {
+ modids: modIds,
+ }
+ }).json<{ [modId: string]: boolean }>();
+
+ const modIdToIsTypeModKeys = Object.keys(modIdToIsTypeMod);
+
+ for (const modId of modIdToIsTypeModKeys) {
+ const mapData = map.get(modId);
+ if (!mapData) continue;
+
+ if (modIdToIsTypeMod[modId]) {
+ clientMods.push(mapData);
+ } else {
+ serverMods.push(mapData);
+ }
+ }
+ } catch (error: any) {
+ logger.error("Dexpub 检查失败", error);
+ }
+
+ return { serverMods, clientMods };
+ }
+
+ async getServerMods(files: IFileInfo[]): Promise {
+ const result = await this.checkDexpubForClientMods(files);
+ return result.serverMods;
+ }
+}
diff --git a/backend/src/dearth/strategies/HashFilter.ts b/backend/src/dearth/strategies/HashFilter.ts
new file mode 100644
index 0000000..162f34c
--- /dev/null
+++ b/backend/src/dearth/strategies/HashFilter.ts
@@ -0,0 +1,53 @@
+import got from "got";
+import { Utils } from "../../utils/utils.js";
+import { logger } from "../../utils/logger.js";
+import { IFilterStrategy, IFileInfo, IHashResponse, IProjectInfo } from "../types.js";
+
+export class HashFilter implements IFilterStrategy {
+ name = "HashFilter";
+ private utils: Utils;
+
+ constructor() {
+ this.utils = new Utils();
+ }
+
+ async filter(files: IFileInfo[]): Promise {
+ const hashToFilename = new Map();
+ const hashes = files.map(file => {
+ hashToFilename.set(file.hash, file.filename);
+ return file.hash;
+ });
+
+ logger.debug("Checking mod hashes with Modrinth API", { fileCount: files.length });
+
+ try {
+ const fileInfoResponse = await got.post(`${this.utils.modrinth_url}/v2/version_files`, {
+ headers: { "User-Agent": "DeEarth", "Content-Type": "application/json" },
+ json: { hashes, algorithm: "sha1" }
+ }).json();
+
+ const projectIdToFilename = new Map();
+ const projectIds = Object.entries(fileInfoResponse)
+ .map(([hash, info]) => {
+ const filename = hashToFilename.get(hash);
+ if (filename) projectIdToFilename.set(info.project_id, filename);
+ return info.project_id;
+ });
+
+ const projectsResponse = await got.get(`${this.utils.modrinth_url}/v2/projects?ids=${JSON.stringify(projectIds)}`, {
+ headers: { "User-Agent": "DeEarth" }
+ }).json();
+
+ const clientMods = projectsResponse
+ .filter(p => p.client_side === "required" && p.server_side === "unsupported")
+ .map(p => projectIdToFilename.get(p.id))
+ .filter(Boolean) as string[];
+
+ logger.debug("Hash check completed", { count: clientMods.length });
+ return clientMods;
+ } catch (error: any) {
+ logger.error("Hash check failed", error);
+ return [];
+ }
+ }
+}
diff --git a/backend/src/dearth/strategies/MixinFilter.ts b/backend/src/dearth/strategies/MixinFilter.ts
new file mode 100644
index 0000000..39a6ab6
--- /dev/null
+++ b/backend/src/dearth/strategies/MixinFilter.ts
@@ -0,0 +1,27 @@
+import { logger } from "../../utils/logger.js";
+import { IFilterStrategy, IFileInfo } from "../types.js";
+
+export class MixinFilter implements IFilterStrategy {
+ name = "MixinFilter";
+
+ async filter(files: IFileInfo[]): Promise {
+ const clientMods: string[] = [];
+
+ for (const file of files) {
+ for (const mixin of file.mixins) {
+ try {
+ const config = JSON.parse(mixin.data);
+ if (!config.mixins?.length && config.client?.length > 0 && !file.filename.includes("lib")) {
+ clientMods.push(file.filename);
+ break;
+ }
+ } catch (error: any) {
+ logger.warn("Failed to parse mixin config", { filename: file.filename, mixin: mixin.name, error: error.message });
+ }
+ }
+ }
+
+ logger.debug("Mixins check completed", { count: clientMods.length });
+ return [...new Set(clientMods)];
+ }
+}
diff --git a/backend/src/dearth/strategies/ModrinthFilter.ts b/backend/src/dearth/strategies/ModrinthFilter.ts
new file mode 100644
index 0000000..89de528
--- /dev/null
+++ b/backend/src/dearth/strategies/ModrinthFilter.ts
@@ -0,0 +1,107 @@
+import { IFilterStrategy, IFileInfo } from "../types.js";
+import { logger } from "../../utils/logger.js";
+
+interface IModrinthProject {
+ client_side: string;
+ server_side: string;
+ project_type: string;
+ categories: string[];
+}
+
+export class ModrinthFilter implements IFilterStrategy {
+ name = "ModrinthFilter";
+ private readonly API_BASE = "https://api.modrinth.com/v2";
+
+ private extractProjectId(infos: { name: string; data: string }[]): string | null {
+ for (const info of infos) {
+ if (info.name === "modrinth.index.json" || info.name === "modrinth.json") {
+ try {
+ const data = JSON.parse(info.data);
+ return data.project_id || null;
+ } catch {
+ continue;
+ }
+ }
+ }
+ return null;
+ }
+
+ private async fetchProjectInfo(projectIds: string[]): Promise