微信小游戏相关代码,迁移至WechatFileSystem,修改packageversion缓存逻辑

pull/368/head
jcakCheng 2024-09-13 20:59:46 +08:00
parent e0427d3062
commit 093dd25e0f
5 changed files with 152 additions and 101 deletions

View File

@ -0,0 +1,88 @@
#if UNITY_WEBGL && WEIXINMINIGAME
using System.Collections.Generic;
using WeChatWASM;
using YooAsset;
using UnityEngine;
using System.Linq;
internal class WXFSClearAllBundleFilesOperation : FSClearAllBundleFilesOperation
{
private enum ESteps
{
None,
GetAllCacheFiles,
ClearAllWXCacheBundleFiles,
Done,
}
private List<string> _wxBundleFilePaths;
private int _fileTotalCount = 0;
private WechatFileSystem _fileSystem;
private ESteps _steps = ESteps.None;
internal WXFSClearAllBundleFilesOperation(WechatFileSystem fileSystem)
{
_fileSystem = fileSystem;
var allCacheFilePathDic = _fileSystem.GetWXAllCacheFilePath();
_wxBundleFilePaths = allCacheFilePathDic.Values.ToList();
}
internal override void InternalOnStart()
{
_steps = ESteps.GetAllCacheFiles;
}
internal override void InternalOnUpdate()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.GetAllCacheFiles)
{
if (_wxBundleFilePaths == null)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
return;
}
else
{
_steps = ESteps.ClearAllWXCacheBundleFiles;
_fileTotalCount = _wxBundleFilePaths.Count;
}
}
if (_steps == ESteps.ClearAllWXCacheBundleFiles)
{
for (int i = _wxBundleFilePaths.Count - 1; i >= 0; i--)
{
string bundlePath = _wxBundleFilePaths[i];
if (_fileSystem.CheckWXFileIsExist(bundlePath))
{
WX.RemoveFile(bundlePath, (bool isOk) =>
{
Debug.Log($"{_wxBundleFilePaths.Count}---删除缓存文件路径成功====={bundlePath}==");
_wxBundleFilePaths.Remove(bundlePath);
});
}
else
{
_wxBundleFilePaths.Remove(bundlePath);
//Debug.LogWarning($"Not Exit Cache file:{bundlePath}");
}
if (OperationSystem.IsBusy)
break;
}
if (_fileTotalCount == 0)
Progress = 1.0f;
else
Progress = 1.0f - (_wxBundleFilePaths.Count / _fileTotalCount);
if (_wxBundleFilePaths.Count == 0)
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
}
}
}
#endif

View File

@ -28,6 +28,8 @@ internal class WXFSClearUnusedBundleFilesAsync : FSClearUnusedBundleFilesOperati
private string _packageHash; private string _packageHash;
private int _unusedFileTotalCount = 0; private int _unusedFileTotalCount = 0;
private string _lastPackageVersion; private string _lastPackageVersion;
private string _cacheManifestHashPath;
private string _cacheManifestPath;
internal WXFSClearUnusedBundleFilesAsync(WechatFileSystem fileSystem, PackageManifest manifest) internal WXFSClearUnusedBundleFilesAsync(WechatFileSystem fileSystem, PackageManifest manifest)
{ {
@ -116,7 +118,7 @@ internal class WXFSClearUnusedBundleFilesAsync : FSClearUnusedBundleFilesOperati
{ {
if (bundle != null) if (bundle != null)
{ {
var cachePath = GetUnuseCachePathByBundleName(bundle.FileName); var cachePath = GetCachePathByFileName(bundle.FileName);
WX.RemoveFile(cachePath, (bool isOk) => WX.RemoveFile(cachePath, (bool isOk) =>
{ {
Debug.Log($"{_unusedBundleGUIDs.Count}---删除缓存文件路径成功====={cachePath}=="); Debug.Log($"{_unusedBundleGUIDs.Count}---删除缓存文件路径成功====={cachePath}==");
@ -139,6 +141,7 @@ internal class WXFSClearUnusedBundleFilesAsync : FSClearUnusedBundleFilesOperati
if (_unusedBundleGUIDs.Count == 0) if (_unusedBundleGUIDs.Count == 0)
{ {
CheckPackageVerion();
_steps = ESteps.Done; _steps = ESteps.Done;
Status = EOperationStatus.Succeed; Status = EOperationStatus.Succeed;
} }
@ -162,16 +165,39 @@ internal class WXFSClearUnusedBundleFilesAsync : FSClearUnusedBundleFilesOperati
private void LoadManifestInfo() private void LoadManifestInfo()
{ {
var packageName = _fileSystem.PackageName; var packageName = _fileSystem.PackageName;
_lastPackageVersion = WX.StorageGetStringSync(YooAssets.DefaultPackageVersion_Key, YooAssets.DefaultPcakageVersion); var packageVersion = _manifest.PackageVersion;
Debug.Log($"==========取出本地数据版本文件成功==={_lastPackageVersion}"); if (WX.StorageHasKeySync(YooAssets.DefaultPackageVersion_Key))
if (!string.IsNullOrEmpty(_lastPackageVersion))
{ {
var cacheManifestHashPath = GetUnuseCachePathByBundleName(YooAssetSettingsData.GetPackageHashFileName(packageName, _lastPackageVersion)); _lastPackageVersion = WX.StorageGetStringSync(YooAssets.DefaultPackageVersion_Key, YooAssets.DefaultPcakageVersion);
var cacheManifestPath = GetUnuseCachePathByBundleName(YooAssetSettingsData.GetManifestBinaryFileName(packageName, _lastPackageVersion)); Debug.Log($"==========Get Storage PackageVerion Succ==={_lastPackageVersion}");
if(string.IsNullOrEmpty(cacheManifestHashPath) || string.IsNullOrEmpty(cacheManifestPath)) { return; } if (!string.IsNullOrEmpty(_lastPackageVersion) && (_lastPackageVersion != packageVersion))
{
_cacheManifestHashPath = GetCachePathByFileName(YooAssetSettingsData.GetPackageHashFileName(packageName, _lastPackageVersion));
_cacheManifestPath = GetCachePathByFileName(YooAssetSettingsData.GetManifestBinaryFileName(packageName, _lastPackageVersion));
if(string.IsNullOrEmpty(_cacheManifestHashPath) || string.IsNullOrEmpty(_cacheManifestPath)) { return; }
_packageHash = _fileSystem.ReadFileText(cacheManifestHashPath); _packageHash = _fileSystem.ReadFileText(_cacheManifestHashPath);
_fileData = _fileSystem.ReadFileData(cacheManifestPath); _fileData = _fileSystem.ReadFileData(_cacheManifestPath);
}
}
else
{
WX.StorageSetStringSync(YooAssets.DefaultPackageVersion_Key, packageVersion);
Debug.Log($"first Set Storage PackageVerion Succ==={packageVersion}");
}
}
private void CheckPackageVerion()
{
var packageName = _fileSystem.PackageName;
var packageVersion = _manifest.PackageVersion;
if (_lastPackageVersion != packageVersion)
{
WX.StorageSetStringSync(YooAssets.DefaultPackageVersion_Key, packageVersion);
//删除旧的资源清单文件和哈希文件
WX.RemoveFile(_cacheManifestHashPath, (bool isOk) => { Debug.Log("====Delect manifestHashPath Succ"); });
WX.RemoveFile(_cacheManifestPath, (bool isOk) => { Debug.Log("====Delect manifestPath Succ"); });
Debug.Log($"==========Set Storage PackageVerion Succ==={packageVersion}");
} }
} }

View File

@ -3,21 +3,17 @@ using System.Collections.Generic;
using UnityEngine; using UnityEngine;
using YooAsset; using YooAsset;
using WeChatWASM; using WeChatWASM;
using System;
public static class WechatFileSystemCreater public static class WechatFileSystemCreater
{ {
public static FileSystemParameters CreateWechatFileSystemParameters(IRemoteServices remoteServices,string rootDirectory = null) public static FileSystemParameters CreateWechatFileSystemParameters(IRemoteServices remoteServices)
{ {
string fileSystemClass = $"{nameof(WechatFileSystem)},YooAsset.RuntimeExtension"; string fileSystemClass = $"{nameof(WechatFileSystem)},YooAsset.RuntimeExtension";
var fileSystemParams = new FileSystemParameters(fileSystemClass, rootDirectory); var fileSystemParams = new FileSystemParameters(fileSystemClass, null);
fileSystemParams.AddParameter("REMOTE_SERVICES", remoteServices); fileSystemParams.AddParameter("REMOTE_SERVICES", remoteServices);
return fileSystemParams; return fileSystemParams;
} }
/// <summary>
/// AppVersion
/// </summary>
public static string AppVersion { get; set; }
} }
/// <summary> /// <summary>
@ -56,9 +52,12 @@ internal class WechatFileSystem : IFileSystem
} }
} }
private readonly Dictionary<string, string> _cacheFilePaths = new Dictionary<string, string>(10000); /// <summary>
private WXFileSystemManager _fileSystemManager; /// Key:资源包GUID Value:缓存路径
private string _fileCacheRoot = string.Empty; /// </summary>
private readonly Dictionary<string, string> _wxFilePaths = new Dictionary<string, string>(10000);
private WXFileSystemManager _wxFileSystemMgr;
private string _wxFileCacheRoot = string.Empty;
/// <summary> /// <summary>
/// 包裹名称 /// 包裹名称
@ -72,7 +71,7 @@ internal class WechatFileSystem : IFileSystem
{ {
get get
{ {
return _fileCacheRoot; return _wxFileCacheRoot;
} }
} }
@ -87,12 +86,12 @@ internal class WechatFileSystem : IFileSystem
} }
} }
#region 自定义参数 #region 自定义参数
/// <summary> /// <summary>
/// 自定义参数:远程服务接口 /// 自定义参数:远程服务接口
/// </summary> /// </summary>
public IRemoteServices RemoteServices { private set; get; } = null; public IRemoteServices RemoteServices { private set; get; } = null;
#endregion #endregion
public WechatFileSystem() public WechatFileSystem()
@ -122,6 +121,7 @@ internal class WechatFileSystem : IFileSystem
OperationSystem.StartOperation(PackageName, operation); OperationSystem.StartOperation(PackageName, operation);
return operation; return operation;
} }
public virtual FSClearUnusedBundleFilesOperation ClearUnusedBundleFilesAsync(PackageManifest manifest) public virtual FSClearUnusedBundleFilesOperation ClearUnusedBundleFilesAsync(PackageManifest manifest)
{ {
var operation = new WXFSClearUnusedBundleFilesAsync(this, manifest); var operation = new WXFSClearUnusedBundleFilesAsync(this, manifest);
@ -171,8 +171,9 @@ internal class WechatFileSystem : IFileSystem
RemoteServices = new WebRemoteServices(webRoot); RemoteServices = new WebRemoteServices(webRoot);
} }
_fileSystemManager = WX.GetFileSystemManager(); _wxFileSystemMgr = WX.GetFileSystemManager();
_fileCacheRoot = rootDirectory;// WX.PluginCachePath; //WX.env.USER_DATA_PATH; //注意:如果有子目录,请修改此处! _wxFileCacheRoot = PathUtility.Combine(WX.PluginCachePath, $"StreamingAssets/WebGL");// WX.PluginCachePath; //注意:如果有子目录,请修改此处!
Debug.Log($"==_wxFileCacheRoot=={_wxFileCacheRoot}");
} }
public virtual void OnUpdate() public virtual void OnUpdate()
{ {
@ -193,6 +194,7 @@ internal class WechatFileSystem : IFileSystem
if (Belong(bundle) == false) if (Belong(bundle) == false)
return false; return false;
//Debug.Log($"WX NeedDownload: bundleName:{bundle.BundleName} + Exists:{Exists(bundle)}");
return Exists(bundle) == false; return Exists(bundle) == false;
} }
public virtual bool NeedUnpack(PackageBundle bundle) public virtual bool NeedUnpack(PackageBundle bundle)
@ -212,6 +214,7 @@ internal class WechatFileSystem : IFileSystem
{ {
throw new System.NotImplementedException(); throw new System.NotImplementedException();
} }
public byte[] ReadFileData(string filePath) public byte[] ReadFileData(string filePath)
{ {
if (CheckWXFileIsExist(filePath)) if (CheckWXFileIsExist(filePath))
@ -229,6 +232,7 @@ internal class WechatFileSystem : IFileSystem
return string.Empty; return string.Empty;
//throw new System.NotImplementedException(); //throw new System.NotImplementedException();
} }
/// <summary> /// <summary>
/// 获取所有缓存文件的路径 /// 获取所有缓存文件的路径
/// </summary> /// </summary>
@ -247,68 +251,16 @@ internal class WechatFileSystem : IFileSystem
string result = _wxFileSystemMgr.AccessSync(filePath); string result = _wxFileSystemMgr.AccessSync(filePath);
return result.Equals("access:ok"); return result.Equals("access:ok");
} }
#region 调用微信小游戏接口删除缓存文件目录下所有文件 #region 内部方法
public void ClearAllCacheFile() private string GetWXFileLoadPath(PackageBundle bundle)
{ {
#if !UNITY_EDITOR && UNITY_WEBGL && WEIXINMINIGAME if (_wxFilePaths.TryGetValue(bundle.BundleGUID, out string filePath) == false)
ShowModalOption showModalOp = new ShowModalOption();
showModalOp.title = "提示";
showModalOp.content = "是否确定要清理缓存并重启";
showModalOp.confirmText = "确定";
showModalOp.cancelText = "取消";
showModalOp.complete = (GeneralCallbackResult callResult) => { Debug.Log($"complete==={callResult.errMsg}"); };
showModalOp.fail = (GeneralCallbackResult callResult) => { Debug.Log($"fail==={callResult.errMsg}"); };
showModalOp.success = (ShowModalSuccessCallbackResult callResult) =>
{ {
if(callResult.confirm) filePath = PathUtility.Combine(_wxFileCacheRoot, bundle.FileName);
RestartMiniGame(); _wxFilePaths.Add(bundle.BundleGUID, filePath);
};
WX.ShowModal(showModalOp);
#endif
}
/// <summary>
/// 微信小游戏清除缓存并且重启小游戏
/// 参考小游戏=>出发吧麦芬
/// </summary>
private void RestartMiniGame()
{
WX.CleanAllFileCache((bool isOk) =>
{
RestartMiniProgramOption restartMini = new RestartMiniProgramOption();
restartMini.complete = RestartMiniComplete;
restartMini.fail = RestartMiniFailComplete;
restartMini.success = RestartMiniSuccComplete;
WX.RestartMiniProgram(restartMini);
});
}
private void RestartMiniComplete(GeneralCallbackResult result)
{
Debug.Log($"RestartMiniComplete:{result.errMsg}");
}
private void RestartMiniFailComplete(GeneralCallbackResult result)
{
Debug.Log($"RestartMiniFailComplete:{result.errMsg}");
}
private void RestartMiniSuccComplete(GeneralCallbackResult result)
{
Debug.Log($"RestartMiniSuccComplete:{result.errMsg}");
}
#endregion
#region 内部方法
private string GetCacheFileLoadPath(PackageBundle bundle)
{
if (_cacheFilePaths.TryGetValue(bundle.BundleGUID, out string filePath) == false)
{
filePath = PathUtility.Combine(_fileCacheRoot, bundle.FileName);
_cacheFilePaths.Add(bundle.BundleGUID, filePath);
} }
return filePath; return filePath;
} }
#endregion #endregion
} }
#endif #endif

View File

@ -32,20 +32,6 @@ internal class FsmClearPackageCache : IStateNode
private void Operation_Completed(YooAsset.AsyncOperationBase obj) private void Operation_Completed(YooAsset.AsyncOperationBase obj)
{ {
#if UNITY_WEBGL && WEIXINMINIGAME
//删除旧的资源清单文件和哈希文件
if (WX.StorageHasKeySync(YooAssets.DefaultPackageVersion_Key))
{
var packageName = (string)_machine.GetBlackboardValue("PackageName");
var packageVersion = (string)_machine.GetBlackboardValue("PackageVersion");
var lastPackageVersion = WX.StorageGetStringSync(YooAssets.DefaultPackageVersion_Key, "");
if (lastPackageVersion != packageVersion)
{
WX.StorageSetStringSync(YooAssets.DefaultPackageVersion_Key, packageVersion);
}
}
#endif
_machine.ChangeState<FsmUpdaterDone>(); _machine.ChangeState<FsmUpdaterDone>();
} }
} }

View File

@ -75,11 +75,10 @@ internal class FsmInitializePackage : IStateNode
{ {
var createParameters = new WebPlayModeParameters(); var createParameters = new WebPlayModeParameters();
#if UNITY_WEBGL && WEIXINMINIGAME && !UNITY_EDITOR #if UNITY_WEBGL && WEIXINMINIGAME && !UNITY_EDITOR
string defaultHostServer = GetHostServerURL(); string defaultHostServer = GetHostServerURL();
string fallbackHostServer = GetHostServerURL(); string fallbackHostServer = GetHostServerURL();
IRemoteServices remoteServices = new RemoteServices(defaultHostServer, fallbackHostServer); IRemoteServices remoteServices = new RemoteServices(defaultHostServer, fallbackHostServer);
var rootDir = string.Format("{0}/{1}", WX.PluginCachePath, $"StreamingAssets/WebGL/v1.0.0");//这个1.0.0是App大版本文件转微信小游戏后没删除 createParameters.WebFileSystemParameters = WechatFileSystemCreater.CreateWechatFileSystemParameters(remoteServices);
createParameters.WebFileSystemParameters = WechatFileSystemCreater.CreateWechatFileSystemParameters(remoteServices, rootDir);
#else #else
createParameters.WebFileSystemParameters = FileSystemParameters.CreateDefaultWebFileSystemParameters(); createParameters.WebFileSystemParameters = FileSystemParameters.CreateDefaultWebFileSystemParameters();
#endif #endif