DownloadManager.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  1. using LitJson;
  2. using Newtonsoft.Json;
  3. using SC.XR.Unity;
  4. using System;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Text;
  9. using UnityEngine;
  10. using UnityEngine.Networking;
  11. using UnityEngine.UI;
  12. public class DownloadManager : SingletonMono<DownloadManager>
  13. {
  14. /// <summary>
  15. /// 图片集合
  16. /// </summary>
  17. private Dictionary<string, Texture2D> m_ImageDic;
  18. /// <summary>
  19. /// 等待下载
  20. /// </summary>
  21. private List<DownloadData> m_WaitDownload;
  22. private Dictionary<string, List<DownloadData>> m_WaitDownloadData;
  23. /// <summary>
  24. /// 正在下载中的数据
  25. /// </summary>
  26. private List<DownloadData> m_Downloading;
  27. /// <summary>
  28. /// 已下载完成的数据
  29. /// </summary>
  30. private List<DownloadData> m_Downloaded;
  31. /// <summary>
  32. /// 下载失败
  33. /// </summary>
  34. private List<DownloadData> m_FiledDownload;
  35. /// <summary>
  36. /// 本地已下载数据
  37. /// </summary>
  38. //private List<DownloadData> m_LocaData;
  39. private Dictionary<string, List<DownloadData>> m_LocaData;
  40. /// <summary>
  41. /// 本地数据记录表存储路径
  42. /// </summary>
  43. private string m_LocaConfigPath;
  44. /// <summary>
  45. /// 本地数据存储路径
  46. /// </summary>
  47. private string m_LocaDataPath;
  48. public string LocaDataPath
  49. {
  50. get { return m_LocaDataPath; }
  51. private set { m_LocaDataPath = value; }
  52. }
  53. private Dictionary<string, GameObject> m_AbObjs;
  54. public List<DownloadData> GetDownloaded()
  55. {
  56. return m_Downloaded;
  57. }
  58. private void Awake()
  59. {
  60. m_ImageDic = new Dictionary<string, Texture2D>();
  61. m_WaitDownload = new List<DownloadData>();
  62. m_WaitDownloadData = new Dictionary<string, List<DownloadData>>();
  63. m_Downloading = new List<DownloadData>();
  64. m_Downloaded = new List<DownloadData>();
  65. m_FiledDownload = new List<DownloadData>();
  66. m_LocaData = new Dictionary<string, List<DownloadData>>();
  67. m_AbObjs = new Dictionary<string, GameObject>();
  68. m_LocaConfigPath = FileManager.CalFilePath(Path.Combine(Application.persistentDataPath, "DataConfig.Json"));
  69. LocaDataPath = FileManager.CalFilePath(Application.persistentDataPath + "/MaterialData");
  70. if (!Directory.Exists(LocaDataPath))
  71. {
  72. Directory.CreateDirectory(LocaDataPath);
  73. }
  74. //Debug.Log(LocaDataPath);
  75. //Debug.Log(m_LocaConfigPath);
  76. ReadLocaData();
  77. }
  78. /// <summary>
  79. /// 读取本地数据
  80. /// </summary>
  81. private void ReadLocaData()
  82. {
  83. string str = FileManager.ReadFile(m_LocaConfigPath);
  84. foreach (JsonData item in JsonMapper.ToObject(str))
  85. {
  86. DownloadData data = new DownloadData(item);
  87. if (File.Exists(data.localSavePath))
  88. {
  89. if (!m_LocaData.ContainsKey(data.downloadPath))
  90. {
  91. List<DownloadData> datas = new List<DownloadData>();
  92. datas.Add(data);
  93. m_LocaData.Add(data.downloadPath, datas);
  94. }
  95. else
  96. {
  97. var datas = m_LocaData[data.downloadPath];
  98. bool iscontains = false;
  99. for (int i = 0; i < datas.Count; i++)
  100. {
  101. if (datas[i].localSavePath == data.localSavePath)
  102. {
  103. iscontains = true;
  104. }
  105. }
  106. if (!iscontains)
  107. {
  108. datas.Add(data);
  109. m_LocaData[data.downloadPath] = datas;
  110. }
  111. }
  112. //if (!m_LocaData.Contains(data))
  113. //{
  114. // m_LocaData.Add(data);
  115. //}
  116. }
  117. }
  118. }
  119. /// <summary>
  120. /// 保存本地数据
  121. /// </summary>
  122. private void SaveLocaData()
  123. {
  124. string str = "[]";
  125. if (m_LocaData.Count > 0)
  126. {
  127. JsonData jsonData = new JsonData();
  128. foreach (string key in m_LocaData.Keys)
  129. {
  130. var data = m_LocaData[key];
  131. for (int i = 0; i < data.Count; i++)
  132. {
  133. jsonData.AddToIList(data[i].ToJsonData());
  134. }
  135. }
  136. str = jsonData.ToJson();
  137. Debug.Log("保存本地数据:" + str);
  138. }
  139. FileManager.WriteFile(str, m_LocaConfigPath);
  140. }
  141. /// <summary>
  142. /// 检查是否已经下载了资源
  143. /// </summary>
  144. public bool CheckDownloadData(DownloadData data)
  145. {
  146. if (string.IsNullOrWhiteSpace(data.downloadPath))
  147. {
  148. return true;
  149. }
  150. if (m_LocaData.ContainsKey(data.downloadPath))
  151. {
  152. var datas = m_LocaData[data.downloadPath];
  153. for (int i = 0; i < datas.Count; i++)
  154. {
  155. if (datas[i].localSavePath == data.localSavePath)
  156. {
  157. var loca = datas[i];
  158. if (!File.Exists(data.localSavePath))
  159. {
  160. datas.RemoveAt(i);
  161. m_LocaData[data.downloadPath] = datas;
  162. return false;
  163. }
  164. else
  165. {
  166. DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  167. var locatime = startTime.AddSeconds((double)loca.updateTime);
  168. var datatime = startTime.AddSeconds((double)data.updateTime);
  169. if (DateTime.Compare(locatime, datatime) >= 0)
  170. {
  171. //Debug.Log(string.Format("{0}>{1}", locatime, datatime));
  172. return true;
  173. }
  174. else
  175. {
  176. datas.RemoveAt(i);
  177. m_LocaData[data.downloadPath] = datas;
  178. File.Delete(data.localSavePath);
  179. return false;
  180. }
  181. }
  182. }
  183. }
  184. }
  185. else
  186. {
  187. return false;
  188. }
  189. return false;
  190. }
  191. public void AddDownloadData(DownloadData data)
  192. {
  193. if (!m_WaitDownloadData.ContainsKey(data.downloadPath))
  194. {
  195. m_WaitDownload.Add(data);
  196. List<DownloadData> datas = new List<DownloadData>();
  197. datas.Add(data);
  198. m_WaitDownloadData.Add(data.downloadPath, datas);
  199. }
  200. else
  201. {
  202. var datas = m_WaitDownloadData[data.downloadPath];
  203. for (int i = 0; i < datas.Count; i++)
  204. {
  205. if (datas[i].localSavePath == data.localSavePath)
  206. {
  207. return;
  208. }
  209. }
  210. m_WaitDownloadData[data.downloadPath].Add(data);
  211. m_WaitDownload.Add(data);
  212. }
  213. //if (!m_WaitDownloadURL.Contains(data.downloadPath))
  214. //{
  215. // m_WaitDownload.Add(data);
  216. // m_WaitDownloadURL.Add(data.downloadPath);
  217. //}
  218. }
  219. public void UpdataData()
  220. {
  221. m_Downloaded.Clear();
  222. StartCoroutine(StarDownload());
  223. Debug.Log(m_WaitDownload.Count + "===================================");
  224. }
  225. IEnumerator StarDownload()
  226. {
  227. var loadUI = (LoadingPanel)UIManager.Instance.GetUI(UINameConfig.LoadingPanel);
  228. var count = m_WaitDownload.Count;
  229. yield return new WaitForSeconds(2f);
  230. while (true)
  231. {
  232. if (m_Downloading.Count < 1 && m_WaitDownload.Count > 0)
  233. {
  234. var data = m_WaitDownload[0];
  235. m_WaitDownload.RemoveAt(0);
  236. if (CheckDownloadData(data))
  237. {
  238. m_Downloaded.Add(data);
  239. AddLocaData(data);
  240. continue;
  241. }
  242. m_Downloading.Add(data);
  243. loadUI.TextStr = data.downloadPath;
  244. switch (data.type)
  245. {
  246. case (int)MaterialType.Image:
  247. GetImage(data, (Image)null);
  248. //m_Downloading.Remove(data);
  249. //m_Downloaded.Add(data);
  250. //AddLocaData(data);
  251. break;
  252. case (int)MaterialType.Video:
  253. DownloadFile(data);
  254. break;
  255. case (int)MaterialType.Model:
  256. DownloadFile(data);
  257. //GetAssetBundle(data);
  258. break;
  259. case (int)MaterialType.Vuforia:
  260. DownloadFile(data);
  261. break;
  262. default:
  263. break;
  264. }
  265. }
  266. //yield return new WaitForSeconds(1f);
  267. if (m_Downloading.Count <= 0 && m_Downloaded.Count + m_FiledDownload.Count == count)
  268. {
  269. SaveLocaData();
  270. loadUI.ProgressStr = "";
  271. UIManager.Instance.ShowUI(UINameConfig.LoadingPanel, typeof(LoadingPanel), (int)ELoadState.updateEnd);
  272. yield break;
  273. }
  274. loadUI.ProgressStr = ((float)(m_Downloaded.Count + m_FiledDownload.Count) / count).ToString("P");
  275. yield return null;
  276. }
  277. }
  278. #region public 请求方法
  279. /// <summary>
  280. /// 获取图片
  281. /// </summary>
  282. /// <param name="url">图片地址</param>
  283. /// <param name="image">图片类型</param>
  284. public void GetImage(DownloadData data, Image image)
  285. {
  286. if (string.IsNullOrEmpty(data.downloadPath))
  287. {
  288. m_Downloading.Remove(data);
  289. m_FiledDownload.Add(data);
  290. return;
  291. }
  292. StartCoroutine(LoadImage(data, (tex) =>
  293. {
  294. Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
  295. if (image != null)
  296. {
  297. image.sprite = sprite;
  298. }
  299. }));
  300. }
  301. /// <summary>
  302. /// 获取图片
  303. /// </summary>
  304. /// <param name="url">图片地址</param>
  305. /// <param name="image">图片类型</param>
  306. public void GetImage(DownloadData data, RawImage image)
  307. {
  308. if (string.IsNullOrEmpty(data.downloadPath))
  309. {
  310. image.texture = null;
  311. return;
  312. }
  313. StartCoroutine(LoadImage(data, (tex) =>
  314. {
  315. if (image == null)
  316. {
  317. return;
  318. }
  319. image.texture = tex;
  320. }));
  321. }
  322. /// <summary>
  323. /// 请求服务器地址上的音效
  324. /// </summary>
  325. /// <param name="url">没有音效地址</param>
  326. /// <param name="actionResult">请求发起后处理回调结果的委托,处理请求结果的AudioClip</param>
  327. /// <param name="audioType">音效类型</param>
  328. /// <returns></returns>
  329. public void GetAudioClip(string url, Action<AudioClip> actionResult, AudioType audioType = AudioType.WAV)
  330. {
  331. StartCoroutine(DownloadAudioClip(url, actionResult, audioType));
  332. }
  333. /// <summary>
  334. /// 请求AssetBundle
  335. /// </summary>
  336. /// <param name="url">AssetBundle地址</param>
  337. /// <param name="actionResult">请求发起后处理回调结果的委托,处理请求结果的AssetBundle</param>
  338. /// <returns></returns>
  339. public void GetAssetBundle(DownloadData data, Action<AssetBundle> actionResult = null)
  340. {
  341. StartCoroutine(_GetAssetBundle(data, actionResult));
  342. }
  343. /// <summary>
  344. /// 下载文件
  345. /// </summary>
  346. /// <param name="url">请求地址</param>
  347. /// <param name="filePath">储存文件的路径,路径需包含文件名</param>
  348. /// <param name="actionResult">请求发起后处理回调结果的委托,处理请求对象</param>
  349. /// <returns></returns>
  350. public void DownloadFile(DownloadData data, Action<UnityWebRequest> actionResult = null)
  351. {
  352. StartCoroutine(_DownloadFile(data, actionResult));
  353. }
  354. #endregion
  355. #region 文件
  356. /// <summary>
  357. /// 下载文件
  358. /// </summary>
  359. /// <param name="url">请求地址</param>
  360. /// <param name="filePath">储存文件的路径</param>
  361. /// <param name="actionResult">请求发起后处理回调结果的委托,处理请求对象</param>
  362. /// <returns></returns>
  363. IEnumerator _DownloadFile(DownloadData data, Action<UnityWebRequest> actionResult = null)
  364. {
  365. string url = HttpTool.Instance.BaseUrl + "/file/download";
  366. FileDown file = new FileDown();
  367. if (string.IsNullOrWhiteSpace(data.downloadPath))
  368. {
  369. m_Downloading.Remove(data);
  370. m_FiledDownload.Add(data);
  371. yield break;
  372. }
  373. file.url = data.downloadPath;
  374. string jsonString = JsonConvert.SerializeObject(file);
  375. byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
  376. if (File.Exists(data.localSavePath))
  377. {
  378. m_Downloading.Remove(data);
  379. m_Downloaded.Add(data);
  380. AddLocaData(data);
  381. //Debug.Log(data.downloadPath + "---------------------------------");
  382. yield break;
  383. }
  384. Debug.LogFormat("{0}:{1}", "文件下载路径为", url);
  385. UnityWebRequest uwr = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST);
  386. uwr.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
  387. uwr.downloadHandler = new DownloadHandlerFile(data.localSavePath);
  388. uwr.SetRequestHeader("authorization", HttpTool.Instance.Token);
  389. foreach (var v in HttpTool.Instance.RequestHeader)
  390. {
  391. uwr.SetRequestHeader(v.Key, v.Value);
  392. }
  393. yield return uwr.SendWebRequest();
  394. while (!uwr.isDone)
  395. {
  396. Debug.Log(uwr.downloadProgress);
  397. }
  398. m_Downloading.Remove(data);
  399. //Debug.Log(data.downloadPath + "---------------------------------");
  400. if (uwr.isNetworkError || uwr.isHttpError)
  401. {
  402. Debug.LogErrorFormat("{0}:{1}", "当前下载发生错误", uwr.error);
  403. m_FiledDownload.Add(data);
  404. }
  405. else
  406. {
  407. AddLocaData(data);
  408. m_Downloaded.Add(data);
  409. }
  410. if (actionResult != null)
  411. {
  412. actionResult(uwr);
  413. }
  414. uwr.Abort();
  415. uwr.Dispose();
  416. }
  417. #endregion
  418. #region 图片下载
  419. public void LoadMap(DownloadData data, Image image, Action<Texture2D> loadEnd)
  420. {
  421. StartCoroutine(LoadImage(data, loadEnd));
  422. }
  423. /// <summary>
  424. /// 加载图片
  425. /// </summary>
  426. /// <param name="url"></param>
  427. /// <param name="loadEnd"></param>
  428. /// <returns></returns>
  429. private IEnumerator LoadImage(DownloadData data, Action<Texture2D> loadEnd)
  430. {
  431. Texture2D texture = null;
  432. //先从内存加载
  433. if (m_ImageDic.TryGetValue(data.downloadPath, out texture))
  434. {
  435. Debug.Log("从内存获取");
  436. //Debug.Log(data.downloadPath + "---------------------------------");
  437. m_Downloading.Remove(data);
  438. m_Downloaded.Add(data);
  439. AddLocaData(data);
  440. loadEnd.Invoke(texture);
  441. yield break;
  442. }
  443. //Debug.Log("下载路径为" + filePath);
  444. //从本地加载
  445. bool hasLoad = false;
  446. if (File.Exists(data.localSavePath))
  447. yield return DownloadTexture(data, (state, localTexture) =>
  448. {
  449. Debug.Log("从本地获取 " + data.localSavePath);
  450. hasLoad = state;
  451. if (state)
  452. {
  453. loadEnd.Invoke(localTexture);
  454. if (!m_ImageDic.ContainsKey(data.downloadPath))
  455. {
  456. m_ImageDic.Add(data.downloadPath, localTexture);
  457. }
  458. //Debug.Log(data.downloadPath + "---------------------------------");
  459. m_Downloading.Remove(data);
  460. m_Downloaded.Add(data);
  461. AddLocaData(data);
  462. }
  463. }, true);
  464. if (hasLoad) yield break; //loaded
  465. //下载
  466. yield return DownloadTexture(data, (state, downloadTexture) =>
  467. {
  468. hasLoad = state;
  469. if (state)
  470. {
  471. Debug.Log("网络下载");
  472. loadEnd.Invoke(downloadTexture);
  473. if (!m_ImageDic.ContainsKey(data.downloadPath))
  474. m_ImageDic.Add(data.downloadPath, downloadTexture);
  475. Save2LocalPath(data.localSavePath, downloadTexture);
  476. AddLocaData(data);
  477. m_Downloaded.Add(data);
  478. }
  479. else
  480. {
  481. m_FiledDownload.Add(data);
  482. }
  483. m_Downloading.Remove(data);
  484. //Debug.Log(data.downloadPath + "---------------------------------");
  485. }, false);
  486. }
  487. /// <summary>
  488. /// 下载图片
  489. /// </summary>
  490. /// <param name="url"></param>
  491. /// <param name="downloadEnd">下载结果</param>
  492. /// <param name="isLoca">判断是从网络下载还是从本地加载</param>
  493. /// <returns></returns>
  494. private IEnumerator DownloadTexture(DownloadData data, Action<bool, Texture2D> downloadEnd, bool isLoca)
  495. {
  496. string realUrl = isLoca ? data.localSavePath : HttpTool.Instance.BaseUrl + data.downloadPath;
  497. //Debug.Log("图片下载地址为" + realUrl);
  498. //if (isLoca)
  499. //{
  500. //string realUrl = data.localSavePath;
  501. if (!isLoca && File.Exists(data.localSavePath))
  502. {
  503. File.Delete(data.localSavePath);
  504. }
  505. if (isLoca)
  506. {
  507. #if UNITY_EDITOR
  508. realUrl = data.localSavePath;
  509. #elif UNITY_ANDROID
  510. realUrl = "file://" + data.localSavePath;
  511. #endif
  512. }
  513. using (UnityWebRequest request = new UnityWebRequest(realUrl))
  514. {
  515. DownloadHandlerTexture downloadHandlerTexture = new DownloadHandlerTexture(true);
  516. request.downloadHandler = downloadHandlerTexture;
  517. yield return request.SendWebRequest();
  518. if (string.IsNullOrEmpty(request.error))
  519. {
  520. Texture2D localTexture = downloadHandlerTexture.texture;
  521. downloadEnd.Invoke(true, localTexture);
  522. Resources.UnloadUnusedAssets();
  523. }
  524. else
  525. {
  526. downloadEnd.Invoke(false, null);
  527. if (File.Exists(data.localSavePath))
  528. {
  529. File.Delete(data.localSavePath);
  530. }
  531. Debug.LogError(request.error);
  532. Debug.LogError(isLoca);
  533. Debug.LogError(realUrl);
  534. Debug.LogError(data.localSavePath);
  535. Debug.LogError(data.downloadPath);
  536. Debug.LogError("图片下载失败");
  537. }
  538. request.Abort();
  539. request.downloadHandler.Dispose();
  540. request.Dispose();
  541. }
  542. //}
  543. //else
  544. //{
  545. // string realUrl = HttpTool.Instance.BaseUrl + "/file/download";
  546. // FileDown file = new FileDown();
  547. // file.url = data.downloadPath;
  548. // string jsonString = JsonMapper.ToJson(file);
  549. // byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
  550. // using (UnityWebRequest request = new UnityWebRequest(realUrl, "POST"))
  551. // {
  552. // request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
  553. // DownloadHandlerTexture downloadHandlerTexture = new DownloadHandlerTexture(true);
  554. // request.downloadHandler = downloadHandlerTexture;
  555. // request.SetRequestHeader("authorization", HttpTool.Instance.Token);
  556. // foreach (var v in HttpTool.Instance.RequestHeader)
  557. // {
  558. // request.SetRequestHeader(v.Key, v.Value);
  559. // }
  560. // yield return request.SendWebRequest();
  561. // if (string.IsNullOrEmpty(request.error))
  562. // {
  563. // Texture2D localTexture = downloadHandlerTexture.texture;
  564. // downloadEnd.Invoke(true, localTexture);
  565. // }
  566. // else
  567. // {
  568. // downloadEnd.Invoke(false, null);
  569. // if (File.Exists(data.localSavePath))
  570. // {
  571. // File.Delete(data.localSavePath);
  572. // }
  573. // Debug.Log(request.error);
  574. // Debug.Log(data.downloadPath);
  575. // Debug.LogError("图片下载失败");
  576. // }
  577. // request.Abort();
  578. // request.Dispose();
  579. // }
  580. //}
  581. }
  582. public void GetMapImage(DownloadData data, Image image, Action<bool, Texture2D> loadEnd)
  583. {
  584. StartCoroutine(GetMapImage(data, loadEnd));
  585. }
  586. IEnumerator GetMapImage(DownloadData data, Action<bool, Texture2D> downloadEnd)
  587. {
  588. string realUrl = HttpTool.Instance.BaseUrl + "/file/download";
  589. FileDown file = new FileDown();
  590. file.url = data.downloadPath;
  591. string jsonString = JsonConvert.SerializeObject(file);
  592. byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
  593. using (UnityWebRequest request = new UnityWebRequest(realUrl, "POST"))
  594. {
  595. request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
  596. DownloadHandlerTexture downloadHandlerTexture = new DownloadHandlerTexture(true);
  597. request.downloadHandler = downloadHandlerTexture;
  598. request.SetRequestHeader("authorization", HttpTool.Instance.Token);
  599. foreach (var v in HttpTool.Instance.RequestHeader)
  600. {
  601. request.SetRequestHeader(v.Key, v.Value);
  602. }
  603. yield return request.SendWebRequest();
  604. if (string.IsNullOrEmpty(request.error))
  605. {
  606. Texture2D localTexture = downloadHandlerTexture.texture;
  607. downloadEnd.Invoke(true, localTexture);
  608. Resources.UnloadUnusedAssets();
  609. }
  610. else
  611. {
  612. downloadEnd.Invoke(false, null);
  613. if (File.Exists(data.localSavePath))
  614. {
  615. File.Delete(data.localSavePath);
  616. }
  617. Debug.LogError(request.error);
  618. Debug.LogError(data.downloadPath);
  619. Debug.LogError("小地图下载失败");
  620. }
  621. request.Abort();
  622. request.downloadHandler.Dispose();
  623. request.Dispose();
  624. }
  625. }
  626. /// <summary>
  627. /// 保存图片
  628. /// </summary>
  629. /// <param name="url"></param>
  630. /// <param name="texture"></param>
  631. private void Save2LocalPath(string path, Texture2D texture)
  632. {
  633. byte[] bytes = texture.EncodeToPNG();
  634. //string savePath = GetLocalPath();
  635. //string filename = Path.GetFileName(url);
  636. if (!Directory.Exists(path))
  637. {
  638. DirectoryInfo pathInfo = new DirectoryInfo(path);
  639. pathInfo.Parent.Create();
  640. }
  641. if (File.Exists(path))
  642. {
  643. File.Delete(path);
  644. }
  645. try
  646. {
  647. File.WriteAllBytes(path, bytes);
  648. }
  649. catch (Exception ex)
  650. {
  651. Debug.LogError(ex.ToString());
  652. }
  653. }
  654. /// <summary>
  655. /// 获取图片保存路径
  656. /// 是否加入用户/场景目录
  657. /// </summary>
  658. /// <returns></returns>
  659. private string GetLocalPath()
  660. {
  661. string savePath = LocaDataPath + "/" + DataManager.Instance.CurrentScene.id.ToString() + "/pics/";
  662. if (!Directory.Exists(savePath))
  663. {
  664. Directory.CreateDirectory(savePath);
  665. }
  666. return savePath;
  667. }
  668. #endregion
  669. #region 音效
  670. /// <summary>
  671. /// 请求服务器地址上的音效
  672. /// </summary>
  673. /// <param name="url">音效地址</param>
  674. /// <param name="actionResult">请求发起后处理回调结果的委托,处理请求结果的AudioClip</param>
  675. /// <param name="audioType">音效类型</param>
  676. /// <returns></returns>
  677. IEnumerator DownloadAudioClip(string url, Action<AudioClip> actionResult, AudioType audioType = AudioType.WAV)
  678. {
  679. using (var uwr = UnityWebRequestMultimedia.GetAudioClip(url, audioType))
  680. {
  681. yield return uwr.SendWebRequest();
  682. if (!(uwr.isNetworkError || uwr.isHttpError))
  683. {
  684. if (actionResult != null)
  685. {
  686. actionResult(DownloadHandlerAudioClip.GetContent(uwr));
  687. }
  688. }
  689. }
  690. }
  691. #endregion
  692. #region AssetBundle
  693. /// <summary>
  694. /// 请求AssetBundle
  695. /// </summary>
  696. /// <param name="url">AssetBundle地址 </param>
  697. /// <param name="actionResult">请求发起后处理回调结果的委托,处理请求结果的AssetBundle</param>
  698. /// <returns></returns>
  699. IEnumerator _GetAssetBundle(DownloadData data, Action<AssetBundle> actionResult = null)
  700. {
  701. if (string.IsNullOrWhiteSpace(data.downloadPath))
  702. {
  703. m_Downloading.Remove(data);
  704. m_FiledDownload.Add(data);
  705. yield break;
  706. }
  707. else
  708. {
  709. if (m_AbObjs.ContainsKey(Util.MD5Encrypt(data.downloadPath)))
  710. {
  711. m_Downloading.Remove(data);
  712. m_Downloaded.Add(data);
  713. //Debug.Log(data.downloadPath + "---------------------------------");
  714. yield break;
  715. }
  716. string baseUrl = HttpTool.Instance.BaseUrl + data.downloadPath;
  717. //Debug.Log(baseUrl + "ABABABABABAB");
  718. AssetBundle ab = null;
  719. UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(baseUrl);
  720. request.SetRequestHeader("authorization", HttpTool.Instance.Token);
  721. yield return request.SendWebRequest();
  722. if (request.isNetworkError || request.isHttpError)
  723. {
  724. m_Downloading.Remove(data);
  725. m_FiledDownload.Add(data);
  726. Debug.LogError(request.error);
  727. }
  728. else
  729. {
  730. ab = DownloadHandlerAssetBundle.GetContent(request);
  731. if (ab == null)
  732. {
  733. request.Dispose();
  734. yield break;
  735. }
  736. AssetBundleRequest abrequest = ab.LoadAssetAsync<GameObject>(data.name);
  737. yield return abrequest;
  738. GameObject obj = abrequest.asset as GameObject;
  739. var @object = Instantiate(obj);
  740. @object.SetActive(false);
  741. m_AbObjs.Add(Util.MD5Encrypt(data.downloadPath), @object);
  742. m_Downloading.Remove(data);
  743. m_Downloaded.Add(data);
  744. AddLocaData(data);
  745. ab.Unload(false);
  746. }
  747. request.Abort();
  748. request.Dispose();
  749. }
  750. }
  751. #endregion
  752. private void AddLocaData(DownloadData data)
  753. {
  754. if (m_LocaData.ContainsKey(data.downloadPath))
  755. {
  756. var datas = m_LocaData[data.downloadPath];
  757. bool iscontains = false;
  758. for (int i = 0; i < datas.Count; i++)
  759. {
  760. if (datas[i].localSavePath == data.localSavePath)
  761. {
  762. iscontains = true;
  763. DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  764. var time1 = startTime.AddSeconds((double)datas[i].updateTime);
  765. var time2 = startTime.AddSeconds((double)data.updateTime);
  766. if (DateTime.Compare(time1, time2) >= 0)
  767. {
  768. //Debug.Log(string.Format("{0}>{1}", time1, time2));
  769. return;
  770. }
  771. else
  772. {
  773. datas.RemoveAt(i);
  774. datas.Add(data);
  775. m_LocaData[data.downloadPath] = datas;
  776. return;
  777. }
  778. }
  779. }
  780. if (!iscontains)
  781. {
  782. datas.Add(data);
  783. m_LocaData[data.downloadPath] = datas;
  784. }
  785. }
  786. else
  787. {
  788. List<DownloadData> datas = new List<DownloadData>();
  789. datas.Add(data);
  790. m_LocaData.Add(data.downloadPath, datas);
  791. }
  792. }
  793. private void OnApplicationQuit()
  794. {
  795. Debug.Log("退出程序");
  796. }
  797. public GameObject GetAbObj(string DownloadPath)
  798. {
  799. if (m_AbObjs.ContainsKey(DownloadPath))
  800. {
  801. return m_AbObjs[DownloadPath];
  802. }
  803. else
  804. {
  805. return null;
  806. }
  807. }
  808. }
  809. public class FileDown
  810. {
  811. public string url { get; set; }
  812. }