101 lines
4.2 KiB
C#
101 lines
4.2 KiB
C#
using UnityEngine;
|
|
using System.IO;
|
|
using System.Threading.Tasks;
|
|
using System.Collections.Generic;
|
|
|
|
namespace Bansonic.datacheck
|
|
{
|
|
public class DataCheck : MonoBehaviour
|
|
{
|
|
[Header("Settings")]
|
|
[Tooltip("是否在游戏启动时自动执行异步数据检查")]
|
|
public bool checkOnStart = true;
|
|
|
|
private const string SALT = "bansonic2026@fudongyouxi";
|
|
|
|
async void Start()
|
|
{
|
|
if (!checkOnStart)
|
|
{
|
|
Debug.Log("[DataCheck] 自动检查已关闭 (checkOnStart = false)");
|
|
return;
|
|
}
|
|
|
|
Debug.Log("[DataCheck] 开始异步验证所有歌曲存档...");
|
|
|
|
// 记录开始时间
|
|
float startTime = Time.realtimeSinceStartup;
|
|
|
|
int totalFiles = 0;
|
|
int corruptedFiles = 0;
|
|
|
|
// 在主线程提前获取路径,避免子线程调用 Unity API 报错
|
|
string persistentPath = Application.persistentDataPath;
|
|
|
|
// 执行异步检查任务
|
|
await Task.Run(() =>
|
|
{
|
|
string path = persistentPath;
|
|
string[] files = Directory.GetFiles(path, "SongData_*.json");
|
|
totalFiles = files.Length;
|
|
|
|
foreach (string file in files)
|
|
{
|
|
try
|
|
{
|
|
string content = File.ReadAllText(file);
|
|
// 1. 首先尝试完整校验(包含 Hash)
|
|
if (!SongData.VerifyJsonIntegrity(content, SALT, out SongDataSerializable serializable))
|
|
{
|
|
// 2. 如果校验失败,尝试直接解析 JSON(不看 Hash)
|
|
try
|
|
{
|
|
SongDataSerializable fallbackData = JsonUtility.FromJson<SongDataSerializable>(content);
|
|
if (fallbackData != null)
|
|
{
|
|
// 属于“正常更新”:格式变动导致 Hash 不匹配,但数据可读
|
|
// 重新计算 Hash 并保存以修复文件
|
|
string jsonWithoutHash = JsonUtility.ToJson(fallbackData);
|
|
fallbackData.dataHash = SongData.StaticCalculateMD5(jsonWithoutHash + SALT);
|
|
string fixedJson = JsonUtility.ToJson(fallbackData, true);
|
|
File.WriteAllText(file, fixedJson);
|
|
|
|
Debug.Log($"[DataCheck] 已自动修复正常更新的存档: {Path.GetFileName(file)}");
|
|
}
|
|
else
|
|
{
|
|
// 彻底无法解析,视为损坏
|
|
corruptedFiles++;
|
|
Debug.LogError($"[DataCheck] 存档已损坏且无法修复: {Path.GetFileName(file)}");
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
corruptedFiles++;
|
|
Debug.LogError($"[DataCheck] 存档严重损坏: {Path.GetFileName(file)}");
|
|
}
|
|
}
|
|
}
|
|
catch (System.Exception e)
|
|
{
|
|
corruptedFiles++;
|
|
Debug.LogError($"[DataCheck] 读取文件失败 {file}: {e.Message}");
|
|
}
|
|
}
|
|
});
|
|
|
|
float duration = Time.realtimeSinceStartup - startTime;
|
|
Debug.Log($"[DataCheck] 验证完成。耗时: {duration:F4}s | 总文件: {totalFiles} | 损坏/篡改: {corruptedFiles}");
|
|
|
|
if (corruptedFiles > 0)
|
|
{
|
|
Debug.LogWarning("[DataCheck] 部分存档存在异常,SongData 加载时将自动修复。");
|
|
}
|
|
else if (totalFiles > 0)
|
|
{
|
|
Debug.Log("[DataCheck] 所有存档通过一致性校验,数据安全。");
|
|
}
|
|
}
|
|
}
|
|
}
|