123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900 |
- using LitJson;
- using Newtonsoft.Json;
- using SC.XR.Unity;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.IO;
- using System.Text;
- using UnityEngine;
- using UnityEngine.Networking;
- using UnityEngine.UI;
- public class DownloadManager : SingletonMono<DownloadManager>
- {
-
-
-
- private Dictionary<string, Texture2D> m_ImageDic;
-
-
-
- private List<DownloadData> m_WaitDownload;
- private Dictionary<string, List<DownloadData>> m_WaitDownloadData;
-
-
-
- private List<DownloadData> m_Downloading;
-
-
-
- private List<DownloadData> m_Downloaded;
-
-
-
- private List<DownloadData> m_FiledDownload;
-
-
-
-
- private Dictionary<string, List<DownloadData>> m_LocaData;
-
-
-
- private string m_LocaConfigPath;
-
-
-
- private string m_LocaDataPath;
- public string LocaDataPath
- {
- get { return m_LocaDataPath; }
- private set { m_LocaDataPath = value; }
- }
- private Dictionary<string, GameObject> m_AbObjs;
- public List<DownloadData> GetDownloaded()
- {
- return m_Downloaded;
- }
- private void Awake()
- {
- m_ImageDic = new Dictionary<string, Texture2D>();
- m_WaitDownload = new List<DownloadData>();
- m_WaitDownloadData = new Dictionary<string, List<DownloadData>>();
- m_Downloading = new List<DownloadData>();
- m_Downloaded = new List<DownloadData>();
- m_FiledDownload = new List<DownloadData>();
- m_LocaData = new Dictionary<string, List<DownloadData>>();
- m_AbObjs = new Dictionary<string, GameObject>();
- m_LocaConfigPath = FileManager.CalFilePath(Path.Combine(Application.persistentDataPath, "DataConfig.Json"));
- LocaDataPath = FileManager.CalFilePath(Application.persistentDataPath + "/MaterialData");
- if (!Directory.Exists(LocaDataPath))
- {
- Directory.CreateDirectory(LocaDataPath);
- }
-
-
- ReadLocaData();
- }
-
-
-
- private void ReadLocaData()
- {
- string str = FileManager.ReadFile(m_LocaConfigPath);
- foreach (JsonData item in JsonMapper.ToObject(str))
- {
- DownloadData data = new DownloadData(item);
- if (File.Exists(data.localSavePath))
- {
- if (!m_LocaData.ContainsKey(data.downloadPath))
- {
- List<DownloadData> datas = new List<DownloadData>();
- datas.Add(data);
- m_LocaData.Add(data.downloadPath, datas);
- }
- else
- {
- var datas = m_LocaData[data.downloadPath];
- bool iscontains = false;
- for (int i = 0; i < datas.Count; i++)
- {
- if (datas[i].localSavePath == data.localSavePath)
- {
- iscontains = true;
- }
- }
- if (!iscontains)
- {
- datas.Add(data);
- m_LocaData[data.downloadPath] = datas;
- }
- }
-
-
-
-
- }
- }
- }
-
-
-
- private void SaveLocaData()
- {
- string str = "[]";
- if (m_LocaData.Count > 0)
- {
- JsonData jsonData = new JsonData();
- foreach (string key in m_LocaData.Keys)
- {
- var data = m_LocaData[key];
- for (int i = 0; i < data.Count; i++)
- {
- jsonData.Add(data[i].ToJsonData());
- }
- }
- str = jsonData.ToJson();
- Debug.Log("保存本地数据:" + str);
- }
- FileManager.WriteFile(str, m_LocaConfigPath);
- }
-
-
-
- public bool CheckDownloadData(DownloadData data)
- {
- if (string.IsNullOrWhiteSpace(data.downloadPath))
- {
- return true;
- }
-
- if (m_LocaData.ContainsKey(data.downloadPath))
- {
- var datas = m_LocaData[data.downloadPath];
- for (int i = 0; i < datas.Count; i++)
- {
- if (datas[i].localSavePath == data.localSavePath)
- {
- var loca = datas[i];
- if (!File.Exists(data.localSavePath))
- {
- datas.RemoveAt(i);
- m_LocaData[data.downloadPath] = datas;
- return false;
- }
- else
- {
- DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
- var locatime = startTime.AddSeconds((double)loca.updateTime);
- var datatime = startTime.AddSeconds((double)data.updateTime);
- if (DateTime.Compare(locatime, datatime) >= 0)
- {
-
- return true;
- }
- else
- {
- datas.RemoveAt(i);
- m_LocaData[data.downloadPath] = datas;
- File.Delete(data.localSavePath);
- return false;
- }
- }
- }
- }
- }
- else
- {
- return false;
- }
- return false;
- }
- public void AddDownloadData(DownloadData data)
- {
- if (!m_WaitDownloadData.ContainsKey(data.downloadPath))
- {
- m_WaitDownload.Add(data);
- List<DownloadData> datas = new List<DownloadData>();
- datas.Add(data);
- m_WaitDownloadData.Add(data.downloadPath, datas);
- }
- else
- {
- var datas = m_WaitDownloadData[data.downloadPath];
- for (int i = 0; i < datas.Count; i++)
- {
- if (datas[i].localSavePath == data.localSavePath)
- {
- return;
- }
- }
- m_WaitDownloadData[data.downloadPath].Add(data);
- m_WaitDownload.Add(data);
- }
-
-
-
-
-
- }
- public void UpdataData()
- {
- m_Downloaded.Clear();
- StartCoroutine(StarDownload());
- Debug.Log(m_WaitDownload.Count + "===================================");
- }
- IEnumerator StarDownload()
- {
- var loadUI = (LoadingPanel)UIManager.Instance.GetUI(UINameConfig.LoadingPanel);
- var count = m_WaitDownload.Count;
- yield return new WaitForSeconds(2f);
- while (true)
- {
- if (m_Downloading.Count < 1 && m_WaitDownload.Count > 0)
- {
- var data = m_WaitDownload[0];
- m_WaitDownload.RemoveAt(0);
- if (CheckDownloadData(data))
- {
- m_Downloaded.Add(data);
- AddLocaData(data);
- continue;
- }
- m_Downloading.Add(data);
- loadUI.TextStr = data.downloadPath;
- switch (data.type)
- {
- case (int)MaterialType.Image:
- GetImage(data, (Image)null);
-
-
-
- break;
- case (int)MaterialType.Video:
- DownloadFile(data);
- break;
- case (int)MaterialType.Model:
- DownloadFile(data);
-
- break;
- case (int)MaterialType.Vuforia:
- DownloadFile(data);
- break;
- default:
- break;
- }
- }
-
- if (m_Downloading.Count <= 0 && m_Downloaded.Count + m_FiledDownload.Count == count)
- {
- SaveLocaData();
- loadUI.ProgressStr = "";
- UIManager.Instance.ShowUI(UINameConfig.LoadingPanel, typeof(LoadingPanel), (int)ELoadState.updateEnd);
- yield break;
- }
- loadUI.ProgressStr = ((float)(m_Downloaded.Count + m_FiledDownload.Count) / count).ToString("P");
- yield return null;
- }
- }
- #region public 请求方法
-
-
-
-
-
- public void GetImage(DownloadData data, Image image)
- {
- if (string.IsNullOrEmpty(data.downloadPath))
- {
- m_Downloading.Remove(data);
- m_FiledDownload.Add(data);
- return;
- }
- StartCoroutine(LoadImage(data, (tex) =>
- {
- Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
- if (image != null)
- {
- image.sprite = sprite;
- }
- }));
- }
-
-
-
-
-
- public void GetImage(DownloadData data, RawImage image)
- {
- if (string.IsNullOrEmpty(data.downloadPath))
- {
- image.texture = null;
- return;
- }
- StartCoroutine(LoadImage(data, (tex) =>
- {
- if (image == null)
- {
- return;
- }
- image.texture = tex;
- }));
- }
-
-
-
-
-
-
-
- public void GetAudioClip(string url, Action<AudioClip> actionResult, AudioType audioType = AudioType.WAV)
- {
- StartCoroutine(DownloadAudioClip(url, actionResult, audioType));
- }
-
-
-
-
-
-
- public void GetAssetBundle(DownloadData data, Action<AssetBundle> actionResult = null)
- {
- StartCoroutine(_GetAssetBundle(data, actionResult));
- }
-
-
-
-
-
-
-
- public void DownloadFile(DownloadData data, Action<UnityWebRequest> actionResult = null)
- {
- StartCoroutine(_DownloadFile(data, actionResult));
- }
- #endregion
- #region 文件
-
-
-
-
-
-
-
- IEnumerator _DownloadFile(DownloadData data, Action<UnityWebRequest> actionResult = null)
- {
- string url = HttpTool.Instance.BaseUrl + "/file/download";
- FileDown file = new FileDown();
- if (string.IsNullOrWhiteSpace(data.downloadPath))
- {
- m_Downloading.Remove(data);
- m_FiledDownload.Add(data);
- yield break;
- }
- file.url = data.downloadPath;
- string jsonString = JsonConvert.SerializeObject(file);
- byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
- if (File.Exists(data.localSavePath))
- {
- m_Downloading.Remove(data);
- m_Downloaded.Add(data);
- AddLocaData(data);
-
- yield break;
- }
- Debug.LogFormat("{0}:{1}", "文件下载路径为", url);
- UnityWebRequest uwr = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST);
- uwr.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
- uwr.downloadHandler = new DownloadHandlerFile(data.localSavePath);
- uwr.SetRequestHeader("authorization", HttpTool.Instance.Token);
- foreach (var v in HttpTool.Instance.RequestHeader)
- {
- uwr.SetRequestHeader(v.Key, v.Value);
- }
- yield return uwr.SendWebRequest();
- while (!uwr.isDone)
- {
- Debug.Log(uwr.downloadProgress);
- }
- m_Downloading.Remove(data);
-
- if (uwr.isNetworkError || uwr.isHttpError)
- {
- Debug.LogErrorFormat("{0}:{1}", "当前下载发生错误", uwr.error);
- m_FiledDownload.Add(data);
- }
- else
- {
- AddLocaData(data);
- m_Downloaded.Add(data);
- }
- if (actionResult != null)
- {
- actionResult(uwr);
- }
- uwr.Abort();
- uwr.Dispose();
- }
- #endregion
- #region 图片下载
- public void LoadMap(DownloadData data, Image image, Action<Texture2D> loadEnd)
- {
- StartCoroutine(LoadImage(data, loadEnd));
- }
-
-
-
-
-
-
- private IEnumerator LoadImage(DownloadData data, Action<Texture2D> loadEnd)
- {
- Texture2D texture = null;
-
- if (m_ImageDic.TryGetValue(data.downloadPath, out texture))
- {
- Debug.Log("从内存获取");
-
- m_Downloading.Remove(data);
- m_Downloaded.Add(data);
- AddLocaData(data);
- loadEnd.Invoke(texture);
- yield break;
- }
-
-
- bool hasLoad = false;
- if (File.Exists(data.localSavePath))
- yield return DownloadTexture(data, (state, localTexture) =>
- {
- Debug.Log("从本地获取 " + data.localSavePath);
- hasLoad = state;
- if (state)
- {
- loadEnd.Invoke(localTexture);
- if (!m_ImageDic.ContainsKey(data.downloadPath))
- {
- m_ImageDic.Add(data.downloadPath, localTexture);
- }
-
- m_Downloading.Remove(data);
- m_Downloaded.Add(data);
- AddLocaData(data);
- }
- }, true);
- if (hasLoad) yield break;
-
- yield return DownloadTexture(data, (state, downloadTexture) =>
- {
- hasLoad = state;
- if (state)
- {
- Debug.Log("网络下载");
- loadEnd.Invoke(downloadTexture);
- if (!m_ImageDic.ContainsKey(data.downloadPath))
- m_ImageDic.Add(data.downloadPath, downloadTexture);
- Save2LocalPath(data.localSavePath, downloadTexture);
- AddLocaData(data);
- m_Downloaded.Add(data);
- }
- else
- {
- m_FiledDownload.Add(data);
- }
- m_Downloading.Remove(data);
-
- }, false);
- }
-
-
-
-
-
-
-
- private IEnumerator DownloadTexture(DownloadData data, Action<bool, Texture2D> downloadEnd, bool isLoca)
- {
- string realUrl = isLoca ? data.localSavePath : HttpTool.Instance.BaseUrl + data.downloadPath;
-
-
-
-
- if (!isLoca && File.Exists(data.localSavePath))
- {
- File.Delete(data.localSavePath);
- }
- if (isLoca)
- {
- #if UNITY_EDITOR
- realUrl = data.localSavePath;
- #elif UNITY_ANDROID
- realUrl = "file://" + data.localSavePath;
- #endif
- }
- using (UnityWebRequest request = new UnityWebRequest(realUrl))
- {
- DownloadHandlerTexture downloadHandlerTexture = new DownloadHandlerTexture(true);
- request.downloadHandler = downloadHandlerTexture;
- yield return request.SendWebRequest();
- if (string.IsNullOrEmpty(request.error))
- {
- Texture2D localTexture = downloadHandlerTexture.texture;
- downloadEnd.Invoke(true, localTexture);
- Resources.UnloadUnusedAssets();
- }
- else
- {
- downloadEnd.Invoke(false, null);
- if (File.Exists(data.localSavePath))
- {
- File.Delete(data.localSavePath);
- }
- Debug.LogError(request.error);
- Debug.LogError(isLoca);
- Debug.LogError(realUrl);
- Debug.LogError(data.localSavePath);
- Debug.LogError(data.downloadPath);
- Debug.LogError("图片下载失败");
- }
- request.Abort();
- request.downloadHandler.Dispose();
- request.Dispose();
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- }
- public void GetMapImage(DownloadData data, Image image, Action<bool, Texture2D> loadEnd)
- {
- StartCoroutine(GetMapImage(data, loadEnd));
- }
- IEnumerator GetMapImage(DownloadData data, Action<bool, Texture2D> downloadEnd)
- {
- string realUrl = HttpTool.Instance.BaseUrl + "/file/download";
- FileDown file = new FileDown();
- file.url = data.downloadPath;
- string jsonString = JsonConvert.SerializeObject(file);
- byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
- using (UnityWebRequest request = new UnityWebRequest(realUrl, "POST"))
- {
- request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
- DownloadHandlerTexture downloadHandlerTexture = new DownloadHandlerTexture(true);
- request.downloadHandler = downloadHandlerTexture;
- request.SetRequestHeader("authorization", HttpTool.Instance.Token);
- foreach (var v in HttpTool.Instance.RequestHeader)
- {
- request.SetRequestHeader(v.Key, v.Value);
- }
- yield return request.SendWebRequest();
- if (string.IsNullOrEmpty(request.error))
- {
- Texture2D localTexture = downloadHandlerTexture.texture;
- downloadEnd.Invoke(true, localTexture);
- Resources.UnloadUnusedAssets();
- }
- else
- {
- downloadEnd.Invoke(false, null);
- if (File.Exists(data.localSavePath))
- {
- File.Delete(data.localSavePath);
- }
- Debug.LogError(request.error);
- Debug.LogError(data.downloadPath);
- Debug.LogError("小地图下载失败");
- }
- request.Abort();
- request.downloadHandler.Dispose();
- request.Dispose();
- }
- }
-
-
-
-
-
- private void Save2LocalPath(string path, Texture2D texture)
- {
- byte[] bytes = texture.EncodeToPNG();
-
-
- if (!Directory.Exists(path))
- {
- DirectoryInfo pathInfo = new DirectoryInfo(path);
- pathInfo.Parent.Create();
- }
- if (File.Exists(path))
- {
- File.Delete(path);
- }
- try
- {
- File.WriteAllBytes(path, bytes);
- }
- catch (Exception ex)
- {
- Debug.LogError(ex.ToString());
- }
- }
-
-
-
-
-
- private string GetLocalPath()
- {
- string savePath = LocaDataPath + "/" + DataManager.Instance.CurrentScene.id.ToString() + "/pics/";
- if (!Directory.Exists(savePath))
- {
- Directory.CreateDirectory(savePath);
- }
- return savePath;
- }
- #endregion
- #region 音效
-
-
-
-
-
-
-
- IEnumerator DownloadAudioClip(string url, Action<AudioClip> actionResult, AudioType audioType = AudioType.WAV)
- {
- using (var uwr = UnityWebRequestMultimedia.GetAudioClip(url, audioType))
- {
- yield return uwr.SendWebRequest();
- if (!(uwr.isNetworkError || uwr.isHttpError))
- {
- if (actionResult != null)
- {
- actionResult(DownloadHandlerAudioClip.GetContent(uwr));
- }
- }
- }
- }
- #endregion
- #region AssetBundle
-
-
-
-
-
-
- IEnumerator _GetAssetBundle(DownloadData data, Action<AssetBundle> actionResult = null)
- {
- if (string.IsNullOrWhiteSpace(data.downloadPath))
- {
- m_Downloading.Remove(data);
- m_FiledDownload.Add(data);
- yield break;
- }
- else
- {
- if (m_AbObjs.ContainsKey(Util.MD5Encrypt(data.downloadPath)))
- {
- m_Downloading.Remove(data);
- m_Downloaded.Add(data);
-
- yield break;
- }
- string baseUrl = HttpTool.Instance.BaseUrl + data.downloadPath;
-
- AssetBundle ab = null;
- UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(baseUrl);
- request.SetRequestHeader("authorization", HttpTool.Instance.Token);
- yield return request.SendWebRequest();
- if (request.isNetworkError || request.isHttpError)
- {
- m_Downloading.Remove(data);
- m_FiledDownload.Add(data);
- Debug.LogError(request.error);
- }
- else
- {
- ab = DownloadHandlerAssetBundle.GetContent(request);
- if (ab == null)
- {
- request.Dispose();
- yield break;
- }
- AssetBundleRequest abrequest = ab.LoadAssetAsync<GameObject>(data.name);
- yield return abrequest;
- GameObject obj = abrequest.asset as GameObject;
- var @object = Instantiate(obj);
- @object.SetActive(false);
- m_AbObjs.Add(Util.MD5Encrypt(data.downloadPath), @object);
- m_Downloading.Remove(data);
- m_Downloaded.Add(data);
- AddLocaData(data);
- ab.Unload(false);
- }
- request.Abort();
- request.Dispose();
- }
- }
- #endregion
- private void AddLocaData(DownloadData data)
- {
- if (m_LocaData.ContainsKey(data.downloadPath))
- {
- var datas = m_LocaData[data.downloadPath];
- bool iscontains = false;
- for (int i = 0; i < datas.Count; i++)
- {
- if (datas[i].localSavePath == data.localSavePath)
- {
- iscontains = true;
- DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
- var time1 = startTime.AddSeconds((double)datas[i].updateTime);
- var time2 = startTime.AddSeconds((double)data.updateTime);
- if (DateTime.Compare(time1, time2) >= 0)
- {
-
- return;
- }
- else
- {
- datas.RemoveAt(i);
- datas.Add(data);
- m_LocaData[data.downloadPath] = datas;
- return;
- }
- }
- }
- if (!iscontains)
- {
- datas.Add(data);
- m_LocaData[data.downloadPath] = datas;
- }
- }
- else
- {
- List<DownloadData> datas = new List<DownloadData>();
- datas.Add(data);
- m_LocaData.Add(data.downloadPath, datas);
- }
- }
- private void OnApplicationQuit()
- {
- Debug.Log("退出程序");
- }
- public GameObject GetAbObj(string DownloadPath)
- {
- if (m_AbObjs.ContainsKey(DownloadPath))
- {
- return m_AbObjs[DownloadPath];
- }
- else
- {
- return null;
- }
- }
- }
- public class FileDown
- {
- public string url { get; set; }
- }
|