package backup import ( "crypto/rand" "fmt" "io" "path/filepath" "reflect" "regexp" "strings" "time" ) // randReader 安全随机源。 func randReader() io.Reader { return rand.Reader } // sliceToAny 把任意切片转成 []any,便于统一 JSON 序列化。 func sliceToAny(slice any) []any { if slice == nil { return nil } v := reflect.ValueOf(slice) if v.Kind() != reflect.Slice { return nil } out := make([]any, v.Len()) for i := 0; i < v.Len(); i++ { out[i] = v.Index(i).Interface() } return out } // complement 计算 [start,end] 在被若干区间并集覆盖后的缺失段(闭区间,秒)。 func complement(intervals [][2]int64, start, end int64) []MissingSeg { if start > end { return nil } ivs := make([][2]int64, 0, len(intervals)) for _, iv := range intervals { if iv[0] <= iv[1] && iv[1] >= start && iv[0] <= end { ivs = append(ivs, [2]int64{maxInt64(iv[0], start), minInt64(iv[1], end)}) } } sortIntervals(ivs) missing := make([]MissingSeg, 0) cur := start for _, iv := range ivs { if iv[0] > cur { missing = append(missing, MissingSeg{Start: cur, End: iv[0] - 1}) } if iv[1] > cur { cur = iv[1] + 1 } } if cur <= end { missing = append(missing, MissingSeg{Start: cur, End: end}) } return missing } func sortIntervals(ivs [][2]int64) { for i := 0; i < len(ivs); i++ { for j := i + 1; j < len(ivs); j++ { if ivs[j][0] < ivs[i][0] { ivs[i], ivs[j] = ivs[j], ivs[i] } } } } func maxInt64(a, b int64) int64 { if a > b { return a } return b } func minInt64(a, b int64) int64 { if a < b { return a } return b } func formatMissing(segs []MissingSeg) string { parts := make([]string, 0, len(segs)) for _, s := range segs { parts = append(parts, fmt.Sprintf("%s ~ %s", time.Unix(s.Start, 0).Format("2006-01-02"), time.Unix(s.End, 0).Format("2006-01-02"))) } return strings.Join(parts, ";") } // coverageSegments 基于已排序备份区间计算 [start,end] 内的已覆盖段与缺失段(均为闭区间,秒)。 // covered=窗口 ∩ 备份区间并集(合并相邻/重叠段);missing=窗口内未被任何备份覆盖的段。 func coverageSegments(intervals [][2]int64, start, end int64) (covered, missing []MissingSeg) { if start > end { return nil, nil } ivs := make([][2]int64, 0, len(intervals)) for _, iv := range intervals { if iv[0] <= iv[1] && iv[1] >= start && iv[0] <= end { ivs = append(ivs, [2]int64{maxInt64(iv[0], start), minInt64(iv[1], end)}) } } sortIntervals(ivs) // 合并重叠/相邻段 → covered merged := make([][2]int64, 0, len(ivs)) for _, iv := range ivs { if n := len(merged); n > 0 && iv[0] <= merged[n-1][1]+1 { if iv[1] > merged[n-1][1] { merged[n-1][1] = iv[1] } continue } merged = append(merged, iv) } covered = make([]MissingSeg, 0, len(merged)) for _, iv := range merged { covered = append(covered, MissingSeg{Start: iv[0], End: iv[1]}) } return covered, complement(intervals, start, end) } // validateAck 强制清理实名留痕校验。 var phoneRe = regexp.MustCompile(`^1\d{10}$`) func validateAck(req CleanupRequest) error { if strings.TrimSpace(req.AckName) == "" { return fmt.Errorf("强制清理须填写确认人姓名(警示留痕)") } if !phoneRe.MatchString(strings.TrimSpace(req.AckPhone)) { return fmt.Errorf("强制清理须填写有效的 11 位手机号(警示留痕)") } return nil } func summaryDeleted(deleted, skipped []ItemResult) string { var b strings.Builder for _, d := range deleted { fmt.Fprintf(&b, "%s 删除 %d 行;", d.Name, d.Rows) } if len(skipped) > 0 { b.WriteString(" 跳过共享附件(对端未备份):") for _, s := range skipped { fmt.Fprintf(&b, "%s %d 个;", s.Name, s.Rows) } } return strings.TrimRight(b.String(), ";") } // htmlEscape 最小 HTML 转义(路径/操作人可能含特殊字符)。 func htmlEscape(s string) string { return strings.NewReplacer("&", "&", "<", "<", ">", ">", `"`, """).Replace(s) } // buildIndexHTML 生成备份包内 index.html:清单 + 包内目录说明 + 打开/校验/恢复指引。 // 双击即可离线查看;不内嵌数据预览(数据在包内 data.jsonl 与 attachments/ 中)。 func buildIndexHTML(title string, manifest map[string]any, checksum string, defs []ItemDef) string { items, _ := manifest["items"].([]ItemResult) zipPath, _ := manifest["zipPath"].(string) if zipPath == "" { zipPath, _ = manifest["targetPath"].(string) } zipName := "备份包" if zipPath != "" { zipName = filepath.Base(zipPath) } descByName := make(map[string]string, len(defs)) for _, d := range defs { descByName[d.Name] = d.Desc } // 数据项明细行 var rows strings.Builder for _, it := range items { desc := descByName[it.Name] loc := htmlEscape(it.Key) + "/data.jsonl" if it.Key == "attachments" || it.Key == "attachment" { loc = "attachments/(附件原文件,含已删除)+ attachment/data.jsonl(元数据,含删除状态标注)" } fmt.Fprintf(&rows, "%s%s%s%d%s\n", htmlEscape(it.Name), htmlEscape(desc), loc, it.Rows, humanBytes(it.Bytes)) } // 包内目录树 var tree strings.Builder fmt.Fprintf(&tree, "%s\n├─ index.html ← 本文件(清单 / 使用说明 / 恢复指引)\n├─ manifest.json ← 机器可读元数据(记事本可直接查看)\n", zipName) for _, it := range items { if it.Key == "attachments" || it.Key == "attachment" { fmt.Fprintf(&tree, "├─ attachments/ ← 附件原文件(按备份时的原始相对路径存放)\n└─ attachment/\n └─ data.jsonl ← 附件元数据索引(每行一条 JSON)\n") } else { fmt.Fprintf(&tree, "├─ %s/\n └─ data.jsonl ← %s(每行一条 JSON,可用记事本/VS Code 打开)\n", it.Key, htmlEscape(it.Name)) } } treeStr := htmlEscape(tree.String()) cs := checksum if cs == "" { if c, ok := manifest["checksum"].(string); ok { cs = c } } csHTML := "

校验和(sha256):包内为流式写入无法回填,请以系统内「数据归档 → 备份/清理历史 → 详情」中的校验和为准。

" if cs != "" { csHTML = "

校验和(sha256):" + cs + "

" } verifyCmd := "" if zipPath != "" { verifyCmd = "

本地核对完整 zip 文件:在命令行执行 certutil -hashfile \"" + htmlEscape(zipPath) + "\" SHA256,与历史详情中的校验和比对。

" } return fmt.Sprintf(` %s

%s

备份时间窗:%s ~ %s(含起止日)| 生成时间:%s | 操作人:%s
归档位置:%s
数据项:共 %d 项 | 明细大小合计:%s(zip 实际大小以文件属性为准,压缩后略小)

%s %s

一、包内目录结构

%s

二、数据项明细

%s
数据项业务说明包内位置行数 / 文件数大小

三、如何打开与查看

  1. 本文件:双击即可离线查看,无需联网、无需安装任何软件。
  2. 日志类数据(data.jsonl):每行一条 JSON 记录。用记事本 / Notepad++ / VS Code 直接打开查看;如需用 Excel 分析,请在 Excel 中「数据 → 获取数据 → 自文件 → 从 JSON」导入(切勿直接双击用 Excel 打开,避免长数字精度丢失)。
  3. 附件(attachments/ 目录):按备份时的原始相对路径存放原文件,可直接双击打开(图片、PDF、Office 文档等)。附件的清单(编号、原文件名、路径、大小、删除状态)见 attachment/data.jsonl——时间窗内已删除的附件同样包含在包内(元数据 deleted 标注),本机彻底清除后可凭包内拷贝找回(介质可读性由保管人自行核对)。
  4. manifest.json:机器可读元数据(时间窗、数据项、大小、生成时间、操作人),可供脚本化核对或二次导入使用。

四、恢复与保管说明

本包为离线冷备份,删除系统数据前请务必确认:

本文件由系统在备份时自动生成,仅作清单、说明与校验用途,不含任何业务数据内容。

`, title, title, manifest["rangeStartText"], manifest["rangeEndText"], manifest["generatedAt"], manifest["operator"], htmlEscape(zipPath), len(items), humanBytes(sumItemBytes(items)), csHTML, verifyCmd, treeStr, rows.String()) } func sumItemBytes(items []ItemResult) int64 { var n int64 for _, it := range items { n += it.Bytes } return n }