UnityWebRequestRenewalAsync.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using UnityEngine;
  5. using UnityEngine.Networking;
  6. namespace ET
  7. {
  8. public class UnityWebRequestRenewalUpdateSystem: UpdateSystem<UnityWebRequestRenewalAsync>
  9. {
  10. public override void Update(UnityWebRequestRenewalAsync self)
  11. {
  12. self.Update();
  13. }
  14. }
  15. /// <summary>
  16. /// 断点续传实现
  17. /// </summary>
  18. public class UnityWebRequestRenewalAsync: Entity
  19. {
  20. public class AcceptAllCertificate: CertificateHandler
  21. {
  22. protected override bool ValidateCertificate(byte[] certificateData)
  23. {
  24. return true;
  25. }
  26. }
  27. public static AcceptAllCertificate certificateHandler = new AcceptAllCertificate();
  28. public UnityWebRequest headRequest;
  29. public bool isCancel;
  30. public ETTaskCompletionSource tcs;
  31. //请求资源类型
  32. private class RequestType
  33. {
  34. public const int None = 0; //未开始
  35. public const int Head = 1; //文件头
  36. public const int Data = 2; //文件数据
  37. }
  38. //当前请求资源类型
  39. private int requestType = RequestType.None;
  40. //多任务同时请求
  41. private readonly List<UnityWebRequest> dataRequests = new List<UnityWebRequest>();
  42. //当前下载的文件流 边下边存文件流
  43. private FileStream fileStream;
  44. //资源地址
  45. private string Url;
  46. //每个下载包长度
  47. private int packageLength = 1000000; //1M
  48. //同时开启任务最大个数
  49. private int maxCount = 20;
  50. //已经写入文件的大小
  51. private long byteWrites;
  52. //文件总大小
  53. private long totalBytes;
  54. //当前请求的位置
  55. private long downloadIndex;
  56. //文件下载是否出错
  57. private string dataError
  58. {
  59. get
  60. {
  61. foreach (UnityWebRequest webRequest in this.dataRequests)
  62. if (!string.IsNullOrEmpty(webRequest.error))
  63. return webRequest.error;
  64. return "";
  65. }
  66. }
  67. //批量开启任务下载
  68. void DownloadPackages()
  69. {
  70. if (dataRequests.Count >= maxCount || this.downloadIndex == totalBytes - 1)
  71. return;
  72. //开启一个下载任务
  73. void DownloadPackage(long start, long end)
  74. {
  75. this.downloadIndex = end;
  76. Log.Debug($"Request Data ({start}~{end}):{Url}");
  77. UnityWebRequest request = UnityWebRequest.Get(Url);
  78. dataRequests.Add(request);
  79. request.certificateHandler = certificateHandler;
  80. request.SetRequestHeader("Range", $"bytes={start}-{end}");
  81. request.SendWebRequest();
  82. }
  83. //开启批量下载
  84. for (int i = dataRequests.Count; i < maxCount; i++)
  85. {
  86. long start = this.byteWrites + i * packageLength;
  87. long end = this.byteWrites + (i + 1) * packageLength - 1;
  88. if (end > this.totalBytes)
  89. end = this.totalBytes - 1;
  90. DownloadPackage(start, end);
  91. if (end == this.totalBytes - 1)
  92. break;
  93. }
  94. }
  95. //一次批量下载完成后写文件
  96. void WritePackages()
  97. {
  98. //写入单个包
  99. void WritePackage(UnityWebRequest webRequest)
  100. {
  101. byte[] buff = webRequest.downloadHandler.data;
  102. if (buff != null && buff.Length > 0)
  103. {
  104. this.fileStream.Write(buff, 0, buff.Length);
  105. this.byteWrites += buff.Length;
  106. }
  107. Log.Debug($"write file Length:{byteWrites}");
  108. }
  109. //从第一个开始顺序写入
  110. while (this.dataRequests.Count > 0 && dataRequests[0].isDone)
  111. {
  112. UnityWebRequest first = dataRequests[0];
  113. dataRequests.RemoveAt(0);
  114. WritePackage(first);
  115. first.Dispose();
  116. }
  117. }
  118. //更新文件体下载
  119. void UpdatePackages()
  120. {
  121. if (this.isCancel)
  122. {
  123. this.tcs.SetException(new Exception($"request data error: {dataError}"));
  124. return;
  125. }
  126. if (!string.IsNullOrEmpty(dataError))
  127. {
  128. this.tcs.SetException(new Exception($"request data error: {dataError}"));
  129. return;
  130. }
  131. this.WritePackages();
  132. if (this.byteWrites == this.totalBytes)
  133. this.tcs.SetResult();
  134. else
  135. this.DownloadPackages();
  136. }
  137. //更新文件头下载
  138. void UpdateHead()
  139. {
  140. if (this.isCancel)
  141. {
  142. this.tcs.SetException(new Exception($"request error: {this.headRequest.error}"));
  143. return;
  144. }
  145. if (!this.headRequest.isDone)
  146. {
  147. return;
  148. }
  149. if (!string.IsNullOrEmpty(this.headRequest.error))
  150. {
  151. this.tcs.SetException(new Exception($"request error: {this.headRequest.error}"));
  152. return;
  153. }
  154. this.tcs.SetResult();
  155. }
  156. //检测是不是同一个文件
  157. bool CheckSameFile(string modifiedTime)
  158. {
  159. string cacheValue = PlayerPrefs.GetString(Url);
  160. string currentValue = this.totalBytes+"|"+modifiedTime;
  161. if (cacheValue == currentValue)
  162. return true;
  163. PlayerPrefs.SetString(Url, currentValue);
  164. PlayerPrefs.Save();
  165. Log.Debug($"断点续传下载一个新的文件:{Url} cacheValue:{cacheValue} currentValue:{currentValue}");
  166. return false;
  167. }
  168. /// <summary>
  169. /// 断点续传入口
  170. /// </summary>
  171. /// <param name="url">文件下载地址</param>
  172. /// <param name="filePath">文件写入路径</param>
  173. /// <param name="packageLength">单个任务包体字节大小</param>
  174. /// <param name="maxCount">同时开启最大任务个数</param>
  175. /// <returns></returns>
  176. public async ETTask DownloadAsync(string url, string filePath, int packageLength = 1000000, int maxCount = 20)
  177. {
  178. try
  179. {
  180. url = url.Replace(" ", "%20");
  181. this.Url = url;
  182. this.packageLength = packageLength;
  183. this.maxCount = maxCount;
  184. Log.Debug("Web Request:" + url);
  185. #region Download File Header
  186. this.requestType = RequestType.Head;
  187. //下载文件头
  188. Log.Debug($"Request Head: {Url}");
  189. this.tcs = new ETTaskCompletionSource();
  190. this.headRequest = UnityWebRequest.Head(Url);
  191. this.headRequest.SendWebRequest();
  192. await this.tcs.Task;
  193. this.totalBytes = long.Parse(this.headRequest.GetResponseHeader("Content-Length"));
  194. string modifiedTime = this.headRequest.GetResponseHeader("Last-Modified");
  195. Log.Debug($"totalBytes: {this.totalBytes}");
  196. this.headRequest?.Dispose();
  197. this.headRequest = null;
  198. #endregion
  199. #region Check Local File
  200. //打开或创建
  201. fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
  202. //获取已下载长度
  203. this.byteWrites = fileStream.Length;
  204. //通过本地缓存的服务器文件修改时间和文件总长度检测服务器是否是同一个文件 不是同一个从头开始写入
  205. if (!CheckSameFile(modifiedTime))
  206. this.byteWrites = 0;
  207. Log.Debug($"byteWrites: {this.byteWrites}");
  208. if (this.byteWrites == this.totalBytes)
  209. {
  210. Log.Debug("已经下载完成2");
  211. return;
  212. }
  213. //设置开始写入位置
  214. fileStream.Seek(this.byteWrites, SeekOrigin.Begin);
  215. #endregion
  216. #region Download File Data
  217. //下载文件数据
  218. requestType = RequestType.Data;
  219. Log.Debug($"Request Data: {Url}");
  220. this.tcs = new ETTaskCompletionSource();
  221. this.DownloadPackages();
  222. await this.tcs.Task;
  223. #endregion
  224. }
  225. catch (Exception e)
  226. {
  227. Log.Error($"下载:{Url} Exception:{e}");
  228. throw;
  229. }
  230. }
  231. //下载进度
  232. public float Progress
  233. {
  234. get
  235. {
  236. if (this.totalBytes == 0)
  237. return 0;
  238. return (float) ((this.byteWrites + ByteDownloaded) / (double) this.totalBytes);
  239. }
  240. }
  241. //当前任务已经下载的长度
  242. public long ByteDownloaded
  243. {
  244. get
  245. {
  246. long length = 0;
  247. foreach (UnityWebRequest dataRequest in this.dataRequests)
  248. length += dataRequest.downloadHandler.data.Length;
  249. return length;
  250. }
  251. }
  252. public void Update()
  253. {
  254. if (this.requestType == RequestType.Head)
  255. this.UpdateHead();
  256. if (this.requestType == RequestType.Data)
  257. this.UpdatePackages();
  258. }
  259. public override void Dispose()
  260. {
  261. if (this.IsDisposed)
  262. {
  263. return;
  264. }
  265. base.Dispose();
  266. headRequest?.Dispose();
  267. headRequest = null;
  268. foreach (UnityWebRequest dataRequest in this.dataRequests)
  269. dataRequest.Dispose();
  270. dataRequests.Clear();
  271. this.fileStream?.Close();
  272. this.fileStream?.Dispose();
  273. this.fileStream = null;
  274. this.isCancel = false;
  275. }
  276. }
  277. }