fengye/fk101/wb_unity_pro/Assets/Scripts/VerCheck.cs

724 lines
34 KiB
C#
Raw Permalink Normal View History

2025-11-27 00:09:24 +08:00
using UnityEngine;
using System.Collections;
using System.IO;
using FairyGUI;
using MiniJSON;
using UnityEngine.Networking;
using taurus.unity;
using System.Text;
using System;
public class VerCheck : MonoBehaviour
{
GComponent _version_view;
public static VerCheck Instance { get; private set; }
public securityConnection conn;
public bool isGFF = false;
public bool isDXYGFF = true;
void Awake()
{
Instance = this;
}
// Use this for initialization
void Start()
{
GameApplication.Instance.isAndroid64bit = IsAndroid64bit();
CreateVersionView();
StartCoroutine(CheckNet());
}
internal void ResetGame()
{
CreateVersionView();
StartCoroutine(__WaitReset());
}
IEnumerator __WaitReset()
{
var _luaClient = GameApplication.Instance.GetComponent<DSLuaClient>();
UnityEngine.Object.Destroy(_luaClient);
System.GC.Collect();
FontManager.Clear();
UIPackage.RemoveAllPackages();
ResourcesManager.DestroyAll();
CreateVersionView();
yield return null;
StartCoroutine(CheckNet());
}
void CreateVersionView()
{
ResourcesManager.ReadAssetConfig("base/embed");
UIPackage.AddPackage("base/embed/ui/Hotupdate");
if (_version_view != null) _version_view.Dispose();
_version_view = null;
_version_view = UIPackage.CreateObjectFromURL("ui://Hotupdate/Version").asCom;
GRoot.inst.AddChildAt(_version_view,0);
_version_view.x = (GRoot.inst.width - _version_view.width) / 2;
Debug.LogError(Application.persistentDataPath);
}
public bool IsAndroid64bit()
{
#if UNITY_ANDROID && !UNITY_EDITOR
if (IntPtr.Size == 8)
{
return true;
}
return false;
#else
return false;
#endif
}
IEnumerator CheckNet()
{
string json_data = string.Empty;
isDXYGFF= false;
isGFF = false;
//string init_url = "http://8.138.94.89:9898/NewFK/config/init2_1.json";
string init_url = "http://8.138.242.190:29898/NewFK/config/init2_1.json";
if (isGFF==false&&isDXYGFF==false)
{
}
else
{
if (isGFF)
{
int rc = AppVest.init("8ef91e7e799b5851a8ce810aae0c697c", "U5ayF4voVvRh1ElqBIVUCR9dSFskPGvCkfreFxdxzi39hoU0faqZWjFzC90Cta50egaQatCbPxm6XTlvi2+o++PrSozoZ+HUUY0y8tBloMWaOYQX59SAhjA/DyIDHJgGbE1I");
if (rc != 0)
{
// Debug.LogError("init failed");
ShowTip("GF init failed!", () =>
{
StartCoroutine(CheckNet());
});
}
// Debug.LogError("init successful");
conn.ip = "";
conn.port = 0;
int rc1 = AppVest.getServerIPAndPort(ref conn, "", 5021);
if (rc1 != 0)
{
ShowTip("getServerIPAndPort failed!", () =>
{
StartCoroutine(CheckNet());
});
yield break;
}
}
else
{
string key = "i+7rC56qpxid1g8AAIgW9C4eD6Fp9rBFSstdlMCd7kn1aQVoPvNaeEBHaET5fnXQY88zI1D0vXO26UTRTBNX/gCp7rWDrLY5w5VhIY5rSstWjDDvacr3AaqQsVOvhyss7mhET46/TbUZ+F+6kpvkSp53e7/iZ5Q0sO0K8fliiTxqNTElJ/k9lj951nBrPW0PqmezNwtqSIfSD56ftVq7tW8iT11pvyOjOeSAaI8kyHJ/+kaSrlIw/uupURdbnN/jvSEASO0QpOpED/wm6d/3rkYsILoTKQcc8FBxv20LSJwEm6puI3+Eb1VbTZ5UChQLsaLPLnwl0JQZ4kLeQg2CqmqVxOxt2ck+LoD0Fu8r8XSc1BGrOhZgFo6XPLpjff15ChpNp7W6u6SfUiUnGnpIv7HP8Id4UtGAPj+wCLTyqB1dZe1cX2pHtnerGUVtCRJFxGhCY+EPOvGsAnb1p2lpXPz8NfsKJrrACH4+o7+Ycf49DshM3Rqfma4DrJWXHlfx1P5vUkdsSnyQmxHlWf57oGgEHCNSyS0FJxN9EpcHMM7mkavZpz2K46l8mRMYKXbLJg8GN/QFjZp1JyhN6/n+Nz1Yar1aXlCvl5kLb+w/i05JsMy7HNd5ewIGCTcQatsEUMV5DLUG+0xcuvspA8Aj7Md8iIZNR9NrHg2keZMGDVDB4sNmv2k+RjzoadAzS7F/gJoHuUKpZdYr30UCAzXGk/j+QU0s+NrBRzGUNxZaJmGDuvVZKOvLk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GiOAH0fkp1thaL37WcJPmJ5NNYE0LWd
int rc = DxyVest.Start(key);//AppVest.init("553c12676eb80b82183e0944df97cd19", "K8N/nk3cAxhGo7Oy0yoP/Ye5jcQUaMf+8+AutonLIoCXTbHXSHJ/D8W3/iIBHJq/4SABnAF7RvIeNRnF+x+wjB6cB1TEwIUviviQlofNvM4qJFLH55ON85n2pFBhSGW3qLF/");
if (rc != 150)
{
Debug.LogError("wwwwwwwwwwwwwwwwwwwwwww init failed");
ShowTip("GF init failed!", () =>
{
StartCoroutine(CheckNet());
});
}
// Debug.LogError("init successful");
conn.ip = "127.0.0.1";
conn.port = 29898;
//int rc1 = AppVest.getServerIPAndPort(ref conn, "", 8077);
//if (rc1 != 0)
//{
// ShowTip("getServerIPAndPort failed!", () =>
// {
// StartCoroutine(CheckNet());
// });
// yield break;
//}
}
init_url = "http://" + conn.ip + ":" + conn.port + "/NewFK/config/init2_1.json";
Debug.LogError("init_url : " + init_url);
}
// Debug.LogError("开始下载资源===>>>");
// Debug.LogError(init_url);
2025-11-27 00:09:24 +08:00
//Debug.LogError("init_url============================ "+ init_url);
float downTimeOut = 5;
using (WWW request1 = new WWW(init_url))
{
float timeOut = Time.time;
float process = request1.progress;
while (request1!=null && request1.isDone==false)
{
//Debug.LogError("wwwwwwwwwwwwwwwwwww11111111111111111111111");
if(process<request1.progress)
{
timeOut = Time.time;
process = request1.progress;
}
if(Time.time-timeOut>downTimeOut)
{
ShowTip("资源配置下载失败,请检查您的网络设置!", () =>
{
StartCoroutine(CheckNet());
});
yield break;
}
yield return null;
}
yield return request1;
// Debug.LogError("request1.error"+request1.error);
if (string.IsNullOrEmpty(request1.error))
{
//Debug.LogError("wwwwwwwwwwwwwwwww222222222222222222222222");
json_data = request1.text;
//优化
GameApplication.Instance.GameInfo = json_data;
Hashtable json = Json.Deserialize(json_data) as Hashtable;
//json["pack_url"] = "http://8.134.59.224:8909/NewFKtest";
Hotupdate.PackUrl = (string)json["pack_url"];
Hashtable _plat_data = null;
#if UNITY_IPHONE
_plat_data = json["iOS"] as Hashtable;
#endif
#if UNITY_ANDROID
_plat_data = json["Android"] as Hashtable;
#endif
#if UNITY_STANDALONE
_plat_data = json["Win"] as Hashtable;
#endif
var check = _plat_data[string.Format("check{0}", GameApplication.AppVersion.ToString())];
if (check != null && (bool)check)
{
GameApplication.HideSdk = true;
GameApplication.Instance.accountTest = false;
}
Version server_version = new Version((string)_plat_data["version"]);
if (!GameApplication.HideSdk)
{
if (GameApplication.AppVersion.max_version < server_version.max_version || (GameApplication.AppVersion.max_version == server_version.max_version && GameApplication.AppVersion.min_version < server_version.min_version))
{
ShowTip("您版本需要更新!", () =>
{
#if UNITY_ANDROID
StartCoroutine(DownApp((string)_plat_data["appurl"], server_version.ToString()));
#else
DeleteOldPack();
Application.OpenURL((string)_plat_data["appurl"]);
Application.Quit();
#endif
});
yield break;
}
}
Voice.VoiceUpload = json["voice_upload_url"] as string;
Voice.VoiceDownload = json["voice_download_url"] as string;
//GameApplication.PackVersion = server_version.pack_version;
if (!GameApplication.Instance.buildApp)
{
GameApplication.AppVersion.FillData(server_version);
_version_view.Dispose();
GameApplication.Instance.StartGame();
}
else
{
StartCoroutine(CheckAssetConfig(server_version));
}
}
else
{
ShowTip("资源配置下载失败,请检查您的网络设置!", () =>
{
StartCoroutine(CheckNet());
});
//yield break;
}
}
}
IEnumerator CheckAssetConfig(Version server_version)
{
GObject v_tex_info = _version_view.GetChild("tex_info");
Version local_version = Hotupdate.GetLocalVersion(string.Empty);
ArrayList asset_config_list = null;
string asset_config_text = null;
if (local_version == null || local_version.ContainAll(server_version))
{
string ac_url="";
if(isGFF==false)
ac_url = string.Format("{0}/config/asset_config{1}.json", Hotupdate.PackUrl, server_version.ToString());
else
ac_url = string.Format("http://{0}/NewFK/config/asset_config{1}.json", conn.ip + ":" + conn.port, server_version.ToString());
// Debugger.LogError("CheckAssetConfig===>>>");
// Debugger.LogError(ac_url);
float downTimeOut = 5;
using (var request = new WWW(ac_url))
{
float timeOut = Time.time;
float process = request.progress;
while (request != null && request.isDone == false)
{
if (process < request.progress)
{
timeOut = Time.time;
process = request.progress;
}
if (Time.time - timeOut > downTimeOut)
{
ShowTip("游戏配置下载异常,请检查您的网络设置!", () =>
{
StartCoroutine(CheckNet());
});
yield break;
}
yield return null;
}
yield return request;
if (string.IsNullOrEmpty(request.error))
{
asset_config_text = request.text;
asset_config_list = Json.Deserialize(asset_config_text) as ArrayList;
if (asset_config_list == null)
{
ShowTip("游戏配置下载异常,请检查您的网络设置!", () =>
{
StartCoroutine(CheckAssetConfig(server_version));
});
yield break;
}
//
v_tex_info.text = "正在检查资源。。。";
GSlider _pd = _version_view.GetChild("pb_progress").asSlider;
_pd.value = 0.0;
//开始检查所有资源
bool size_check = false;
long total_size = 0;
StartCoroutine(VersionUpdateCheckSize2(asset_config_list, (all_size, finish) =>
{
total_size = all_size;
size_check = finish;
}));
while (!size_check)
{
yield return null;
}
Debug.Log($"总大小:{(total_size / 1024f / 1024f):F2} MB");
2025-11-27 00:09:24 +08:00
bool ver_check = false;
StartCoroutine(VersionUpdateCheck(asset_config_list, (progress, finish) =>
{
if (ver_check)
{
_pd.value = 100f;
ver_check = finish;
}
else
{
v_tex_info.text = $"正在下载资源({(progress / 1024f / 1024f):F2} MB/{(total_size / 1024f / 1024f):F2} MB";
_pd.value = progress / total_size * 100f;
ver_check = finish;
}
}));
2025-11-27 00:09:24 +08:00
while (!ver_check)
{
yield return null;
}
bool unZip_check = false;
v_tex_info.text = "正在解压文件(该过程不消耗流量)";
_pd.value = 100f;
StartCoroutine(VersionUpdateUnZip(asset_config_list, (finish) =>
{
unZip_check = finish;
}));
while (!unZip_check)
{
yield return null;
}
2025-11-27 00:09:24 +08:00
string arv = string.Format("{0}asset_config{1}.json", ResourcesManager.PACK_PATH, server_version.ToString());
File.WriteAllText(arv, asset_config_text, System.Text.Encoding.UTF8);
string rv = ResourcesManager.PACK_PATH + "version.txt";
File.WriteAllText(rv, server_version.ToString(), System.Text.Encoding.UTF8);
}
else
{
ShowTip("游戏资源下载失败,请检查您的网络设置!", () =>
{
StartCoroutine(CheckAssetConfig(server_version));
});
yield break;
}
}
}else
{
// string arv = string.Format("{0}asset_config{1}.json", ResourcesManager.PACK_PATH, server_version.ToString());
string arv =ResourcesManager.PACK_PATH+"asset_config"+server_version.ToString()+".json";
//Debug.LogError("ARV===>>>" + arv);
try
{
asset_config_text = File.ReadAllText(arv);
asset_config_list = Json.Deserialize(asset_config_text) as ArrayList;
foreach (Hashtable tem in asset_config_list)
{
string b_path = "base/" + tem["name"];
ResourcesManager.ReadAssetConfig(b_path);
}
}
catch (Exception s)
{
Debug.LogError(s.ToString());
ShowTip("游戏资源损坏,请重新安装新包!", () =>
{
StartCoroutine(CheckAssetConfig(server_version));
});
yield break;
}
//IEnumerator enumerator = asset_config_list.GetEnumerator();
//try
//{
// while (enumerator!=null && enumerator.MoveNext())
// {
// Hashtable hashtable = (Hashtable)enumerator.Current;
// string base_path = "base/" + hashtable["name"].ToString();
// ResourcesManager.ReadAssetConfig(base_path);
// yield return null;
// }
//}
//finally
//{
// IDisposable disposable;
// if ((disposable = (enumerator as IDisposable)) != null)
// {
// disposable.Dispose();
// }
//}
}
GameApplication.AppVersion.FillData(server_version);
v_tex_info.text = "正在加载资源请稍后。。";
//ResourcesManager.Init();
yield return null;
_version_view.Dispose();
GameApplication.Instance.StartGame();
}
/// <summary>
/// 检查基本更新包
/// </summary>
/// <param name="asset_config_list"></param>
/// <param name="onback"></param>
/// <param name="tip"></param>
/// <returns></returns>
IEnumerator VersionUpdateCheck(ArrayList asset_config_list, System.Action<float, bool> onback)
2025-11-27 00:09:24 +08:00
{
Version local_version = Version.DEFUALT;
float download_size = 0;
2025-11-27 00:09:24 +08:00
for(int i=0;i< asset_config_list.Count; ++i)
{
var tem = asset_config_list[i] as Hashtable;
string b_path = "base/" + tem["name"].ToString();
Hotupdate version_update = new Hotupdate(b_path + "/", local_version, new Version((string)tem["ver"]));
version_update.AssetName = b_path;
version_update.HideDetail = true;
version_update.SetTipCallback((text,callback)=>
{
ShowTip(text, callback);
});
version_update.LoadAsset();
while (!version_update.Done)
{
onback(download_size + version_update.Progress* (float)tem["size"], false);
2025-11-27 00:09:24 +08:00
yield return null;
}
download_size += (float)tem["size"];
2025-11-27 00:09:24 +08:00
ResourcesManager.ReadAssetConfig(b_path);
}
onback(1, true);
}
/// <summary>
/// 检查基本更新包大小
/// </summary>
/// <param name="asset_config_list"></param>
/// <param name="onback"></param>
/// <param name="tip"></param>
/// <returns></returns>
IEnumerator VersionUpdateCheckSize(ArrayList asset_config_list, System.Action<long, bool> onback)
{
Version local_version_one = Version.DEFUALT;
long totalSize = 0;
for (int i = 0; i < asset_config_list.Count; ++i)
{
var tem_one = asset_config_list[i] as Hashtable;
string b_path_one = "base/" + tem_one["name"].ToString();
local_version_one = Hotupdate.GetLocalVersion(b_path_one);
var update_pack2 = local_version_one == null || local_version_one.ContainAll(new Version((string)tem_one["ver"]));
string osPath = ResourcesManager.OS_Dir;
if (update_pack2)
{
var pack_path = string.Format("{0}/asset_pack{1}.bytes", b_path_one, (string)tem_one["ver"]);
var url = "";
if (VerCheck.Instance.isGFF == false && VerCheck.Instance.isDXYGFF == false)
url = string.Format("{0}/{1}/{2}", Hotupdate.PackUrl, osPath, pack_path);
else
url = string.Format("{0}/{1}/{2}", "http://" + VerCheck.Instance.conn.ip + ":" + VerCheck.Instance.conn.port + "/NewFKN", osPath, pack_path);
url = string.Format("{0}/{1}/{2}", Hotupdate.PackUrl, osPath, pack_path);
if (Application.platform == RuntimePlatform.WindowsEditor)
Debug.Log("check_url:" + url);
using (UnityWebRequest head = UnityWebRequest.Head(url))
{
yield return head.SendWebRequest();
#if UNITY_2020_2_OR_NEWER
if (head.result == UnityWebRequest.Result.Success)
#else
if (!head.isNetworkError && !head.isHttpError)
#endif
{
string len = head.GetResponseHeader("Content-Length");
if (!string.IsNullOrEmpty(len) && long.TryParse(len, out long size))
{
totalSize += size;
tem_one["size"] = size;
yield return null;
}
else
{
Debug.LogWarning($"无法获取文件大小: {url}");
yield return 0L;
}
}
else
{
Debug.LogError($"获取文件大小失败: {head.error}");
yield return 0L;
}
}
}
}
onback(totalSize, true);
}
IEnumerator VersionUpdateCheckSize2(ArrayList asset_config_list, System.Action<long, bool> onback)
{
Version local_version = Version.DEFUALT;
long totalSize = 0;
for (int i = 0; i < asset_config_list.Count; ++i)
{
var tem = asset_config_list[i] as Hashtable;
string b_path = "base/" + tem["name"].ToString();
Hotupdate version_update = new Hotupdate(b_path + "/", local_version, new Version((string)tem["ver"]));
version_update.AssetName = b_path;
version_update.HideDetail = true;
version_update.SetTipCallback((text, callback) =>
{
ShowTip(text, callback);
});
version_update.LoadAssetSize();
while (!version_update.Done)
{
yield return null;
}
tem["size"] = version_update.Size;
totalSize += (long)version_update.Size;
ResourcesManager.ReadAssetConfig(b_path);
}
onback(totalSize, true);
}
/// <summary>
/// 解压下载的资源文件
/// </summary>
/// <param name="asset_config_list"></param>
/// <param name="onback"></param>
/// <returns></returns>
IEnumerator VersionUpdateUnZip(ArrayList asset_config_list, System.Action<bool> onback)
{
for (int i = 0; i < asset_config_list.Count; ++i)
{
var tem = asset_config_list[i] as Hashtable;
string b_path = "base/" + tem["name"].ToString();
ResourcesManager.ReadAssetConfig(b_path);
yield return null;
}
onback(true);
}
2025-11-27 00:09:24 +08:00
#if UNITY_ANDROID
IEnumerator DownApp(string appurl,string version)
{
var v_tex_info = _version_view.GetChild("tex_info");
v_tex_info.text = "正在下载新的安装包(0KB/0KB)";
var _pd = _version_view.GetChild("pb_progress").asSlider;
var request = new BestHTTP.HTTPRequest(new System.Uri(appurl));
request.EnableTimoutForStreaming = false;
request.UseStreaming = true;
request.IsKeepAlive = true;
request.Send();
var filePath = Application.persistentDataPath + "/update" + version + ".apk";
if (File.Exists(filePath))
{
File.Delete(filePath);
}
FileStream stream = null;
request.OnProgress = (originalRequest, downloaded, downloadLength) =>
{
v_tex_info.text = string.Format("正在下载新的安装包({0}KB/{1}KB)", downloaded / 1024, downloadLength / 1024);
_pd.value = (downloaded / (float)downloadLength) * 100;
var fragments = originalRequest.Response.GetStreamedFragments();
if (fragments != null)
{
if (stream == null)
{
stream = File.Create(filePath);
}
foreach(byte[] buffer in fragments)
{
stream.Write(buffer, 0, buffer.Length);
}
}
};
while (request.State < BestHTTP.HTTPRequestStates.Finished)
{
yield return null;
}
yield return new WaitForSeconds(1);
stream.Dispose();
request.OnProgress = null;
if (request.State == BestHTTP.HTTPRequestStates.Finished && request.Response.IsSuccess)
{
DeleteOldPack();
PlatformAndroid.Instance.UpdateApp(filePath);
}
else
{
ShowTip("请检查您的网络设置!", () =>
{
StartCoroutine(DownApp(appurl, version));
});
}
}
#endif
public void ShowTip(string text, System.Action callback)
{
var ctr_state = _version_view.GetController("state");
ctr_state.selectedIndex = 1;
_version_view.GetChild("tex_tip").text = text;
_version_view.GetChild("btn_ok").onClick.Set(() =>
{
ctr_state.selectedIndex = 0;
if (callback != null) callback();
});
}
public IEnumerator CopyFromStreamingAssetsCoroutine(string relativePath, string toFolder = null, System.Action<string> onDone = null)
{
if (string.IsNullOrEmpty(toFolder)) toFolder = Application.persistentDataPath;
string sourcePath = Path.Combine(Application.streamingAssetsPath, relativePath);
string destPath = Path.Combine(toFolder, relativePath);
if (File.Exists(sourcePath))
{
yield return null;
}
Directory.CreateDirectory(Path.GetDirectoryName(destPath));
#if UNITY_ANDROID && !UNITY_EDITOR
// Android: streamingAssets 在 apk 内,需要 UnityWebRequest
using (UnityWebRequest uwr = UnityWebRequest.Get(sourcePath))
{
yield return uwr.SendWebRequest();
if (uwr.isNetworkError || uwr.isHttpError)
{
Debug.LogError("读取失败: " + sourcePath + " 错误: " + uwr.error);
onDone?.Invoke(null);
yield break;
}
byte[] data = uwr.downloadHandler.data;
File.WriteAllBytes(destPath, data);
Debug.Log("复制完成(Android): " + destPath);
onDone?.Invoke(destPath);
}
#else
// 非 Android直接从文件系统读取
if (!File.Exists(sourcePath))
{
Debug.LogError($"源文件不存在: {sourcePath}");
onDone?.Invoke(null);
yield break;
}
byte[] data = File.ReadAllBytes(sourcePath);
File.WriteAllBytes(destPath, data);
Debug.Log($"复制完成: {destPath}");
onDone?.Invoke(destPath);
yield break;
#endif
}
2025-11-27 00:09:24 +08:00
/// <summary>
/// 移除本地缓存包
/// </summary>
public static void DeleteOldPack()
{
string dir = ResourcesManager.RES_PATH;
string rv = dir + "version.txt";
if (File.Exists(rv)) File.Delete(rv);
if (Directory.Exists(dir)) Directory.Delete(dir, true);
}
}