UnityWebRequestRenewalAsync.cs 10 KB

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