微信小游戏相关代码,迁移至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 int _unusedFileTotalCount = 0;
private string _lastPackageVersion;
private string _cacheManifestHashPath;
private string _cacheManifestPath;
internal WXFSClearUnusedBundleFilesAsync(WechatFileSystem fileSystem, PackageManifest manifest)
{
@ -116,7 +118,7 @@ internal class WXFSClearUnusedBundleFilesAsync : FSClearUnusedBundleFilesOperati
{
if (bundle != null)
{
var cachePath = GetUnuseCachePathByBundleName(bundle.FileName);
var cachePath = GetCachePathByFileName(bundle.FileName);
WX.RemoveFile(cachePath, (bool isOk) =>
{
Debug.Log($"{_unusedBundleGUIDs.Count}---删除缓存文件路径成功====={cachePath}==");
@ -139,6 +141,7 @@ internal class WXFSClearUnusedBundleFilesAsync : FSClearUnusedBundleFilesOperati
if (_unusedBundleGUIDs.Count == 0)
{
CheckPackageVerion();
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
@ -162,16 +165,39 @@ internal class WXFSClearUnusedBundleFilesAsync : FSClearUnusedBundleFilesOperati
private void LoadManifestInfo()
{
var packageName = _fileSystem.PackageName;
_lastPackageVersion = WX.StorageGetStringSync(YooAssets.DefaultPackageVersion_Key, YooAssets.DefaultPcakageVersion);
Debug.Log($"==========取出本地数据版本文件成功==={_lastPackageVersion}");
if (!string.IsNullOrEmpty(_lastPackageVersion))
var packageVersion = _manifest.PackageVersion;
if (WX.StorageHasKeySync(YooAssets.DefaultPackageVersion_Key))
{
var cacheManifestHashPath = GetUnuseCachePathByBundleName(YooAssetSettingsData.GetPackageHashFileName(packageName, _lastPackageVersion));
var cacheManifestPath = GetUnuseCachePathByBundleName(YooAssetSettingsData.GetManifestBinaryFileName(packageName, _lastPackageVersion));
if(string.IsNullOrEmpty(cacheManifestHashPath) || string.IsNullOrEmpty(cacheManifestPath)) { return; }
_lastPackageVersion = WX.StorageGetStringSync(YooAssets.DefaultPackageVersion_Key, YooAssets.DefaultPcakageVersion);
Debug.Log($"==========Get Storage PackageVerion Succ==={_lastPackageVersion}");
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);
_fileData = _fileSystem.ReadFileData(cacheManifestPath);
_packageHash = _fileSystem.ReadFileText(_cacheManifestHashPath);
_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 YooAsset;
using WeChatWASM;
using System;
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";
var fileSystemParams = new FileSystemParameters(fileSystemClass, rootDirectory);
var fileSystemParams = new FileSystemParameters(fileSystemClass, null);
fileSystemParams.AddParameter("REMOTE_SERVICES", remoteServices);
return fileSystemParams;
}
/// <summary>
/// AppVersion
/// </summary>
public static string AppVersion { get; set; }
}
/// <summary>
@ -56,9 +52,12 @@ internal class WechatFileSystem : IFileSystem
}
}
private readonly Dictionary<string, string> _cacheFilePaths = new Dictionary<string, string>(10000);
private WXFileSystemManager _fileSystemManager;
private string _fileCacheRoot = string.Empty;
/// <summary>
/// Key:资源包GUID Value:缓存路径
/// </summary>
private readonly Dictionary<string, string> _wxFilePaths = new Dictionary<string, string>(10000);
private WXFileSystemManager _wxFileSystemMgr;
private string _wxFileCacheRoot = string.Empty;
/// <summary>
/// 包裹名称
@ -72,7 +71,7 @@ internal class WechatFileSystem : IFileSystem
{
get
{
return _fileCacheRoot;
return _wxFileCacheRoot;
}
}
@ -87,12 +86,12 @@ internal class WechatFileSystem : IFileSystem
}
}
#region 自定义参数
#region 自定义参数
/// <summary>
/// 自定义参数:远程服务接口
/// </summary>
public IRemoteServices RemoteServices { private set; get; } = null;
#endregion
#endregion
public WechatFileSystem()
@ -122,6 +121,7 @@ internal class WechatFileSystem : IFileSystem
OperationSystem.StartOperation(PackageName, operation);
return operation;
}
public virtual FSClearUnusedBundleFilesOperation ClearUnusedBundleFilesAsync(PackageManifest manifest)
{
var operation = new WXFSClearUnusedBundleFilesAsync(this, manifest);
@ -171,8 +171,9 @@ internal class WechatFileSystem : IFileSystem
RemoteServices = new WebRemoteServices(webRoot);
}
_fileSystemManager = WX.GetFileSystemManager();
_fileCacheRoot = rootDirectory;// WX.PluginCachePath; //WX.env.USER_DATA_PATH; //注意:如果有子目录,请修改此处!
_wxFileSystemMgr = WX.GetFileSystemManager();
_wxFileCacheRoot = PathUtility.Combine(WX.PluginCachePath, $"StreamingAssets/WebGL");// WX.PluginCachePath; //注意:如果有子目录,请修改此处!
Debug.Log($"==_wxFileCacheRoot=={_wxFileCacheRoot}");
}
public virtual void OnUpdate()
{
@ -193,6 +194,7 @@ internal class WechatFileSystem : IFileSystem
if (Belong(bundle) == false)
return false;
//Debug.Log($"WX NeedDownload: bundleName:{bundle.BundleName} + Exists:{Exists(bundle)}");
return Exists(bundle) == false;
}
public virtual bool NeedUnpack(PackageBundle bundle)
@ -212,6 +214,7 @@ internal class WechatFileSystem : IFileSystem
{
throw new System.NotImplementedException();
}
public byte[] ReadFileData(string filePath)
{
if (CheckWXFileIsExist(filePath))
@ -229,6 +232,7 @@ internal class WechatFileSystem : IFileSystem
return string.Empty;
//throw new System.NotImplementedException();
}
/// <summary>
/// 获取所有缓存文件的路径
/// </summary>
@ -247,68 +251,16 @@ internal class WechatFileSystem : IFileSystem
string result = _wxFileSystemMgr.AccessSync(filePath);
return result.Equals("access:ok");
}
#region 调用微信小游戏接口删除缓存文件目录下所有文件
public void ClearAllCacheFile()
#region 内部方法
private string GetWXFileLoadPath(PackageBundle bundle)
{
#if !UNITY_EDITOR && UNITY_WEBGL && WEIXINMINIGAME
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)
RestartMiniGame();
};
WX.ShowModal(showModalOp);
#endif
}
/// <summary>
/// 微信小游戏清除缓存并且重启小游戏
/// 参考小游戏=>出发吧麦芬
/// </summary>
private void RestartMiniGame()
{
WX.CleanAllFileCache((bool isOk) =>
if (_wxFilePaths.TryGetValue(bundle.BundleGUID, out string filePath) == false)
{
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);
filePath = PathUtility.Combine(_wxFileCacheRoot, bundle.FileName);
_wxFilePaths.Add(bundle.BundleGUID, filePath);
}
return filePath;
}
#endregion
#endregion
}
#endif

View File

@ -32,20 +32,6 @@ internal class FsmClearPackageCache : IStateNode
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>();
}
}

View File

@ -75,11 +75,10 @@ internal class FsmInitializePackage : IStateNode
{
var createParameters = new WebPlayModeParameters();
#if UNITY_WEBGL && WEIXINMINIGAME && !UNITY_EDITOR
string defaultHostServer = GetHostServerURL();
string fallbackHostServer = GetHostServerURL();
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, rootDir);
string defaultHostServer = GetHostServerURL();
string fallbackHostServer = GetHostServerURL();
IRemoteServices remoteServices = new RemoteServices(defaultHostServer, fallbackHostServer);
createParameters.WebFileSystemParameters = WechatFileSystemCreater.CreateWechatFileSystemParameters(remoteServices);
#else
createParameters.WebFileSystemParameters = FileSystemParameters.CreateDefaultWebFileSystemParameters();
#endif