DownloadManager.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  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.Add(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. if(tex)
  295. {
  296. Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
  297. if (image != null)
  298. {
  299. image.sprite = sprite;
  300. image.transform.localScale = new Vector3(1, (float)tex.height / (float)tex.width, 1);
  301. }
  302. }
  303. }));
  304. }
  305. /// <summary>
  306. /// 获取图片
  307. /// </summary>
  308. /// <param name="url">图片地址</param>
  309. /// <param name="image">图片类型</param>
  310. public void GetImage(DownloadData data, RawImage image)
  311. {
  312. if (string.IsNullOrEmpty(data.downloadPath))
  313. {
  314. image.texture = null;
  315. return;
  316. }
  317. StartCoroutine(LoadImage(data, (tex) =>
  318. {
  319. if (image == null)
  320. {
  321. return;
  322. }
  323. image.texture = tex;
  324. }));
  325. }
  326. /// <summary>
  327. /// 请求服务器地址上的音效
  328. /// </summary>
  329. /// <param name="url">没有音效地址</param>
  330. /// <param name="actionResult">请求发起后处理回调结果的委托,处理请求结果的AudioClip</param>
  331. /// <param name="audioType">音效类型</param>
  332. /// <returns></returns>
  333. public void GetAudioClip(string url, Action<AudioClip> actionResult, AudioType audioType = AudioType.WAV)
  334. {
  335. StartCoroutine(DownloadAudioClip(url, actionResult, audioType));
  336. }
  337. /// <summary>
  338. /// 请求AssetBundle
  339. /// </summary>
  340. /// <param name="url">AssetBundle地址</param>
  341. /// <param name="actionResult">请求发起后处理回调结果的委托,处理请求结果的AssetBundle</param>
  342. /// <returns></returns>
  343. public void GetAssetBundle(DownloadData data, Action<AssetBundle> actionResult = null)
  344. {
  345. StartCoroutine(_GetAssetBundle(data, actionResult));
  346. }
  347. /// <summary>
  348. /// 下载文件
  349. /// </summary>
  350. /// <param name="url">请求地址</param>
  351. /// <param name="filePath">储存文件的路径,路径需包含文件名</param>
  352. /// <param name="actionResult">请求发起后处理回调结果的委托,处理请求对象</param>
  353. /// <returns></returns>
  354. public void DownloadFile(DownloadData data, Action<UnityWebRequest> actionResult = null)
  355. {
  356. StartCoroutine(_DownloadFile(data, actionResult));
  357. }
  358. #endregion
  359. #region 文件
  360. /// <summary>
  361. /// 下载文件
  362. /// </summary>
  363. /// <param name="url">请求地址</param>
  364. /// <param name="filePath">储存文件的路径</param>
  365. /// <param name="actionResult">请求发起后处理回调结果的委托,处理请求对象</param>
  366. /// <returns></returns>
  367. IEnumerator _DownloadFile(DownloadData data, Action<UnityWebRequest> actionResult = null)
  368. {
  369. string url = HttpAction.baseurl + HttpAction.file_download;
  370. FileDown file = new FileDown();
  371. if (string.IsNullOrWhiteSpace(data.downloadPath))
  372. {
  373. m_Downloading.Remove(data);
  374. m_FiledDownload.Add(data);
  375. yield break;
  376. }
  377. file.url = data.downloadPath;
  378. string jsonString = JsonConvert.SerializeObject(file);
  379. byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
  380. if (File.Exists(data.localSavePath))
  381. {
  382. m_Downloading.Remove(data);
  383. m_Downloaded.Add(data);
  384. AddLocaData(data);
  385. //Debug.Log(data.downloadPath + "---------------------------------");
  386. yield break;
  387. }
  388. Debug.LogFormat("{0}:{1}", "文件下载路径为", url);
  389. UnityWebRequest uwr = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST);
  390. uwr.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
  391. uwr.downloadHandler = new DownloadHandlerFile(data.localSavePath);
  392. uwr.SetRequestHeader("authorization", UserInfo.Instance.Token);
  393. foreach (var v in HttpTool.Instance.RequestHeader)
  394. {
  395. uwr.SetRequestHeader(v.Key, v.Value);
  396. }
  397. yield return uwr.SendWebRequest();
  398. while (!uwr.isDone)
  399. {
  400. Debug.Log(uwr.downloadProgress);
  401. }
  402. m_Downloading.Remove(data);
  403. //Debug.Log(data.downloadPath + "---------------------------------");
  404. if (uwr.isNetworkError || uwr.isHttpError)
  405. {
  406. Debug.LogErrorFormat("{0}:{1}", "当前下载发生错误", uwr.error);
  407. m_FiledDownload.Add(data);
  408. }
  409. else
  410. {
  411. AddLocaData(data);
  412. m_Downloaded.Add(data);
  413. }
  414. if (actionResult != null)
  415. {
  416. actionResult(uwr);
  417. }
  418. uwr.Abort();
  419. uwr.Dispose();
  420. }
  421. #endregion
  422. #region 图片下载
  423. public void LoadMap(DownloadData data, Image image, Action<Texture2D> loadEnd)
  424. {
  425. StartCoroutine(LoadImage(data, loadEnd));
  426. }
  427. /// <summary>
  428. /// 加载图片
  429. /// </summary>
  430. /// <param name="url"></param>
  431. /// <param name="loadEnd"></param>
  432. /// <returns></returns>
  433. private IEnumerator LoadImage(DownloadData data, Action<Texture2D> loadEnd)
  434. {
  435. Texture2D texture = null;
  436. //先从内存加载
  437. if (m_ImageDic.TryGetValue(data.downloadPath, out texture))
  438. {
  439. Debug.Log("从内存获取");
  440. //Debug.Log(data.downloadPath + "---------------------------------");
  441. m_Downloading.Remove(data);
  442. m_Downloaded.Add(data);
  443. AddLocaData(data);
  444. loadEnd.Invoke(texture);
  445. yield break;
  446. }
  447. //Debug.Log("下载路径为" + filePath);
  448. //从本地加载
  449. bool hasLoad = false;
  450. if (File.Exists(data.localSavePath))
  451. yield return DownloadTexture(data, (state, localTexture) =>
  452. {
  453. Debug.Log("从本地获取 " + data.localSavePath);
  454. hasLoad = state;
  455. if (state)
  456. {
  457. loadEnd.Invoke(localTexture);
  458. if (!m_ImageDic.ContainsKey(data.downloadPath))
  459. {
  460. m_ImageDic.Add(data.downloadPath, localTexture);
  461. }
  462. //Debug.Log(data.downloadPath + "---------------------------------");
  463. m_Downloading.Remove(data);
  464. m_Downloaded.Add(data);
  465. AddLocaData(data);
  466. }
  467. }, true);
  468. if (hasLoad) yield break; //loaded
  469. //下载
  470. yield return DownloadTexture(data, (state, downloadTexture) =>
  471. {
  472. hasLoad = state;
  473. if (state)
  474. {
  475. Debug.Log("网络下载");
  476. loadEnd.Invoke(downloadTexture);
  477. if (!m_ImageDic.ContainsKey(data.downloadPath))
  478. m_ImageDic.Add(data.downloadPath, downloadTexture);
  479. Save2LocalPath(data.localSavePath, downloadTexture);
  480. AddLocaData(data);
  481. m_Downloaded.Add(data);
  482. }
  483. else
  484. {
  485. m_FiledDownload.Add(data);
  486. }
  487. m_Downloading.Remove(data);
  488. //Debug.Log(data.downloadPath + "---------------------------------");
  489. }, false);
  490. }
  491. /// <summary>
  492. /// 下载图片
  493. /// </summary>
  494. /// <param name="url"></param>
  495. /// <param name="downloadEnd">下载结果</param>
  496. /// <param name="isLoca">判断是从网络下载还是从本地加载</param>
  497. /// <returns></returns>
  498. private IEnumerator DownloadTexture(DownloadData data, Action<bool, Texture2D> downloadEnd, bool isLoca)
  499. {
  500. string realUrl = isLoca ? data.localSavePath : HttpAction.baseurl + data.downloadPath;
  501. //Debug.Log("图片下载地址为" + realUrl);
  502. //if (isLoca)
  503. //{
  504. //string realUrl = data.localSavePath;
  505. if (!isLoca && File.Exists(data.localSavePath))
  506. {
  507. File.Delete(data.localSavePath);
  508. }
  509. if (isLoca)
  510. {
  511. #if UNITY_EDITOR
  512. realUrl = data.localSavePath;
  513. #elif UNITY_ANDROID
  514. realUrl = "file://" + data.localSavePath;
  515. #endif
  516. }
  517. using (UnityWebRequest request = new UnityWebRequest(realUrl))
  518. {
  519. DownloadHandlerTexture downloadHandlerTexture = new DownloadHandlerTexture(true);
  520. request.downloadHandler = downloadHandlerTexture;
  521. yield return request.SendWebRequest();
  522. if (string.IsNullOrEmpty(request.error))
  523. {
  524. Texture2D localTexture = downloadHandlerTexture.texture;
  525. downloadEnd.Invoke(true, localTexture);
  526. Resources.UnloadUnusedAssets();
  527. }
  528. else
  529. {
  530. downloadEnd.Invoke(false, null);
  531. if (File.Exists(data.localSavePath))
  532. {
  533. File.Delete(data.localSavePath);
  534. }
  535. Debug.LogError(request.error);
  536. Debug.LogError(isLoca);
  537. Debug.LogError(realUrl);
  538. Debug.LogError(data.localSavePath);
  539. Debug.LogError(data.downloadPath);
  540. Debug.LogError("图片下载失败");
  541. }
  542. request.Abort();
  543. request.downloadHandler.Dispose();
  544. request.Dispose();
  545. }
  546. //}
  547. //else
  548. //{
  549. // string realUrl = HttpTool.Instance.BaseUrl + "/file/download";
  550. // FileDown file = new FileDown();
  551. // file.url = data.downloadPath;
  552. // string jsonString = JsonMapper.ToJson(file);
  553. // byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
  554. // using (UnityWebRequest request = new UnityWebRequest(realUrl, "POST"))
  555. // {
  556. // request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
  557. // DownloadHandlerTexture downloadHandlerTexture = new DownloadHandlerTexture(true);
  558. // request.downloadHandler = downloadHandlerTexture;
  559. // request.SetRequestHeader("authorization", HttpTool.Instance.Token);
  560. // foreach (var v in HttpTool.Instance.RequestHeader)
  561. // {
  562. // request.SetRequestHeader(v.Key, v.Value);
  563. // }
  564. // yield return request.SendWebRequest();
  565. // if (string.IsNullOrEmpty(request.error))
  566. // {
  567. // Texture2D localTexture = downloadHandlerTexture.texture;
  568. // downloadEnd.Invoke(true, localTexture);
  569. // }
  570. // else
  571. // {
  572. // downloadEnd.Invoke(false, null);
  573. // if (File.Exists(data.localSavePath))
  574. // {
  575. // File.Delete(data.localSavePath);
  576. // }
  577. // Debug.Log(request.error);
  578. // Debug.Log(data.downloadPath);
  579. // Debug.LogError("图片下载失败");
  580. // }
  581. // request.Abort();
  582. // request.Dispose();
  583. // }
  584. //}
  585. }
  586. public void GetMapImage(DownloadData data, Image image, Action<bool, Texture2D> loadEnd)
  587. {
  588. StartCoroutine(GetMapImage(data, loadEnd));
  589. }
  590. IEnumerator GetMapImage(DownloadData data, Action<bool, Texture2D> downloadEnd)
  591. {
  592. string realUrl = HttpAction.baseurl + HttpAction.file_download;
  593. FileDown file = new FileDown();
  594. file.url = data.downloadPath;
  595. string jsonString = JsonConvert.SerializeObject(file);
  596. byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
  597. using (UnityWebRequest request = new UnityWebRequest(realUrl, "POST"))
  598. {
  599. request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
  600. DownloadHandlerTexture downloadHandlerTexture = new DownloadHandlerTexture(true);
  601. request.downloadHandler = downloadHandlerTexture;
  602. request.SetRequestHeader("authorization", UserInfo.Instance.Token);
  603. foreach (var v in HttpTool.Instance.RequestHeader)
  604. {
  605. request.SetRequestHeader(v.Key, v.Value);
  606. }
  607. yield return request.SendWebRequest();
  608. if (string.IsNullOrEmpty(request.error))
  609. {
  610. Texture2D localTexture = downloadHandlerTexture.texture;
  611. downloadEnd.Invoke(true, localTexture);
  612. Resources.UnloadUnusedAssets();
  613. }
  614. else
  615. {
  616. downloadEnd.Invoke(false, null);
  617. if (File.Exists(data.localSavePath))
  618. {
  619. File.Delete(data.localSavePath);
  620. }
  621. Debug.LogError(request.error);
  622. Debug.LogError(data.downloadPath);
  623. Debug.LogError("小地图下载失败");
  624. }
  625. request.Abort();
  626. request.downloadHandler.Dispose();
  627. request.Dispose();
  628. }
  629. }
  630. /// <summary>
  631. /// 保存图片
  632. /// </summary>
  633. /// <param name="url"></param>
  634. /// <param name="texture"></param>
  635. private void Save2LocalPath(string path, Texture2D texture)
  636. {
  637. byte[] bytes = texture.EncodeToPNG();
  638. //string savePath = GetLocalPath();
  639. //string filename = Path.GetFileName(url);
  640. if (!Directory.Exists(path))
  641. {
  642. DirectoryInfo pathInfo = new DirectoryInfo(path);
  643. pathInfo.Parent.Create();
  644. }
  645. if (File.Exists(path))
  646. {
  647. File.Delete(path);
  648. }
  649. try
  650. {
  651. File.WriteAllBytes(path, bytes);
  652. }
  653. catch (Exception ex)
  654. {
  655. Debug.LogError(ex.ToString());
  656. }
  657. }
  658. /// <summary>
  659. /// 获取图片保存路径
  660. /// 是否加入用户/场景目录
  661. /// </summary>
  662. /// <returns></returns>
  663. private string GetLocalPath()
  664. {
  665. string savePath = LocaDataPath + "/" + DataManager.Instance.CurrentScene.id.ToString() + "/pics/";
  666. if (!Directory.Exists(savePath))
  667. {
  668. Directory.CreateDirectory(savePath);
  669. }
  670. return savePath;
  671. }
  672. #endregion
  673. #region 音效
  674. /// <summary>
  675. /// 请求服务器地址上的音效
  676. /// </summary>
  677. /// <param name="url">音效地址</param>
  678. /// <param name="actionResult">请求发起后处理回调结果的委托,处理请求结果的AudioClip</param>
  679. /// <param name="audioType">音效类型</param>
  680. /// <returns></returns>
  681. IEnumerator DownloadAudioClip(string url, Action<AudioClip> actionResult, AudioType audioType = AudioType.WAV)
  682. {
  683. using (var uwr = UnityWebRequestMultimedia.GetAudioClip(url, audioType))
  684. {
  685. yield return uwr.SendWebRequest();
  686. if (!(uwr.isNetworkError || uwr.isHttpError))
  687. {
  688. if (actionResult != null)
  689. {
  690. actionResult(DownloadHandlerAudioClip.GetContent(uwr));
  691. }
  692. }
  693. }
  694. }
  695. #endregion
  696. #region AssetBundle
  697. /// <summary>
  698. /// 请求AssetBundle
  699. /// </summary>
  700. /// <param name="url">AssetBundle地址 </param>
  701. /// <param name="actionResult">请求发起后处理回调结果的委托,处理请求结果的AssetBundle</param>
  702. /// <returns></returns>
  703. IEnumerator _GetAssetBundle(DownloadData data, Action<AssetBundle> actionResult = null)
  704. {
  705. if (string.IsNullOrWhiteSpace(data.downloadPath))
  706. {
  707. m_Downloading.Remove(data);
  708. m_FiledDownload.Add(data);
  709. yield break;
  710. }
  711. else
  712. {
  713. if (m_AbObjs.ContainsKey(Util.MD5Encrypt(data.downloadPath)))
  714. {
  715. m_Downloading.Remove(data);
  716. m_Downloaded.Add(data);
  717. //Debug.Log(data.downloadPath + "---------------------------------");
  718. yield break;
  719. }
  720. string baseUrl = HttpAction.baseurl + data.downloadPath;
  721. //Debug.Log(baseUrl + "ABABABABABAB");
  722. AssetBundle ab = null;
  723. UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(baseUrl);
  724. request.SetRequestHeader("authorization", UserInfo.Instance.Token);
  725. yield return request.SendWebRequest();
  726. if (request.isNetworkError || request.isHttpError)
  727. {
  728. m_Downloading.Remove(data);
  729. m_FiledDownload.Add(data);
  730. Debug.LogError(request.error);
  731. }
  732. else
  733. {
  734. ab = DownloadHandlerAssetBundle.GetContent(request);
  735. if (ab == null)
  736. {
  737. request.Dispose();
  738. yield break;
  739. }
  740. AssetBundleRequest abrequest = ab.LoadAssetAsync<GameObject>(data.name);
  741. yield return abrequest;
  742. GameObject obj = abrequest.asset as GameObject;
  743. var @object = Instantiate(obj);
  744. @object.SetActive(false);
  745. m_AbObjs.Add(Util.MD5Encrypt(data.downloadPath), @object);
  746. m_Downloading.Remove(data);
  747. m_Downloaded.Add(data);
  748. AddLocaData(data);
  749. ab.Unload(false);
  750. }
  751. request.Abort();
  752. request.Dispose();
  753. }
  754. }
  755. #endregion
  756. private void AddLocaData(DownloadData data)
  757. {
  758. if (m_LocaData.ContainsKey(data.downloadPath))
  759. {
  760. var datas = m_LocaData[data.downloadPath];
  761. bool iscontains = false;
  762. for (int i = 0; i < datas.Count; i++)
  763. {
  764. if (datas[i].localSavePath == data.localSavePath)
  765. {
  766. iscontains = true;
  767. DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  768. var time1 = startTime.AddSeconds((double)datas[i].updateTime);
  769. var time2 = startTime.AddSeconds((double)data.updateTime);
  770. if (DateTime.Compare(time1, time2) >= 0)
  771. {
  772. //Debug.Log(string.Format("{0}>{1}", time1, time2));
  773. return;
  774. }
  775. else
  776. {
  777. datas.RemoveAt(i);
  778. datas.Add(data);
  779. m_LocaData[data.downloadPath] = datas;
  780. return;
  781. }
  782. }
  783. }
  784. if (!iscontains)
  785. {
  786. datas.Add(data);
  787. m_LocaData[data.downloadPath] = datas;
  788. }
  789. }
  790. else
  791. {
  792. List<DownloadData> datas = new List<DownloadData>();
  793. datas.Add(data);
  794. m_LocaData.Add(data.downloadPath, datas);
  795. }
  796. }
  797. private void OnApplicationQuit()
  798. {
  799. Debug.Log("退出程序");
  800. }
  801. public GameObject GetAbObj(string DownloadPath)
  802. {
  803. if (m_AbObjs.ContainsKey(DownloadPath))
  804. {
  805. return m_AbObjs[DownloadPath];
  806. }
  807. else
  808. {
  809. return null;
  810. }
  811. }
  812. }
  813. public class FileDown
  814. {
  815. public string url { get; set; }
  816. }