| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767 |
- using Game.Config;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.IO;
- using System.Reflection;
- using System.Text;
- using UnityEngine;
- using UnityEngine.Networking;
- class LocalFilePathInfo
- {
- public string Path;
- /// <summary>
- /// 是否可读可写文件夹
- /// </summary>
- public bool IsLocalRW;
- public LocalFilePathInfo()
- {
- Path = "";
- IsLocalRW = false;
- }
- public LocalFilePathInfo(string path,bool rw)
- {
- Path = path;
- IsLocalRW = rw;
- }
- }
- public class DownloadMgr : Singleton<DownloadMgr>
- {
- public const int TimeOut = 60;
- private string downloadBaseUrl;
- private string downloadUrl;
- public string DownloadUrl { get => downloadUrl; }
- private int downloadTaskMaxNum;
- public int DownloadTaskMaxNum { get => downloadTaskMaxNum; }
- private string localFilePath;
- public string LocalFilePath { get => localFilePath; }
- private List<DownloadDataEntity> needDownloadList;
- private Dictionary<DownloadDataEntity,ulong> downloadingList;
- private List<DownloadDataEntity> downloadSucessList;
- private List<DownloadDataEntity> remoteResList;
- private Dictionary<string, DownloadDataEntity> localResMap;
- private Dictionary<string, DownloadDataEntity> remoteResMap;
- private bool isInited = false;
- private GameDataFormatInfo downloadFormatInfo;
- private string versionFileName;
- private string assetsFileName;
- private string downloadedAssetsFileName;
- private ulong downloadSize;
- private ulong downloadingSize;
- public ulong DownloadSize { get => downloadSize + GetDownloadingSize(); }
- private ulong totalSize;//总大小
- public ulong TotalSize { get => totalSize; }
- public bool CheckFinish { get;private set; }
- public bool DowmloadError { get; private set; }
- //private byte[] versionData;
- //private byte[] mainfestData;
- private string versionData;
- //private UnityWebRequest mainfestData;
- public override void Init()
- {
- InitField();
- }
- private ulong GetDownloadingSize()
- {
- downloadingSize = 0;
- foreach (var item in downloadingList)
- {
- downloadingSize += item.Value;
- }
- return downloadingSize;
- }
- private string GetIOSDownloadPath()
- {
- return "res/IosRes/";
- //#if GAME_DEBUG
- //#else
- //#endif
- }
- private string GetAndroidDownloadPath()
- {
- #if GAME_ONE
- return "res/WDAndroidRes/";
- #elif GAME_DEBUG
- return "res/TestServerRes/";
- #else
- return "res/WDAndroidRes/";
- #endif
- }
- private string GetDownloadBaseUrl()
- {
- #if GAME_ONE
- return "http://101.43.46.101:88/";
- #elif CN_I7GAME_0_1
- return "http://103.239.245.64:88/";
- #elif GAME_DEBUG
- return "http://110.40.223.119:88/";
- #else
- #if UNITY_EDITOR
- return "http://43.248.187.68:88/";
- #else
- return "http://cdn.yishanyou.com:88/";
- #endif
- #endif
- }
- private string GetDownloadUrl()
- {
- #if UNITY_IOS
- return GetDownloadBaseUrl() + GetIOSDownloadPath();
- #else
- return GetDownloadBaseUrl() + GetAndroidDownloadPath();
- #endif
- }
- private void InitField()
- {
- if (!isInited)
- {
- // //downloadBaseUrl = "http://cxzcdn.hkhappygame.com/";//"http://165.154.29.92:88/"; //http://cxzcdn.hkhappygame.com/res/
- // //downloadBaseUrl = "http://127.0.0.1:8060/";//"http://127.0.0.1:8060/";//
- //#if GAME_DEBUG
- // downloadBaseUrl = "http://110.40.223.119:88/";
- // downloadUrl = downloadBaseUrl + "res/TestServerRes/";
- //#else
- // downloadBaseUrl = "http://cxzcdn.hkhappygame.com/";
- //#if UNITY_IOS
- // downloadUrl = downloadBaseUrl + "res/IosRes/";
- //#else
- // downloadUrl = downloadBaseUrl + "res/AndroidNewRes/";
- //#endif
- //#endif
- downloadUrl = GetDownloadUrl();
- downloadTaskMaxNum = 5;
- localFilePath = GetLocalResPath();//FileSystem.LocalDocumentPath;
- versionFileName = "Version";
- assetsFileName = "mainfest";
- downloadedAssetsFileName = "downloaded";
- needDownloadList = new List<DownloadDataEntity>(100);
- downloadSucessList = new List<DownloadDataEntity>(100);
- downloadingList = new Dictionary<DownloadDataEntity,ulong>(downloadTaskMaxNum);
- remoteResList = new List<DownloadDataEntity>(1024);
- localResMap = new Dictionary<string, DownloadDataEntity>(1024);
- remoteResMap = new Dictionary<string, DownloadDataEntity>(1024);
- isInited = true;
- CheckFinish = false;
- DowmloadError = false;
- downloadSize = 0;
- downloadingSize = 0;
- totalSize = 0;
- }
- }
- public void CheckVersion()
- {
- AssetDownloader.Instance.DownLoadFileByCoroutine(GetRemoteUrl(versionFileName), webRqst =>
- {
- if (webRqst == null)
- {
- CheckFinish = true;
- DowmloadError = true;
- return;
- }
- byte[] data = webRqst.downloadHandler.data;
-
- //versionData = new byte[data.Length];
- //data.CopyTo(versionData,0);
- string version = Encoding.UTF8.GetString(data);
- Debug.Log("服务器 version = " + version);
- versionData = version;
- ReadDataFromFile(versionFileName,lVdatas=>
- {
- //OnloadedVersion(lVdatas, version);
- OnloadedLocalVersion(lVdatas, version);
- },true);
- });
-
- }
- public void DownLoadRemoteRes()
- {
- int size = needDownloadList.Count;
- int downsize = downloadSucessList.Count;
- downloadSize = 0;
- totalSize = 0;
- for (int i = 0; i < size; i++)
- {
- if (needDownloadList[i].FullName == "Version")
- {
- needDownloadList[i].State = DownloadTaskState.DownloadSuccess;
- continue;
- }
- totalSize += needDownloadList[i].Size;
- DownloadDataEntity entity = downloadSucessList.FindFirst(it=>it.FullName == needDownloadList[i].FullName);
- if (downsize > 0 && entity != null && entity.MD5 == needDownloadList[i].MD5)
- {
- needDownloadList[i].State = DownloadTaskState.DownloadSuccess;
- downloadSize += needDownloadList[i].Size;
- }
- else
- {
- needDownloadList[i].Callback = DownloadedCallback;
- needDownloadList[i].UpDateCallback = DownloadedUpdateCallback;
- AssetDownloader.Instance.AddDownloadTask(needDownloadList[i]);
- }
- }
- }
- public bool DownLoadFinish()
- {
- bool ret = true;
- int size = needDownloadList.Count;
- for (int i = 0; i < size; i++)
- {
- if (needDownloadList[i].State != DownloadTaskState.DownloadSuccess)
- {
- ret = false;
- }
- }
- return ret || DowmloadError || !AssetDownloader.Instance.HasTask();
- }
- public bool CheckNeedDownload()
- {
- return downloadSize < totalSize;
- }
- private void DownloadedUpdateCallback(DownloadTask task)
- {
- if (task == null)
- {
- // DowmloadError = true;
- //AssetDownloader.Instance.CancelDownLoad = true;
- return;
- }
- //Debug.Log($"下载:{downloadingSize}/{task.CurDownloadEntity.Size} 进度:{task.CurLoadProgress*100}%");
- //downloadingSize = task.downloadSize;
- if (!downloadingList.ContainsKey(task.CurDownloadEntity))
- {
- downloadingList.Add(task.CurDownloadEntity, task.downloadSize);
- }
- else
- {
- downloadingList[task.CurDownloadEntity] = task.downloadSize;
- }
- }
- private void DownloadedCallback(DownloadTask task)
- {
- if (task == null)
- {
- //DowmloadError = true;
- //AssetDownloader.Instance.CancelDownLoad = true;
- return;
- }
- DownloadDataEntity entity = downloadSucessList.FindFirst(it => it.FullName == task.CurDownloadEntity.FullName);
- if (entity != null)
- {
- entity.MD5 = task.CurDownloadEntity.MD5;
- entity.Size = task.CurDownloadEntity.Size;
- }
- else
- {
- downloadSucessList.Add(task.CurDownloadEntity);
- }
- if (downloadingList.ContainsKey(task.CurDownloadEntity))
- {
- downloadingList.Remove(task.CurDownloadEntity);
- }
- downloadingSize = 0;
- downloadSize += task.downloadSize;
-
- string savepath = localFilePath + downloadedAssetsFileName;
- CsvWriter<DownloadDataEntity> csvWriter = new CsvWriter<DownloadDataEntity>(savepath, "", downloadSucessList, downloadFormatInfo);
- csvWriter.Write();
-
- }
- private List<DownloadDataEntity> SerizlizeResList(byte[] data)
- {
- CsvReader csvReader = new CsvReader(FileHelper.GetName(assetsFileName), data);
- if (downloadFormatInfo == null)
- {
- downloadFormatInfo = new GameDataFormatInfo(csvReader.Fields(), csvReader.Types());
- }
- Type type = typeof(DownloadDataEntity);
- MethodInfo methodInfo = type.GetMethod("OnCsvLoad", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
- methodInfo?.Invoke(null, new object[] { csvReader });
- List<DownloadDataEntity> resList = DownloadDataEntity.AllData();
- DownloadDataEntity.Clear();
- return resList;
- }
- private void GetRemoteResList()
- {
- string remoteversionpath = downloadUrl + assetsFileName;
- AssetDownloader.Instance.DownLoadFileByCoroutine(remoteversionpath, webRqst =>
- {
- if (webRqst == null)
- {
- CheckFinish = true;
- DowmloadError = true;
- return;
- }
- byte[] data = webRqst.downloadHandler.data;
- // mainfestData = new byte[data.Length];
- // data.CopyTo(mainfestData,0);
- //mainfestData = webRqst;
- List<DownloadDataEntity> reResList = SerizlizeResList(data);
-
- if (reResList != null)
- {
- OnRomoteListDownloaded(reResList);
- }
-
- });
- }
- private void OnRomoteListDownloaded(List<DownloadDataEntity> downloadDatas)
- {
- remoteResList.AddRange(downloadDatas);
- int size = downloadDatas.Count;
- for (int i = 0; i < size; i++)
- {
- remoteResMap.Add(downloadDatas[i].FullName, downloadDatas[i]);
- }
- //#if UNITY_IOS
- // ReadDataFromFile(assetsFileName, OnloadedLocalResList, false, 1);
- //#else
- // ReadDataFromFile(assetsFileName, OnloadedLocalResList);
- //#endif
- ReadDataFromFile(assetsFileName, OnloadedLocalResList);
- }
- //uint major
- //uint minor
- //uint release
- //uint patch
- private void SetCheckFinish()
- {
- versionData = null;
- CheckFinish = true;
- }
- private string GetLocalResPath()
- {
- string localPath = FileSystem.LocalDocumentPath;
- //#if UNITY_IOS
- // localPath = "file://" + localPath;
- //#endif
- return localPath;
- }
- private string GetStreamResPath()
- {
- string streamPath = FileSystem.LocalPackagePath;
- #if UNITY_IOS
- streamPath = "file://" + streamPath;
- #endif
- return streamPath;
- }
- private void OnloadedLocalVersion(byte[] datas, string version)
- {
- string lVersionstr = "0.0.0.0";
- if (datas != null)
- {
- lVersionstr = Encoding.UTF8.GetString(datas);
- }
-
-
- VersionCode lVersionCode = lVersionstr;//本地 local version
- VersionCode RVersionCode = version;// 远端 version
- string streamPath = GetStreamResPath();
- AssetDownloader.Instance.AssetLoadByCorutine(streamPath + versionFileName, filedatas =>
- {
- if (filedatas == null)
- {
- GetRemoteResList();
- Debug.Log("====== SVersionstr 为空 =====");
- return;
- }
- VersionCode SVersionCode;// stream data version
- string SVersionstr = Encoding.UTF8.GetString(filedatas);
- SVersionCode = SVersionstr;
- VersionCode localMaxCode = lVersionCode > SVersionCode ? lVersionCode : SVersionCode;
- if (localMaxCode == RVersionCode)
- {
- Debug.Log($"lVersionstr = {lVersionstr} SVersionstr = {SVersionstr} ===== version = {version} 不需要更新");
- SetCheckFinish();
- return;
- }
- if (localMaxCode >= RVersionCode && SVersionCode == localMaxCode)
- {
- Debug.Log($"lVersionstr = {lVersionstr} SVersionstr = {SVersionstr} ===== version = {version} 不需要跟新 需要删除之前下载资源");
- versionData = null;
- ReadDataFromFile(downloadedAssetsFileName, dlocaldatas =>
- {
- if (dlocaldatas != null)
- {
- List<DownloadDataEntity> localdownloadedList = SerizlizeResList(dlocaldatas);
- if (localdownloadedList != null && localdownloadedList.Count > 0)
- {
- downloadSucessList.AddRange(localdownloadedList);
- }
- DeleteDownloadFiles();
- }
- else
- {
- SetCheckFinish();
- }
- },true);
- }
- else
- {
- Debug.Log($"lVersionstr = {lVersionstr} SVersionstr = {SVersionstr} ===== version = {version} 需要更新");
- GetRemoteResList();
- //CheckFinish = true;
- }
- });
- }
- private void OnloadedVersion(byte[] datas,string version)
- {
- if (datas == null)
- {
- GetRemoteResList();
- Debug.Log("====== data 为空 =====");
- }
- else
- {
- string lVersionstr = Encoding.UTF8.GetString(datas);
- Debug.Log($"lVersionstr = {lVersionstr} ===== version = {version} ");
- if (lVersionstr == version)
- {
- Debug.Log($"lVersionstr = {lVersionstr} ===== version = {version} 不需要更新");
- SetCheckFinish();
- return;
- }
- else
- {
- VersionCode lVersionCode = lVersionstr;//本地 local version
- VersionCode RVersionCode = version;// 远端 version
- if (RVersionCode < lVersionCode)
- {
- SetCheckFinish();
- }
- else if (RVersionCode.major > lVersionCode.major || (RVersionCode.major == lVersionCode.major && RVersionCode.minor > lVersionCode.minor))
- {
- AssetDownloader.Instance.AssetLoadByCorutine(GetStreamResPath() + versionFileName, filedatas =>
- {
- VersionCode SVersionCode;// stream data version
- string SVersionstr = Encoding.UTF8.GetString(filedatas);
- SVersionCode = SVersionstr;
- if (SVersionCode >= RVersionCode && SVersionCode >= lVersionCode)
- {
- Debug.Log($"lVersionstr = {SVersionstr} ===== version = {version} 重新安装后需要删除之前资源");
- versionData = null;
- ReadDataFromFile(downloadedAssetsFileName, dlocaldatas=>
- {
- if (dlocaldatas != null)
- {
- List<DownloadDataEntity> localdownloadedList = SerizlizeResList(dlocaldatas);
- if (localdownloadedList != null && localdownloadedList.Count > 0)
- {
- downloadSucessList.AddRange(localdownloadedList);
- }
- DeleteDownloadFiles();
- }
- });
- }
- else
- {
- Debug.Log($"lVersionstr = {lVersionstr} ===== version = {version} 需要更新");
- GetRemoteResList();
- //CheckFinish = true;
- }
- });
- }
- else if (RVersionCode.release > lVersionCode.release || (RVersionCode.release == lVersionCode.release && RVersionCode.patch > lVersionCode.patch))
- {
- Debug.Log($"lVersionstr = {lVersionstr} ===== version = {version} 需要更新");
- GetRemoteResList();
- }
- else
- {
- SetCheckFinish();
- }
- }
- }
- }
- private void OnloadedLocalResList(byte[] datas)
- {
- if (datas == null)
- {
-
- }
- else
- {
- List<DownloadDataEntity> localList = SerizlizeResList(datas);
- if (localList != null)
- {
- int size = localList.Count;
- for (int i = 0; i < size; i++)
- {
- localResMap.Add(localList[i].FullName, localList[i]);
- }
- }
- }
- ReadDataFromFile(downloadedAssetsFileName, OnloadedDownloadResList);
- }
- private void OnloadedDownloadResList(byte[] datas)
- {
- if (datas != null)
- {
- List<DownloadDataEntity> localdownloadedList = SerizlizeResList(datas);
- if (localdownloadedList != null && localdownloadedList.Count > 0)
- {
- downloadSucessList.AddRange(localdownloadedList);
- }
- }
- GetNeedDownloadlist();
- DownLoadRemoteRes();
- }
- private List<DownloadDataEntity> GetLoacalResList(string path)
- {
- List<DownloadDataEntity> resList = null;
- if (System.IO.File.Exists(path))
- {
- byte[] data = System.IO.File.ReadAllBytes(path);
- resList = SerizlizeResList(data);
- }
- return resList;
- }
- private void GetNeedDownloadlist()
- {
- string ver = "Version";
- if (localResMap.ContainsKey(ver) && remoteResMap.ContainsKey(ver)&& localResMap[ver].MD5 == remoteResMap[ver].MD5)
- {
- Debug.Log("版本为最新状态");
- SetCheckFinish();
- //string savepath = localFilePath + downloadedAssetsFileName;
- //FileHelper.DeleteFile(savepath);
- return;
- }
- if (localResMap == null || localResMap.Count <= 0)
- {
- foreach (var item in remoteResMap)
- {
- needDownloadList.Add(item.Value);
- }
- }
- else
- {
- foreach (var item in remoteResMap)
- {
- if (item.Key == ver)
- {
- continue;
- }
- if (!localResMap.ContainsKey(item.Key) || localResMap[item.Key].MD5 != item.Value.MD5)
- {
- Debug.Log($"需跟新文件:{item.Value.FullName}");
- needDownloadList.Add(item.Value);
- }
- }
- }
- CheckFinish = true;
- }
- private string GetRemoteUrl( string name)
- {
- return downloadUrl + name;
- }
- private LocalFilePathInfo GetLocalFilePath(string name, bool onlyLocal = false, uint streamPerPath = 0)
- {
- LocalFilePathInfo ret = new LocalFilePathInfo();
- string path = LocalFilePath + name;
- ret.IsLocalRW = true;
- if (!FileSystem.Exists(path))
- {
- Debug.Log($" ========= LocalFilePath Path = {path} 不存在");
- if (!onlyLocal)
- {
- string lpPath = GetStreamResPath();
- for (int i = 0; i < streamPerPath; i++)
- {
- lpPath += "../";
- }
- path = lpPath + name;
- }
- ret.IsLocalRW = false;
- }
- ret.Path = path;
- Debug.Log($" ========= local Path = {path} ");
- return ret;
- }
- private void ReadDataFromFile(string name,Action<byte[]> callback,bool onlyLocal = false,uint streamPerPath = 0)
- {
- LocalFilePathInfo dlocalPath = GetLocalFilePath(name,onlyLocal, streamPerPath);
- if (dlocalPath.IsLocalRW)
- {
- try
- {
- byte[] dlocaldatas = File.ReadAllBytes(dlocalPath.Path);
- callback?.Invoke(dlocaldatas);
- }
- catch
- {
- Debug.Log("读取失败" + dlocalPath.Path);
- callback?.Invoke(null);
- }
- }
- else if(onlyLocal)
- {
- callback?.Invoke(null);
- }
- else
- {
- AssetDownloader.Instance.AssetLoadByCorutine(dlocalPath.Path, callback);
- }
- }
- private IEnumerator DeleteFiles()
- {
- ;
- int length = downloadSucessList.Count;
- string savepath = null;
- for (int i = 0; i < length; i++)
- {
- if (downloadSucessList[i].FullName == "font.unity3d")
- {
- Debug.Log("跳过删除");
- continue;
- }
- savepath = localFilePath + downloadSucessList[i].FullName;
- Debug.Log(savepath);
- FileHelper.DeleteFile(savepath);
- yield return null;
- }
-
- FileHelper.DeleteFile(localFilePath + downloadedAssetsFileName);
- yield return null;
- FileHelper.DeleteFile(localFilePath + versionFileName);
- yield return null;
- FileHelper.DeleteFile(LocalFilePath + assetsFileName);
- yield return null;
- SetCheckFinish();
- }
- public void DeleteDownloadFiles()
- {
- AssetDownloader.Instance.DoByCorutine(DeleteFiles);
- }
- public void Free()
- {
- //string savepath = localFilePath + downloadedAssetsFileName;
- //FileHelper.DeleteFile(savepath);
- if (!DowmloadError)
- {
- if( !string.IsNullOrEmpty(versionData))
- FileHelper.WirteStringToFile(localFilePath + versionFileName, versionData);
- //PlayerPrefs.SetString(versionFileName, versionData);
- //if(mainfestData!=null)
- // FileHelper.WirteToFile(LocalFilePath + assetsFileName, mainfestData.downloadHandler.data);
- if (remoteResList.Count > 0)
- {
- //Debug.Log($" ============= remoteResList.Count = {remoteResList.Count}" );
- CsvWriter<DownloadDataEntity> csvWriter = new CsvWriter<DownloadDataEntity>(LocalFilePath + assetsFileName, "", remoteResList, downloadFormatInfo);
- csvWriter.Write();
- }
- }
- needDownloadList = null;
- downloadSucessList = null;
- remoteResList = null;
- localResMap = null;
- remoteResMap = null;
- versionData = null;
- //mainfestData = null;
- AssetDownloader.Instance.ClearTasks();
- }
- }
|