poi-plugin-kcsave-exporter 1.0.0 → 1.0.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/README.md CHANGED
@@ -1,17 +1,12 @@
1
- # poi-plugin-kcsave-exporter
1
+ # poi-plugin-kcsave-exporter (poi 12.0.1)
2
2
 
3
- 零外部依赖的 poi 插件,可将当前登录的舰队 Collection 正式服数据一键完全导出为单机版 `.kcsave`(`KCSAVE5`)存档。
4
-
5
- ## 导出内容
6
-
7
- - **自动从 poi 内存读取**:提督信息、8 项资源、全部舰娘(等级/经验/改修/锁船/打孔/装备)、全部装备(改修/熟练度/锁定)、4 支舰队编成、入渠/建造渠、持有道具与家具币、海域攻略进度、基地航空队。
8
- - **自动监听接口捕获(打开对应游戏界面一次即自动记录)**:全部持有家具与母港皮肤(登录时 `require_info`)、编成记录(`preset_deck`)、远征通关记录(`mission`)、舰船/装备图鉴(`picture_book`)、任务列表(`questlist`)。
3
+ 基于 **poi 12.0.1** 插件规范(`.es` ESM + JSX、React Hooks、`react-redux` `useSelector`、`@blueprintjs/core`、`@electron/remote`)编写的零依赖单机版 `.kcsave`(`KCSAVE5`)完全导出插件。
9
4
 
10
5
  ## 安装方法
11
6
 
12
- 1. 将解压后的 `poi-plugin-kcsave-exporter` 整个文件夹复制到 poi 的插件目录:
7
+ 1. 解压后将 `poi-plugin-kcsave-exporter` 文件夹复制到 poi 插件目录:
13
8
  - Windows: `%APPDATA%\poi\plugins\node_modules\`
14
9
  - macOS: `~/Library/Application Support/poi/plugins/node_modules/`
15
10
  - Linux: `~/.config/poi/plugins/node_modules/`
16
- *(也可在 poi 设置 -> 扩展程序 -> 手动安装中直接选择该文件夹)*
17
- 2. 重启 poi,在插件栏打开 **单机存档导出** 即可使用(无需 `npm install`,纯内置模块零依赖)。
11
+ (也可在 poi「设置 -> 扩展程序 -> 手动安装」中选择该文件夹)
12
+ 2. 重启 poi,在插件栏打开 **单机存档导出** 即可使用,无需执行 `npm install`。
package/index.es ADDED
@@ -0,0 +1,228 @@
1
+ import fs from 'fs'
2
+ import path from 'path'
3
+ import React, { useState, useEffect, useCallback } from 'react'
4
+ import { useSelector } from 'react-redux'
5
+ import {
6
+ Button,
7
+ Callout,
8
+ Card,
9
+ Checkbox,
10
+ Divider,
11
+ Elevation,
12
+ Intent,
13
+ Tag,
14
+ } from '@blueprintjs/core'
15
+ import { dialog } from '@electron/remote'
16
+ import { ApiCaptureStore } from './lib/capture'
17
+ import { exportToKcsaveBuffer } from './lib/exporter'
18
+
19
+ const captureStore = new ApiCaptureStore()
20
+
21
+ const formatTime = (ts) => (ts ? new Date(ts).toLocaleTimeString() : '未捕获')
22
+
23
+ const KcsaveExporter = () => {
24
+ const basic = useSelector((state) => state.info?.basic || {})
25
+ const shipsCount = useSelector((state) => Object.keys(state.info?.ships || {}).length)
26
+ const equipsCount = useSelector((state) => Object.keys(state.info?.equips || {}).length)
27
+ const mapsCount = useSelector((state) => Object.keys(state.info?.maps || {}).length)
28
+ const airbaseCount = useSelector((state) => (Array.isArray(state.info?.airbase) ? state.info.airbase.length : 0))
29
+
30
+ const [captured, setCaptured] = useState(() => ({ ...captureStore.data }))
31
+ const [baseFilePath, setBaseFilePath] = useState('')
32
+ const [inheritOfflineProgress, setInheritOfflineProgress] = useState(true)
33
+ const [exporting, setExporting] = useState(false)
34
+ const [status, setStatus] = useState(null)
35
+ const [lastStats, setLastStats] = useState(null)
36
+
37
+ useEffect(() => {
38
+ captureStore.attach()
39
+ const unsub = captureStore.subscribe((data) => {
40
+ setCaptured({ ...data })
41
+ })
42
+ return () => unsub()
43
+ }, [])
44
+
45
+ const handlePickBase = useCallback(async () => {
46
+ try {
47
+ const res = await dialog.showOpenDialog({
48
+ title: '选择已有单机版 .kcsave 模板(可选)',
49
+ filters: [{ name: 'KanColle Offline Save', extensions: ['kcsave'] }],
50
+ properties: ['openFile'],
51
+ })
52
+ const filePath = !res.canceled && res.filePaths?.[0]
53
+ if (filePath) {
54
+ setBaseFilePath(filePath)
55
+ setStatus({ text: `已选择模板:${path.basename(filePath)}`, intent: Intent.PRIMARY })
56
+ }
57
+ } catch (err) {
58
+ setStatus({ text: `选择模板失败:${err.message}`, intent: Intent.DANGER })
59
+ }
60
+ }, [])
61
+
62
+ const handleClearBase = useCallback(() => {
63
+ setBaseFilePath('')
64
+ setStatus({ text: '已清除模板,将使用内置默认配置独立导出。', intent: Intent.NONE })
65
+ }, [])
66
+
67
+ const handleClearCache = useCallback(() => {
68
+ captureStore.clearCache()
69
+ setStatus({ text: '已清空本地捕获缓存,重新打开对应游戏界面后会自动记录。', intent: Intent.NONE })
70
+ }, [])
71
+
72
+ const handleExport = useCallback(async () => {
73
+ setExporting(true)
74
+ setStatus({ text: '正在汇总数据并生成 .kcsave 存档...', intent: Intent.PRIMARY })
75
+ try {
76
+ const reduxState = typeof window.getStore === 'function' ? window.getStore() : {}
77
+ const baseBuf =
78
+ baseFilePath && fs.existsSync(baseFilePath) ? fs.readFileSync(baseFilePath) : null
79
+
80
+ const { buffer, stats } = exportToKcsaveBuffer(reduxState, captureStore.data, baseBuf, {
81
+ inheritOfflineProgress: Boolean(baseBuf && inheritOfflineProgress),
82
+ })
83
+
84
+ const safeName = (stats.nickname || 'admiral').replace(/[\\/:*?"<>|]/g, '_')
85
+ const stamp = new Date().toISOString().slice(0, 10).replace(/-/g, '')
86
+ const defaultPath = `kancolle-${safeName}-${stamp}.kcsave`
87
+
88
+ const res = await dialog.showSaveDialog({
89
+ title: '导出单机版 .kcsave 存档',
90
+ defaultPath,
91
+ filters: [{ name: 'KanColle Offline Save', extensions: ['kcsave'] }],
92
+ })
93
+
94
+ if (res.canceled || !res.filePath) {
95
+ setStatus({ text: '已取消保存。', intent: Intent.NONE })
96
+ return
97
+ }
98
+
99
+ fs.writeFileSync(res.filePath, buffer)
100
+ setLastStats(stats)
101
+ setStatus({
102
+ text: `导出成功!已保存至 ${res.filePath}(${(buffer.length / 1024 / 1024).toFixed(2)} MB)`,
103
+ intent: Intent.SUCCESS,
104
+ })
105
+ } catch (err) {
106
+ setStatus({
107
+ text: `导出失败:${err?.message || String(err)}`,
108
+ intent: Intent.DANGER,
109
+ })
110
+ } finally {
111
+ setExporting(false)
112
+ }
113
+ }, [baseFilePath, inheritOfflineProgress])
114
+
115
+ const capAt = captured.capturedAt || {}
116
+ const furnitureCount = (captured.furnitureOwned || []).length
117
+ const presetsCount = Object.keys(captured.presets || {}).length
118
+ const expeditionsCount = Object.keys(captured.expeditionHistory || {}).length
119
+ const albumShipsCount = Object.keys(captured.albumShips || {}).length
120
+ const albumEquipsCount = Object.keys(captured.albumEquips || {}).length
121
+ const questsCount = Object.keys(captured.quests || {}).length
122
+
123
+ return (
124
+ <div style={{ padding: 14, height: '100%', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 12 }}>
125
+ <Card elevation={Elevation.ONE}>
126
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
127
+ <strong>当前 poi 内存数据</strong>
128
+ <Tag intent={basic.api_nickname ? Intent.SUCCESS : Intent.WARNING} minimal>
129
+ {basic.api_nickname ? `${basic.api_nickname} (Lv.${basic.api_level || 0})` : '未进入母港'}
130
+ </Tag>
131
+ </div>
132
+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
133
+ <Tag minimal>舰娘 {shipsCount}</Tag>
134
+ <Tag minimal>装备 {equipsCount}</Tag>
135
+ <Tag minimal>海域 {mapsCount}</Tag>
136
+ <Tag minimal>陆航 {airbaseCount}</Tag>
137
+ </div>
138
+ </Card>
139
+
140
+ <Card elevation={Elevation.ONE}>
141
+ <strong style={{ display: 'block', marginBottom: 8 }}>额外完整数据捕获状态(打开对应界面自动记录)</strong>
142
+ <div style={{ fontSize: 12, lineHeight: 1.8 }}>
143
+ <div>• 持有家具与设置 (require_info):{furnitureCount} 件({formatTime(capAt.require_info)})</div>
144
+ <div>• 编成记录 (preset_deck):{presetsCount} 组({formatTime(capAt.preset_deck)})</div>
145
+ <div>• 远征通关记录 (mission):{expeditionsCount} 项({formatTime(capAt.mission)})</div>
146
+ <div>• 图鉴记录 (picture_book):舰船 {albumShipsCount} / 装备 {albumEquipsCount}({formatTime(capAt.album_ships || capAt.album_equips)})</div>
147
+ <div>• 任务列表 (questlist):{questsCount} 项({formatTime(capAt.questlist)})</div>
148
+ </div>
149
+ <Divider style={{ margin: '10px 0' }} />
150
+ <div style={{ fontSize: 12, opacity: 0.78 }}>
151
+ 提示:舰娘、装备、资源、舰队、渠位、道具、海域与陆航可直接导出;如需连带家具、远征、编成记录、图鉴与任务一起导出,请先在游戏内打开对应界面一次即可自动捕获。
152
+ </div>
153
+ </Card>
154
+
155
+ <Card elevation={Elevation.ONE}>
156
+ <div style={{ fontSize: 12, marginBottom: 8 }}>
157
+ <strong>可选基础模板:</strong>
158
+ {baseFilePath ? path.basename(baseFilePath) : '无(使用内置默认模板独立导出)'}
159
+ </div>
160
+ <Checkbox
161
+ checked={inheritOfflineProgress}
162
+ disabled={!baseFilePath}
163
+ onChange={(e) => setInheritOfflineProgress(e.currentTarget.checked)}
164
+ label="继承模板中的单机进度(军费、任务进度与历史、活动海域、已探索节点、开发配方、图鉴与单机设置)"
165
+ style={{ fontSize: 12, marginBottom: 10 }}
166
+ />
167
+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
168
+ <Button
169
+ intent={Intent.PRIMARY}
170
+ icon="export"
171
+ loading={exporting}
172
+ onClick={handleExport}
173
+ >
174
+ 一键完全导出 .kcsave
175
+ </Button>
176
+ <Button icon="document-open" onClick={handlePickBase}>
177
+ 选择模板 .kcsave(可选)
178
+ </Button>
179
+ {baseFilePath && (
180
+ <Button icon="cross" onClick={handleClearBase}>
181
+ 清除模板
182
+ </Button>
183
+ )}
184
+ <Button icon="trash" minimal onClick={handleClearCache}>
185
+ 清空捕获缓存
186
+ </Button>
187
+ </div>
188
+ </Card>
189
+
190
+ {status && (
191
+ <Callout intent={status.intent} style={{ wordBreak: 'break-all' }}>
192
+ {status.text}
193
+ </Callout>
194
+ )}
195
+
196
+ {lastStats && (
197
+ <Callout title="本次导出明细" intent={Intent.SUCCESS}>
198
+ <div style={{ fontSize: 12, lineHeight: 1.7 }}>
199
+ <div>
200
+ 提督 {lastStats.nickname} (Lv.{lastStats.level}) | 舰娘 {lastStats.ships} | 装备 {lastStats.equipment} |
201
+ 舰队 {lastStats.decks} | 道具 {lastStats.inventory} | 家具 {lastStats.furniture} |
202
+ 海域 {lastStats.maps} | 陆航 {lastStats.airBases} | 编成记录 {lastStats.presets} |
203
+ 图鉴 {lastStats.albumShips}/{lastStats.albumEquips}
204
+ </div>
205
+ {lastStats.inheritedOffline && (
206
+ <div style={{ marginTop: 4 }}>
207
+ 已继承单机进度:军费 {lastStats.inheritedOffline.treasuryBalance} | 任务 {lastStats.inheritedOffline.questsCount}(历史 {lastStats.inheritedOffline.questHistoryCount}) |
208
+ 活动 {lastStats.inheritedOffline.eventsCount} | 探索海域 {lastStats.inheritedOffline.exploredMapsCount}
209
+ </div>
210
+ )}
211
+ </div>
212
+ </Callout>
213
+ )}
214
+ </div>
215
+ )
216
+ }
217
+
218
+ export const reactClass = KcsaveExporter
219
+
220
+ export const windowMode = false
221
+
222
+ export const pluginDidLoad = () => {
223
+ captureStore.attach()
224
+ }
225
+
226
+ export const pluginWillUnload = () => {
227
+ captureStore.detach()
228
+ }
package/lib/exporter.js CHANGED
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  const crypto = require('crypto');
4
- const { buildSaveSqlite } = require('./sqlite-writer');
5
- const { buildKcsaveBuffer, parseKcsave5 } = require('./kcsave-packer');
4
+ const { buildSaveSqlite, readSaveJsonFromSqlite } = require('./sqlite-writer');
5
+ const { buildKcsaveBuffer, unpackKcsaveTemplate } = require('./kcsave-packer');
6
6
 
7
7
  function toArray(val) {
8
8
  if (!val) return [];
@@ -22,10 +22,14 @@ function mapQuestPeriod(apiType) {
22
22
  }
23
23
  }
24
24
 
25
+ function deepClone(obj) {
26
+ return obj === undefined ? undefined : JSON.parse(JSON.stringify(obj));
27
+ }
28
+
25
29
  /**
26
- * 将 poi Redux store 与实时捕获的 API 数据合并为完整的单机版 save.json 对象。
30
+ * 将 poi Redux store、实时捕获的 API 数据与可选的旧单机模板进度合并为完整的 save.json 对象。
27
31
  */
28
- function buildCompleteSaveObject(reduxState, capturedData = {}) {
32
+ function buildCompleteSaveObject(reduxState, capturedData = {}, templateSave = null) {
29
33
  const info = (reduxState && reduxState.info) || {};
30
34
  const constData = (reduxState && reduxState.const) || {};
31
35
  const mstShips = constData.$ships || {};
@@ -57,7 +61,7 @@ function buildCompleteSaveObject(reduxState, capturedData = {}) {
57
61
  api_level: Number(pb.api_level || 1),
58
62
  api_rank: Number(pb.api_rank || 10),
59
63
  api_experience: Number(pb.api_experience || 0),
60
- api_fleetname: pb.api_fleetname || '本地艦隊',
64
+ api_fleetname: pb.api_fleetname || (templateSave && templateSave.basic && templateSave.basic.api_fleetname) || '本地艦隊',
61
65
  api_firstflag: Number(pb.api_firstflag ?? 1),
62
66
  api_st_win: Number(pb.api_st_win || 0),
63
67
  api_st_lose: Number(pb.api_st_lose || 0),
@@ -81,13 +85,13 @@ function buildCompleteSaveObject(reduxState, capturedData = {}) {
81
85
  api_large_dock: Number(pb.api_large_dock || 0),
82
86
  api_comment: pb.api_comment || '',
83
87
  api_comment_id: String(pb.api_comment_id || '1'),
84
- api_skin_id: Number(capturedData.skinId || 101),
88
+ api_skin_id: Number(capturedData.skinId || (templateSave && templateSave.basic && templateSave.basic.api_skin_id) || 101),
85
89
  api_pvp: Array.isArray(pb.api_pvp) ? pb.api_pvp.map(Number) : [0, 0],
86
90
  api_expedition: [0, 0],
87
91
  api_tutorial_progress: Number(pb.api_tutorial_progress ?? 100),
88
92
  };
89
93
 
90
- // 2. Materials (8 items)
94
+ // 2. Materials
91
95
  let materials = [0, 0, 0, 0, 0, 0, 0, 0];
92
96
  if (Array.isArray(info.resources) && info.resources.length >= 8) {
93
97
  materials = info.resources.slice(0, 8).map(Number);
@@ -189,7 +193,7 @@ function buildCompleteSaveObject(reduxState, capturedData = {}) {
189
193
  }),
190
194
  }));
191
195
 
192
- // 6. Docks (ndock)
196
+ // 6. Docks
193
197
  const docks = rawRepairs.map((nd) => {
194
198
  const state = Number(nd.api_state || 0);
195
199
  const compTime = Number(nd.api_complete_time || 0);
@@ -232,7 +236,7 @@ function buildCompleteSaveObject(reduxState, capturedData = {}) {
232
236
  };
233
237
  });
234
238
 
235
- // 8. Inventory (useitems + furniture coins id 44)
239
+ // 8. Inventory
236
240
  const inventory = {};
237
241
  for (const ui of rawUseitems) {
238
242
  if (ui && ui.api_id !== undefined) {
@@ -243,26 +247,47 @@ function buildCompleteSaveObject(reduxState, capturedData = {}) {
243
247
  inventory['44'] = Number(pb.api_fcoin);
244
248
  }
245
249
 
246
- // 9. Furniture owned
250
+ // 9. Furniture (merge captured + template owned + equipped)
247
251
  const furnSet = new Set(Array.isArray(capturedData.furnitureOwned) ? capturedData.furnitureOwned : []);
252
+ if (templateSave && Array.isArray(templateSave.furniture)) {
253
+ for (const fid of templateSave.furniture) {
254
+ if (Number(fid) > 0) furnSet.add(Number(fid));
255
+ }
256
+ }
248
257
  for (const fid of equippedFurniture) {
249
258
  if (fid > 0) furnSet.add(fid);
250
259
  }
251
260
  const furniture = Array.from(furnSet).sort((a, b) => a - b);
252
261
 
253
- // 10. Map progress (merge Redux info.maps + captured mapinfo)
254
- const mapSource = toArray(info.maps).length > 0 ? toArray(info.maps) : toArray(capturedData.mapInfo);
255
- const mapProgress = mapSource.map((m) => ({
256
- api_id: Number(m.api_id),
257
- api_cleared: Number(m.api_cleared || 0),
258
- api_defeat_count: Number(m.api_defeat_count || 0),
259
- api_air_base_decks: Number(m.api_air_base_decks || 0),
260
- everCleared: Number(m.api_cleared || 0) === 1,
261
- }));
262
+ // 10. Map progress (merge template mapProgress + live info.maps / captured mapInfo)
263
+ const mapById = new Map();
264
+ if (templateSave && Array.isArray(templateSave.mapProgress)) {
265
+ for (const m of templateSave.mapProgress) {
266
+ if (m && m.api_id) mapById.set(Number(m.api_id), deepClone(m));
267
+ }
268
+ }
269
+ const liveMaps = toArray(info.maps).length > 0 ? toArray(info.maps) : toArray(capturedData.mapInfo);
270
+ for (const m of liveMaps) {
271
+ const id = Number(m.api_id);
272
+ const prev = mapById.get(id);
273
+ const cleared = Number(m.api_cleared || 0);
274
+ mapById.set(id, {
275
+ api_id: id,
276
+ api_cleared: cleared,
277
+ api_defeat_count: Number(m.api_defeat_count || 0),
278
+ api_air_base_decks: Number(m.api_air_base_decks || 0),
279
+ everCleared: cleared === 1 || Boolean(prev && prev.everCleared),
280
+ });
281
+ }
282
+ const mapProgress = Array.from(mapById.values()).sort((a, b) => a.api_id - b.api_id);
262
283
 
263
- // 11. Land-Base Air Squadrons (merge Redux info.airbase + captured airBase)
284
+ // 11. Land-Base Air Squadrons
264
285
  const rawAirBases = toArray(info.airbase).length > 0 ? toArray(info.airbase) : toArray(capturedData.airBase);
265
- const airBaseAreas = new Set();
286
+ const airBaseAreas = new Set(
287
+ templateSave && templateSave.operations && Array.isArray(templateSave.operations.airBaseUnlockedAreas)
288
+ ? templateSave.operations.airBaseUnlockedAreas
289
+ : []
290
+ );
266
291
  const airBases = rawAirBases.map((ab) => {
267
292
  const areaId = Number(ab.api_area_id);
268
293
  if (areaId > 0) airBaseAreas.add(areaId);
@@ -292,11 +317,8 @@ function buildCompleteSaveObject(reduxState, capturedData = {}) {
292
317
  };
293
318
  });
294
319
 
295
- // 12. Presets (merge Redux info.presets.api_deck + captured presets)
296
- const rawPresets =
297
- (info.presets && info.presets.api_deck) ||
298
- capturedData.presets ||
299
- {};
320
+ // 12. Presets
321
+ const rawPresets = (info.presets && info.presets.api_deck) || capturedData.presets || {};
300
322
  const presets = {};
301
323
  for (const [key, pr] of Object.entries(rawPresets)) {
302
324
  if (!pr || typeof pr !== 'object') continue;
@@ -315,29 +337,42 @@ function buildCompleteSaveObject(reduxState, capturedData = {}) {
315
337
  };
316
338
  }
317
339
 
318
- // 13. Quests (from captured questlist or Redux info.quests.activeQuests)
319
- const quests = [];
340
+ // 13. Quests (preserve template offline quests + overlay live captured quests)
341
+ const questsById = new Map();
342
+ if (templateSave && Array.isArray(templateSave.quests)) {
343
+ for (const q of templateSave.quests) {
344
+ if (q && q.id) questsById.set(Number(q.id), deepClone(q));
345
+ }
346
+ }
320
347
  const capturedQuests = capturedData.quests || {};
321
348
  const activeQuests = (info.quests && info.quests.activeQuests) || {};
322
- const mergedQuestMap = Object.assign({}, capturedQuests);
349
+ const mergedLiveQuests = Object.assign({}, capturedQuests);
323
350
  for (const [qid, qWrap] of Object.entries(activeQuests)) {
324
- if (qWrap && qWrap.detail && !mergedQuestMap[qid]) {
325
- mergedQuestMap[qid] = qWrap.detail;
351
+ if (qWrap && qWrap.detail && !mergedLiveQuests[qid]) {
352
+ mergedLiveQuests[qid] = qWrap.detail;
326
353
  }
327
354
  }
328
- for (const q of Object.values(mergedQuestMap)) {
355
+ for (const q of Object.values(mergedLiveQuests)) {
329
356
  if (!q || !q.api_no) continue;
330
- quests.push({
331
- id: Number(q.api_no),
357
+ const id = Number(q.api_no);
358
+ const prev = questsById.get(id);
359
+ questsById.set(id, {
360
+ id,
332
361
  period: mapQuestPeriod(q.api_type),
333
362
  accepted: Number(q.api_state) === 2 || Number(q.api_state) === 3,
334
- progress: {},
363
+ progress: (prev && prev.progress) || {},
335
364
  unlocked: true,
336
365
  });
337
366
  }
338
-
339
- // 14. Album (merge captured picture_book + all currently owned ships & equips)
340
- const albumShips = Object.assign({}, capturedData.albumShips || {});
367
+ const quests = Array.from(questsById.values());
368
+
369
+ // 14. Album (merge template album + captured picture_book + currently owned)
370
+ const tplOps = (templateSave && templateSave.operations) || {};
371
+ const albumShips = Object.assign(
372
+ {},
373
+ deepClone((tplOps.album && tplOps.album.ships) || {}),
374
+ deepClone(capturedData.albumShips || {})
375
+ );
341
376
  for (const sh of ships) {
342
377
  const k = String(sh.api_ship_id);
343
378
  const prev = albumShips[k] || { normal: true, damaged: false, married: false };
@@ -347,12 +382,16 @@ function buildCompleteSaveObject(reduxState, capturedData = {}) {
347
382
  married: Boolean(prev.married) || sh.api_lv >= 100,
348
383
  };
349
384
  }
350
- const albumEquips = Object.assign({}, capturedData.albumEquips || {});
385
+ const albumEquips = Object.assign(
386
+ {},
387
+ deepClone((tplOps.album && tplOps.album.equipment) || {}),
388
+ deepClone(capturedData.albumEquips || {})
389
+ );
351
390
  for (const eq of equipment) {
352
391
  albumEquips[String(eq.api_slotitem_id)] = true;
353
392
  }
354
393
 
355
- // 15. Root & head hashes for fresh SQLite lineage/transfer_meta
394
+ // 15. Build operations (inherit offline progress from templateSave if provided, while sanitizing stale ship IDs)
356
395
  const rootId = crypto.randomBytes(20).toString('hex');
357
396
  const headHash = crypto.randomBytes(32).toString('hex');
358
397
 
@@ -361,12 +400,113 @@ function buildCompleteSaveObject(reduxState, capturedData = {}) {
361
400
  rosters[String(dk.api_id)] = dk.api_ship.join(',') + ':0:1';
362
401
  }
363
402
 
403
+ const defaultOps = {
404
+ developmentPresetCapacity: 4,
405
+ equipmentPresetCapacity: 4,
406
+ treasury: { version: 1, balance: 0, progress: 0, receipts: {} },
407
+ honors: {},
408
+ economy: { version: 2, lastReal: nowMs, lastPayment: nowMs, fractions: [0, 0, 0, 0] },
409
+ moraleRecoveryAt: {},
410
+ remodelCostSettlement: { version: 1, fromRevision: 0, root: rootId, afterRestore: 0, legacyEvents: 0 },
411
+ remodelCostAnchor: { revision: 0, ships: [] },
412
+ remodelCostCursor: { root: rootId, id: 0 },
413
+ practiceV2: { version: 2, serial: 1, highestStage: 0, highestStrength: 0 },
414
+ album: { ships: albumShips, equipment: albumEquips },
415
+ events: {},
416
+ questHistory: {},
417
+ training: { version: 1, balance: 0, targets: [], auto: false, serial: 1, receipts: [] },
418
+ expeditionRuns: {},
419
+ portRepair: { started: nowMs, rosters, last: { at: nowMs, elapsed: 0, repairs: [] } },
420
+ airBases,
421
+ purchasedItems: [],
422
+ resourceHistory: [],
423
+ memorialQuestIdVersion: 1,
424
+ questStateVersion: 2,
425
+ friendlySetting: { api_request_flag: 1, api_request_type: 0 },
426
+ exploredMaps: {},
427
+ acquisition: { version: 2, legacyArchive: null, sequence: 1, receipts: {} },
428
+ battleHistory: [],
429
+ battleSupport: {},
430
+ logisticsReceipts: {},
431
+ portNotices: [],
432
+ materialSpentTotals: [0, 0, 0, 0],
433
+ organizeList: capturedData.ossSetting || { api_oss_items: [1, 0, 0, 0, 0, 0, 0, 0], api_language_type: 0 },
434
+ optimizedQuestRounds: {},
435
+ presets,
436
+ expeditionHistory: Object.assign({}, capturedData.expeditionHistory || {}),
437
+ expeditionReceipts: {},
438
+ remodelPayments: {},
439
+ developmentPresets: {},
440
+ largeConstructionUnlocked: basic.api_large_dock === 1,
441
+ selectedEvent: '',
442
+ strikingFleetUnlocked: true,
443
+ airBaseUnlockedAreas: Array.from(airBaseAreas).sort((a, b) => a - b),
444
+ optimizedMilestones: basic.api_level >= 99 ? { 'first-level-99': true } : {},
445
+ };
446
+
447
+ let operations = defaultOps;
448
+ let inheritedSummary = null;
449
+
450
+ if (templateSave && templateSave.operations && typeof templateSave.operations === 'object') {
451
+ operations = Object.assign({}, defaultOps, deepClone(templateSave.operations));
452
+ // 覆盖必须与当前正式服舰娘/装备一致的字段,并清理旧舰娘 ID 悬空引用
453
+ operations.album = { ships: albumShips, equipment: albumEquips };
454
+ operations.airBases = airBases.length > 0 ? airBases : [];
455
+ operations.airBaseUnlockedAreas = Array.from(airBaseAreas).sort((a, b) => a - b);
456
+ operations.presets = presets;
457
+ operations.expeditionHistory = Object.assign(
458
+ {},
459
+ operations.expeditionHistory || {},
460
+ capturedData.expeditionHistory || {}
461
+ );
462
+ if (capturedData.ossSetting) {
463
+ operations.organizeList = capturedData.ossSetting;
464
+ }
465
+ if (basic.api_large_dock === 1) {
466
+ operations.largeConstructionUnlocked = true;
467
+ }
468
+ operations.moraleRecoveryAt = {};
469
+ operations.expeditionRuns = {};
470
+ if (operations.training && typeof operations.training === 'object') {
471
+ operations.training.targets = [];
472
+ }
473
+ operations.portRepair = {
474
+ started: nowMs,
475
+ rosters,
476
+ last: { at: nowMs, elapsed: 0, repairs: [] },
477
+ };
478
+ delete operations.lastSortie;
479
+ operations.remodelCostSettlement = { version: 1, fromRevision: 0, root: rootId, afterRestore: 0, legacyEvents: 0 };
480
+ operations.remodelCostAnchor = { revision: 0, ships: [] };
481
+ operations.remodelCostCursor = { root: rootId, id: 0 };
482
+
483
+ inheritedSummary = {
484
+ treasuryBalance: operations.treasury ? operations.treasury.balance : 0,
485
+ questHistoryCount: Object.keys(operations.questHistory || {}).length,
486
+ eventsCount: Object.keys(operations.events || {}).length,
487
+ exploredMapsCount: Object.keys(operations.exploredMaps || {}).length,
488
+ questsCount: quests.length,
489
+ };
490
+ }
491
+
492
+ const settings =
493
+ templateSave && templateSave.settings
494
+ ? deepClone(templateSave.settings)
495
+ : {
496
+ sinkingProtection: true,
497
+ repairAuto: false,
498
+ repairThresholdSeconds: 60,
499
+ optimizeFleetSpecialAttacks: false,
500
+ animationScale: 4,
501
+ localMapApproximations: true,
502
+ };
503
+
364
504
  const saveObj = {
365
- schemaVersion: 2,
366
- contentId: '6.3.6.0',
367
- rulesVersion: 'optimized-2',
505
+ schemaVersion: (templateSave && templateSave.schemaVersion) || 2,
506
+ contentId: (templateSave && templateSave.contentId) || '6.3.6.0',
507
+ rulesVersion: (templateSave && templateSave.rulesVersion) || 'optimized-2',
368
508
  revision: 0,
369
- createdAt: nowMs,
509
+ createdAt: (templateSave && templateSave.createdAt) || nowMs,
370
510
  lastSeen: nowMs,
371
511
  nextShipId: maxShipId + 1,
372
512
  nextEquipId: maxEquipId + 1,
@@ -379,59 +519,10 @@ function buildCompleteSaveObject(reduxState, capturedData = {}) {
379
519
  kdocks,
380
520
  quests,
381
521
  mapProgress,
382
- settings: {
383
- sinkingProtection: true,
384
- repairAuto: false,
385
- repairThresholdSeconds: 60,
386
- optimizeFleetSpecialAttacks: false,
387
- animationScale: 4,
388
- localMapApproximations: true,
389
- },
522
+ settings,
390
523
  clock: { real: nowMs, game: nowMs },
391
524
  sortie: null,
392
- operations: {
393
- developmentPresetCapacity: 4,
394
- equipmentPresetCapacity: 4,
395
- treasury: { version: 1, balance: 0, progress: 0, receipts: {} },
396
- honors: {},
397
- economy: { version: 2, lastReal: nowMs, lastPayment: nowMs, fractions: [0, 0, 0, 0] },
398
- moraleRecoveryAt: {},
399
- remodelCostSettlement: { version: 1, fromRevision: 0, root: rootId, afterRestore: 0, legacyEvents: 0 },
400
- remodelCostAnchor: { revision: 0, ships: [] },
401
- remodelCostCursor: { root: rootId, id: 0 },
402
- practiceV2: { version: 2, serial: 1, highestStage: 0, highestStrength: 0 },
403
- album: { ships: albumShips, equipment: albumEquips },
404
- events: {},
405
- questHistory: {},
406
- training: { version: 1, balance: 0, targets: [], auto: false, serial: 1, receipts: [] },
407
- expeditionRuns: {},
408
- portRepair: { started: nowMs, rosters, last: { at: nowMs, elapsed: 0, repairs: [] } },
409
- airBases,
410
- purchasedItems: [],
411
- resourceHistory: [],
412
- memorialQuestIdVersion: 1,
413
- questStateVersion: 2,
414
- friendlySetting: { api_request_flag: 1, api_request_type: 0 },
415
- exploredMaps: {},
416
- acquisition: { version: 2, legacyArchive: null, sequence: 1, receipts: {} },
417
- battleHistory: [],
418
- battleSupport: {},
419
- logisticsReceipts: {},
420
- portNotices: [],
421
- materialSpentTotals: [0, 0, 0, 0],
422
- organizeList: capturedData.ossSetting || { api_oss_items: [1, 0, 0, 0, 0, 0, 0, 0], api_language_type: 0 },
423
- optimizedQuestRounds: {},
424
- presets,
425
- expeditionHistory: Object.assign({}, capturedData.expeditionHistory || {}),
426
- expeditionReceipts: {},
427
- remodelPayments: {},
428
- developmentPresets: {},
429
- largeConstructionUnlocked: basic.api_large_dock === 1,
430
- selectedEvent: '',
431
- strikingFleetUnlocked: true,
432
- airBaseUnlockedAreas: Array.from(airBaseAreas).sort((a, b) => a - b),
433
- optimizedMilestones: basic.api_level >= 99 ? { 'first-level-99': true } : {},
434
- },
525
+ operations,
435
526
  inventory,
436
527
  furniture,
437
528
  };
@@ -454,37 +545,51 @@ function buildCompleteSaveObject(reduxState, capturedData = {}) {
454
545
  quests: quests.length,
455
546
  albumShips: Object.keys(albumShips).length,
456
547
  albumEquips: Object.keys(albumEquips).length,
457
- expeditions: Object.keys(saveObj.operations.expeditionHistory).length,
548
+ expeditions: Object.keys(operations.expeditionHistory || {}).length,
549
+ inheritedOffline: inheritedSummary,
458
550
  },
459
551
  };
460
552
  }
461
553
 
462
554
  /**
463
555
  * 直接从 poi 数据生成完整的 .kcsave 二进制 Buffer(零外部依赖)。
464
- * 可选传入 baseKcsaveBuf 以继承原单机存档中的 appearance.json 立绘配置与 contentId。
556
+ * @param {object} reduxState
557
+ * @param {object} capturedData
558
+ * @param {Buffer|null} baseKcsaveBuf
559
+ * @param {object} [options]
560
+ * @param {boolean} [options.inheritOfflineProgress=true] - 是否从模板继承单机专属进度
465
561
  */
466
- function exportToKcsaveBuffer(reduxState, capturedData = {}, baseKcsaveBuf = null) {
467
- const { saveObj, rootId, headHash, stats } = buildCompleteSaveObject(reduxState, capturedData);
562
+ function exportToKcsaveBuffer(
563
+ reduxState,
564
+ capturedData = {},
565
+ baseKcsaveBuf = null,
566
+ options = { inheritOfflineProgress: true }
567
+ ) {
468
568
  let appearance = null;
469
- let contentId = saveObj.contentId;
470
- let rulesVersion = saveObj.rulesVersion;
569
+ let contentId = '6.3.6.0';
570
+ let rulesVersion = 'optimized-2';
571
+ let templateSave = null;
471
572
 
472
573
  if (baseKcsaveBuf) {
473
- try {
474
- const entries = parseKcsave5(baseKcsaveBuf);
475
- const manifest = JSON.parse(entries.get('manifest.json').toString('utf8'));
476
- if (manifest.contentId) contentId = manifest.contentId;
477
- if (manifest.rulesVersion) rulesVersion = manifest.rulesVersion;
478
- const activeId = manifest.activeId || 'legacy';
479
- const appearRaw = entries.get(`profiles/${activeId}/appearance.json`);
480
- if (appearRaw) appearance = JSON.parse(appearRaw.toString('utf8'));
481
- saveObj.contentId = contentId;
482
- saveObj.rulesVersion = rulesVersion;
483
- } catch (_) {
484
- // 忽略无效模板,退回默认配置
574
+ const tpl = unpackKcsaveTemplate(baseKcsaveBuf);
575
+ if (tpl.manifest) {
576
+ if (tpl.manifest.contentId) contentId = tpl.manifest.contentId;
577
+ if (tpl.manifest.rulesVersion) rulesVersion = tpl.manifest.rulesVersion;
578
+ }
579
+ appearance = tpl.appearance;
580
+ if (options && options.inheritOfflineProgress && tpl.sqliteBytes) {
581
+ templateSave = readSaveJsonFromSqlite(tpl.sqliteBytes);
485
582
  }
486
583
  }
487
584
 
585
+ const { saveObj, rootId, headHash, stats } = buildCompleteSaveObject(
586
+ reduxState,
587
+ capturedData,
588
+ templateSave
589
+ );
590
+ saveObj.contentId = contentId;
591
+ saveObj.rulesVersion = rulesVersion;
592
+
488
593
  const saveJson = JSON.stringify(saveObj);
489
594
  const sqliteBytes = buildSaveSqlite({
490
595
  saveJson,
@@ -154,3 +154,85 @@ module.exports = {
154
154
  buildKcsaveBuffer,
155
155
  sha256Hex,
156
156
  };
157
+
158
+ function unpackKcs3(buf) {
159
+ if (buf.subarray(0, 4).toString('ascii') !== 'KCS3') {
160
+ throw new Error('无效的 KCS3 头');
161
+ }
162
+ const hdrLen = buf.readUInt32BE(4);
163
+ const hdrHash = buf.subarray(8, 40);
164
+ const hdrBuf = buf.subarray(40, 40 + hdrLen);
165
+ if (!sha256Buf(hdrBuf).equals(hdrHash)) {
166
+ throw new Error('KCS3 头部校验失败');
167
+ }
168
+ const header = JSON.parse(hdrBuf.toString('utf8'));
169
+ const sqliteBytes = zlib.gunzipSync(buf.subarray(40 + hdrLen));
170
+ return { header, sqliteBytes };
171
+ }
172
+
173
+ function applyKdz5Delta(baseSqliteBytes, deltaBuf) {
174
+ if (deltaBuf.subarray(0, 4).toString('ascii') !== 'KDZ5' || deltaBuf[4] !== 1) {
175
+ throw new Error('无效的 KDZ5 增量头');
176
+ }
177
+ const targetLen = deltaBuf.readUInt32BE(5);
178
+ const expectedHash = deltaBuf.subarray(deltaBuf.length - 32);
179
+ const gzPart = deltaBuf.subarray(9, deltaBuf.length - 32);
180
+ const ops = zlib.gunzipSync(gzPart);
181
+
182
+ const out = Buffer.alloc(targetLen);
183
+ let p = 0;
184
+ let outPos = 0;
185
+ let blkIdx = 0;
186
+ while (p < ops.length && outPos < targetLen) {
187
+ const op = ops[p++];
188
+ const rem = Math.min(256, targetLen - outPos);
189
+ if (op === 0) {
190
+ baseSqliteBytes.copy(out, outPos, blkIdx * 256, blkIdx * 256 + rem);
191
+ } else if (op === 1) {
192
+ ops.copy(out, outPos, p, p + rem);
193
+ p += rem;
194
+ } else if (op === 2) {
195
+ const srcBlk = ops.readUInt32BE(p);
196
+ p += 4;
197
+ baseSqliteBytes.copy(out, outPos, srcBlk * 256, srcBlk * 256 + rem);
198
+ } else {
199
+ throw new Error(`未知 KDZ5 操作码: ${op}`);
200
+ }
201
+ outPos += rem;
202
+ blkIdx += 1;
203
+ }
204
+ if (!sha256Buf(out).equals(expectedHash)) {
205
+ throw new Error('KDZ5 还原后的数据库 SHA-256 校验失败');
206
+ }
207
+ return out;
208
+ }
209
+
210
+ /**
211
+ * 解析基础模板 .kcsave,返回 manifest、appearance 与最新状态的 SQLite Buffer(自动应用 save.delta)。
212
+ */
213
+ function unpackKcsaveTemplate(rawBuf) {
214
+ const entries = parseKcsave5(rawBuf);
215
+ const manifest = JSON.parse(entries.get('manifest.json').toString('utf8'));
216
+ const activeId = manifest.activeId || 'legacy';
217
+ const appearRaw = entries.get(`profiles/${activeId}/appearance.json`);
218
+ const appearance = appearRaw ? JSON.parse(appearRaw.toString('utf8')) : null;
219
+ const slotRaw = entries.get(`profiles/${activeId}/slot-1.json`);
220
+ let sqliteBytes = null;
221
+ if (slotRaw) {
222
+ const { sqliteBytes: slotDb } = unpackKcs3(slotRaw);
223
+ sqliteBytes = slotDb;
224
+ const deltaRaw = entries.get(`profiles/${activeId}/save.delta`);
225
+ if (deltaRaw) {
226
+ try {
227
+ sqliteBytes = applyKdz5Delta(slotDb, deltaRaw);
228
+ } catch (_) {
229
+ // 如果 delta 异常则回退到 slot-1.json
230
+ }
231
+ }
232
+ }
233
+ return { manifest, appearance, sqliteBytes };
234
+ }
235
+
236
+ module.exports.unpackKcs3 = unpackKcs3;
237
+ module.exports.applyKdz5Delta = applyKdz5Delta;
238
+ module.exports.unpackKcsaveTemplate = unpackKcsaveTemplate;
@@ -286,3 +286,165 @@ function buildSaveSqlite({ saveJson, rootId, headHash, revision = 0 }) {
286
286
  }
287
287
 
288
288
  module.exports = { buildSaveSqlite };
289
+
290
+ // ==================== 零依赖纯 JS SQLite 3 读取器 ====================
291
+ // 用于从已有单机版模板 .kcsave 的 SQLite 数据库中读取 save.json(继承单机进度)
292
+
293
+ function readVarint(buf, offset) {
294
+ let val = 0n;
295
+ for (let i = 0; i < 8; i++) {
296
+ const b = buf[offset + i];
297
+ val = (val << 7n) | BigInt(b & 0x7f);
298
+ if ((b & 0x80) === 0) {
299
+ return { value: Number(val), bytes: i + 1 };
300
+ }
301
+ }
302
+ const b8 = buf[offset + 8];
303
+ val = (val << 8n) | BigInt(b8);
304
+ return { value: Number(val), bytes: 9 };
305
+ }
306
+
307
+ function decodeRecord(payload) {
308
+ const { value: hdrSize, bytes: hdrLenBytes } = readVarint(payload, 0);
309
+ const serialTypes = [];
310
+ let pos = hdrLenBytes;
311
+ while (pos < hdrSize) {
312
+ const st = readVarint(payload, pos);
313
+ serialTypes.push(st.value);
314
+ pos += st.bytes;
315
+ }
316
+ let dataPos = hdrSize;
317
+ const values = [];
318
+ for (const st of serialTypes) {
319
+ if (st === 0) {
320
+ values.push(null);
321
+ } else if (st === 1) {
322
+ values.push(payload.readInt8(dataPos));
323
+ dataPos += 1;
324
+ } else if (st === 2) {
325
+ values.push(payload.readInt16BE(dataPos));
326
+ dataPos += 2;
327
+ } else if (st === 3) {
328
+ values.push(payload.readIntBE(dataPos, 3));
329
+ dataPos += 3;
330
+ } else if (st === 4) {
331
+ values.push(payload.readInt32BE(dataPos));
332
+ dataPos += 4;
333
+ } else if (st === 5) {
334
+ values.push(payload.readIntBE(dataPos, 6));
335
+ dataPos += 6;
336
+ } else if (st === 6) {
337
+ values.push(Number(payload.readBigInt64BE(dataPos)));
338
+ dataPos += 8;
339
+ } else if (st === 7) {
340
+ values.push(payload.readDoubleBE(dataPos));
341
+ dataPos += 8;
342
+ } else if (st === 8) {
343
+ values.push(0);
344
+ } else if (st === 9) {
345
+ values.push(1);
346
+ } else if (st >= 12 && st % 2 === 0) {
347
+ const len = (st - 12) / 2;
348
+ values.push(payload.subarray(dataPos, dataPos + len));
349
+ dataPos += len;
350
+ } else if (st >= 13 && st % 2 === 1) {
351
+ const len = (st - 13) / 2;
352
+ values.push(payload.subarray(dataPos, dataPos + len).toString('utf8'));
353
+ dataPos += len;
354
+ } else {
355
+ values.push(null);
356
+ }
357
+ }
358
+ return values;
359
+ }
360
+
361
+ function readTableBTreeRows(dbBuf, pageNum, pageSize, usableSize) {
362
+ const pageOffset = (pageNum - 1) * pageSize;
363
+ const hdrOffset = pageNum === 1 ? 100 : 0;
364
+ const pageType = dbBuf[pageOffset + hdrOffset];
365
+ const cellCount = dbBuf.readUInt16BE(pageOffset + hdrOffset + 3);
366
+ const rows = [];
367
+
368
+ if (pageType === 0x05) {
369
+ // Interior table B-tree page
370
+ const rightMost = dbBuf.readUInt32BE(pageOffset + hdrOffset + 8);
371
+ const ptrStart = pageOffset + hdrOffset + 12;
372
+ for (let i = 0; i < cellCount; i++) {
373
+ const cellOff = dbBuf.readUInt16BE(ptrStart + i * 2);
374
+ const leftChild = dbBuf.readUInt32BE(pageOffset + cellOff);
375
+ rows.push(...readTableBTreeRows(dbBuf, leftChild, pageSize, usableSize));
376
+ }
377
+ rows.push(...readTableBTreeRows(dbBuf, rightMost, pageSize, usableSize));
378
+ } else if (pageType === 0x0d) {
379
+ // Leaf table B-tree page
380
+ const ptrStart = pageOffset + hdrOffset + 8;
381
+ const X = usableSize - 35;
382
+ const M = Math.floor(((usableSize - 12) * 32) / 255) - 23;
383
+ for (let i = 0; i < cellCount; i++) {
384
+ const cellOff = dbBuf.readUInt16BE(ptrStart + i * 2);
385
+ let p = pageOffset + cellOff;
386
+ const pSize = readVarint(dbBuf, p);
387
+ p += pSize.bytes;
388
+ const rowid = readVarint(dbBuf, p);
389
+ p += rowid.bytes;
390
+
391
+ const P = pSize.value;
392
+ let payload;
393
+ if (P <= X) {
394
+ payload = dbBuf.subarray(p, p + P);
395
+ } else {
396
+ const K = M + ((P - M) % (usableSize - 4));
397
+ const localLen = K <= X ? K : M;
398
+ const parts = [dbBuf.subarray(p, p + localLen)];
399
+ let remaining = P - localLen;
400
+ let ovPage = dbBuf.readUInt32BE(p + localLen);
401
+ while (ovPage > 0 && remaining > 0) {
402
+ const ovOff = (ovPage - 1) * pageSize;
403
+ const nextOv = dbBuf.readUInt32BE(ovOff);
404
+ const take = Math.min(remaining, usableSize - 4);
405
+ parts.push(dbBuf.subarray(ovOff + 4, ovOff + 4 + take));
406
+ remaining -= take;
407
+ ovPage = nextOv;
408
+ }
409
+ payload = Buffer.concat(parts);
410
+ }
411
+ rows.push({ rowid: rowid.value, values: decodeRecord(payload) });
412
+ }
413
+ }
414
+ return rows;
415
+ }
416
+
417
+ /**
418
+ * 从 SQLite 3 二进制 Buffer 中读取 save 表 (id=1) 的 json 字段并解析为对象。
419
+ */
420
+ function readSaveJsonFromSqlite(dbBuf) {
421
+ if (!Buffer.isBuffer(dbBuf)) dbBuf = Buffer.from(dbBuf);
422
+ if (dbBuf.subarray(0, 16).toString('ascii') !== 'SQLite format 3\0') {
423
+ throw new Error('无效的 SQLite 3 数据库头');
424
+ }
425
+ let pageSize = dbBuf.readUInt16BE(16);
426
+ if (pageSize === 1) pageSize = 65536;
427
+ const reserved = dbBuf[20];
428
+ const usableSize = pageSize - reserved;
429
+
430
+ const masterRows = readTableBTreeRows(dbBuf, 1, pageSize, usableSize);
431
+ let saveRootPage = 0;
432
+ for (const row of masterRows) {
433
+ if (row.values[0] === 'table' && row.values[1] === 'save') {
434
+ saveRootPage = Number(row.values[3]);
435
+ break;
436
+ }
437
+ }
438
+ if (!saveRootPage) {
439
+ throw new Error('模板 SQLite 中未找到 save 表');
440
+ }
441
+
442
+ const saveRows = readTableBTreeRows(dbBuf, saveRootPage, pageSize, usableSize);
443
+ const target = saveRows.find((r) => r.rowid === 1) || saveRows[0];
444
+ if (!target || typeof target.values[1] !== 'string') {
445
+ throw new Error('模板 save 表中没有有效的 JSON 数据');
446
+ }
447
+ return JSON.parse(target.values[1]);
448
+ }
449
+
450
+ module.exports.readSaveJsonFromSqlite = readSaveJsonFromSqlite;
package/package.json CHANGED
@@ -1,19 +1,22 @@
1
1
  {
2
2
  "name": "poi-plugin-kcsave-exporter",
3
- "version": "1.0.0",
4
- "description": "一键将舰队 Collection 正式服数据完全导出为单机版 .kcsave (KCSAVE5) 存档",
5
- "main": "index.js",
3
+ "version": "1.0.2",
4
+ "description": "一键将舰队 Collection 正式服数据完全导出为单机版 .kcsave (KCSAVE5) 存档(适配 poi 12.0.1)",
5
+ "main": "index.es",
6
6
  "keywords": [
7
- "poi-plugin",
8
7
  "kancolle",
8
+ "poi",
9
+ "poi-plugin",
9
10
  "kcsave"
10
11
  ],
11
12
  "license": "MIT",
12
13
  "poiPlugin": {
13
- "id": "poi-plugin-kcsave-exporter",
14
14
  "title": "单机存档导出",
15
+ "description": "零依赖一键完全导出舰队单机版 .kcsave 存档",
15
16
  "icon": "fa/floppy-o",
16
- "category": "utility",
17
- "description": "零依赖一键完全导出舰队单机版 .kcsave 存档"
17
+ "priority": 100,
18
+ "apiVer": {
19
+ "12.0.0": "1.0.0"
20
+ }
18
21
  }
19
22
  }
package/index.js DELETED
@@ -1,300 +0,0 @@
1
- 'use strict';
2
-
3
- const fs = require('fs');
4
- const path = require('path');
5
- const React = require('react');
6
- const { ApiCaptureStore } = require('./lib/capture');
7
- const { exportToKcsaveBuffer } = require('./lib/exporter');
8
-
9
- const captureStore = new ApiCaptureStore();
10
-
11
- function getElectronDialog() {
12
- try {
13
- const remote = require('@electron/remote');
14
- if (remote && remote.dialog) return remote.dialog;
15
- } catch (_) {}
16
- try {
17
- const electron = require('electron');
18
- if (electron && electron.remote && electron.remote.dialog) {
19
- return electron.remote.dialog;
20
- }
21
- } catch (_) {}
22
- return null;
23
- }
24
-
25
- function getReduxState() {
26
- if (typeof window !== 'undefined' && typeof window.getStore === 'function') {
27
- return window.getStore();
28
- }
29
- return {};
30
- }
31
-
32
- function formatTime(ts) {
33
- if (!ts) return '未捕获';
34
- const d = new Date(ts);
35
- return `${d.toLocaleTimeString()}`;
36
- }
37
-
38
- class KcsaveExporterPanel extends React.Component {
39
- constructor(props) {
40
- super(props);
41
- this.state = {
42
- status: '',
43
- statusType: 'info',
44
- exporting: false,
45
- baseFilePath: '',
46
- lastStats: null,
47
- captured: captureStore.data,
48
- };
49
- this._unsub = null;
50
- this._handleExport = this._handleExport.bind(this);
51
- this._handlePickBase = this._handlePickBase.bind(this);
52
- this._handleClearBase = this._handleClearBase.bind(this);
53
- this._handleClearCache = this._handleClearCache.bind(this);
54
- }
55
-
56
- componentDidMount() {
57
- captureStore.attach();
58
- this._unsub = captureStore.subscribe((data) => {
59
- this.setState({ captured: Object.assign({}, data) });
60
- });
61
- }
62
-
63
- componentWillUnmount() {
64
- if (this._unsub) {
65
- this._unsub();
66
- this._unsub = null;
67
- }
68
- }
69
-
70
- async _handlePickBase() {
71
- const dialog = getElectronDialog();
72
- if (!dialog) {
73
- this.setState({ status: '当前环境无法打开文件选择框,可直接无模板导出。', statusType: 'warn' });
74
- return;
75
- }
76
- try {
77
- const res = await dialog.showOpenDialog({
78
- title: '选择已有单机版 .kcsave 模板(可选)',
79
- filters: [{ name: 'KanColle Offline Save', extensions: ['kcsave'] }],
80
- properties: ['openFile'],
81
- });
82
- const filePath = res && !res.canceled && res.filePaths && res.filePaths[0];
83
- if (filePath) {
84
- this.setState({ baseFilePath: filePath, status: `已选择模板: ${path.basename(filePath)}`, statusType: 'info' });
85
- }
86
- } catch (err) {
87
- this.setState({ status: `选择模板失败: ${err.message}`, statusType: 'error' });
88
- }
89
- }
90
-
91
- _handleClearBase() {
92
- this.setState({ baseFilePath: '', status: '已清除模板,将使用内置默认配置导出。', statusType: 'info' });
93
- }
94
-
95
- _handleClearCache() {
96
- captureStore.clearCache();
97
- this.setState({ status: '已清空本地捕获缓存。重新进入母港或相关页面后会自动重新捕获。', statusType: 'info' });
98
- }
99
-
100
- async _handleExport() {
101
- this.setState({ exporting: true, status: '正在汇总数据并生成 .kcsave 存档...', statusType: 'info' });
102
- try {
103
- const reduxState = getReduxState();
104
- let baseBuf = null;
105
- if (this.state.baseFilePath && fs.existsSync(this.state.baseFilePath)) {
106
- baseBuf = fs.readFileSync(this.state.baseFilePath);
107
- }
108
- const { buffer, stats } = exportToKcsaveBuffer(reduxState, captureStore.data, baseBuf);
109
-
110
- const safeName = (stats.nickname || 'admiral').replace(/[\\/:*?"<>|]/g, '_');
111
- const stamp = new Date().toISOString().slice(0, 10).replace(/-/g, '');
112
- const defaultFile = `kancolle-${safeName}-${stamp}.kcsave`;
113
-
114
- const dialog = getElectronDialog();
115
- if (dialog) {
116
- const res = await dialog.showSaveDialog({
117
- title: '导出单机版 .kcsave 存档',
118
- defaultPath: defaultFile,
119
- filters: [{ name: 'KanColle Offline Save', extensions: ['kcsave'] }],
120
- });
121
- const targetPath = typeof res === 'string' ? res : (res && !res.canceled ? res.filePath : null);
122
- if (!targetPath) {
123
- this.setState({ exporting: false, status: '已取消保存。', statusType: 'info' });
124
- return;
125
- }
126
- fs.writeFileSync(targetPath, buffer);
127
- this.setState({
128
- exporting: false,
129
- lastStats: stats,
130
- status: `导出成功!已保存至: ${targetPath} (${(buffer.length / 1024 / 1024).toFixed(2)} MB)`,
131
- statusType: 'success',
132
- });
133
- } else {
134
- // 浏览器下载回退方案
135
- const blob = new Blob([buffer], { type: 'application/octet-stream' });
136
- const url = URL.createObjectURL(blob);
137
- const a = document.createElement('a');
138
- a.href = url;
139
- a.download = defaultFile;
140
- document.body.appendChild(a);
141
- a.click();
142
- document.body.removeChild(a);
143
- URL.revokeObjectURL(url);
144
- this.setState({
145
- exporting: false,
146
- lastStats: stats,
147
- status: `导出成功!已触发下载 ${defaultFile} (${(buffer.length / 1024 / 1024).toFixed(2)} MB)`,
148
- statusType: 'success',
149
- });
150
- }
151
- } catch (err) {
152
- this.setState({
153
- exporting: false,
154
- status: `导出失败: ${err && err.message ? err.message : String(err)}`,
155
- statusType: 'error',
156
- });
157
- }
158
- }
159
-
160
- render() {
161
- const h = React.createElement;
162
- const reduxState = getReduxState();
163
- const info = (reduxState && reduxState.info) || {};
164
- const basic = info.basic || {};
165
- const shipsCount = info.ships ? Object.keys(info.ships).length : 0;
166
- const equipsCount = info.equips ? Object.keys(info.equips).length : 0;
167
- const mapsCount = info.maps ? Object.keys(info.maps).length : 0;
168
- const airbaseCount = Array.isArray(info.airbase) ? info.airbase.length : 0;
169
- const cap = this.state.captured || {};
170
- const capAt = cap.capturedAt || {};
171
-
172
- const cardStyle = {
173
- padding: '12px 14px',
174
- borderRadius: '6px',
175
- background: 'rgba(255,255,255,0.05)',
176
- border: '1px solid rgba(255,255,255,0.12)',
177
- marginBottom: '12px',
178
- };
179
- const btnPrimary = {
180
- padding: '8px 16px',
181
- borderRadius: '4px',
182
- border: 'none',
183
- background: '#137cbd',
184
- color: '#fff',
185
- fontWeight: 600,
186
- cursor: this.state.exporting ? 'not-allowed' : 'pointer',
187
- marginRight: '8px',
188
- };
189
- const btnSecondary = {
190
- padding: '6px 12px',
191
- borderRadius: '4px',
192
- border: '1px solid rgba(255,255,255,0.22)',
193
- background: 'transparent',
194
- color: 'inherit',
195
- cursor: 'pointer',
196
- marginRight: '8px',
197
- };
198
- const statusColors = {
199
- info: '#8abbff',
200
- success: '#3dcc91',
201
- warn: '#ffb366',
202
- error: '#ff7373',
203
- };
204
-
205
- return h(
206
- 'div',
207
- { style: { padding: '14px', fontSize: '13px', lineHeight: 1.6, overflowY: 'auto', height: '100%' } },
208
- h('h3', { style: { marginTop: 0, marginBottom: '10px' } }, '单机版存档完全导出 (.kcsave)'),
209
-
210
- // 当前游戏状态卡片
211
- h(
212
- 'div',
213
- { style: cardStyle },
214
- h('div', { style: { fontWeight: 600, marginBottom: '6px' } }, '当前内存数据(自动从 poi 读取)'),
215
- h(
216
- 'div',
217
- null,
218
- `提督: ${basic.api_nickname || '未登录'} (Lv.${basic.api_level || 0}) | 舰娘: ${shipsCount} | 装备: ${equipsCount} | 海域: ${mapsCount} | 陆航: ${airbaseCount}`
219
- )
220
- ),
221
-
222
- // 额外捕获状态卡片
223
- h(
224
- 'div',
225
- { style: cardStyle },
226
- h('div', { style: { fontWeight: 600, marginBottom: '6px' } }, '额外完整数据捕获状态(打开对应界面自动记录)'),
227
- h('div', null, `• 登录家具与设置 (require_info): ${(cap.furnitureOwned || []).length} 件家具 (${formatTime(capAt.require_info)})`),
228
- h('div', null, `• 编成记录 (preset_deck): ${Object.keys(cap.presets || {}).length} 组 (${formatTime(capAt.preset_deck)})`),
229
- h('div', null, `• 远征通关记录 (mission): ${Object.keys(cap.expeditionHistory || {}).length} 项 (${formatTime(capAt.mission)})`),
230
- h('div', null, `• 图鉴记录 (picture_book): 舰船 ${Object.keys(cap.albumShips || {}).length} / 装备 ${Object.keys(cap.albumEquips || {}).length} (${formatTime(capAt.album_ships || capAt.album_equips)})`),
231
- h('div', null, `• 任务列表 (questlist): ${Object.keys(cap.quests || {}).length} 项 (${formatTime(capAt.questlist)})`),
232
- h(
233
- 'div',
234
- { style: { marginTop: '6px', opacity: 0.78, fontSize: '12px' } },
235
- '提示:舰娘/装备/资源/舰队/渠位/道具/海域/陆航可直接导出;如需连带家具、远征、编成记录、图鉴一起导出,导出前先在游戏内点开一次对应界面即可自动捕获。'
236
- )
237
- ),
238
-
239
- // 可选模板与操作按钮
240
- h(
241
- 'div',
242
- { style: cardStyle },
243
- h('div', { style: { marginBottom: '8px' } },
244
- h('strong', null, '可选基础模板: '),
245
- this.state.baseFilePath ? path.basename(this.state.baseFilePath) : '无(使用内置默认模板,直接独立导出)'
246
- ),
247
- h(
248
- 'div',
249
- { style: { display: 'flex', flexWrap: 'wrap', gap: '6px', alignItems: 'center' } },
250
- h('button', { style: btnPrimary, disabled: this.state.exporting, onClick: this._handleExport },
251
- this.state.exporting ? '正在导出...' : '一键完全导出 .kcsave'
252
- ),
253
- h('button', { style: btnSecondary, onClick: this._handlePickBase }, '选择模板 .kcsave(可选)'),
254
- this.state.baseFilePath
255
- ? h('button', { style: btnSecondary, onClick: this._handleClearBase }, '清除模板')
256
- : null,
257
- h('button', { style: btnSecondary, onClick: this._handleClearCache }, '清空捕获缓存')
258
- )
259
- ),
260
-
261
- // 状态输出
262
- this.state.status
263
- ? h(
264
- 'div',
265
- {
266
- style: Object.assign({}, cardStyle, {
267
- color: statusColors[this.state.statusType] || '#fff',
268
- wordBreak: 'break-all',
269
- }),
270
- },
271
- this.state.status
272
- )
273
- : null,
274
-
275
- // 最近导出统计
276
- this.state.lastStats
277
- ? h(
278
- 'div',
279
- { style: Object.assign({}, cardStyle, { fontSize: '12px', opacity: 0.9 }) },
280
- h('div', { style: { fontWeight: 600, marginBottom: '4px' } }, '本次导出明细'),
281
- h(
282
- 'div',
283
- null,
284
- `舰娘 ${this.state.lastStats.ships} | 装备 ${this.state.lastStats.equipment} | 舰队 ${this.state.lastStats.decks} | 道具 ${this.state.lastStats.inventory} | 家具 ${this.state.lastStats.furniture} | 海域 ${this.state.lastStats.maps} | 陆航 ${this.state.lastStats.airBases} | 编成记录 ${this.state.lastStats.presets} | 图鉴 ${this.state.lastStats.albumShips}/${this.state.lastStats.albumEquips}`
285
- )
286
- )
287
- : null
288
- );
289
- }
290
- }
291
-
292
- module.exports = {
293
- reactClass: KcsaveExporterPanel,
294
- pluginDidLoad() {
295
- captureStore.attach();
296
- },
297
- pluginWillUnload() {
298
- captureStore.detach();
299
- },
300
- };