@auto-mas/auto-mas-plugin-adapter-bettergi 0.2.0 → 0.2.2
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/dist/server/adapters.js +23 -9
- package/dist/server/builtin-plugins/adapter-bettergi.js +2 -1
- package/dist/server/community/vault.js +65 -0
- package/dist/server/execution.js +111 -30
- package/dist/server/features.js +31 -0
- package/dist/server/game-plugins/bettergi.js +44 -5
- package/dist/server/game-plugins/native-config.js +275 -0
- package/dist/server/maa/account-settings.js +73 -0
- package/dist/server/maa/project.js +27 -9
- package/package.json +9 -1
- package/dist/server/storage.js +0 -76
package/dist/server/adapters.js
CHANGED
|
@@ -3,6 +3,7 @@ import { isAbsolute } from 'node:path';
|
|
|
3
3
|
import { stat } from 'node:fs/promises';
|
|
4
4
|
import { Runner, runProcess } from './execution.js';
|
|
5
5
|
import { generalResultRules, withGeneralResult } from './general-result.js';
|
|
6
|
+
import { applyMaaAccountSettings, maaAccountFields } from './maa/account-settings.js';
|
|
6
7
|
export function optionalText(value) { return typeof value === 'string' ? value.trim() : ''; }
|
|
7
8
|
export function textList(value) {
|
|
8
9
|
if (!value)
|
|
@@ -130,18 +131,31 @@ export async function prepareMaa(input) {
|
|
|
130
131
|
return { projectPath, controller, resource, preset, tasks, projectOptions, agentPython, agentNodeRoot, nativePython, nativeLibraries, address: optionalText(input.address) || undefined,
|
|
131
132
|
adbPath: optionalText(input.adbPath) || undefined, windowHandle: input.windowHandle ? Number(input.windowHandle) : undefined };
|
|
132
133
|
}
|
|
134
|
+
export function maaRunInput(config, plannedTasks) {
|
|
135
|
+
const tasks = textList(plannedTasks ?? config.tasks);
|
|
136
|
+
return {
|
|
137
|
+
projectPath: optionalText(config.projectPath), controller: optionalText(config.controller) || undefined,
|
|
138
|
+
resource: optionalText(config.resource) || undefined, preset: optionalText(config.preset) || undefined, tasks: tasks.length ? tasks : undefined,
|
|
139
|
+
adbPath: optionalText(config.adbPath) || undefined, address: optionalText(config.address) || undefined,
|
|
140
|
+
adbServerPort: typeof config.adbServerPort === 'number' ? config.adbServerPort : undefined, agentPython: optionalText(config.agentPython) || undefined,
|
|
141
|
+
agentNodeRoot: optionalText(config.agentNodeRoot) || undefined,
|
|
142
|
+
nativePython: optionalText(config.nativePython) || undefined, nativeLibraries: optionalText(config.nativeLibraries) || undefined,
|
|
143
|
+
windowHandle: config.windowHandle, options: config.projectOptions,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
133
146
|
const runMaaProject = async (script, config) => {
|
|
134
147
|
const { runMaaSelected } = await import('./maa/native-runtime.js');
|
|
135
|
-
const
|
|
136
|
-
await runMaaSelected(
|
|
137
|
-
resource: optionalText(script.resource) || undefined, preset: optionalText(script.preset) || undefined, tasks: tasks?.length ? tasks : undefined,
|
|
138
|
-
adbPath: optionalText(script.adbPath) || undefined, address: optionalText(script.address) || undefined,
|
|
139
|
-
adbServerPort: typeof script.adbServerPort === 'number' ? script.adbServerPort : undefined, agentPython: optionalText(script.agentPython) || undefined,
|
|
140
|
-
agentNodeRoot: optionalText(script.agentNodeRoot) || undefined,
|
|
141
|
-
nativePython: optionalText(script.nativePython) || undefined, nativeLibraries: optionalText(script.nativeLibraries) || undefined,
|
|
142
|
-
windowHandle: script.windowHandle, options: script.projectOptions }, config);
|
|
148
|
+
const input = applyMaaAccountSettings(maaRunInput(script), script.accountConfig ?? {});
|
|
149
|
+
await runMaaSelected(input, config);
|
|
143
150
|
};
|
|
144
151
|
export const runtimeAdapters = [general, {
|
|
145
152
|
id: 'maafw', title: 'MaaFramework', description: '通过官方 Node SDK 运行 ProjectInterface V2 项目。', group: '通用',
|
|
146
|
-
scriptFields: maaFields, usesPlan: true, prepare: prepareMaa, run: runMaaProject,
|
|
153
|
+
scriptFields: maaFields, accountFields: maaAccountFields('maafw'), usesPlan: true, prepare: prepareMaa, run: runMaaProject,
|
|
154
|
+
async validateAccount(script, account) {
|
|
155
|
+
if (!Object.keys(account).length)
|
|
156
|
+
return;
|
|
157
|
+
const input = applyMaaAccountSettings(maaRunInput(script), account);
|
|
158
|
+
const { loadProject, planRun } = await import('./maa/project.js');
|
|
159
|
+
planRun(await loadProject(input.projectPath), input);
|
|
160
|
+
},
|
|
147
161
|
}];
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { adapterFeature } from '../adapters.js';
|
|
2
|
-
import { bettergi, betterGiProfiles } from '../game-plugins/bettergi.js';
|
|
2
|
+
import { bettergi, betterGiGroups, betterGiProfiles } from '../game-plugins/bettergi.js';
|
|
3
3
|
import { scopedProfileOptions } from '../game-plugins/profile-options.js';
|
|
4
4
|
export default function createFeature() {
|
|
5
5
|
return adapterFeature(bettergi, { icon: new URL('./icons/bettergi.png', import.meta.url), apply(ctx) {
|
|
6
6
|
scopedProfileOptions(ctx, bettergi.id, 'bettergi.profiles', betterGiProfiles);
|
|
7
|
+
scopedProfileOptions(ctx, bettergi.id, 'bettergi.groups', betterGiGroups);
|
|
7
8
|
} });
|
|
8
9
|
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
|
|
2
|
+
import { lstat, readFile, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
export class CredentialVault {
|
|
5
|
+
path;
|
|
6
|
+
namespace;
|
|
7
|
+
pending;
|
|
8
|
+
constructor(dataDir, scope = 'community') {
|
|
9
|
+
this.path = join(dataDir, scope === 'community' ? '.community-key' : '.plugin-config-key');
|
|
10
|
+
this.namespace = scope === 'community' ? 'Cordis MAS community sign-in v1:cloud-genshin' : 'AUTO-MASC plugin configuration v1';
|
|
11
|
+
}
|
|
12
|
+
async load(create) {
|
|
13
|
+
try {
|
|
14
|
+
const info = await lstat(this.path);
|
|
15
|
+
if (!info.isFile() || info.size !== 32 || (process.platform !== 'win32' && (info.mode & 0o077) !== 0)) {
|
|
16
|
+
throw new Error('本机加密密钥文件无效或权限过宽');
|
|
17
|
+
}
|
|
18
|
+
return await readFile(this.path);
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
if (error.code !== 'ENOENT')
|
|
22
|
+
throw error;
|
|
23
|
+
if (!create)
|
|
24
|
+
throw new Error('找不到本机加密密钥,请重新配置');
|
|
25
|
+
const key = randomBytes(32);
|
|
26
|
+
try {
|
|
27
|
+
await writeFile(this.path, key, { flag: 'wx', mode: 0o600 });
|
|
28
|
+
}
|
|
29
|
+
catch (writeError) {
|
|
30
|
+
if (writeError.code !== 'EEXIST')
|
|
31
|
+
throw writeError;
|
|
32
|
+
return this.load(false);
|
|
33
|
+
}
|
|
34
|
+
return key;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
key(create) {
|
|
38
|
+
this.pending ??= this.load(create).catch(error => { this.pending = undefined; throw error; });
|
|
39
|
+
return this.pending;
|
|
40
|
+
}
|
|
41
|
+
context(id) {
|
|
42
|
+
return Buffer.from(`${this.namespace}:${id}`);
|
|
43
|
+
}
|
|
44
|
+
async seal(id, secret) {
|
|
45
|
+
const nonce = randomBytes(12);
|
|
46
|
+
const cipher = createCipheriv('aes-256-gcm', await this.key(true), nonce);
|
|
47
|
+
cipher.setAAD(this.context(id));
|
|
48
|
+
const data = Buffer.concat([cipher.update(secret, 'utf8'), cipher.final()]);
|
|
49
|
+
return { version: 1, nonce: nonce.toString('base64'), cipher: data.toString('base64'), tag: cipher.getAuthTag().toString('base64') };
|
|
50
|
+
}
|
|
51
|
+
async reveal(id, secret) {
|
|
52
|
+
const key = await this.key(false);
|
|
53
|
+
try {
|
|
54
|
+
if (secret.version !== 1)
|
|
55
|
+
throw new Error('Unrecognized credential');
|
|
56
|
+
const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(secret.nonce, 'base64'), { authTagLength: 16 });
|
|
57
|
+
decipher.setAAD(this.context(id));
|
|
58
|
+
decipher.setAuthTag(Buffer.from(secret.tag, 'base64'));
|
|
59
|
+
return Buffer.concat([decipher.update(Buffer.from(secret.cipher, 'base64')), decipher.final()]).toString('utf8');
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
throw new Error('无法解密本机配置,请重新配置');
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
package/dist/server/execution.js
CHANGED
|
@@ -3,7 +3,6 @@ import { randomUUID } from 'node:crypto';
|
|
|
3
3
|
import { realpathSync } from 'node:fs';
|
|
4
4
|
import { resolve, sep } from 'node:path';
|
|
5
5
|
import { createInterface } from 'node:readline';
|
|
6
|
-
import { Store } from './storage.js';
|
|
7
6
|
import { runPhases } from './run-lifecycle.js';
|
|
8
7
|
export function forAccount(store, script, account) {
|
|
9
8
|
if (account.scriptId !== script.id || account.enabled === false)
|
|
@@ -112,26 +111,42 @@ export class Runner {
|
|
|
112
111
|
finished;
|
|
113
112
|
options;
|
|
114
113
|
lifecycle;
|
|
115
|
-
|
|
114
|
+
persistence;
|
|
115
|
+
constructor(store, changed, finished = () => { }, options = {}, lifecycle = {}, persistence) {
|
|
116
116
|
this.store = store;
|
|
117
117
|
this.changed = changed;
|
|
118
118
|
this.finished = finished;
|
|
119
119
|
this.options = options;
|
|
120
120
|
this.lifecycle = lifecycle;
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
const
|
|
124
|
-
|
|
125
|
-
for (const stage of runPhases) {
|
|
126
|
-
const last = stages.findLast(event => event.stage === stage);
|
|
127
|
-
if (last && last.status !== 'started')
|
|
128
|
-
continue;
|
|
129
|
-
const status = last || stage === 'finish-task' ? 'failed' : 'skipped';
|
|
130
|
-
stages.push({ runId: run.id, scriptId: run.scriptId, adapter, sequence: stages.length + 1, stage, status, at: finished,
|
|
131
|
-
message: stage === 'finish-task' ? '上次运行中断,未能确认清理' : '上次运行中断' });
|
|
121
|
+
this.persistence = persistence;
|
|
122
|
+
if (!persistence)
|
|
123
|
+
for (const run of this.store.list('runs').filter(run => run.status === 'running')) {
|
|
124
|
+
this.store.put('runs', this.interrupted(run, this.store.get('scripts', run.scriptId)));
|
|
132
125
|
}
|
|
133
|
-
|
|
126
|
+
}
|
|
127
|
+
interrupted(run, script) {
|
|
128
|
+
const finished = new Date().toISOString();
|
|
129
|
+
const stages = [...(run.stages ?? [])];
|
|
130
|
+
const adapter = stages[0]?.adapter ?? script?.adapter ?? 'unknown';
|
|
131
|
+
for (const stage of runPhases) {
|
|
132
|
+
const last = stages.findLast(event => event.stage === stage);
|
|
133
|
+
if (last && last.status !== 'started')
|
|
134
|
+
continue;
|
|
135
|
+
const status = last || stage === 'finish-task' ? 'failed' : 'skipped';
|
|
136
|
+
stages.push({ runId: run.id, scriptId: run.scriptId, adapter, sequence: stages.length + 1, stage, status, at: finished,
|
|
137
|
+
message: stage === 'finish-task' ? '上次运行中断,未能确认清理' : '上次运行中断' });
|
|
134
138
|
}
|
|
139
|
+
return { ...run, stages, status: 'error', error: '上次运行中断', finished };
|
|
140
|
+
}
|
|
141
|
+
async recoverInterrupted() {
|
|
142
|
+
if (!this.persistence)
|
|
143
|
+
return;
|
|
144
|
+
const { database } = this.persistence;
|
|
145
|
+
await database.transaction(async (tx) => {
|
|
146
|
+
const runs = await tx.list('runs', { where: { status: 'running' } });
|
|
147
|
+
for (const run of runs)
|
|
148
|
+
await tx.put('runs', this.interrupted(run, await tx.get('scripts', run.scriptId)));
|
|
149
|
+
});
|
|
135
150
|
}
|
|
136
151
|
register(id, execute) {
|
|
137
152
|
if (this.owners.has(id))
|
|
@@ -166,6 +181,19 @@ export class Runner {
|
|
|
166
181
|
};
|
|
167
182
|
}
|
|
168
183
|
start(input) {
|
|
184
|
+
const { run, done } = this.startRun(input);
|
|
185
|
+
return { run, done };
|
|
186
|
+
}
|
|
187
|
+
async startAsync(input, mayStart) {
|
|
188
|
+
if (mayStart && !mayStart())
|
|
189
|
+
throw new Error('运行请求已失效');
|
|
190
|
+
if (!this.persistence)
|
|
191
|
+
return this.start(input);
|
|
192
|
+
const { run, done, ready } = this.startRun(input, this.persistence.database, mayStart);
|
|
193
|
+
await ready;
|
|
194
|
+
return { run, done };
|
|
195
|
+
}
|
|
196
|
+
startRun(input, database, mayStart) {
|
|
169
197
|
if (!this.accepting)
|
|
170
198
|
throw new Error('执行服务正在退出');
|
|
171
199
|
if (this.startsPaused)
|
|
@@ -194,7 +222,8 @@ export class Runner {
|
|
|
194
222
|
throw new Error('脚本、工作目录或设备已被占用');
|
|
195
223
|
const run = { id: randomUUID(), name: script.name, scriptId: script.id, status: 'running', started: new Date().toISOString(), logs: [], stages: [],
|
|
196
224
|
workflow: script.workflow && Object.freeze(script.workflow), executionTarget: script.executionTarget };
|
|
197
|
-
|
|
225
|
+
if (!database)
|
|
226
|
+
this.store.put('runs', run);
|
|
198
227
|
keys.forEach(key => this.claimed.add(key));
|
|
199
228
|
const claimAdb = (address, serverPort) => {
|
|
200
229
|
const key = serverPort && serverPort !== 5037 ? `adb:${serverPort}:${address.trim().toLowerCase()}` : `adb:${address.trim().toLowerCase()}`;
|
|
@@ -206,17 +235,38 @@ export class Runner {
|
|
|
206
235
|
this.claimed.add(key);
|
|
207
236
|
};
|
|
208
237
|
const controller = new AbortController();
|
|
209
|
-
|
|
238
|
+
let released = false;
|
|
239
|
+
const release = () => {
|
|
240
|
+
if (released)
|
|
241
|
+
return;
|
|
242
|
+
released = true;
|
|
243
|
+
keys.forEach(key => this.claimed.delete(key));
|
|
244
|
+
this.active.delete(run.id);
|
|
245
|
+
};
|
|
246
|
+
const ready = database ? database.put('runs', run).then(async () => {
|
|
247
|
+
try {
|
|
248
|
+
if (mayStart && !mayStart())
|
|
249
|
+
throw new Error('运行请求已失效');
|
|
250
|
+
}
|
|
251
|
+
catch (error) {
|
|
252
|
+
await database.remove('runs', run.id);
|
|
253
|
+
throw error;
|
|
254
|
+
}
|
|
255
|
+
this.changed();
|
|
256
|
+
}) : Promise.resolve();
|
|
257
|
+
const done = ready.then(async () => {
|
|
210
258
|
const timeout = setTimeout(() => controller.abort(new Error('运行超时')), (script.timeoutSeconds ?? this.defaultTimeout()) * 1000);
|
|
211
259
|
try {
|
|
212
|
-
await this.execute(run, script, adapter, controller.signal, claimAdb);
|
|
260
|
+
await this.execute(run, script, adapter, controller.signal, claimAdb, database);
|
|
213
261
|
}
|
|
214
262
|
finally {
|
|
215
263
|
clearTimeout(timeout);
|
|
216
|
-
keys.forEach(key => this.claimed.delete(key));
|
|
217
|
-
this.active.delete(run.id);
|
|
218
264
|
run.finished = new Date().toISOString();
|
|
219
|
-
|
|
265
|
+
if (database)
|
|
266
|
+
await database.put('runs', run);
|
|
267
|
+
else
|
|
268
|
+
this.store.put('runs', run);
|
|
269
|
+
release();
|
|
220
270
|
this.changed();
|
|
221
271
|
try {
|
|
222
272
|
this.finished(run);
|
|
@@ -226,13 +276,17 @@ export class Runner {
|
|
|
226
276
|
}
|
|
227
277
|
}
|
|
228
278
|
return run;
|
|
229
|
-
});
|
|
279
|
+
}).finally(release);
|
|
280
|
+
if (database)
|
|
281
|
+
void done.catch(error => console.error('运行记录保存失败', error));
|
|
230
282
|
this.active.set(run.id, { controller, done, snapshot: run });
|
|
231
|
-
|
|
232
|
-
|
|
283
|
+
if (!database)
|
|
284
|
+
this.changed();
|
|
285
|
+
return { run, done, ready };
|
|
233
286
|
}
|
|
234
|
-
async execute(run, original, adapter, signal, claimAdb) {
|
|
287
|
+
async execute(run, original, adapter, signal, claimAdb, database) {
|
|
235
288
|
const stages = run.stages;
|
|
289
|
+
let writing = Promise.resolve();
|
|
236
290
|
const log = line => {
|
|
237
291
|
run.logs.push(line.slice(0, 16000));
|
|
238
292
|
if (run.logs.length > (this.options.logLineLimit ?? 4000))
|
|
@@ -244,13 +298,25 @@ export class Runner {
|
|
|
244
298
|
sequence: stages.length + 1, stage, status, at: new Date().toISOString(), ...(message ? { message: message.slice(0, 2000) } : {}),
|
|
245
299
|
...(run.workflow ? { workflow: run.workflow } : {}) });
|
|
246
300
|
stages.push(event);
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
301
|
+
const announce = () => {
|
|
302
|
+
this.changed();
|
|
303
|
+
try {
|
|
304
|
+
this.lifecycle.stage?.(event);
|
|
305
|
+
}
|
|
306
|
+
catch (error) {
|
|
307
|
+
log(`运行事件处理失败: ${String(error)}`);
|
|
308
|
+
}
|
|
309
|
+
};
|
|
310
|
+
if (database) {
|
|
311
|
+
const snapshot = structuredClone(run);
|
|
312
|
+
writing = writing.then(async () => {
|
|
313
|
+
await database.put('runs', snapshot);
|
|
314
|
+
announce();
|
|
315
|
+
}).catch(error => console.error('运行阶段保存失败', error));
|
|
251
316
|
}
|
|
252
|
-
|
|
253
|
-
|
|
317
|
+
else {
|
|
318
|
+
this.store.put('runs', run);
|
|
319
|
+
announce();
|
|
254
320
|
}
|
|
255
321
|
};
|
|
256
322
|
const options = { signal, log, report };
|
|
@@ -332,15 +398,30 @@ export class Runner {
|
|
|
332
398
|
else
|
|
333
399
|
report('finish-task', 'completed');
|
|
334
400
|
run.status = outcome;
|
|
401
|
+
await writing;
|
|
335
402
|
}
|
|
336
403
|
}
|
|
337
404
|
get(id) { return this.active.get(id)?.snapshot ?? this.store.get('runs', id); }
|
|
405
|
+
async getAsync(id) {
|
|
406
|
+
if (!this.persistence)
|
|
407
|
+
return this.get(id);
|
|
408
|
+
return this.active.get(id)?.snapshot ?? this.persistence.database.get('runs', id);
|
|
409
|
+
}
|
|
338
410
|
list() {
|
|
339
411
|
return this.store.recentRuns().map(run => this.active.get(run.id)?.snapshot ?? run);
|
|
340
412
|
}
|
|
341
413
|
summary() {
|
|
342
414
|
return this.list().map(({ logs, stages, output, ...summary }) => summary);
|
|
343
415
|
}
|
|
416
|
+
async listAsync() {
|
|
417
|
+
if (!this.persistence)
|
|
418
|
+
return this.list();
|
|
419
|
+
const runs = await this.persistence.history.recentRuns();
|
|
420
|
+
return runs.map(run => this.active.get(run.id)?.snapshot ?? run);
|
|
421
|
+
}
|
|
422
|
+
async summaryAsync() {
|
|
423
|
+
return (await this.listAsync()).map(({ logs, stages, output, ...summary }) => summary);
|
|
424
|
+
}
|
|
344
425
|
stop(id) {
|
|
345
426
|
const task = this.active.get(id);
|
|
346
427
|
if (!task)
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export const ui = (ctx) => ctx.get('mas.ui');
|
|
2
|
+
export const store = (ctx) => ctx.get('mas.storage-core');
|
|
3
|
+
export const runner = (ctx) => ctx.get('mas.runner');
|
|
4
|
+
export function text(input, key, label, required = true) {
|
|
5
|
+
const value = input[key];
|
|
6
|
+
if (typeof value === 'string' && value.trim())
|
|
7
|
+
return value.trim();
|
|
8
|
+
if (required)
|
|
9
|
+
throw new Error(`请输入${label}`);
|
|
10
|
+
return '';
|
|
11
|
+
}
|
|
12
|
+
export function strings(value) {
|
|
13
|
+
if (!value)
|
|
14
|
+
return [];
|
|
15
|
+
if (Array.isArray(value) && value.every(item => typeof item === 'string'))
|
|
16
|
+
return value;
|
|
17
|
+
if (typeof value === 'string') {
|
|
18
|
+
if (value.trim().startsWith('[')) {
|
|
19
|
+
const parsed = JSON.parse(value);
|
|
20
|
+
if (Array.isArray(parsed) && parsed.every(item => typeof item === 'string'))
|
|
21
|
+
return parsed;
|
|
22
|
+
throw new Error('JSON 必须是字符串数组');
|
|
23
|
+
}
|
|
24
|
+
return value.split(/[\n,]+/).map(item => item.trim()).filter(Boolean);
|
|
25
|
+
}
|
|
26
|
+
throw new Error('请输入字符串列表');
|
|
27
|
+
}
|
|
28
|
+
export const field = (key, label, extra = {}) => ({ key, label, ...extra });
|
|
29
|
+
export const columns = (...pairs) => pairs.map(([key, label]) => ({ key, label }));
|
|
30
|
+
export const action = (id, label) => ({ id, label });
|
|
31
|
+
export const runColumns = columns(['name', '托管'], ['status', '状态'], ['started', '开始时间'], ['finished', '结束时间'], ['error', '结果详情']);
|
|
@@ -1,25 +1,64 @@
|
|
|
1
1
|
import { join } from 'node:path';
|
|
2
|
+
import { textList } from '../adapters.js';
|
|
2
3
|
import { configName, executableField, existingPath, nativeAdapter, optionalText, prepareExecutable, requiredText, windowsOnly } from './native.js';
|
|
4
|
+
import { readNativeConfigurationFile } from './native-config.js';
|
|
3
5
|
import { profileOption, profilesIn } from './profile-options.js';
|
|
4
6
|
const betterGiProgram = (input) => prepareExecutable(input, 'BetterGI.exe', ['bettergi.exe']);
|
|
5
7
|
const profilesDirectory = (path) => join(path, 'User', 'OneDragon');
|
|
6
8
|
export async function betterGiProfiles(input) { return profilesIn(profilesDirectory((await betterGiProgram(input)).installRoot)); }
|
|
9
|
+
async function groupOptions(root) {
|
|
10
|
+
const directory = join(root, 'User', 'ScriptGroup');
|
|
11
|
+
const files = await profilesIn(directory);
|
|
12
|
+
const groups = new Map();
|
|
13
|
+
for (const { value } of files) {
|
|
14
|
+
try {
|
|
15
|
+
const contents = await readNativeConfigurationFile({ root, directory, file: `${value}.json` });
|
|
16
|
+
const document = JSON.parse(contents.replace(/^\uFEFF/u, ''));
|
|
17
|
+
const name = document?.Name ?? document?.name;
|
|
18
|
+
if (typeof name !== 'string' || name !== name.trim() || /[\u0000-\u001f]/u.test(name))
|
|
19
|
+
continue;
|
|
20
|
+
configName(name, 'BetterGI 配置组');
|
|
21
|
+
groups.set(name, (groups.get(name) ?? 0) + 1);
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return [...groups].filter(([, count]) => count === 1)
|
|
28
|
+
.map(([value]) => ({ value, label: value })).sort((a, b) => a.label.localeCompare(b.label));
|
|
29
|
+
}
|
|
30
|
+
export async function betterGiGroups(input) {
|
|
31
|
+
return groupOptions((await betterGiProgram(input)).installRoot);
|
|
32
|
+
}
|
|
7
33
|
export async function betterGiLaunch(config, account) {
|
|
8
34
|
const command = requiredText(config, 'command', 'BetterGI.exe');
|
|
9
35
|
const cwd = requiredText(config, 'installRoot', 'BetterGI 安装目录');
|
|
36
|
+
const groups = textList(account.groups);
|
|
37
|
+
const logs = { directory: join(cwd, 'log'), filenames: /^better-genshin-impact\d{8}\.log$/u, closeOnCompletion: true };
|
|
38
|
+
if (groups.length) {
|
|
39
|
+
const available = new Set((await groupOptions(cwd)).map(group => group.value));
|
|
40
|
+
for (const name of groups)
|
|
41
|
+
if (!available.has(name))
|
|
42
|
+
throw new Error(`BetterGI 配置组不存在或同名:${name}`);
|
|
43
|
+
return { command, cwd, args: ['--startGroups', ...groups], logs: { ...logs,
|
|
44
|
+
success: /一条龙和配置组任务结束|→\s*任务结束\s*$/u,
|
|
45
|
+
failure: /传入的配置组名称不存在|需要执行的配置组为空|执行脚本时发生异常|取消执行配置组|任务启动失败/u,
|
|
46
|
+
} };
|
|
47
|
+
}
|
|
10
48
|
const profile = configName(optionalText(account, 'profile') || optionalText(config, 'profile'), '一条龙配置');
|
|
11
49
|
// Upstream silently uses its selected profile if a supplied name is missing.
|
|
12
50
|
await existingPath(join(profilesDirectory(cwd), `${profile}.json`), 'BetterGI 一条龙配置文件');
|
|
13
|
-
return { command, cwd, args: ['startOneDragon', profile], logs: {
|
|
14
|
-
directory: join(cwd, 'log'), filenames: /^better-genshin-impact\d{8}\.log$/u,
|
|
15
|
-
success: /一条龙和配置组任务结束/u, closeOnCompletion: true,
|
|
16
|
-
} };
|
|
51
|
+
return { command, cwd, args: ['startOneDragon', profile], logs: { ...logs, success: /一条龙和配置组任务结束/u } };
|
|
17
52
|
}
|
|
18
53
|
export const bettergi = {
|
|
19
54
|
id: 'bettergi', title: '原神 · BetterGI 原生一条龙', group: '游戏专项', supports: windowsOnly,
|
|
20
55
|
description: '调用 BetterGI 0.45.3 以上的命名一条龙入口。请在 BetterGI 中设置任务及结束后退出。',
|
|
21
56
|
scriptFields: [executableField('BetterGI.exe'), profileOption('profile', '默认一条龙配置名称', 'bettergi.profiles', 'command', true)],
|
|
22
|
-
accountFields: [
|
|
57
|
+
accountFields: [
|
|
58
|
+
profileOption('profile', '一条龙配置名称覆盖(可选)', 'bettergi.profiles', 'scriptId'),
|
|
59
|
+
{ key: 'groups', kind: 'multiselect', label: '配置组(可选)', source: 'bettergi.groups', sourceBy: 'scriptId',
|
|
60
|
+
hint: '依照列表顺序交给支持 --startGroups 的 BetterGI。留空时运行一条龙配置。' },
|
|
61
|
+
],
|
|
23
62
|
prepare: async (input) => {
|
|
24
63
|
const paths = await betterGiProgram(input);
|
|
25
64
|
const config = { ...paths, profile: requiredText(input, 'profile', '一条龙配置名称') };
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { lstat, open, readdir, realpath, rename, unlink, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { isAbsolute, join, relative, sep } from 'node:path';
|
|
5
|
+
import { CredentialVault } from '../community/vault.js';
|
|
6
|
+
import { field, store, text, ui } from '../features.js';
|
|
7
|
+
import { assertWindowsProgramIdle, windowsOnly } from './native.js';
|
|
8
|
+
const collection = 'native-config-backups';
|
|
9
|
+
const maxFiles = 256;
|
|
10
|
+
const maxBytes = 8 * 1024 * 1024;
|
|
11
|
+
const fileName = /^[^/\\:*?"<>|\u0000-\u001f]+\.json$/iu;
|
|
12
|
+
const explicitFileName = /^[^/\\:*?"<>|\u0000-\u001f]+\.(?:json|yaml|yml)$/iu;
|
|
13
|
+
function contained(root, candidate) {
|
|
14
|
+
const rel = relative(root, candidate);
|
|
15
|
+
if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel))
|
|
16
|
+
throw new Error('原生配置目录必须位于已保存的安装目录内');
|
|
17
|
+
return rel;
|
|
18
|
+
}
|
|
19
|
+
async function configDirectory(source, allowMissing = false) {
|
|
20
|
+
const root = await realpath(source.root);
|
|
21
|
+
const rel = contained(root, source.directory);
|
|
22
|
+
let location = root;
|
|
23
|
+
for (const part of rel.split(sep)) {
|
|
24
|
+
location = join(location, part);
|
|
25
|
+
const info = await lstat(location).catch(error => {
|
|
26
|
+
if (allowMissing && error.code === 'ENOENT')
|
|
27
|
+
return undefined;
|
|
28
|
+
throw error;
|
|
29
|
+
});
|
|
30
|
+
if (!info)
|
|
31
|
+
return undefined;
|
|
32
|
+
if (!info.isDirectory() || info.isSymbolicLink())
|
|
33
|
+
throw new Error('原生配置目录路径无效或含重定向');
|
|
34
|
+
}
|
|
35
|
+
return location;
|
|
36
|
+
}
|
|
37
|
+
function validateName(name, targets) {
|
|
38
|
+
if (!(targets ? explicitFileName : fileName).test(name) || name.length > 160 || name.startsWith('.')
|
|
39
|
+
|| name.startsWith(' ') || name !== name.trim() || (targets && !targets.includes(name)))
|
|
40
|
+
throw new Error('原生配置备份的文件名无效');
|
|
41
|
+
}
|
|
42
|
+
function targetsFor(source) { return source.files ?? (source.file ? [source.file] : undefined); }
|
|
43
|
+
async function configFiles(directory, targets) {
|
|
44
|
+
const entries = await readdir(directory, { withFileTypes: true });
|
|
45
|
+
return entries.filter(entry => targets ? targets.includes(entry.name) : fileName.test(entry.name));
|
|
46
|
+
}
|
|
47
|
+
async function readContent(directory, targets) {
|
|
48
|
+
for (const filename of targets ?? [])
|
|
49
|
+
validateName(filename, targets);
|
|
50
|
+
const files = await configFiles(directory, targets);
|
|
51
|
+
if (files.length > maxFiles)
|
|
52
|
+
throw new Error('原生配置文件数量超过可备份范围');
|
|
53
|
+
const content = Object.create(null);
|
|
54
|
+
let total = 0;
|
|
55
|
+
for (const entry of files) {
|
|
56
|
+
validateName(entry.name, targets);
|
|
57
|
+
if (!entry.isFile() || entry.isSymbolicLink())
|
|
58
|
+
throw new Error('原生配置含非普通文件');
|
|
59
|
+
const path = join(directory, entry.name);
|
|
60
|
+
const info = await lstat(path);
|
|
61
|
+
if (info.isSymbolicLink() || !info.isFile() || info.size > maxBytes - total)
|
|
62
|
+
throw new Error('原生配置含链接或超过可备份大小');
|
|
63
|
+
const handle = await open(path, 'r');
|
|
64
|
+
try {
|
|
65
|
+
const body = await handle.readFile();
|
|
66
|
+
total += body.length;
|
|
67
|
+
if (total > maxBytes)
|
|
68
|
+
throw new Error('原生配置超过可备份大小');
|
|
69
|
+
content[entry.name] = body.toString('base64');
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
await handle.close();
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return content;
|
|
76
|
+
}
|
|
77
|
+
export async function readNativeConfigurationFile(source) {
|
|
78
|
+
const directory = await configDirectory(source);
|
|
79
|
+
const content = directory && (await readContent(directory, [source.file]))[source.file];
|
|
80
|
+
if (content === undefined)
|
|
81
|
+
throw new Error('原生配置文件不存在');
|
|
82
|
+
return Buffer.from(content, 'base64').toString('utf8');
|
|
83
|
+
}
|
|
84
|
+
function decode(snapshot, targets) {
|
|
85
|
+
const parsed = JSON.parse(snapshot);
|
|
86
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
87
|
+
throw new Error('原生配置备份格式无效');
|
|
88
|
+
const entries = Object.entries(parsed);
|
|
89
|
+
if (entries.length > maxFiles)
|
|
90
|
+
throw new Error('原生配置备份文件数量无效');
|
|
91
|
+
let total = 0;
|
|
92
|
+
for (const [name, value] of entries) {
|
|
93
|
+
validateName(name, targets);
|
|
94
|
+
if (typeof value !== 'string' || !/^[A-Za-z0-9+/]*={0,2}$/u.test(value) || value.length % 4 !== 0)
|
|
95
|
+
throw new Error('原生配置备份内容无效');
|
|
96
|
+
total += Buffer.byteLength(value, 'base64');
|
|
97
|
+
if (total > maxBytes)
|
|
98
|
+
throw new Error('原生配置备份大小无效');
|
|
99
|
+
}
|
|
100
|
+
return Object.fromEntries(entries);
|
|
101
|
+
}
|
|
102
|
+
async function replaceFile(directory, name, content) {
|
|
103
|
+
const destination = join(directory, name);
|
|
104
|
+
const temp = join(directory, `.masc-${randomUUID()}.tmp`);
|
|
105
|
+
const current = await lstat(destination).catch(error => {
|
|
106
|
+
if (error.code === 'ENOENT')
|
|
107
|
+
return undefined;
|
|
108
|
+
throw error;
|
|
109
|
+
});
|
|
110
|
+
if (current && (!current.isFile() || current.isSymbolicLink()))
|
|
111
|
+
throw new Error('目标配置不是普通文件');
|
|
112
|
+
await writeFile(temp, Buffer.from(content, 'base64'), { flag: 'wx', mode: current?.mode ?? 0o600 });
|
|
113
|
+
try {
|
|
114
|
+
await rename(temp, destination);
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
await unlink(temp).catch(() => { });
|
|
118
|
+
throw error;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
async function replaceNativeConfigurationFile(source, expected, updated) {
|
|
122
|
+
const directory = await configDirectory(source);
|
|
123
|
+
const files = directory && await readContent(directory, [source.file]);
|
|
124
|
+
const current = files && files[source.file];
|
|
125
|
+
if (!current || Buffer.from(current, 'base64').toString('utf8') !== expected)
|
|
126
|
+
throw new Error('原生配置已变化,请刷新后再保存');
|
|
127
|
+
if (Buffer.byteLength(updated) > maxBytes)
|
|
128
|
+
throw new Error('文件超过原生配置大小限制');
|
|
129
|
+
await replaceFile(directory, source.file, Buffer.from(updated, 'utf8').toString('base64'));
|
|
130
|
+
}
|
|
131
|
+
export function nativeConfigurationComponents(adapter, script, options = {}) {
|
|
132
|
+
const fixed = { scriptId: script.id };
|
|
133
|
+
return [
|
|
134
|
+
{ type: 'metrics', title: '检测原生配置', query: `${adapter}.native.info`, queryInput: fixed },
|
|
135
|
+
...(options.open === false ? [] : [{ type: 'form', title: '原生配置', action: `${adapter}.native.open`, fixed,
|
|
136
|
+
fields: options.confirmOpen ? [field('confirmed', options.confirmOpen, { kind: 'boolean' })] : [], submitLabel: '打开原生配置窗口', result: true }]),
|
|
137
|
+
{ type: 'form', title: '备份原生配置', action: `${adapter}.native.backup`, fixed, fields: [], submitLabel: '保存原生配置备份', result: true },
|
|
138
|
+
{ type: 'form', title: '恢复原生配置', action: `${adapter}.native.restore`, fixed, submitLabel: '恢复所选备份', result: true,
|
|
139
|
+
fields: [field('backupId', '备份', { kind: 'select', required: true, source: `${adapter}.native.snapshots`, sourceBy: 'scriptId' }),
|
|
140
|
+
field('confirmed', '确认覆盖所选备份中的同名配置文件', { kind: 'boolean' })] },
|
|
141
|
+
];
|
|
142
|
+
}
|
|
143
|
+
export function registerNativeConfiguration(ctx, dataDir, adapter, resolve, edit) {
|
|
144
|
+
const vault = new CredentialVault(dataDir, 'plugin');
|
|
145
|
+
ctx.inject(['mas.ui', 'mas.scripts', 'mas.runner', 'mas.storage-core'], scope => {
|
|
146
|
+
const scripts = scope.get('mas.scripts');
|
|
147
|
+
const runner = scope.get('mas.runner');
|
|
148
|
+
const db = store(scope);
|
|
149
|
+
const sourceFor = (input) => {
|
|
150
|
+
const script = scripts.get(text(input, 'scriptId', '托管 ID'));
|
|
151
|
+
if (!script || script.adapter !== adapter)
|
|
152
|
+
throw new Error('未找到对应专项托管');
|
|
153
|
+
return resolve(script.adapterConfig ?? {}, input);
|
|
154
|
+
};
|
|
155
|
+
async function ownerFor(source) {
|
|
156
|
+
const root = await realpath(source.root);
|
|
157
|
+
const location = contained(root, source.directory);
|
|
158
|
+
const key = JSON.stringify([adapter, root.toLowerCase(), location.toLowerCase(), targetsFor(source) ?? []]);
|
|
159
|
+
return createHash('sha256').update(key).digest('hex');
|
|
160
|
+
}
|
|
161
|
+
async function writeSnapshot(owner, content) {
|
|
162
|
+
const id = randomUUID();
|
|
163
|
+
const date = new Date().toISOString();
|
|
164
|
+
const secret = await vault.seal(`${collection}:${id}`, JSON.stringify(content));
|
|
165
|
+
return db.put(collection, { id, owner, date, count: Object.keys(content).length, secret });
|
|
166
|
+
}
|
|
167
|
+
async function ensureIdle(source) {
|
|
168
|
+
const reason = windowsOnly();
|
|
169
|
+
if (reason)
|
|
170
|
+
throw new Error(reason);
|
|
171
|
+
for (const command of new Set([source.command, ...source.additionalPrograms ?? []])) {
|
|
172
|
+
await assertWindowsProgramIdle(command, AbortSignal.timeout(10_000));
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
async function useSource(input, action) {
|
|
176
|
+
const source = await sourceFor(input);
|
|
177
|
+
const release = runner.claimInstallation(source.root);
|
|
178
|
+
try {
|
|
179
|
+
await ensureIdle(source);
|
|
180
|
+
return await action(source);
|
|
181
|
+
}
|
|
182
|
+
finally {
|
|
183
|
+
release();
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
ui(scope).scope(scope, undefined, { [`${adapter}.native.info`]: async (input) => {
|
|
187
|
+
const source = await sourceFor(input);
|
|
188
|
+
const directory = await configDirectory(source, true);
|
|
189
|
+
const files = directory ? await configFiles(directory, targetsFor(source)) : [];
|
|
190
|
+
return [{ label: '配置目录', value: source.directory }, { label: '配置文件', value: files.length,
|
|
191
|
+
detail: files.length ? files.slice(0, 8).map(entry => entry.name).join('、') : '等待在原生程序中首次保存配置' }];
|
|
192
|
+
}, [`${adapter}.native.snapshots`]: async (input) => {
|
|
193
|
+
const owner = await ownerFor(await sourceFor(input));
|
|
194
|
+
return db.list(collection).filter(entry => entry.owner === owner && entry.count > 0).reverse()
|
|
195
|
+
.map(entry => ({ value: entry.id, label: `${entry.date.replace('T', ' ').replace(/\.\d+Z$/u, ' UTC')} · ${entry.count} 项` }));
|
|
196
|
+
} }, {
|
|
197
|
+
[`${adapter}.native.open`]: async (input) => {
|
|
198
|
+
const source = await sourceFor(input);
|
|
199
|
+
if (source.open === false)
|
|
200
|
+
throw new Error('此专项没有独立的原生配置窗口入口');
|
|
201
|
+
if (source.confirmOpen && input.confirmed !== true)
|
|
202
|
+
throw new Error('请确认允许按原生设置启动程序');
|
|
203
|
+
const release = runner.claimInstallation(source.root);
|
|
204
|
+
try {
|
|
205
|
+
await ensureIdle(source);
|
|
206
|
+
const directory = await configDirectory(source, true);
|
|
207
|
+
if (directory) {
|
|
208
|
+
const content = await readContent(directory, targetsFor(source));
|
|
209
|
+
if (Object.keys(content).length)
|
|
210
|
+
await writeSnapshot(await ownerFor(source), content);
|
|
211
|
+
}
|
|
212
|
+
const child = spawn(source.command, source.args ?? [], { cwd: source.cwd ?? source.root, shell: false,
|
|
213
|
+
detached: true, stdio: 'ignore' });
|
|
214
|
+
child.once('close', release);
|
|
215
|
+
await new Promise((accept, reject) => { child.once('spawn', accept); child.once('error', reject); });
|
|
216
|
+
child.unref();
|
|
217
|
+
return { message: '已在后端主机打开原生配置,关闭窗口后可恢复调度' };
|
|
218
|
+
}
|
|
219
|
+
catch (error) {
|
|
220
|
+
release();
|
|
221
|
+
throw error;
|
|
222
|
+
}
|
|
223
|
+
},
|
|
224
|
+
...(edit ? { [`${adapter}.native.edit`]: (input) => useSource(input, async (source) => {
|
|
225
|
+
if (!source.file)
|
|
226
|
+
throw new Error('原生配置未指定单个编辑文件');
|
|
227
|
+
if (input.confirmed !== true)
|
|
228
|
+
throw new Error('请确认保存所选原生配置');
|
|
229
|
+
const file = { ...source, file: source.file };
|
|
230
|
+
const before = await readNativeConfigurationFile(file);
|
|
231
|
+
const updated = edit(before, input, file.file);
|
|
232
|
+
if (updated === before)
|
|
233
|
+
return { message: '原生配置无变化' };
|
|
234
|
+
const preserved = await writeSnapshot(await ownerFor(source), { [file.file]: Buffer.from(before, 'utf8').toString('base64') });
|
|
235
|
+
await replaceNativeConfigurationFile(file, before, updated);
|
|
236
|
+
return { message: '原生配置已保存', 操作前备份时间: preserved.date };
|
|
237
|
+
}) } : {}),
|
|
238
|
+
[`${adapter}.native.backup`]: input => useSource(input, async (source) => {
|
|
239
|
+
const directory = await configDirectory(source);
|
|
240
|
+
const content = await readContent(directory, targetsFor(source));
|
|
241
|
+
if (!Object.keys(content).length)
|
|
242
|
+
throw new Error('未找到可备份的原生配置,请先通过原生窗口保存设置');
|
|
243
|
+
const snapshot = await writeSnapshot(await ownerFor(source), content);
|
|
244
|
+
return { 备份时间: snapshot.date, 配置项: snapshot.count };
|
|
245
|
+
}),
|
|
246
|
+
[`${adapter}.native.restore`]: input => useSource(input, async (source) => {
|
|
247
|
+
if (input.confirmed !== true)
|
|
248
|
+
throw new Error('请确认覆盖所选备份中的同名配置文件');
|
|
249
|
+
const owner = await ownerFor(source);
|
|
250
|
+
const backup = db.get(collection, text(input, 'backupId', '备份'));
|
|
251
|
+
if (!backup || backup.owner !== owner || !backup.count)
|
|
252
|
+
throw new Error('该备份不属于当前原生配置目录');
|
|
253
|
+
const directory = (await configDirectory(source));
|
|
254
|
+
const before = await readContent(directory, targetsFor(source));
|
|
255
|
+
const snapshot = decode(await vault.reveal(`${collection}:${backup.id}`, backup.secret), targetsFor(source));
|
|
256
|
+
const preserved = await writeSnapshot(owner, before);
|
|
257
|
+
const published = [];
|
|
258
|
+
try {
|
|
259
|
+
for (const [name, content] of Object.entries(snapshot)) {
|
|
260
|
+
await replaceFile(directory, name, content);
|
|
261
|
+
published.push(name);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
catch (error) {
|
|
265
|
+
const rolledBack = await Promise.allSettled(published.map(name => Object.hasOwn(before, name)
|
|
266
|
+
? replaceFile(directory, name, before[name]) : unlink(join(directory, name))));
|
|
267
|
+
if (rolledBack.some(result => result.status === 'rejected'))
|
|
268
|
+
throw new Error(`恢复中断,部分配置未能回退。操作前备份时间为 ${preserved.date}`);
|
|
269
|
+
throw new Error('恢复失败,已撤回本次写入', { cause: error });
|
|
270
|
+
}
|
|
271
|
+
return { 已恢复: published.length, 操作前备份时间: preserved.date };
|
|
272
|
+
}),
|
|
273
|
+
});
|
|
274
|
+
});
|
|
275
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
export function maaAccountFields(id) {
|
|
2
|
+
const choice = (key, label, kind, source, sourceInputs = []) => ({
|
|
3
|
+
key, label, kind, source: `${id}.account.${source}`, sourceBy: 'scriptId', sourceInputs,
|
|
4
|
+
});
|
|
5
|
+
const selection = ['controller', 'resource'];
|
|
6
|
+
return [
|
|
7
|
+
choice('controller', '账号控制器覆盖', 'select', 'controllers'),
|
|
8
|
+
{ ...choice('resource', '账号资源覆盖', 'select', 'resources', ['controller']), hint: '留空时继承托管资源。切换控制器时请核对资源。' },
|
|
9
|
+
{ ...choice('preset', '账号项目预设覆盖', 'select', 'presets', selection), hint: '未选账号任务队列时,账号预设优先于任务计划和托管队列。' },
|
|
10
|
+
{ ...choice('tasks', '账号任务队列覆盖', 'multiselect', 'tasks', selection), hint: '留空时按账号预设、任务计划或托管设置执行。' },
|
|
11
|
+
{ ...choice('projectOptions', '账号 ProjectInterface 选项覆盖', 'json-object', 'options', selection), hint: '只覆盖已填写的值。专项账号字段优先于同名选项。' },
|
|
12
|
+
];
|
|
13
|
+
}
|
|
14
|
+
function object(value) {
|
|
15
|
+
return !!value && typeof value === 'object' && !Array.isArray(value);
|
|
16
|
+
}
|
|
17
|
+
function selection(input, key) {
|
|
18
|
+
const value = input[key];
|
|
19
|
+
if (value === undefined)
|
|
20
|
+
return undefined;
|
|
21
|
+
if (typeof value !== 'string')
|
|
22
|
+
throw new Error('账号 ProjectInterface 选择必须为字符串');
|
|
23
|
+
return value.trim() || undefined;
|
|
24
|
+
}
|
|
25
|
+
function accountTasks(value) {
|
|
26
|
+
if (value === undefined)
|
|
27
|
+
return undefined;
|
|
28
|
+
if (!Array.isArray(value) || value.some(item => typeof item !== 'string' || !item.trim())) {
|
|
29
|
+
throw new Error('账号任务队列必须为任务名称列表');
|
|
30
|
+
}
|
|
31
|
+
return value.length ? value : undefined;
|
|
32
|
+
}
|
|
33
|
+
function accountOptions(value) {
|
|
34
|
+
if (value === undefined || typeof value === 'string' && !value.trim())
|
|
35
|
+
return undefined;
|
|
36
|
+
let parsed;
|
|
37
|
+
try {
|
|
38
|
+
parsed = typeof value === 'string' ? JSON.parse(value) : value;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
throw new Error('账号 ProjectInterface 选项必须是有效的 JSON 对象');
|
|
42
|
+
}
|
|
43
|
+
if (!object(parsed))
|
|
44
|
+
throw new Error('账号 ProjectInterface 选项必须是有效的 JSON 对象');
|
|
45
|
+
for (const [key, option] of Object.entries(parsed)) {
|
|
46
|
+
if (typeof option === 'string' || typeof option === 'boolean')
|
|
47
|
+
continue;
|
|
48
|
+
if (Array.isArray(option) && option.every(item => typeof item === 'string'))
|
|
49
|
+
continue;
|
|
50
|
+
if (object(option) && Object.values(option).every(item => typeof item === 'string'))
|
|
51
|
+
continue;
|
|
52
|
+
throw new Error(`账号 ProjectInterface 选项格式无效:${key}`);
|
|
53
|
+
}
|
|
54
|
+
return parsed;
|
|
55
|
+
}
|
|
56
|
+
export function applyMaaAccountSettings(input, account) {
|
|
57
|
+
const preset = selection(account, 'preset');
|
|
58
|
+
const overrides = accountOptions(account.projectOptions);
|
|
59
|
+
const options = new Map(Object.entries(input.options ?? {}));
|
|
60
|
+
for (const [key, value] of Object.entries(overrides ?? {})) {
|
|
61
|
+
const inherited = options.get(key);
|
|
62
|
+
options.set(key, object(value) && object(inherited) ? { ...inherited, ...value } : value);
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
...input,
|
|
66
|
+
controller: selection(account, 'controller') ?? input.controller,
|
|
67
|
+
resource: selection(account, 'resource') ?? input.resource,
|
|
68
|
+
preset: preset ?? input.preset,
|
|
69
|
+
tasks: accountTasks(account.tasks) ?? (preset ? undefined : input.tasks),
|
|
70
|
+
options: options.size ? Object.fromEntries(options) : undefined,
|
|
71
|
+
requiredOptions: Object.keys(overrides ?? {}),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
@@ -427,6 +427,15 @@ export function planRun(project, input) {
|
|
|
427
427
|
if (!project.options.has(key))
|
|
428
428
|
throw new Error(`ProjectInterface has unknown option "${key}".`);
|
|
429
429
|
}
|
|
430
|
+
const unapplied = new Set(input.requiredOptions);
|
|
431
|
+
for (const key of unapplied) {
|
|
432
|
+
const option = project.options.get(key);
|
|
433
|
+
const value = object(overrides.get(key));
|
|
434
|
+
if (option?.type === 'input' && value && namedObjects(option.inputs, `option ${key}.inputs`)
|
|
435
|
+
.some(field => field.password === true && Object.hasOwn(value, field.name))) {
|
|
436
|
+
throw new Error('当前版本无法安全保存 MaaFramework 密码选项');
|
|
437
|
+
}
|
|
438
|
+
}
|
|
430
439
|
const controller = input.controller === undefined
|
|
431
440
|
? project.controllers.find((item) => supportsController(item.type))
|
|
432
441
|
: project.controllers.find((item) => item.name === input.controller);
|
|
@@ -465,30 +474,39 @@ export function planRun(project, input) {
|
|
|
465
474
|
presetOptions.set(task.name, entries);
|
|
466
475
|
}
|
|
467
476
|
const withPreset = (options) => options ? new Map(Object.entries(merge(options, specified))) : overrides;
|
|
477
|
+
function resolveApplied(keys, values) {
|
|
478
|
+
const resolved = resolveOptions(project, selection, keys, values);
|
|
479
|
+
for (const name of Object.keys(resolved.selected))
|
|
480
|
+
unapplied.delete(name);
|
|
481
|
+
return resolved;
|
|
482
|
+
}
|
|
468
483
|
const sharedKeys = [...project.globalOptions, ...resource.option ?? [], ...controller.option ?? []];
|
|
469
|
-
const sharedOptions =
|
|
484
|
+
const sharedOptions = resolveApplied(sharedKeys, overrides).override;
|
|
470
485
|
const tasks = names.map((name) => {
|
|
471
486
|
const task = tasksByName.get(name);
|
|
472
487
|
if (!task)
|
|
473
488
|
throw new Error(`Unknown ProjectInterface task "${name}".`);
|
|
474
489
|
if (!matches(task, selection))
|
|
475
490
|
throw new Error(`Task "${name}" cannot run with controller "${controller.name}" and resource "${resource.name}".`);
|
|
476
|
-
const taskOptions =
|
|
491
|
+
const taskOptions = resolveApplied(task.option ?? [], withPreset(presetOptions.get(name)?.shift())).override;
|
|
477
492
|
return { name: task.name, entry: task.entry, override: merge(merge(pipeline(task.pipeline_override, `task ${name}`), sharedOptions), taskOptions) };
|
|
478
493
|
});
|
|
479
494
|
const presetPretasks = preset?.pretask && new Map(preset.pretask.map(item => [item.name, item]));
|
|
495
|
+
const pretasks = project.pretasks.filter(item => matches(item, selection)
|
|
496
|
+
&& (!presetPretasks || item.name && presetPretasks.get(item.name)?.enabled)).map((item) => ({
|
|
497
|
+
...item,
|
|
498
|
+
optionArgument: item.option?.length
|
|
499
|
+
? JSON.stringify(resolveApplied(item.option, withPreset(item.name ? presetPretasks?.get(item.name)?.option : undefined)).selected)
|
|
500
|
+
: undefined,
|
|
501
|
+
}));
|
|
502
|
+
if (unapplied.size)
|
|
503
|
+
throw new Error(`账号选项不适用于当前任务、控制器或资源:${[...unapplied].join('、')}`);
|
|
480
504
|
return {
|
|
481
505
|
controller, resource, tasks,
|
|
482
506
|
resourcePaths: resource.path.map((path) => projectPath(project.directory, path)),
|
|
483
507
|
attachedPaths: (controller.attach_resource_path ?? []).map((path) => projectPath(project.directory, path)),
|
|
484
508
|
agents: project.agents,
|
|
485
|
-
pretasks
|
|
486
|
-
&& (!presetPretasks || item.name && presetPretasks.get(item.name)?.enabled)).map((item) => ({
|
|
487
|
-
...item,
|
|
488
|
-
optionArgument: item.option?.length
|
|
489
|
-
? JSON.stringify(resolveOptions(project, selection, item.option, withPreset(item.name ? presetPretasks?.get(item.name)?.option : undefined)).selected)
|
|
490
|
-
: undefined,
|
|
491
|
-
})),
|
|
509
|
+
pretasks,
|
|
492
510
|
agentEnvironment: {
|
|
493
511
|
PI_INTERFACE_VERSION: 'v2.8.1',
|
|
494
512
|
PI_CLIENT_NAME: 'Cordis MAS',
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@auto-mas/auto-mas-plugin-adapter-bettergi",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"license": "AGPL-3.0-only",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -18,6 +18,14 @@
|
|
|
18
18
|
"access": "public"
|
|
19
19
|
},
|
|
20
20
|
"description": "AUTO-MAS bettergi Cordis component",
|
|
21
|
+
"mas": {
|
|
22
|
+
"hidden": false,
|
|
23
|
+
"category": "adapter",
|
|
24
|
+
"description": {
|
|
25
|
+
"zh": "通过 BetterGI 运行原神一条龙任务",
|
|
26
|
+
"en": "Run Genshin Impact daily routines with BetterGI"
|
|
27
|
+
}
|
|
28
|
+
},
|
|
21
29
|
"autoMas": {
|
|
22
30
|
"id": "bettergi",
|
|
23
31
|
"abi": 1,
|
package/dist/server/storage.js
DELETED
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
import { mkdirSync } from 'node:fs';
|
|
2
|
-
import { join } from 'node:path';
|
|
3
|
-
import { DatabaseSync } from 'node:sqlite';
|
|
4
|
-
export class Store {
|
|
5
|
-
db;
|
|
6
|
-
lease;
|
|
7
|
-
constructor(directory) {
|
|
8
|
-
mkdirSync(directory, { recursive: true });
|
|
9
|
-
this.lease = new DatabaseSync(join(directory, 'session.db'));
|
|
10
|
-
try {
|
|
11
|
-
this.lease.exec('PRAGMA busy_timeout = 0; BEGIN EXCLUSIVE');
|
|
12
|
-
}
|
|
13
|
-
catch (error) {
|
|
14
|
-
this.lease.close();
|
|
15
|
-
if (error.errcode === 5)
|
|
16
|
-
throw new Error('该数据目录已有 MAS 后端在运行');
|
|
17
|
-
throw error;
|
|
18
|
-
}
|
|
19
|
-
try {
|
|
20
|
-
this.db = new DatabaseSync(join(directory, 'mas.db'));
|
|
21
|
-
this.db.exec(`PRAGMA journal_mode = WAL;
|
|
22
|
-
CREATE TABLE IF NOT EXISTS entries (
|
|
23
|
-
collection TEXT NOT NULL, id TEXT NOT NULL, value TEXT NOT NULL,
|
|
24
|
-
PRIMARY KEY (collection, id)
|
|
25
|
-
);
|
|
26
|
-
CREATE INDEX IF NOT EXISTS run_start ON entries (
|
|
27
|
-
unixepoch(json_extract(value, '$.started'), 'subsec') DESC
|
|
28
|
-
) WHERE collection = 'runs'`);
|
|
29
|
-
}
|
|
30
|
-
catch (error) {
|
|
31
|
-
this.lease.close();
|
|
32
|
-
throw error;
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
recentRuns() {
|
|
36
|
-
return this.db.prepare(`SELECT value FROM entries WHERE collection = 'runs'
|
|
37
|
-
ORDER BY unixepoch(json_extract(value, '$.started'), 'subsec') DESC, rowid DESC LIMIT 200`)
|
|
38
|
-
.all().map(row => JSON.parse(String(row.value)));
|
|
39
|
-
}
|
|
40
|
-
list(collection) {
|
|
41
|
-
const rows = this.db.prepare('SELECT value FROM entries WHERE collection = ? ORDER BY rowid').all(collection);
|
|
42
|
-
return rows.map(row => JSON.parse(String(row.value)));
|
|
43
|
-
}
|
|
44
|
-
get(collection, id) {
|
|
45
|
-
const row = this.db.prepare('SELECT value FROM entries WHERE collection = ? AND id = ?').get(collection, id);
|
|
46
|
-
return row && JSON.parse(String(row.value));
|
|
47
|
-
}
|
|
48
|
-
put(collection, entry) {
|
|
49
|
-
this.db.prepare('INSERT INTO entries VALUES (?, ?, ?) ON CONFLICT(collection, id) DO UPDATE SET value = excluded.value')
|
|
50
|
-
.run(collection, entry.id, JSON.stringify(entry));
|
|
51
|
-
return entry;
|
|
52
|
-
}
|
|
53
|
-
remove(collection, id) {
|
|
54
|
-
this.db.prepare('DELETE FROM entries WHERE collection = ? AND id = ?').run(collection, id);
|
|
55
|
-
}
|
|
56
|
-
transaction(callback) {
|
|
57
|
-
this.db.exec('BEGIN IMMEDIATE');
|
|
58
|
-
try {
|
|
59
|
-
const result = callback();
|
|
60
|
-
this.db.exec('COMMIT');
|
|
61
|
-
return result;
|
|
62
|
-
}
|
|
63
|
-
catch (error) {
|
|
64
|
-
this.db.exec('ROLLBACK');
|
|
65
|
-
throw error;
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
close() {
|
|
69
|
-
try {
|
|
70
|
-
this.db.close();
|
|
71
|
-
}
|
|
72
|
-
finally {
|
|
73
|
-
this.lease.close();
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
}
|