dsh-modpack-kit 0.2.3 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +91 -23
- package/annotate/index.mjs +62 -0
- package/annotate/manifest.json +18 -0
- package/client.js +2366 -185
- package/community/README.md +34 -0
- package/community/index.mjs +29 -0
- package/community/manifest.json +22 -0
- package/docs/ANNOTATIONS.md +60 -0
- package/docs/CODE-MAP.md +441 -242
- package/docs/DETAIL.md +30 -114
- package/docs/MARKET.txt +19 -0
- package/index.js +1008 -15
- package/lib/annotate.mjs +172 -0
- package/lib/classify.mjs +11 -0
- package/lib/community.mjs +77 -0
- package/lib/compat.mjs +11 -0
- package/lib/github.mjs +300 -0
- package/lib/groups.mjs +12 -0
- package/lib/http.mjs +10 -0
- package/lib/install.mjs +12 -0
- package/lib/manifest.mjs +12 -0
- package/lib/market-catalog.mjs +12 -0
- package/lib/modpack-catalog.mjs +39 -1
- package/lib/net.mjs +11 -0
- package/lib/pack.mjs +12 -0
- package/lib/plugin-graph.mjs +461 -0
- package/lib/plugin-manager.mjs +557 -0
- package/lib/profile.mjs +12 -0
- package/lib/registry.mjs +12 -0
- package/lib/repack.mjs +68 -0
- package/lib/scan.mjs +12 -0
- package/lib/semver.mjs +10 -0
- package/lib/store.mjs +40 -0
- package/lib/subplugins.mjs +141 -0
- package/lib/tar.mjs +10 -0
- package/lib/testmode.mjs +102 -0
- package/lib/theme.mjs +186 -0
- package/lib/yamlish.mjs +11 -0
- package/lib/zip.mjs +12 -0
- package/locale/en.json +1 -1
- package/locale/zh.json +2 -2
- package/package.json +5 -2
- package/plugin-tree/index.mjs +74 -0
- package/plugin-tree/manifest.json +23 -0
package/index.js
CHANGED
|
@@ -1,3 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file index.js
|
|
3
|
+
* @role 宿主半边:注册所有 /dsh-modpack-kit/api/* 路由、跑打包/安装/重装任务队列、给悬浮窗供数据、挂载三个附属小插件的路由表
|
|
4
|
+
* @sub 打包、安装、插件管理、社区资源、代码标注、插件树、任务队列、悬浮窗数据
|
|
5
|
+
* @exports api:route / api:createJob / api:publicJob / api:pruneJobs / api:mountSubRoutes / api:subRoute
|
|
6
|
+
* @reads profile(.dsh/profiles/<名字>)、插件自己的 config.json 与 packs/、各附属小插件的 manifest.json
|
|
7
|
+
* @writes 只写插件自己的状态目录与整合包文件;装插件、改启用态一律交给 lib/install.mjs 与 lib/plugin-manager.mjs
|
|
8
|
+
* @risk 路由名与 client.js 里的 api() 调用必须一一对应,改一个不改另一个就是 404;任务队列的状态机(running/paused/done/failed/cancelled)被悬浮窗与测试同时盯着
|
|
9
|
+
* @touch 改路由要同步 client.js、test/host-smoke.mjs、dev/tools/verify.cjs 的路由清单与 docs/CODE-MAP.md;改任务字段要同步 publicJob 与客户端的 JobDock
|
|
10
|
+
* @since 0.3.0
|
|
11
|
+
*/
|
|
12
|
+
|
|
1
13
|
/**
|
|
2
14
|
* dsh-modpack-kit —— Host 侧。
|
|
3
15
|
*
|
|
@@ -9,26 +21,53 @@
|
|
|
9
21
|
*/
|
|
10
22
|
import fs from 'node:fs'
|
|
11
23
|
import path from 'node:path'
|
|
24
|
+
import { fileURLToPath } from 'node:url'
|
|
25
|
+
import { spawn } from 'node:child_process'
|
|
12
26
|
import { randomBytes, createHash } from 'node:crypto'
|
|
13
27
|
import { loadConfig, saveConfig, pathsFor, profileName, readHistory, appendHistory, clearHistory, removeHistory, appendLog, ensureDir, slugify, DEFAULT_CONFIG } from './lib/store.mjs'
|
|
14
|
-
import { listInstalled, dshVersion, readProfilePackage, readBundles } from './lib/profile.mjs'
|
|
28
|
+
import { listInstalled, dshVersion, readProfilePackage, readBundles, runDshPlugin } from './lib/profile.mjs'
|
|
15
29
|
import { downloadPackage, npmMetadata, pickVersion, fetchLimited, relativeTime, probeRegistry } from './lib/registry.mjs'
|
|
16
30
|
import { buildPack, PackRefused } from './lib/pack.mjs'
|
|
17
|
-
import { inspectPackBuffer, installPack, readPackFromUrl
|
|
31
|
+
import { inspectPackBuffer, installPack, readPackFromUrl } from './lib/install.mjs'
|
|
18
32
|
import { checkCompatibility } from './lib/compat.mjs'
|
|
19
33
|
import { readMarketGroups, groupViews } from './lib/groups.mjs'
|
|
20
34
|
import { classifyPlugin } from './lib/classify.mjs'
|
|
21
35
|
import { groupFindings } from './lib/scan.mjs'
|
|
22
36
|
import { catalogSummary, searchCatalog, syncCatalog, categoryMapFor, lookupPlugins } from './lib/market-catalog.mjs'
|
|
23
|
-
import { marketSummary, searchMarket, syncMarket, findMarketPack, fetchMarketPack } from './lib/modpack-catalog.mjs'
|
|
37
|
+
import { CATEGORY_FALLBACK, marketSummary, searchMarket, syncMarket, findMarketPack, fetchMarketPack } from './lib/modpack-catalog.mjs'
|
|
38
|
+
import { resolveCommunity } from './lib/community.mjs'
|
|
39
|
+
import { findSubplugin, subEnabled, listSubplugins } from './lib/subplugins.mjs'
|
|
40
|
+
import { listManaged, setPluginEnabled, reinstallPlugin, resolveReinstallVersion, revealPluginDir, isValidPluginName, isValidVersion, pluginIcon, updatableItems, updatePlugins } from './lib/plugin-manager.mjs'
|
|
41
|
+
import { whoAmI, openPackPullRequest, entryFileName, packFileName, ensureRelease, uploadReleaseAsset } from './lib/github.mjs'
|
|
42
|
+
import { themeActive, themeOf, themeVars, themeOptions } from './lib/theme.mjs'
|
|
24
43
|
import { parseYaml } from './lib/yamlish.mjs'
|
|
25
44
|
import { readPatch } from './lib/profile.mjs'
|
|
26
45
|
import { buildReadme } from './lib/manifest.mjs'
|
|
27
|
-
import {
|
|
46
|
+
import { rewritePackManifest } from './lib/repack.mjs'
|
|
47
|
+
import { testModeOn, playTestJob, testNote, testStepsFor } from './lib/testmode.mjs'
|
|
48
|
+
import { sendJson as json, readRawBody, readJsonBody, MAX_DROP_BODY } from './lib/http.mjs'
|
|
28
49
|
|
|
29
50
|
const VERSION = (() => {
|
|
30
51
|
try { return JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version || '0.0.0' } catch { return '0.0.0' }
|
|
31
52
|
})()
|
|
53
|
+
// 插件自己的根目录:附属小插件读源码标注、读清单都从这里出发(不许由请求决定)
|
|
54
|
+
const ROOT = path.dirname(fileURLToPath(import.meta.url))
|
|
55
|
+
// 这份代码是什么时候被加载进进程的:客户端用「磁盘文件比它新」来判断要不要提示重启。
|
|
56
|
+
const LOADED_AT = Date.now()
|
|
57
|
+
// 只看自己这层的入口文件,够用来判断「磁盘上有人改过、但这一份还是旧的」
|
|
58
|
+
const RUNTIME_FILES = ['index.js', 'client.js', 'lib/subplugins.mjs', 'lib/theme.mjs', 'community/index.mjs', 'annotate/index.mjs', 'plugin-tree/index.mjs']
|
|
59
|
+
|
|
60
|
+
function runtimeFreshness() {
|
|
61
|
+
let newest = 0
|
|
62
|
+
let newestFile = ''
|
|
63
|
+
for (const rel of RUNTIME_FILES) {
|
|
64
|
+
try {
|
|
65
|
+
const st = fs.statSync(path.join(ROOT, rel))
|
|
66
|
+
if (st.mtimeMs > newest) { newest = st.mtimeMs; newestFile = rel }
|
|
67
|
+
} catch {}
|
|
68
|
+
}
|
|
69
|
+
return { loadedAt: LOADED_AT, newestMtime: Math.round(newest), newestFile, stale: newest > LOADED_AT + 1500 }
|
|
70
|
+
}
|
|
32
71
|
const PENDING_TTL = 30 * 60 * 1000
|
|
33
72
|
const PENDING_MAX = 4
|
|
34
73
|
const PENDING_BYTES = 512 * 1024 * 1024
|
|
@@ -86,6 +125,18 @@ export default {
|
|
|
86
125
|
electron: process.versions.electron || '',
|
|
87
126
|
dshVersion: version,
|
|
88
127
|
pluginVersion: VERSION,
|
|
128
|
+
// 测试模式:界面据此在顶部挂一个橙色标记,免得有人以为真装了东西
|
|
129
|
+
testMode: testModeOn(config),
|
|
130
|
+
// 配色:id + 两个实色 + 算好的 CSS 变量,界面直接挂到 :root 上。
|
|
131
|
+
// native(跟宿主黑白)时 vars 是空的,界面据此什么都不注入。
|
|
132
|
+
theme: (() => {
|
|
133
|
+
const theme = themeOf(config)
|
|
134
|
+
// 界面风格选「经典(改版前)」时干脆不给变量:客户端就算漏判也注入不了颜色
|
|
135
|
+
return { ...theme, vars: config.uiStyle === 'classic' ? {} : themeVars(theme), themed: themeActive(theme, config.uiStyle) }
|
|
136
|
+
})(),
|
|
137
|
+
themePresets: themeOptions(),
|
|
138
|
+
// 界面风格:classic = 改版前的界面(客户端据此不注入配色、设置页回平铺列表)
|
|
139
|
+
uiStyle: config.uiStyle === 'classic' ? 'classic' : 'new',
|
|
89
140
|
profile: profileName(config),
|
|
90
141
|
paths: pathsFor(config),
|
|
91
142
|
catalog,
|
|
@@ -93,6 +144,18 @@ export default {
|
|
|
93
144
|
modpackMarket: (() => {
|
|
94
145
|
try { return marketSummary(config) } catch { return { present: false, stale: true, count: 0, categories: [], repo: '' } }
|
|
95
146
|
})(),
|
|
147
|
+
// 附属小插件:mode=builtin 表示用插件内置实现;profile 里装了声明兼容的外部实现时是 external
|
|
148
|
+
community: (() => {
|
|
149
|
+
try { return resolveCommunity(dir, config) } catch { return null }
|
|
150
|
+
})(),
|
|
151
|
+
// 附属小插件清单:本插件下面挂着谁、各自几个接口、是内置还是外部实现、开没开
|
|
152
|
+
subplugins: (() => {
|
|
153
|
+
try { return listSubplugins(ROOT, dir, config) } catch { return [] }
|
|
154
|
+
})(),
|
|
155
|
+
// 磁盘上的文件是不是比运行中的这份新:界面据此提示「重启 DSH 才生效」
|
|
156
|
+
runtime: (() => {
|
|
157
|
+
try { return runtimeFreshness() } catch { return null }
|
|
158
|
+
})(),
|
|
96
159
|
placements: {
|
|
97
160
|
settings: config.showInSettings !== false,
|
|
98
161
|
sidebar: config.showInSidebar !== false,
|
|
@@ -179,6 +242,76 @@ export default {
|
|
|
179
242
|
return false
|
|
180
243
|
}
|
|
181
244
|
|
|
245
|
+
// 社区资源是「整合包」的附属小插件:关掉它的时候,那几条接口统一回 404
|
|
246
|
+
// (不是 405/500),界面据此提示「去设置里打开」,主体照常。
|
|
247
|
+
// 附属小插件统一走这里:谁被关掉,谁的接口就统一回 404(不是 405/500),
|
|
248
|
+
// 界面据此提示「去设置 → 附属小插件里打开」,主体照常跑。
|
|
249
|
+
// 名字里的括注(「社区资源(整合包的附属小插件)」)是给人看的全名,报错里只留短名。
|
|
250
|
+
const subLabel = (manifest) => {
|
|
251
|
+
const raw = String((manifest && (manifest.label || manifest.name)) || '这个附属小插件')
|
|
252
|
+
return raw.replace(/([^)]*)/gu, '').replace(/\([^)]*\)/gu, '').trim() || '这个附属小插件'
|
|
253
|
+
}
|
|
254
|
+
const subRoute = (id, pathname, handler) => route(pathname, async (req, res) => {
|
|
255
|
+
let manifest = null
|
|
256
|
+
try { manifest = findSubplugin(ROOT, id) } catch { manifest = null }
|
|
257
|
+
if (manifest && !subEnabled(manifest, config)) {
|
|
258
|
+
json(res, 404, { ok: false, error: subLabel(manifest) + '已关闭(附属小插件没启用):在设置 → 附属小插件里打开' })
|
|
259
|
+
return
|
|
260
|
+
}
|
|
261
|
+
await handler(req, res)
|
|
262
|
+
})
|
|
263
|
+
|
|
264
|
+
const communityRoute = (pathname, handler) => subRoute('dsh-modpack-community', pathname, handler)
|
|
265
|
+
|
|
266
|
+
// 代码标注、插件树这两个附属小插件自己带接口表;宿主只负责鉴权、方法校验与 JSON 包装。
|
|
267
|
+
// 它们的实现按需加载:启动时只读各自的 manifest(几百字节)来登记路由,
|
|
268
|
+
// 第一次真的有人调接口时才 import(插件树那条会顺带拉进 lib/plugin-graph.mjs)。
|
|
269
|
+
const subEngines = new Map()
|
|
270
|
+
const subTable = (id) => {
|
|
271
|
+
if (!subEngines.has(id)) {
|
|
272
|
+
const builders = {
|
|
273
|
+
'dsh-modpack-annotate': () => import('./annotate/index.mjs').then((mod) => mod.annotateRoutes({ root: ROOT })),
|
|
274
|
+
'dsh-modpack-plugin-tree': () => import('./plugin-tree/index.mjs').then((mod) => mod.treeRoutes({ root: ROOT, context: () => ({ profileDir: profileDir(), config }) })),
|
|
275
|
+
}
|
|
276
|
+
const build = builders[id]
|
|
277
|
+
if (!build) return null
|
|
278
|
+
const promise = build().catch((error) => {
|
|
279
|
+
subEngines.delete(id)
|
|
280
|
+
throw error
|
|
281
|
+
})
|
|
282
|
+
subEngines.set(id, promise)
|
|
283
|
+
}
|
|
284
|
+
return subEngines.get(id)
|
|
285
|
+
}
|
|
286
|
+
const mountLazySub = (id) => {
|
|
287
|
+
const manifest = (() => { try { return findSubplugin(ROOT, id) } catch { return null } })()
|
|
288
|
+
const listed = manifest && Array.isArray(manifest.routes) ? manifest.routes : []
|
|
289
|
+
for (const fullPath of listed) {
|
|
290
|
+
route(fullPath, async (req, res) => {
|
|
291
|
+
const now = (() => { try { return findSubplugin(ROOT, id) } catch { return null } })()
|
|
292
|
+
if (now && !subEnabled(now, config)) {
|
|
293
|
+
json(res, 404, { ok: false, error: subLabel(now) + '已关闭(附属小插件没启用):在设置 → 附属小插件里打开' })
|
|
294
|
+
return
|
|
295
|
+
}
|
|
296
|
+
const table = await subTable(id)
|
|
297
|
+
const item = (table || []).find((one) => one.path === fullPath || '/dsh-modpack-kit/api' + one.path === fullPath)
|
|
298
|
+
if (!item) {
|
|
299
|
+
json(res, 404, { ok: false, error: '这个附属小插件没有登记这条接口:' + fullPath })
|
|
300
|
+
return
|
|
301
|
+
}
|
|
302
|
+
const methods = Array.isArray(item.methods) && item.methods.length ? item.methods : ['GET']
|
|
303
|
+
if (!methods.includes(req.method)) {
|
|
304
|
+
json(res, 405, { ok: false, error: '只接受 ' + methods.join(' / ') })
|
|
305
|
+
return
|
|
306
|
+
}
|
|
307
|
+
const data = await item.run(req, res)
|
|
308
|
+
if (!res.writableEnded) json(res, 200, { ok: true, ...(data && typeof data === 'object' ? data : { data }) })
|
|
309
|
+
})
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
mountLazySub('dsh-modpack-annotate')
|
|
313
|
+
mountLazySub('dsh-modpack-plugin-tree')
|
|
314
|
+
|
|
182
315
|
function pendingBytes() {
|
|
183
316
|
let total = 0
|
|
184
317
|
for (const item of pending.values()) total += item.buffer ? item.buffer.length : 0
|
|
@@ -318,7 +451,16 @@ export default {
|
|
|
318
451
|
return
|
|
319
452
|
}
|
|
320
453
|
config = saveConfig(next)
|
|
321
|
-
|
|
454
|
+
// 改完立刻把配色也算回去:界面拿这一份就地重挂主题变量,不用等下一次 /status
|
|
455
|
+
const themeNow = themeOf(config)
|
|
456
|
+
json(res, 200, {
|
|
457
|
+
ok: true,
|
|
458
|
+
config,
|
|
459
|
+
uiStyle: config.uiStyle === 'classic' ? 'classic' : 'new',
|
|
460
|
+
theme: { ...themeNow, vars: config.uiStyle === 'classic' ? {} : themeVars(themeNow), themed: themeActive(themeNow, config.uiStyle) },
|
|
461
|
+
themed: themeActive(themeNow, config.uiStyle),
|
|
462
|
+
themePresets: themeOptions(),
|
|
463
|
+
})
|
|
322
464
|
})
|
|
323
465
|
|
|
324
466
|
// —— 插件目录:分类、词条、分页搜索都照插件市场的来 ——
|
|
@@ -402,7 +544,7 @@ export default {
|
|
|
402
544
|
|
|
403
545
|
// —— 社区资源(自建目录) ——
|
|
404
546
|
// 只做三件事:读目录、检索、取包;校验/扫描/安装全部复用 /inspect 与 /install 那条老路。
|
|
405
|
-
|
|
547
|
+
communityRoute('/dsh-modpack-kit/api/market', async (req, res) => {
|
|
406
548
|
if (req.method !== 'GET') { json(res, 405, { ok: false }); return }
|
|
407
549
|
let summary = null
|
|
408
550
|
try { summary = marketSummary(config) } catch (e) { summary = { present: false, stale: true, count: 0, categories: [], error: String((e && e.message) || e) } }
|
|
@@ -420,7 +562,7 @@ export default {
|
|
|
420
562
|
|
|
421
563
|
// 社区资源的检索同样按 key 缓存 20 秒:连按几个键不该每次都重新打分
|
|
422
564
|
const marketSearchCache = new Map()
|
|
423
|
-
|
|
565
|
+
communityRoute('/dsh-modpack-kit/api/market/search', async (req, res) => {
|
|
424
566
|
if (!needPost(req, res)) return
|
|
425
567
|
const body = await readJsonBody(req)
|
|
426
568
|
const installed = installedOrEmpty().filter((p) => p.isPlugin).map((p) => p.name)
|
|
@@ -444,7 +586,7 @@ export default {
|
|
|
444
586
|
}
|
|
445
587
|
})
|
|
446
588
|
|
|
447
|
-
|
|
589
|
+
communityRoute('/dsh-modpack-kit/api/market/sync', async (req, res) => {
|
|
448
590
|
if (!needPost(req, res)) return
|
|
449
591
|
const body = await readJsonBody(req)
|
|
450
592
|
try {
|
|
@@ -458,22 +600,447 @@ export default {
|
|
|
458
600
|
}
|
|
459
601
|
})
|
|
460
602
|
|
|
603
|
+
communityRoute('/dsh-modpack-kit/api/upload/status', async (req, res) => {
|
|
604
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
605
|
+
json(res, 405, { ok: false, error: '只接受 GET' })
|
|
606
|
+
return
|
|
607
|
+
}
|
|
608
|
+
const token = readUploadToken()
|
|
609
|
+
json(res, 200, {
|
|
610
|
+
ok: true,
|
|
611
|
+
configured: Boolean(token),
|
|
612
|
+
login: uploadWho ? uploadWho.login : '',
|
|
613
|
+
repo: UPLOAD_REPO,
|
|
614
|
+
maxBytes: UPLOAD_MAX_BYTES,
|
|
615
|
+
memoryOnly: true,
|
|
616
|
+
})
|
|
617
|
+
})
|
|
618
|
+
|
|
619
|
+
// 保存 / 清除 GitHub 凭据:只放内存,不落盘、不进 settings;上传结束立刻丢
|
|
620
|
+
communityRoute('/dsh-modpack-kit/api/upload/token', async (req, res) => {
|
|
621
|
+
if (!needPost(req, res)) return
|
|
622
|
+
const body = (await readJsonBody(req)) || {}
|
|
623
|
+
const token = String(body.token || '').trim()
|
|
624
|
+
if (!token) {
|
|
625
|
+
setUploadToken('')
|
|
626
|
+
json(res, 200, { ok: true, configured: false, memoryOnly: true })
|
|
627
|
+
return
|
|
628
|
+
}
|
|
629
|
+
if (!/^[A-Za-z0-9_]{20,}$/u.test(token)) {
|
|
630
|
+
json(res, 400, { ok: false, error: '看起来不像 GitHub token(应是 ghp_ 或 github_pat_ 开头的一长串)' })
|
|
631
|
+
return
|
|
632
|
+
}
|
|
633
|
+
try {
|
|
634
|
+
const user = await whoAmI(token)
|
|
635
|
+
setUploadToken(token)
|
|
636
|
+
uploadWho = user
|
|
637
|
+
appendLog('upload token verified for ' + user.login)
|
|
638
|
+
json(res, 200, { ok: true, configured: true, login: user.login, memoryOnly: true })
|
|
639
|
+
} catch (error) {
|
|
640
|
+
json(res, 400, { ok: false, error: '这个 token 用不了:' + String((error && error.message) || error) })
|
|
641
|
+
}
|
|
642
|
+
})
|
|
643
|
+
|
|
644
|
+
// 上传前的「读一眼」:把包内清单读出来填到可编辑的输入框里。
|
|
645
|
+
// 只读清单、不扫描、不要凭据;参数(类型/格式/大小)仍由 submit 再判一次。
|
|
646
|
+
communityRoute('/dsh-modpack-kit/api/upload/preview', async (req, res) => {
|
|
647
|
+
if (!needPost(req, res)) return
|
|
648
|
+
const body = (await readJsonBody(req, {}, 48 * 1024 * 1024)) || {}
|
|
649
|
+
let got
|
|
650
|
+
try {
|
|
651
|
+
got = readUploadBytes(body)
|
|
652
|
+
} catch (error) {
|
|
653
|
+
json(res, 400, { ok: false, error: String((error && error.message) || error) })
|
|
654
|
+
return
|
|
655
|
+
}
|
|
656
|
+
try {
|
|
657
|
+
const inspected = await inspectPackBuffer(got.bytes, {
|
|
658
|
+
config,
|
|
659
|
+
force: true,
|
|
660
|
+
scanBeforeInstall: false,
|
|
661
|
+
extraScanRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [],
|
|
662
|
+
})
|
|
663
|
+
const manifest = inspected.manifest || {}
|
|
664
|
+
const pluginList = (manifest.plugins || []).map((plugin) => ({
|
|
665
|
+
name: plugin.name,
|
|
666
|
+
version: plugin.latest === true ? '' : String(plugin.version || ''),
|
|
667
|
+
latest: plugin.latest === true,
|
|
668
|
+
group: plugin.group || '',
|
|
669
|
+
configMode: plugin.configMode === 'custom' ? 'custom' : 'preset',
|
|
670
|
+
configIncluded: plugin.configIncluded === true,
|
|
671
|
+
configKeys: Array.isArray(plugin.configRedacted) ? plugin.configRedacted.length : 0,
|
|
672
|
+
dataIncluded: plugin.dataIncluded === true,
|
|
673
|
+
dataRedacted: Number(plugin.dataRedacted || 0),
|
|
674
|
+
embedded: plugin.embedded === true,
|
|
675
|
+
}))
|
|
676
|
+
const withConfig = pluginList.filter((item) => item.configMode === 'custom' || item.configIncluded)
|
|
677
|
+
const withData = pluginList.filter((item) => item.dataIncluded)
|
|
678
|
+
json(res, 200, {
|
|
679
|
+
ok: true,
|
|
680
|
+
fileName: got.fileName,
|
|
681
|
+
size: got.bytes.length,
|
|
682
|
+
sha256: createHash('sha256').update(got.bytes).digest('hex'),
|
|
683
|
+
format: manifest.format,
|
|
684
|
+
fields: {
|
|
685
|
+
name: String(manifest.name || ''),
|
|
686
|
+
author: String(body.author || manifest.author || ''),
|
|
687
|
+
description: String(manifest.description || ''),
|
|
688
|
+
homepage: String(manifest.homepage || ''),
|
|
689
|
+
},
|
|
690
|
+
plugins: pluginList.length,
|
|
691
|
+
pluginList,
|
|
692
|
+
summary: {
|
|
693
|
+
configMode: withConfig.length > 0 ? 'custom' : 'preset',
|
|
694
|
+
configCount: withConfig.length,
|
|
695
|
+
dataCount: withData.length,
|
|
696
|
+
redacted: pluginList.reduce((sum, item) => sum + item.configKeys + item.dataRedacted, 0),
|
|
697
|
+
groups: [...new Set(pluginList.map((item) => item.group).filter(Boolean))],
|
|
698
|
+
embeddedCount: pluginList.filter((item) => item.embedded).length,
|
|
699
|
+
},
|
|
700
|
+
})
|
|
701
|
+
} catch (error) {
|
|
702
|
+
json(res, 400, { ok: false, error: '读不了这个包:' + String((error && error.message) || error) })
|
|
703
|
+
}
|
|
704
|
+
})
|
|
705
|
+
|
|
706
|
+
// 上传的字节:页面直接选文件时走 base64;从「浏览文件夹」挑的走本机路径。
|
|
707
|
+
// 两条都限死在 UPLOAD_MAX_BYTES,路径只认 .dshpack 且必须是文件。
|
|
708
|
+
const readUploadBytes = (body) => {
|
|
709
|
+
const b64 = String((body && body.base64) || '').replace(/^data:[^,]+,/u, '')
|
|
710
|
+
if (b64) return { bytes: Buffer.from(b64, 'base64'), fileName: String((body && body.fileName) || '').trim() }
|
|
711
|
+
const raw = String((body && body.file) || '').trim()
|
|
712
|
+
if (!raw) throw new Error('缺 base64 或 file(先把包选上)')
|
|
713
|
+
const target = path.resolve(raw)
|
|
714
|
+
if (!target.toLowerCase().endsWith('.dshpack')) throw new Error('只认 .dshpack 整合包')
|
|
715
|
+
let stat
|
|
716
|
+
try { stat = fs.statSync(target) } catch { throw new Error('这个路径读不到:' + target) }
|
|
717
|
+
if (!stat.isFile()) throw new Error('这个路径不是文件:' + target)
|
|
718
|
+
if (stat.size > UPLOAD_MAX_BYTES) throw new Error('包超过 32 MB:目录不收这么大的,完整包请放发布页')
|
|
719
|
+
return { bytes: fs.readFileSync(target), fileName: path.basename(target) }
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
// 一键上传:收包 → 校验(只收轻量/混合)→ fork/分支 → 放包与条目 → 开 PR
|
|
723
|
+
// 顺序:先把包本身验完(不需要凭据),再要 token——这样参数错误不会白白消耗一次 GitHub 调用
|
|
724
|
+
communityRoute('/dsh-modpack-kit/api/upload/submit', async (req, res) => {
|
|
725
|
+
if (!needPost(req, res)) return
|
|
726
|
+
const body = (await readJsonBody(req, {}, 48 * 1024 * 1024)) || {}
|
|
727
|
+
let bytes = Buffer.alloc(0)
|
|
728
|
+
let fileName = String(body.fileName || '').trim()
|
|
729
|
+
try {
|
|
730
|
+
const got = readUploadBytes(body)
|
|
731
|
+
bytes = got.bytes
|
|
732
|
+
fileName = fileName || got.fileName
|
|
733
|
+
} catch (error) {
|
|
734
|
+
json(res, 400, { ok: false, error: String((error && error.message) || error) })
|
|
735
|
+
return
|
|
736
|
+
}
|
|
737
|
+
const edits = body.edits && typeof body.edits === 'object' ? body.edits : {}
|
|
738
|
+
const category = String(body.category || '').trim()
|
|
739
|
+
const homepage = String(body.homepage || '').trim()
|
|
740
|
+
// 放哪:默认把包放进目录仓库(零额外步骤,但没有逐文件下载计数);
|
|
741
|
+
// host=release 时放到使用者自己的 GitHub Release 里,那边资产自带 download_count,
|
|
742
|
+
// 目录构建时读出来就是「真实下载量」。
|
|
743
|
+
const host = body.host === 'release' ? 'release' : 'repo'
|
|
744
|
+
// 演练:把整套检查(类型、读包、改词条、封面、条目拼装)真跑一遍,
|
|
745
|
+
// 但不碰 GitHub、不开 PR、不需要凭据。用来验实现,也方便先看条目长什么样。
|
|
746
|
+
// 测试模式:上传一律按「演练」处理,连凭据都不读
|
|
747
|
+
const dryRun = body.dryRun === true || testModeOn(config)
|
|
748
|
+
const ownerRepo = String(body.repo || '').trim()
|
|
749
|
+
const tag = String(body.tag || '').trim()
|
|
750
|
+
|
|
751
|
+
if (!fileName) {
|
|
752
|
+
json(res, 400, { ok: false, error: '缺文件名:页面会从选择的文件里带过来' })
|
|
753
|
+
return
|
|
754
|
+
}
|
|
755
|
+
if (!category) {
|
|
756
|
+
json(res, 400, { ok: false, error: '选一个类型(工作办公 / 性能优化 / 界面美化 / 实用功能 / 开发调试 / 娱乐休闲 / 学习资料 / 其它 / 水槽)' })
|
|
757
|
+
return
|
|
758
|
+
}
|
|
759
|
+
const allowedCategories = new Set(CATEGORY_FALLBACK.map((item) => item.label))
|
|
760
|
+
if (!allowedCategories.has(category)) {
|
|
761
|
+
json(res, 400, { ok: false, error: '不认识的类型「' + category + '」:可选 ' + Array.from(allowedCategories).join(' / ') })
|
|
762
|
+
return
|
|
763
|
+
}
|
|
764
|
+
if (!bytes.length) {
|
|
765
|
+
json(res, 400, { ok: false, error: '包是空的' })
|
|
766
|
+
return
|
|
767
|
+
}
|
|
768
|
+
if (bytes.length > UPLOAD_MAX_BYTES) {
|
|
769
|
+
json(res, 400, { ok: false, error: '包超过 32 MB:目录不收这么大的,完整包请放发布页' })
|
|
770
|
+
return
|
|
771
|
+
}
|
|
772
|
+
let inspected
|
|
773
|
+
try {
|
|
774
|
+
// 注意:inspectPackBuffer 的第二个参数是 options,config 要挂在 options.config 上。
|
|
775
|
+
// 之前这里直接传了 config,导致 maxPackBytes / extraScanRules 全被忽略。
|
|
776
|
+
inspected = await inspectPackBuffer(bytes, {
|
|
777
|
+
config,
|
|
778
|
+
force: true,
|
|
779
|
+
scanBeforeInstall: false,
|
|
780
|
+
extraScanRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [],
|
|
781
|
+
})
|
|
782
|
+
} catch (error) {
|
|
783
|
+
json(res, 400, { ok: false, error: '读不了这个包:' + String((error && error.message) || error) })
|
|
784
|
+
return
|
|
785
|
+
}
|
|
786
|
+
// 「名称 / 作者 / 简介 / 主页」允许在上传前自己改:目录只认包里的清单,
|
|
787
|
+
// 所以改的时候是原地改写包内的 dsh-modpack.json(顺带重写 README.txt 与 integrity.json),
|
|
788
|
+
// 而不是在条目里另存一份覆盖字段——这样别人装到的包和目录里显示的也是改后的内容。
|
|
789
|
+
let edited = null
|
|
790
|
+
if (Object.keys(edits).length > 0) {
|
|
791
|
+
try {
|
|
792
|
+
const result = rewritePackManifest(bytes, edits)
|
|
793
|
+
if (result.changed) {
|
|
794
|
+
bytes = result.buffer
|
|
795
|
+
edited = result.patch
|
|
796
|
+
inspected = await inspectPackBuffer(bytes, {
|
|
797
|
+
config,
|
|
798
|
+
force: true,
|
|
799
|
+
scanBeforeInstall: false,
|
|
800
|
+
extraScanRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [],
|
|
801
|
+
})
|
|
802
|
+
}
|
|
803
|
+
} catch (error) {
|
|
804
|
+
json(res, 400, { ok: false, error: '改清单时出错了:' + String((error && error.message) || error) })
|
|
805
|
+
return
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
const manifest = inspected.manifest || {}
|
|
809
|
+
const strategy = String(manifest.format || 'lite')
|
|
810
|
+
if (strategy !== 'lite' && strategy !== 'hybrid') {
|
|
811
|
+
json(res, 400, { ok: false, error: '目录只收轻量包与混合包;这个是完整包(' + strategy + ')' })
|
|
812
|
+
return
|
|
813
|
+
}
|
|
814
|
+
const slug = String(fileName).replace(/\.dshpack$/iu, '').toLowerCase().replace(/[^a-z0-9-]+/gu, '-').replace(/^-+|-+$/gu, '')
|
|
815
|
+
const id = slug.length >= 3 && slug.length <= 40 ? slug : ('pack-' + Date.now().toString(36))
|
|
816
|
+
if (!/^[a-z0-9][a-z0-9-]{2,40}$/u.test(id)) {
|
|
817
|
+
json(res, 400, { ok: false, error: '文件名转不出合法的 id(要 3~40 位小写字母数字短横线),把包名改成英文再试' })
|
|
818
|
+
return
|
|
819
|
+
}
|
|
820
|
+
const file = packFileName(id, strategy)
|
|
821
|
+
const sha = inspected.integrity && inspected.integrity.sha256
|
|
822
|
+
? inspected.integrity.sha256
|
|
823
|
+
: createHash('sha256').update(bytes).digest('hex')
|
|
824
|
+
const today = new Date().toISOString().slice(0, 10)
|
|
825
|
+
const releaseRepo = ownerRepo
|
|
826
|
+
const releaseTag = tag || ('packs-' + id)
|
|
827
|
+
if (host === 'release') {
|
|
828
|
+
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(releaseRepo)) {
|
|
829
|
+
json(res, 400, { ok: false, error: '要放 Release 的话,得先填你自己的仓库(owner/name)' })
|
|
830
|
+
return
|
|
831
|
+
}
|
|
832
|
+
if (!/^[A-Za-z0-9._-]{1,60}$/u.test(releaseTag)) {
|
|
833
|
+
json(res, 400, { ok: false, error: 'tag 只能用字母、数字、点、下划线与短横线(1~60 位)' })
|
|
834
|
+
return
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
// 封面图:只认 png/jpeg 的 data URL,大小限住,别让一张图把 PR 撑成几十 MB
|
|
838
|
+
const COVER_DATA_RE = /^data:image\/(?:png|jpeg);base64,[A-Za-z0-9+/=]+$/u
|
|
839
|
+
const COVER_MAX_BYTES = 300 * 1024
|
|
840
|
+
const parseCover = (value) => {
|
|
841
|
+
const text = String(value || '')
|
|
842
|
+
const match = /^data:image\/(png|jpeg);base64,([A-Za-z0-9+/=]+)$/u.exec(text)
|
|
843
|
+
if (!match) throw new Error('封面只认 PNG 或 JPG')
|
|
844
|
+
const coverBytes = Buffer.from(match[2], 'base64')
|
|
845
|
+
if (coverBytes.length === 0) throw new Error('封面是空的')
|
|
846
|
+
if (coverBytes.length > COVER_MAX_BYTES) {
|
|
847
|
+
throw new Error('封面太大:' + Math.round(coverBytes.length / 1024) + ' KB,上限 300 KB(建议 512×512 以内)')
|
|
848
|
+
}
|
|
849
|
+
return { ext: match[1] === 'jpeg' ? 'jpg' : 'png', bytes: coverBytes }
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
let coverPath = ''
|
|
853
|
+
if (body.cover) {
|
|
854
|
+
const cover = parseCover(body.cover)
|
|
855
|
+
coverPath = 'covers/' + id + '.' + cover.ext
|
|
856
|
+
}
|
|
857
|
+
const entry = {
|
|
858
|
+
id,
|
|
859
|
+
category,
|
|
860
|
+
customization: strategy === 'lite' ? 'none' : 'custom',
|
|
861
|
+
...(coverPath ? { cover: coverPath } : {}),
|
|
862
|
+
file,
|
|
863
|
+
sha256: sha,
|
|
864
|
+
size: bytes.length,
|
|
865
|
+
createdAt: today,
|
|
866
|
+
updatedAt: today,
|
|
867
|
+
homepage,
|
|
868
|
+
...(host === 'release'
|
|
869
|
+
? { host: 'release', repo: releaseRepo, tag: releaseTag }
|
|
870
|
+
: { repo: UPLOAD_REPO }),
|
|
871
|
+
}
|
|
872
|
+
// 包验完了才要凭据:没填 token 时上面的错误都已经返回,不会走到这里。
|
|
873
|
+
// 演练模式不需要凭据。
|
|
874
|
+
const token = dryRun ? '' : readUploadToken()
|
|
875
|
+
if (!dryRun && !token) {
|
|
876
|
+
json(res, 400, { ok: false, error: '还没有 GitHub 凭据:先在上传页填一次 token(只存在内存里,不会被抄进整合包)' })
|
|
877
|
+
return
|
|
878
|
+
}
|
|
879
|
+
// 上传也走任务队列:进度显示在左下角悬浮窗,出错也停在那一行等你点「我已知晓」
|
|
880
|
+
const job = createJob('upload', (dryRun ? '演练上传「' : '上传整合包「') + (manifest.name || id) + '」')
|
|
881
|
+
const steps = []
|
|
882
|
+
const push = (text, pct) => {
|
|
883
|
+
if (job.cancelled) {
|
|
884
|
+
const stop = new Error('已取消')
|
|
885
|
+
stop.name = 'JobCancelled'
|
|
886
|
+
throw stop
|
|
887
|
+
}
|
|
888
|
+
if (text) steps.push(text)
|
|
889
|
+
if (typeof pct === 'number') job.pct = pct
|
|
890
|
+
job.note = steps[steps.length - 1] || job.note
|
|
891
|
+
job.updatedAt = new Date().toISOString()
|
|
892
|
+
}
|
|
893
|
+
push('读取包与清单', 10)
|
|
894
|
+
;(async () => {
|
|
895
|
+
try {
|
|
896
|
+
if (dryRun) {
|
|
897
|
+
push('类型 / 读包 / 格式检查通过(' + strategy + ')', 30)
|
|
898
|
+
if (edited) push('会按你改的内容重写清单:' + Object.keys(edited).join('、'), 45)
|
|
899
|
+
if (coverPath) push('会放封面:' + coverPath, 55)
|
|
900
|
+
if (host === 'release') push('会放 Release:' + releaseRepo + ' · ' + releaseTag, 65)
|
|
901
|
+
else push('会把包写进 packs/' + file, 65)
|
|
902
|
+
push('会写条目 ' + entryFileName(id) + '(sha256 ' + sha.slice(0, 12) + '…)', 85)
|
|
903
|
+
job.status = 'done'
|
|
904
|
+
job.pct = 100
|
|
905
|
+
job.note = '演练完成:没有真的上传'
|
|
906
|
+
job.data = { dryRun: true, entry, steps }
|
|
907
|
+
return
|
|
908
|
+
}
|
|
909
|
+
const user = await whoAmI(token)
|
|
910
|
+
push('登录为 ' + user.login, 20)
|
|
911
|
+
if (!uploadWho) uploadWho = user
|
|
912
|
+
if (edited) push('按你改的内容重写清单:' + Object.keys(edited).join('、'), 15)
|
|
913
|
+
if (host === 'release') {
|
|
914
|
+
push('准备 Release', 35)
|
|
915
|
+
const release = await ensureRelease(token, releaseRepo, releaseTag, manifest.name || id, (text) => push(text, 45))
|
|
916
|
+
const asset = await uploadReleaseAsset(token, releaseRepo, release.id, file, bytes, (text) => push(text, 60))
|
|
917
|
+
push('下载地址:' + (asset.url || ('https://github.com/' + releaseRepo + '/releases/download/' + releaseTag + '/' + file)), 70)
|
|
918
|
+
}
|
|
919
|
+
const pr = await openPackPullRequest({
|
|
920
|
+
token,
|
|
921
|
+
catalog: UPLOAD_REPO,
|
|
922
|
+
login: user.login,
|
|
923
|
+
branch: 'add-pack-' + id + '-' + Date.now().toString(36).slice(-4),
|
|
924
|
+
// 条目里的 file 是裸文件名,仓库里落在 packs/ 下
|
|
925
|
+
packPath: host === 'release' ? '' : 'packs/' + file,
|
|
926
|
+
packBase64: host === 'release' ? '' : base64,
|
|
927
|
+
entryPath: entryFileName(id),
|
|
928
|
+
...(coverPath ? { coverPath, coverBase64: (body.cover ? String(body.cover).split(',')[1] : ''), packId: id } : {}),
|
|
929
|
+
entryText: JSON.stringify(entry, null, 2) + '\n',
|
|
930
|
+
title: 'catalog: add ' + (manifest.name || id),
|
|
931
|
+
body: [
|
|
932
|
+
'新增整合包:**' + (manifest.name || id) + '**',
|
|
933
|
+
'',
|
|
934
|
+
'- 类型:' + category,
|
|
935
|
+
'- 格式:' + strategy + '(' + (entry.customization === 'custom' ? '有自定义' : '无修改') + ')',
|
|
936
|
+
'- 插件:' + ((manifest.plugins || []).length) + ' 个',
|
|
937
|
+
'- sha256:' + sha,
|
|
938
|
+
'- 存放:' + (host === 'release' ? 'GitHub Release(' + releaseRepo + ' · ' + releaseTag + ')' : '目录仓库 packs/'),
|
|
939
|
+
'',
|
|
940
|
+
'由 dsh-modpack-kit 的上传页自动生成。',
|
|
941
|
+
].join('\n'),
|
|
942
|
+
onStep: (text) => push(text, job.pct < 70 ? 75 : 85),
|
|
943
|
+
})
|
|
944
|
+
appendLog('upload ' + id + ' -> PR #' + pr.number)
|
|
945
|
+
job.status = 'done'
|
|
946
|
+
job.pct = 100
|
|
947
|
+
job.note = 'PR 开好了:#' + pr.number
|
|
948
|
+
job.data = { pr, entry, steps }
|
|
949
|
+
} catch (error) {
|
|
950
|
+
if (error && error.name === 'JobCancelled') {
|
|
951
|
+
job.status = 'cancelled'
|
|
952
|
+
job.note = '已取消(没有开 PR)'
|
|
953
|
+
job.error = '已取消'
|
|
954
|
+
} else {
|
|
955
|
+
job.status = 'failed'
|
|
956
|
+
job.note = '卡住了'
|
|
957
|
+
job.error = String((error && error.message) || error)
|
|
958
|
+
}
|
|
959
|
+
job.data = { steps, entry, id }
|
|
960
|
+
} finally {
|
|
961
|
+
// 用后即刻清除:不管成没成,内存里的 token 都不留
|
|
962
|
+
clearUploadToken()
|
|
963
|
+
job.finishedAt = new Date().toISOString()
|
|
964
|
+
job.updatedAt = job.finishedAt
|
|
965
|
+
}
|
|
966
|
+
})()
|
|
967
|
+
json(res, 202, { ok: true, async: true, job: publicJob(job), entryId: id })
|
|
968
|
+
})
|
|
969
|
+
|
|
970
|
+
// 本地预览:把刚选好的包临时当成社区目录里的一条,
|
|
971
|
+
// 让「预览」能真的走一遍下载 → 读包 → 安装,全程不联网、不开 PR。
|
|
972
|
+
let localPreview = null
|
|
973
|
+
const PREVIEW_ID = '__local_preview__'
|
|
974
|
+
communityRoute('/dsh-modpack-kit/api/market/preview', async (req, res) => {
|
|
975
|
+
if (!needPost(req, res)) return
|
|
976
|
+
const body = await readJsonBody(req, {}, MAX_DROP_BODY)
|
|
977
|
+
try {
|
|
978
|
+
const gotBytes = readUploadBytes(body)
|
|
979
|
+
const bytes = gotBytes.bytes
|
|
980
|
+
const inspected = inspectPackBuffer(bytes, {
|
|
981
|
+
config,
|
|
982
|
+
force: true,
|
|
983
|
+
scanBeforeInstall: false,
|
|
984
|
+
extraScanRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [],
|
|
985
|
+
})
|
|
986
|
+
const manifest = inspected.manifest
|
|
987
|
+
const count = Array.isArray(manifest.plugins) ? manifest.plugins.length : 0
|
|
988
|
+
localPreview = { bytes, manifest, at: Date.now() }
|
|
989
|
+
const sha256 = createHash('sha256').update(bytes).digest('hex')
|
|
990
|
+
json(res, 200, {
|
|
991
|
+
ok: true,
|
|
992
|
+
pack: {
|
|
993
|
+
id: PREVIEW_ID,
|
|
994
|
+
name: String(body.name || manifest.name || '本地预览包'),
|
|
995
|
+
author: String(manifest.author || ''),
|
|
996
|
+
description: { zh: String(body.description || manifest.description || ''), en: '' },
|
|
997
|
+
category: String(body.category || '其它'),
|
|
998
|
+
strategy: manifest.format === 'hybrid' ? 'hybrid' : 'lite',
|
|
999
|
+
pluginCount: count,
|
|
1000
|
+
tier: count >= 13 ? 'huge' : count >= 9 ? 'large' : count >= 4 ? 'medium' : 'small',
|
|
1001
|
+
plugins: (manifest.plugins || []).map((p) => ({ name: p.name, version: p.version || '', latest: p.latest === true })),
|
|
1002
|
+
cover: COVER_DATA_RE.test(String(body.cover || '')) ? String(body.cover) : '',
|
|
1003
|
+
file: PREVIEW_ID + '.dshpack',
|
|
1004
|
+
sha256,
|
|
1005
|
+
size: bytes.length,
|
|
1006
|
+
local: true,
|
|
1007
|
+
pluginsDetail: manifest.plugins || [],
|
|
1008
|
+
},
|
|
1009
|
+
})
|
|
1010
|
+
} catch (e) {
|
|
1011
|
+
json(res, 200, { ok: false, error: String((e && e.message) || e) })
|
|
1012
|
+
}
|
|
1013
|
+
})
|
|
1014
|
+
|
|
461
1015
|
// 下载一个整合包:只认目录里登记过的条目,sha256 必须对得上,
|
|
462
1016
|
// 下完直接在内存里交给原来的 inspect(安全检测、兼容、许可证那一套原样走)。
|
|
463
|
-
|
|
1017
|
+
communityRoute('/dsh-modpack-kit/api/market/download', async (req, res) => {
|
|
464
1018
|
if (!needPost(req, res)) return
|
|
465
1019
|
const body = await readJsonBody(req)
|
|
466
|
-
const
|
|
1020
|
+
const saveOnly = body.saveOnly === true
|
|
1021
|
+
const isPreview = body.id === PREVIEW_ID
|
|
1022
|
+
const found = isPreview
|
|
1023
|
+
? (localPreview
|
|
1024
|
+
? {
|
|
1025
|
+
ok: true,
|
|
1026
|
+
pack: {
|
|
1027
|
+
id: PREVIEW_ID,
|
|
1028
|
+
name: localPreview.manifest.name || '本地预览包',
|
|
1029
|
+
sha256: createHash('sha256').update(localPreview.bytes).digest('hex'),
|
|
1030
|
+
},
|
|
1031
|
+
}
|
|
1032
|
+
: { ok: false, error: '还没有可以预览的包:先在「上传我的整合包」里选一个,再点预览' })
|
|
1033
|
+
: findMarketPack(config, body.id)
|
|
467
1034
|
if (!found.ok) { json(res, 200, { ok: false, error: found.error }); return }
|
|
468
1035
|
const pack = found.pack
|
|
469
1036
|
try {
|
|
470
|
-
const fetched = await fetchMarketPack(config, pack)
|
|
1037
|
+
const fetched = isPreview ? { url: 'local://' + PREVIEW_ID, buffer: localPreview.bytes } : await fetchMarketPack(config, pack)
|
|
471
1038
|
const bytes = fetched.buffer
|
|
472
1039
|
if (pack.size > 0 && bytes.length !== pack.size) {
|
|
473
1040
|
throw new Error('包体积和目录里登记的不一致(登记 ' + pack.size + ' 字节,实际 ' + bytes.length + ' 字节)')
|
|
474
1041
|
}
|
|
475
1042
|
const actual = createHash('sha256').update(bytes).digest('hex')
|
|
476
|
-
if (pack.sha256 && actual !== pack.sha256) {
|
|
1043
|
+
if (!isPreview && pack.sha256 && actual !== pack.sha256) {
|
|
477
1044
|
throw new Error('sha256 对不上:目录登记 ' + pack.sha256.slice(0, 12) + '…,实际 ' + actual.slice(0, 12) + '…')
|
|
478
1045
|
}
|
|
479
1046
|
const inspected = inspectPackBuffer(bytes, {
|
|
@@ -483,12 +1050,37 @@ export default {
|
|
|
483
1050
|
extraScanRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [],
|
|
484
1051
|
})
|
|
485
1052
|
const fileName = slugify(inspected.manifest.name || pack.id, 'pack') + '.dshpack'
|
|
486
|
-
const token = rememberPending(fileName, { buffer: bytes, manifest: inspected.manifest, report: inspected.report, scan: inspected.scan })
|
|
487
|
-
appendLog('market download ' + pack.id + ' ' + bytes.length + ' bytes')
|
|
1053
|
+
const token = saveOnly ? '' : rememberPending(fileName, { buffer: bytes, manifest: inspected.manifest, report: inspected.report, scan: inspected.scan })
|
|
1054
|
+
appendLog('market ' + (saveOnly ? 'save' : 'download') + ' ' + pack.id + ' ' + bytes.length + ' bytes')
|
|
1055
|
+
// 下载的包也留一份在插件自己的 packs 目录里:安装页能直接再选它,
|
|
1056
|
+
// 关掉 DSH 之后那些内存里的 token 就没了,磁盘上这份还在。
|
|
1057
|
+
const packsDir = pathsFor(config).packs
|
|
1058
|
+
let savedPath = ''
|
|
1059
|
+
let savedName = ''
|
|
1060
|
+
try {
|
|
1061
|
+
fs.mkdirSync(packsDir, { recursive: true })
|
|
1062
|
+
const base = slugify(inspected.manifest.name || pack.name || pack.id || 'pack', 'pack')
|
|
1063
|
+
const wantName = base + '-' + String(actual).slice(0, 8) + '.dshpack'
|
|
1064
|
+
const target = path.join(packsDir, wantName)
|
|
1065
|
+
if (!fs.existsSync(target)) fs.writeFileSync(target, bytes)
|
|
1066
|
+
savedPath = target
|
|
1067
|
+
savedName = wantName
|
|
1068
|
+
appendLog('market save ' + wantName + ' ' + bytes.length + ' bytes')
|
|
1069
|
+
} catch (e) {
|
|
1070
|
+
// 存不下不影响这次安装:token 里还有字节,装完再说
|
|
1071
|
+
appendLog('market save failed: ' + String((e && e.message) || e))
|
|
1072
|
+
}
|
|
1073
|
+
if (saveOnly) {
|
|
1074
|
+
json(res, 200, { ok: true, savedOnly: true, savedPath, savedName, savedDir: packsDir, size: bytes.length, packId: pack.id, packName: pack.name, sha256: actual })
|
|
1075
|
+
return
|
|
1076
|
+
}
|
|
488
1077
|
json(res, 200, {
|
|
489
1078
|
ok: true,
|
|
490
1079
|
token,
|
|
491
1080
|
fileName,
|
|
1081
|
+
savedPath,
|
|
1082
|
+
savedName,
|
|
1083
|
+
savedDir: packsDir,
|
|
492
1084
|
size: bytes.length,
|
|
493
1085
|
packId: pack.id,
|
|
494
1086
|
packName: pack.name,
|
|
@@ -584,6 +1176,8 @@ export default {
|
|
|
584
1176
|
finishedAt: '',
|
|
585
1177
|
error: '',
|
|
586
1178
|
data: null,
|
|
1179
|
+
// 分步骤的任务(重装插件)用它显示「做到哪一步了」;别的任务留空数组
|
|
1180
|
+
steps: [],
|
|
587
1181
|
// 风险停下来的任务:保留原始请求,等你选「立即停止」还是「我知道在干什么」
|
|
588
1182
|
risk: null,
|
|
589
1183
|
body: null,
|
|
@@ -603,6 +1197,7 @@ export default {
|
|
|
603
1197
|
finishedAt: job.finishedAt,
|
|
604
1198
|
error: job.error,
|
|
605
1199
|
data: job.data,
|
|
1200
|
+
steps: Array.isArray(job.steps) ? job.steps : [],
|
|
606
1201
|
risk: job.risk,
|
|
607
1202
|
// 只有「可确认继续」的风险任务才给「我知道在干什么」;停下来的任务都能删
|
|
608
1203
|
canAck: Boolean(job.risk && job.risk.needsAck && job.status === 'paused'),
|
|
@@ -785,6 +1380,11 @@ export default {
|
|
|
785
1380
|
}
|
|
786
1381
|
const startPackJob = (body, label) => {
|
|
787
1382
|
const job = createJob('pack', label || ('打包「' + String((body.options && body.options.name) || 'DSH 整合包') + '」'))
|
|
1383
|
+
if (testModeOn(config)) {
|
|
1384
|
+
// 测试模式:不打包、不联网、不写文件,只把流程与进度演一遍(见 lib/testmode.mjs)
|
|
1385
|
+
playTestJob(job, testStepsFor('pack'), { action: '打包', cancelled: () => Boolean(job.cancelled), data: { selection: Array.isArray(body.selection) ? body.selection : [] } })
|
|
1386
|
+
return job
|
|
1387
|
+
}
|
|
788
1388
|
// 留一份原始请求:风险停下来之后,界面上点「我知道在干什么」要能照原样再跑一次
|
|
789
1389
|
try {
|
|
790
1390
|
job.body = JSON.parse(JSON.stringify({
|
|
@@ -821,6 +1421,288 @@ export default {
|
|
|
821
1421
|
}
|
|
822
1422
|
})
|
|
823
1423
|
|
|
1424
|
+
// 社区资源 → 插件 这一层的「装 / 更新」:跟插件市场同一个来源(npm 上的 name@version),
|
|
1425
|
+
// 优先交给宿主的插件管理器;管理器不在时退回官方命令行。装完插件市场认的就是市场版。
|
|
1426
|
+
route('/dsh-modpack-kit/api/plugin/install', async (req, res) => {
|
|
1427
|
+
if (!needPost(req, res)) return
|
|
1428
|
+
const body = await readJsonBody(req)
|
|
1429
|
+
const name = typeof body.name === 'string' ? body.name.trim() : ''
|
|
1430
|
+
if (!/^(?:@[A-Za-z0-9][A-Za-z0-9._-]*\/)?[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(name)) {
|
|
1431
|
+
json(res, 400, { ok: false, error: '插件名不合法' })
|
|
1432
|
+
return
|
|
1433
|
+
}
|
|
1434
|
+
const version = typeof body.version === 'string' ? body.version.trim() : ''
|
|
1435
|
+
const wanted = /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/u.test(version) ? name + '@' + version : name
|
|
1436
|
+
if (testModeOn(config)) {
|
|
1437
|
+
json(res, 200, { ok: true, test: true, note: testNote('安装插件'), spec: wanted, application: 'restart-required', restartRequired: true, error: '', output: '' })
|
|
1438
|
+
return
|
|
1439
|
+
}
|
|
1440
|
+
const manager = ctx.get('pluginManager')
|
|
1441
|
+
try {
|
|
1442
|
+
if (manager && typeof manager.installBundle === 'function') {
|
|
1443
|
+
const change = await manager.installBundle(wanted, { enabled: true })
|
|
1444
|
+
const application = String((change && change.application) || '')
|
|
1445
|
+
appendLog('plugin ' + wanted + ' via=manager application=' + application)
|
|
1446
|
+
json(res, 200, {
|
|
1447
|
+
ok: application !== 'failed' && application !== 'cancelled',
|
|
1448
|
+
spec: wanted,
|
|
1449
|
+
application,
|
|
1450
|
+
restartRequired: application === 'restart-required',
|
|
1451
|
+
error: change && change.error ? String((change.error && change.error.code) || change.error) : '',
|
|
1452
|
+
output: change && change.packageResult ? String(change.packageResult.output || '').slice(-800) : '',
|
|
1453
|
+
})
|
|
1454
|
+
return
|
|
1455
|
+
}
|
|
1456
|
+
const profile = profileName(config)
|
|
1457
|
+
const result = await runDshPlugin(profile, ['add', wanted], { timeoutMs: 300000 })
|
|
1458
|
+
const code = result && typeof result.code === 'number' ? result.code : 1
|
|
1459
|
+
appendLog('plugin ' + wanted + ' via=cli exit=' + code)
|
|
1460
|
+
json(res, 200, {
|
|
1461
|
+
ok: code === 0,
|
|
1462
|
+
spec: wanted,
|
|
1463
|
+
application: code === 0 ? 'restart-required' : 'failed',
|
|
1464
|
+
restartRequired: code === 0,
|
|
1465
|
+
error: code === 0 ? '' : String((result && result.output) || '').slice(-800),
|
|
1466
|
+
})
|
|
1467
|
+
} catch (error) {
|
|
1468
|
+
json(res, 500, { ok: false, spec: wanted, error: String((error && error.message) || error), hint: '命令行这条路失败时,也可以在插件市场里装;两边来源一样。' })
|
|
1469
|
+
}
|
|
1470
|
+
})
|
|
1471
|
+
|
|
1472
|
+
// —— 插件管理:列表 / 启用禁用 / 重装 ——
|
|
1473
|
+
// 数据是「已装插件 + 插件市场那份状态」,市场不在也能用(停用退回配置层)。
|
|
1474
|
+
route('/dsh-modpack-kit/api/plugins', (req, res) => {
|
|
1475
|
+
if (req.method !== 'GET') { json(res, 405, { ok: false, error: '只支持 GET' }); return }
|
|
1476
|
+
try {
|
|
1477
|
+
json(res, 200, { ok: true, ...listManaged(profileDir(), config), profile: profileName(config) })
|
|
1478
|
+
} catch (error) {
|
|
1479
|
+
json(res, 500, { ok: false, error: String((error && error.message) || error) })
|
|
1480
|
+
}
|
|
1481
|
+
})
|
|
1482
|
+
|
|
1483
|
+
route('/dsh-modpack-kit/api/plugins/toggle', async (req, res) => {
|
|
1484
|
+
if (!needPost(req, res)) return
|
|
1485
|
+
const body = await readJsonBody(req)
|
|
1486
|
+
const name = typeof body.name === 'string' ? body.name.trim() : ''
|
|
1487
|
+
if (!isValidPluginName(name)) { json(res, 400, { ok: false, error: '插件名不合法' }); return }
|
|
1488
|
+
if (typeof body.enabled !== 'boolean') { json(res, 400, { ok: false, error: 'enabled 要给 true 或 false' }); return }
|
|
1489
|
+
if (testModeOn(config)) {
|
|
1490
|
+
json(res, 200, { ok: true, test: true, note: testNote(body.enabled ? '启用插件' : '停用插件'), name, enabled: body.enabled, restartRequired: true })
|
|
1491
|
+
return
|
|
1492
|
+
}
|
|
1493
|
+
try {
|
|
1494
|
+
json(res, 200, { ok: true, ...setPluginEnabled(profileDir(), name, body.enabled) })
|
|
1495
|
+
} catch (error) {
|
|
1496
|
+
json(res, 400, {
|
|
1497
|
+
ok: false,
|
|
1498
|
+
name,
|
|
1499
|
+
error: String((error && error.message) || error),
|
|
1500
|
+
hint: '停用状态写在插件市场那份名单里(没装市场就写配置层),下次启动 DSH 才生效。',
|
|
1501
|
+
})
|
|
1502
|
+
}
|
|
1503
|
+
})
|
|
1504
|
+
|
|
1505
|
+
route('/dsh-modpack-kit/api/plugins/reveal', async (req, res) => {
|
|
1506
|
+
if (!needPost(req, res)) return
|
|
1507
|
+
const body = await readJsonBody(req)
|
|
1508
|
+
const name = typeof body.name === 'string' ? body.name.trim() : ''
|
|
1509
|
+
try {
|
|
1510
|
+
json(res, 200, { ok: true, ...revealPluginDir(profileDir(), name) })
|
|
1511
|
+
} catch (error) {
|
|
1512
|
+
json(res, 400, { ok: false, error: String((error && error.message) || error) })
|
|
1513
|
+
}
|
|
1514
|
+
})
|
|
1515
|
+
|
|
1516
|
+
// 行首图标:只从已装插件的包里读(市场装的也是 npm 包),不联网。
|
|
1517
|
+
route('/dsh-modpack-kit/api/plugins/icon', (req, res) => {
|
|
1518
|
+
if (req.method !== 'GET') { json(res, 405, { ok: false, error: '只支持 GET' }); return }
|
|
1519
|
+
let name = ''
|
|
1520
|
+
try {
|
|
1521
|
+
const url = new URL(String(req.url || '/'), 'http://dsh.local')
|
|
1522
|
+
name = String(url.searchParams.get('name') || '').trim()
|
|
1523
|
+
} catch { name = '' }
|
|
1524
|
+
if (!isValidPluginName(name)) { json(res, 400, { ok: false, error: '插件名不合法' }); return }
|
|
1525
|
+
try {
|
|
1526
|
+
const icon = pluginIcon(profileDir(), name)
|
|
1527
|
+
json(res, 200, { ok: true, name: icon.name, mime: icon.mime, file: icon.file, size: icon.size, dataUrl: 'data:' + icon.mime + ';base64,' + icon.base64 })
|
|
1528
|
+
} catch (error) {
|
|
1529
|
+
json(res, 404, { ok: false, name, error: String((error && error.message) || error) })
|
|
1530
|
+
}
|
|
1531
|
+
})
|
|
1532
|
+
|
|
1533
|
+
// 一键更新:可更新 + 启用中 + 不是按路径装的,才算进来;停用的一律不跟着批量动。
|
|
1534
|
+
route('/dsh-modpack-kit/api/plugins/update-all', async (req, res) => {
|
|
1535
|
+
if (!needPost(req, res)) return
|
|
1536
|
+
const body = await readJsonBody(req)
|
|
1537
|
+
const dir = profileDir()
|
|
1538
|
+
let items = []
|
|
1539
|
+
try { items = listManaged(dir, config).items } catch (error) {
|
|
1540
|
+
json(res, 500, { ok: false, error: String((error && error.message) || error) })
|
|
1541
|
+
return
|
|
1542
|
+
}
|
|
1543
|
+
const wanted = Array.isArray(body.names) ? body.names.map((name) => String(name || '').trim()).filter(Boolean) : []
|
|
1544
|
+
let targets = updatableItems(items)
|
|
1545
|
+
if (wanted.length) targets = targets.filter((item) => wanted.includes(item.name))
|
|
1546
|
+
if (!targets.length) {
|
|
1547
|
+
json(res, 400, {
|
|
1548
|
+
ok: false,
|
|
1549
|
+
error: '没有可更新的插件',
|
|
1550
|
+
hint: '停用的插件、按路径装的插件不在一键更新里;要单独更新请用行尾的「更新」。',
|
|
1551
|
+
})
|
|
1552
|
+
return
|
|
1553
|
+
}
|
|
1554
|
+
const job = createJob('update', '一键更新 ' + targets.length + ' 个插件')
|
|
1555
|
+
if (testModeOn(config)) {
|
|
1556
|
+
const skipped = items.filter((item) => item.hasUpdate && updatableItems([item]).length === 0).map((item) => item.name)
|
|
1557
|
+
playTestJob(job, testStepsFor('update'), {
|
|
1558
|
+
action: '更新',
|
|
1559
|
+
cancelled: () => Boolean(job.cancelled),
|
|
1560
|
+
data: { updated: targets.map((item) => ({ name: item.name, from: item.version, to: item.latest })), failed: [], skipped },
|
|
1561
|
+
})
|
|
1562
|
+
json(res, 200, { ok: true, job: publicJob(job), names: targets.map((item) => item.name), test: true })
|
|
1563
|
+
return
|
|
1564
|
+
}
|
|
1565
|
+
job.steps = targets.map((item) => ({ key: item.name, label: item.name + (item.latest ? ' → ' + item.latest : ''), state: 'pending', note: '' }))
|
|
1566
|
+
job.note = '准备更新 ' + targets.length + ' 个插件'
|
|
1567
|
+
job.data = { names: targets.map((item) => item.name), skipped: items.filter((item) => item.hasUpdate && !updatableItems([item]).length).map((item) => item.name) }
|
|
1568
|
+
json(res, 200, { ok: true, job: publicJob(job), names: targets.map((item) => item.name) })
|
|
1569
|
+
;(async () => {
|
|
1570
|
+
let current = ''
|
|
1571
|
+
try {
|
|
1572
|
+
const result = await updatePlugins({
|
|
1573
|
+
profileDir: dir,
|
|
1574
|
+
profile: profileName(config),
|
|
1575
|
+
config,
|
|
1576
|
+
targets: targets.map((item) => ({ name: item.name, latest: item.latest })),
|
|
1577
|
+
isCancelled: () => Boolean(job.cancelled),
|
|
1578
|
+
onProgress: (info) => {
|
|
1579
|
+
if (job.cancelled) return
|
|
1580
|
+
job.pct = Math.max(job.pct || 0, Number(info.pct) || 0)
|
|
1581
|
+
job.note = String(info.note || job.note)
|
|
1582
|
+
job.updatedAt = new Date().toISOString()
|
|
1583
|
+
if (info.step && info.step !== current) {
|
|
1584
|
+
const at = job.steps.findIndex((step) => step.key === info.step)
|
|
1585
|
+
if (at >= 0) {
|
|
1586
|
+
job.steps.forEach((step, index) => {
|
|
1587
|
+
if (index < at && step.state !== 'done' && step.state !== 'failed') step.state = 'done'
|
|
1588
|
+
})
|
|
1589
|
+
const row = job.steps[at]
|
|
1590
|
+
if (row.state === 'pending') row.state = 'running'
|
|
1591
|
+
}
|
|
1592
|
+
current = info.step
|
|
1593
|
+
}
|
|
1594
|
+
},
|
|
1595
|
+
})
|
|
1596
|
+
const failedNames = new Set((result.results || []).filter((row) => !row.ok).map((row) => row.name))
|
|
1597
|
+
job.steps = job.steps.map((step) => (
|
|
1598
|
+
failedNames.has(step.key)
|
|
1599
|
+
? { ...step, state: 'failed', note: ((result.results || []).find((row) => row.name === step.key) || {}).error || '' }
|
|
1600
|
+
: { ...step, state: 'done' }
|
|
1601
|
+
))
|
|
1602
|
+
job.cancelled = false
|
|
1603
|
+
job.status = 'done'
|
|
1604
|
+
job.pct = 100
|
|
1605
|
+
job.note = result.failed ? '更新完成,' + result.failed + ' 个没成功(点开看原因)' : '全部更新完成(' + result.updated + ' 个)'
|
|
1606
|
+
job.data = { ...result, skipped: (job.data && job.data.skipped) || [] }
|
|
1607
|
+
} catch (error) {
|
|
1608
|
+
const message = String((error && error.message) || error)
|
|
1609
|
+
const running = job.steps.find((step) => step.state === 'running')
|
|
1610
|
+
if (running) { running.state = 'failed'; running.note = message.slice(0, 200) }
|
|
1611
|
+
job.status = job.cancelled ? 'cancelled' : 'failed'
|
|
1612
|
+
job.error = message
|
|
1613
|
+
job.note = job.cancelled ? '已取消' : message.slice(0, 160)
|
|
1614
|
+
} finally {
|
|
1615
|
+
job.finishedAt = new Date().toISOString()
|
|
1616
|
+
job.updatedAt = job.finishedAt
|
|
1617
|
+
}
|
|
1618
|
+
})()
|
|
1619
|
+
})
|
|
1620
|
+
|
|
1621
|
+
route('/dsh-modpack-kit/api/plugins/reinstall', async (req, res) => {
|
|
1622
|
+
if (!needPost(req, res)) return
|
|
1623
|
+
const body = await readJsonBody(req)
|
|
1624
|
+
const name = typeof body.name === 'string' ? body.name.trim() : ''
|
|
1625
|
+
if (!isValidPluginName(name)) { json(res, 400, { ok: false, error: '插件名不合法' }); return }
|
|
1626
|
+
const wanted = typeof body.version === 'string' ? body.version.trim() : ''
|
|
1627
|
+
if (wanted && !isValidVersion(wanted)) { json(res, 400, { ok: false, error: '版本号要给完整 semver(例如 1.2.3)' }); return }
|
|
1628
|
+
const keepConfig = body.keepConfig !== false
|
|
1629
|
+
const dir = profileDir()
|
|
1630
|
+
let current = null
|
|
1631
|
+
try {
|
|
1632
|
+
current = listManaged(dir, config).items.find((item) => item.name === name) || null
|
|
1633
|
+
} catch { current = null }
|
|
1634
|
+
if (!current) { json(res, 404, { ok: false, error: '本机没有这个插件:' + name }); return }
|
|
1635
|
+
const target = wanted || resolveReinstallVersion(current)
|
|
1636
|
+
const job = createJob('reinstall', '重装 ' + name + (target ? '@' + target : ''))
|
|
1637
|
+
const plan = [
|
|
1638
|
+
['read', '读取当前状态'],
|
|
1639
|
+
['config', keepConfig ? '保留本机配置' : '清掉本机配置'],
|
|
1640
|
+
['remove', '卸载旧版本'],
|
|
1641
|
+
['install', '安装' + (target ? ' ' + target : ' 最新版')],
|
|
1642
|
+
['restore', '恢复启用状态'],
|
|
1643
|
+
['done', '收尾'],
|
|
1644
|
+
]
|
|
1645
|
+
job.steps = plan.map(([key, label]) => ({ key, label, state: 'pending', note: '' }))
|
|
1646
|
+
job.note = '准备重装 ' + name
|
|
1647
|
+
const markStep = (key) => {
|
|
1648
|
+
const at = job.steps.findIndex((step) => step.key === key)
|
|
1649
|
+
if (at < 0) return
|
|
1650
|
+
job.steps.forEach((step, index) => {
|
|
1651
|
+
if (index < at && step.state !== 'done') step.state = 'done'
|
|
1652
|
+
if (index === at && step.state === 'pending') step.state = 'running'
|
|
1653
|
+
})
|
|
1654
|
+
}
|
|
1655
|
+
if (testModeOn(config)) {
|
|
1656
|
+
// 测试模式:步骤清单照旧显示,但一条也不执行(不卸载、不安装、不动配置)
|
|
1657
|
+
playTestJob(job, testStepsFor('reinstall'), { action: '重装', cancelled: () => Boolean(job.cancelled), data: { name, target, keepConfig } })
|
|
1658
|
+
json(res, 200, { ok: true, job: publicJob(job), target, test: true })
|
|
1659
|
+
return
|
|
1660
|
+
}
|
|
1661
|
+
json(res, 200, { ok: true, job: publicJob(job), target })
|
|
1662
|
+
;(async () => {
|
|
1663
|
+
try {
|
|
1664
|
+
const result = await reinstallPlugin({
|
|
1665
|
+
profileDir: dir,
|
|
1666
|
+
profile: profileName(config),
|
|
1667
|
+
name,
|
|
1668
|
+
version: target || undefined,
|
|
1669
|
+
keepConfig,
|
|
1670
|
+
config,
|
|
1671
|
+
isCancelled: () => Boolean(job.cancelled),
|
|
1672
|
+
onProgress: (info) => {
|
|
1673
|
+
if (job.cancelled) return
|
|
1674
|
+
job.pct = Math.max(job.pct || 0, Number(info.pct) || 0)
|
|
1675
|
+
job.note = String(info.note || job.note)
|
|
1676
|
+
job.updatedAt = new Date().toISOString()
|
|
1677
|
+
if (info.step) markStep(info.step)
|
|
1678
|
+
},
|
|
1679
|
+
})
|
|
1680
|
+
// 插件已经装回来了:这时候即便点过取消也不能报取消,不然人会以为没装
|
|
1681
|
+
const wasCancelled = Boolean(job.cancelled)
|
|
1682
|
+
job.cancelled = false
|
|
1683
|
+
job.steps = job.steps.map((step) => ({ ...step, state: step.state === 'pending' || step.state === 'running' ? 'done' : step.state }))
|
|
1684
|
+
job.status = 'done'
|
|
1685
|
+
job.pct = 100
|
|
1686
|
+
job.note = '已重装 ' + name + (result.toVersion ? ' → ' + result.toVersion : '') + (wasCancelled ? '(中途点了取消,但已经装回来了)' : '')
|
|
1687
|
+
job.data = result
|
|
1688
|
+
} catch (error) {
|
|
1689
|
+
const message = String((error && error.message) || error)
|
|
1690
|
+
const cancelled = Boolean(job.cancelled) || /已取消/u.test(message)
|
|
1691
|
+
const running = job.steps.find((step) => step.state === 'running')
|
|
1692
|
+
if (running) {
|
|
1693
|
+
running.state = cancelled ? 'cancelled' : 'failed'
|
|
1694
|
+
running.note = message.slice(0, 200)
|
|
1695
|
+
}
|
|
1696
|
+
job.status = cancelled ? 'cancelled' : 'failed'
|
|
1697
|
+
job.error = message
|
|
1698
|
+
job.note = cancelled ? '已取消' : message.slice(0, 160)
|
|
1699
|
+
} finally {
|
|
1700
|
+
job.finishedAt = new Date().toISOString()
|
|
1701
|
+
job.updatedAt = job.finishedAt
|
|
1702
|
+
}
|
|
1703
|
+
})()
|
|
1704
|
+
})
|
|
1705
|
+
|
|
824
1706
|
route('/dsh-modpack-kit/api/pack', async (req, res) => {
|
|
825
1707
|
if (!needPost(req, res)) return
|
|
826
1708
|
const body = await readJsonBody(req)
|
|
@@ -840,6 +1722,10 @@ export default {
|
|
|
840
1722
|
json(res, 200, { ok: true, async: true, job: publicJob(job) })
|
|
841
1723
|
return
|
|
842
1724
|
}
|
|
1725
|
+
if (testModeOn(config)) {
|
|
1726
|
+
json(res, 200, { ok: true, test: true, note: testNote('打包'), selection: [], groups: [] })
|
|
1727
|
+
return
|
|
1728
|
+
}
|
|
843
1729
|
const payload = await performPack(body, null)
|
|
844
1730
|
json(res, 200, payload)
|
|
845
1731
|
})
|
|
@@ -945,6 +1831,19 @@ export default {
|
|
|
945
1831
|
route('/dsh-modpack-kit/api/download', async (req, res) => {
|
|
946
1832
|
if (!needPost(req, res)) return
|
|
947
1833
|
const body = await readJsonBody(req)
|
|
1834
|
+
const safeName0 = String(body.fileName || 'pack.dshpack').replace(/[^\w.\-]+/gu, '_')
|
|
1835
|
+
if (testModeOn(config)) {
|
|
1836
|
+
// 测试模式:不吐真实包体,给一份能存下来的占位文件,保存对话框、文件名、大小照走
|
|
1837
|
+
const fake = Buffer.from('测试模式:这份「' + safeName0 + '」只是流程占位,里面没有真的整合包数据。\n', 'utf8')
|
|
1838
|
+
res.writeHead(200, {
|
|
1839
|
+
'Content-Type': 'application/octet-stream',
|
|
1840
|
+
'Content-Disposition': 'attachment; filename="' + safeName0 + '"',
|
|
1841
|
+
'Content-Length': fake.length,
|
|
1842
|
+
'Cache-Control': 'no-store',
|
|
1843
|
+
})
|
|
1844
|
+
res.end(fake)
|
|
1845
|
+
return
|
|
1846
|
+
}
|
|
948
1847
|
const item = pending.get(String(body.token || ''))
|
|
949
1848
|
if (!item) { json(res, 404, { ok: false, error: '打包结果已过期,请重新打包' }); return }
|
|
950
1849
|
const safeName = String(body.fileName || item.fileName || 'pack.dshpack').replace(/[^\w.\-]+/gu, '_')
|
|
@@ -960,6 +1859,11 @@ export default {
|
|
|
960
1859
|
route('/dsh-modpack-kit/api/save', async (req, res) => {
|
|
961
1860
|
if (!needPost(req, res)) return
|
|
962
1861
|
const body = await readJsonBody(req)
|
|
1862
|
+
if (testModeOn(config)) {
|
|
1863
|
+
const fakeName = slugify(body.fileName || 'test-pack', 'pack') + '.dshpack'
|
|
1864
|
+
json(res, 200, { ok: true, test: true, note: testNote('保存'), path: path.join(pathsFor(config).packs, fakeName), size: 0 })
|
|
1865
|
+
return
|
|
1866
|
+
}
|
|
963
1867
|
const item = pending.get(String(body.token || ''))
|
|
964
1868
|
if (!item) { json(res, 404, { ok: false, error: '打包结果已过期,请重新打包' }); return }
|
|
965
1869
|
const paths = pathsFor(config)
|
|
@@ -1011,6 +1915,50 @@ export default {
|
|
|
1011
1915
|
json(res, 200, { ok: !listed.error, dir, items: listed.items, error: listed.error })
|
|
1012
1916
|
})
|
|
1013
1917
|
|
|
1918
|
+
// 打开插件自己的 packs 目录(设置里那个按钮)
|
|
1919
|
+
route('/dsh-modpack-kit/api/packs/open', async (req, res) => {
|
|
1920
|
+
if (!needPost(req, res)) return
|
|
1921
|
+
const dir = pathsFor(config).packs
|
|
1922
|
+
try {
|
|
1923
|
+
ensureDir(dir)
|
|
1924
|
+
if (process.platform === 'win32') spawn('explorer.exe', [dir], { detached: true, stdio: 'ignore' }).unref()
|
|
1925
|
+
else if (process.platform === 'darwin') spawn('open', [dir], { detached: true, stdio: 'ignore' }).unref()
|
|
1926
|
+
else spawn('xdg-open', [dir], { detached: true, stdio: 'ignore' }).unref()
|
|
1927
|
+
} catch (e) {
|
|
1928
|
+
json(res, 500, { ok: false, error: '打不开目录:' + ((e && e.message) || e) })
|
|
1929
|
+
return
|
|
1930
|
+
}
|
|
1931
|
+
json(res, 200, { ok: true, dir })
|
|
1932
|
+
})
|
|
1933
|
+
// 删掉插件自己 packs 目录里的一个包(安装页「已下载」那张卡用)
|
|
1934
|
+
route('/dsh-modpack-kit/api/packs/remove', async (req, res) => {
|
|
1935
|
+
if (!needPost(req, res)) return
|
|
1936
|
+
const body = await readJsonBody(req)
|
|
1937
|
+
const raw = String(body.name || '').trim()
|
|
1938
|
+
// 只认「纯粹的文件名」:带目录、带 .. 一律拒,别让它变成越界删除
|
|
1939
|
+
if (!raw || raw !== path.basename(raw) || /[\\/]/u.test(raw) || !raw.toLowerCase().endsWith('.dshpack')) {
|
|
1940
|
+
json(res, 400, { ok: false, error: '只删 packs 目录里的 .dshpack 文件名(不能带路径)' })
|
|
1941
|
+
return
|
|
1942
|
+
}
|
|
1943
|
+
const name = raw
|
|
1944
|
+
const dir = pathsFor(config).packs
|
|
1945
|
+
if (testModeOn(config)) {
|
|
1946
|
+
json(res, 200, { ok: true, test: true, note: testNote('删除安装包'), dir, items: listPacks(dir).items })
|
|
1947
|
+
return
|
|
1948
|
+
}
|
|
1949
|
+
const target = path.join(dir, name)
|
|
1950
|
+
if (path.dirname(target) !== path.resolve(dir)) { json(res, 400, { ok: false, error: '不在插件自己的 packs 目录里' }); return }
|
|
1951
|
+
try {
|
|
1952
|
+
fs.rmSync(target, { force: true })
|
|
1953
|
+
appendLog('packs remove ' + name)
|
|
1954
|
+
} catch (e) {
|
|
1955
|
+
json(res, 500, { ok: false, error: String((e && e.message) || e) })
|
|
1956
|
+
return
|
|
1957
|
+
}
|
|
1958
|
+
const listed = listPacks(dir)
|
|
1959
|
+
json(res, 200, { ok: true, dir, items: listed.items, error: listed.error })
|
|
1960
|
+
})
|
|
1961
|
+
|
|
1014
1962
|
// 拖到界面上的整合包:原始字节能走就走原始字节,走不通再走 base64 JSON
|
|
1015
1963
|
route('/dsh-modpack-kit/api/pack/drop', async (req, res) => {
|
|
1016
1964
|
if (!needPost(req, res)) return
|
|
@@ -1231,7 +2179,35 @@ export default {
|
|
|
1231
2179
|
}
|
|
1232
2180
|
push(4, '读取整合包')
|
|
1233
2181
|
const inspected = await inspectInput(body)
|
|
1234
|
-
|
|
2182
|
+
if (testModeOn(config)) {
|
|
2183
|
+
// 测试模式:包是真读的(校验 / 扫描 / 清单都照跑,只读不写),安装这一步只演
|
|
2184
|
+
if (job) {
|
|
2185
|
+
await playTestJob(job, testStepsFor('install'), { action: '安装', cancelled: () => Boolean(job.cancelled), data: { manifest: inspected.manifest && inspected.manifest.name, items: [] } })
|
|
2186
|
+
}
|
|
2187
|
+
return {
|
|
2188
|
+
ok: true,
|
|
2189
|
+
test: true,
|
|
2190
|
+
note: testNote('安装'),
|
|
2191
|
+
actions: [],
|
|
2192
|
+
manifest: inspected.manifest,
|
|
2193
|
+
scan: inspected.scan,
|
|
2194
|
+
integrity: inspected.integrity,
|
|
2195
|
+
report: inspected.report,
|
|
2196
|
+
}
|
|
2197
|
+
}
|
|
2198
|
+
const payload = await runInstall(inspected, body, job)
|
|
2199
|
+
// 装完按设置把这份安装包清掉:只删插件自己 packs 目录里的文件,别的路径不碰
|
|
2200
|
+
if (payload && payload.ok && config.autoClearPack === true) {
|
|
2201
|
+
const want = String(body.sourcePackFile || '')
|
|
2202
|
+
const packsDir = path.resolve(pathsFor(config).packs)
|
|
2203
|
+
if (want) {
|
|
2204
|
+
const target = path.resolve(want)
|
|
2205
|
+
if (path.dirname(target) === packsDir && target.toLowerCase().endsWith('.dshpack')) {
|
|
2206
|
+
try { fs.rmSync(target, { force: true }); appendLog('auto clear pack ' + path.basename(target)) } catch (e) { appendLog('auto clear failed: ' + ((e && e.message) || e)) }
|
|
2207
|
+
}
|
|
2208
|
+
}
|
|
2209
|
+
}
|
|
2210
|
+
return payload
|
|
1235
2211
|
} catch (error) {
|
|
1236
2212
|
if (error instanceof JobCancelled) return { ok: false, cancelled: true, error: '已取消(没有改动 profile)' }
|
|
1237
2213
|
return { ok: false, error: String((error && error.message) || error) }
|
|
@@ -1353,6 +2329,23 @@ export default {
|
|
|
1353
2329
|
return catalogJob
|
|
1354
2330
|
}
|
|
1355
2331
|
|
|
2332
|
+
// ---- 一键上传:GitHub 凭据只存本机,不进 settings,也不会被抽进整合包 ----
|
|
2333
|
+
const UPLOAD_REPO = 'Vesna-Strivozha-cn/dsh-modpack-catalog'
|
|
2334
|
+
const UPLOAD_MAX_BYTES = 32 * 1024 * 1024
|
|
2335
|
+
// 凭据只在内存里活着:不落盘、不进 settings、不进日志。
|
|
2336
|
+
// 每次上传都要重新填一次;上传结束(成功或失败)立刻丢掉。
|
|
2337
|
+
let uploadToken = ''
|
|
2338
|
+
let uploadWho = null
|
|
2339
|
+
const setUploadToken = (token) => {
|
|
2340
|
+
uploadToken = String(token || '').trim()
|
|
2341
|
+
if (!uploadToken) uploadWho = null
|
|
2342
|
+
}
|
|
2343
|
+
const clearUploadToken = () => {
|
|
2344
|
+
uploadToken = ''
|
|
2345
|
+
uploadWho = null
|
|
2346
|
+
}
|
|
2347
|
+
const readUploadToken = () => uploadToken
|
|
2348
|
+
|
|
1356
2349
|
// 社区资源也照这个套路:启动补一次、过期在后台补、十分钟内失败不重敲
|
|
1357
2350
|
let marketJob = null
|
|
1358
2351
|
let lastMarketTry = 0
|