DownloaderOperation.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. namespace YooAsset
  4. {
  5. public abstract class DownloaderOperation : AsyncOperationBase
  6. {
  7. private enum ESteps
  8. {
  9. None,
  10. Check,
  11. Loading,
  12. Done,
  13. }
  14. private const int MAX_LOADER_COUNT = 64;
  15. public delegate void OnDownloadOver(bool isSucceed);
  16. public delegate void OnDownloadProgress(int totalDownloadCount, int currentDownloadCount, long totalDownloadBytes, long currentDownloadBytes);
  17. public delegate void OnDownloadError(string fileName, string error);
  18. public delegate void OnStartDownloadFile(string fileName, long sizeBytes);
  19. private readonly DownloadManager _downloadMgr;
  20. private readonly string _packageName;
  21. private readonly int _downloadingMaxNumber;
  22. private readonly int _failedTryAgain;
  23. private readonly int _timeout;
  24. private readonly List<BundleInfo> _bundleInfoList;
  25. private readonly List<DownloaderBase> _downloaders = new List<DownloaderBase>(MAX_LOADER_COUNT);
  26. private readonly List<DownloaderBase> _removeList = new List<DownloaderBase>(MAX_LOADER_COUNT);
  27. private readonly List<DownloaderBase> _failedList = new List<DownloaderBase>(MAX_LOADER_COUNT);
  28. // 数据相关
  29. private bool _isPause = false;
  30. private long _lastDownloadBytes = 0;
  31. private int _lastDownloadCount = 0;
  32. private long _cachedDownloadBytes = 0;
  33. private int _cachedDownloadCount = 0;
  34. private ESteps _steps = ESteps.None;
  35. /// <summary>
  36. /// 统计的下载文件总数量
  37. /// </summary>
  38. public int TotalDownloadCount { private set; get; }
  39. /// <summary>
  40. /// 统计的下载文件的总大小
  41. /// </summary>
  42. public long TotalDownloadBytes { private set; get; }
  43. /// <summary>
  44. /// 当前已经完成的下载总数量
  45. /// </summary>
  46. public int CurrentDownloadCount
  47. {
  48. get { return _lastDownloadCount; }
  49. }
  50. /// <summary>
  51. /// 当前已经完成的下载总大小
  52. /// </summary>
  53. public long CurrentDownloadBytes
  54. {
  55. get { return _lastDownloadBytes; }
  56. }
  57. /// <summary>
  58. /// 当下载器结束(无论成功或失败)
  59. /// </summary>
  60. public OnDownloadOver OnDownloadOverCallback { set; get; }
  61. /// <summary>
  62. /// 当下载进度发生变化
  63. /// </summary>
  64. public OnDownloadProgress OnDownloadProgressCallback { set; get; }
  65. /// <summary>
  66. /// 当某个文件下载失败
  67. /// </summary>
  68. public OnDownloadError OnDownloadErrorCallback { set; get; }
  69. /// <summary>
  70. /// 当开始下载某个文件
  71. /// </summary>
  72. public OnStartDownloadFile OnStartDownloadFileCallback { set; get; }
  73. internal DownloaderOperation(DownloadManager downloadMgr, string packageName, List<BundleInfo> downloadList, int downloadingMaxNumber, int failedTryAgain, int timeout)
  74. {
  75. _downloadMgr = downloadMgr;
  76. _packageName = packageName;
  77. _bundleInfoList = downloadList;
  78. _downloadingMaxNumber = UnityEngine.Mathf.Clamp(downloadingMaxNumber, 1, MAX_LOADER_COUNT); ;
  79. _failedTryAgain = failedTryAgain;
  80. _timeout = timeout;
  81. // 设置包裹名称 (fix #210)
  82. SetPackageName(packageName);
  83. // 统计下载信息
  84. CalculatDownloaderInfo();
  85. }
  86. internal override void InternalOnStart()
  87. {
  88. YooLogger.Log($"Begine to download : {TotalDownloadCount} files and {TotalDownloadBytes} bytes");
  89. _steps = ESteps.Check;
  90. }
  91. internal override void InternalOnUpdate()
  92. {
  93. if (_steps == ESteps.None || _steps == ESteps.Done)
  94. return;
  95. if (_steps == ESteps.Check)
  96. {
  97. if (_bundleInfoList == null)
  98. {
  99. _steps = ESteps.Done;
  100. Status = EOperationStatus.Failed;
  101. Error = "Download list is null.";
  102. }
  103. else
  104. {
  105. _steps = ESteps.Loading;
  106. }
  107. }
  108. if (_steps == ESteps.Loading)
  109. {
  110. // 检测下载器结果
  111. _removeList.Clear();
  112. long downloadBytes = _cachedDownloadBytes;
  113. foreach (var downloader in _downloaders)
  114. {
  115. downloadBytes += (long)downloader.DownloadedBytes;
  116. if (downloader.IsDone() == false)
  117. continue;
  118. // 检测是否下载失败
  119. if (downloader.HasError())
  120. {
  121. _removeList.Add(downloader);
  122. _failedList.Add(downloader);
  123. continue;
  124. }
  125. // 下载成功
  126. _removeList.Add(downloader);
  127. _cachedDownloadCount++;
  128. _cachedDownloadBytes += downloader.GetDownloadFileSize();
  129. }
  130. // 移除已经完成的下载器(无论成功或失败)
  131. foreach (var loader in _removeList)
  132. {
  133. _downloaders.Remove(loader);
  134. }
  135. // 如果下载进度发生变化
  136. if (_lastDownloadBytes != downloadBytes || _lastDownloadCount != _cachedDownloadCount)
  137. {
  138. _lastDownloadBytes = downloadBytes;
  139. _lastDownloadCount = _cachedDownloadCount;
  140. Progress = (float)_lastDownloadBytes / TotalDownloadBytes;
  141. OnDownloadProgressCallback?.Invoke(TotalDownloadCount, _lastDownloadCount, TotalDownloadBytes, _lastDownloadBytes);
  142. }
  143. // 动态创建新的下载器到最大数量限制
  144. // 注意:如果期间有下载失败的文件,暂停动态创建下载器
  145. if (_bundleInfoList.Count > 0 && _failedList.Count == 0)
  146. {
  147. if (_isPause)
  148. return;
  149. if (_downloaders.Count < _downloadingMaxNumber)
  150. {
  151. int index = _bundleInfoList.Count - 1;
  152. var bundleInfo = _bundleInfoList[index];
  153. var downloader = bundleInfo.CreateDownloader(_failedTryAgain, _timeout);
  154. downloader.SendRequest();
  155. _downloaders.Add(downloader);
  156. _bundleInfoList.RemoveAt(index);
  157. OnStartDownloadFileCallback?.Invoke(bundleInfo.Bundle.BundleName, bundleInfo.Bundle.FileSize);
  158. }
  159. }
  160. // 下载结算
  161. if (_downloaders.Count == 0)
  162. {
  163. if (_failedList.Count > 0)
  164. {
  165. var failedDownloader = _failedList[0];
  166. string bundleName = failedDownloader.GetDownloadBundleName();
  167. _steps = ESteps.Done;
  168. Status = EOperationStatus.Failed;
  169. Error = $"Failed to download file : {bundleName}";
  170. OnDownloadErrorCallback?.Invoke(bundleName, failedDownloader.GetLastError());
  171. OnDownloadOverCallback?.Invoke(false);
  172. }
  173. else
  174. {
  175. // 结算成功
  176. _steps = ESteps.Done;
  177. Status = EOperationStatus.Succeed;
  178. OnDownloadOverCallback?.Invoke(true);
  179. }
  180. }
  181. }
  182. }
  183. private void CalculatDownloaderInfo()
  184. {
  185. if (_bundleInfoList != null)
  186. {
  187. TotalDownloadBytes = 0;
  188. TotalDownloadCount = _bundleInfoList.Count;
  189. foreach (var packageBundle in _bundleInfoList)
  190. {
  191. TotalDownloadBytes += packageBundle.Bundle.FileSize;
  192. }
  193. }
  194. else
  195. {
  196. TotalDownloadBytes = 0;
  197. TotalDownloadCount = 0;
  198. }
  199. }
  200. /// <summary>
  201. /// 合并其它下载器
  202. /// </summary>
  203. /// <param name="downloader">合并的下载器</param>
  204. public void Combine(DownloaderOperation downloader)
  205. {
  206. if (_packageName != downloader._packageName)
  207. {
  208. YooLogger.Error("The downloaders have different resource packages !");
  209. return;
  210. }
  211. if (Status != EOperationStatus.None)
  212. {
  213. YooLogger.Error("The downloader is running, can not combine with other downloader !");
  214. return;
  215. }
  216. HashSet<string> temper = new HashSet<string>();
  217. foreach (var bundleInfo in _bundleInfoList)
  218. {
  219. if (temper.Contains(bundleInfo.CachedDataFilePath) == false)
  220. {
  221. temper.Add(bundleInfo.CachedDataFilePath);
  222. }
  223. }
  224. // 合并下载列表
  225. foreach (var bundleInfo in downloader._bundleInfoList)
  226. {
  227. if (temper.Contains(bundleInfo.CachedDataFilePath) == false)
  228. {
  229. _bundleInfoList.Add(bundleInfo);
  230. }
  231. }
  232. // 重新统计下载信息
  233. CalculatDownloaderInfo();
  234. }
  235. /// <summary>
  236. /// 开始下载
  237. /// </summary>
  238. public void BeginDownload()
  239. {
  240. if (_steps == ESteps.None)
  241. {
  242. OperationSystem.StartOperation(this);
  243. }
  244. }
  245. /// <summary>
  246. /// 暂停下载
  247. /// </summary>
  248. public void PauseDownload()
  249. {
  250. _isPause = true;
  251. }
  252. /// <summary>
  253. /// 恢复下载
  254. /// </summary>
  255. public void ResumeDownload()
  256. {
  257. _isPause = false;
  258. }
  259. /// <summary>
  260. /// 取消下载
  261. /// </summary>
  262. public void CancelDownload()
  263. {
  264. if (_steps != ESteps.Done)
  265. {
  266. _steps = ESteps.Done;
  267. Status = EOperationStatus.Failed;
  268. Error = "User cancel.";
  269. ReleaseAllDownloader();
  270. }
  271. }
  272. private void ReleaseAllDownloader()
  273. {
  274. foreach (var downloader in _downloaders)
  275. {
  276. downloader.Release();
  277. }
  278. // 注意:停止不再使用的下载器
  279. _downloadMgr.AbortUnusedDownloader();
  280. }
  281. }
  282. public sealed class ResourceDownloaderOperation : DownloaderOperation
  283. {
  284. internal ResourceDownloaderOperation(DownloadManager downloadMgr, string packageName, List<BundleInfo> downloadList, int downloadingMaxNumber, int failedTryAgain, int timeout)
  285. : base(downloadMgr, packageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout)
  286. {
  287. }
  288. /// <summary>
  289. /// 创建空的下载器
  290. /// </summary>
  291. internal static ResourceDownloaderOperation CreateEmptyDownloader(DownloadManager downloadMgr, string packageName, int downloadingMaxNumber, int failedTryAgain, int timeout)
  292. {
  293. List<BundleInfo> downloadList = new List<BundleInfo>();
  294. var operation = new ResourceDownloaderOperation(downloadMgr, packageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout);
  295. return operation;
  296. }
  297. }
  298. public sealed class ResourceUnpackerOperation : DownloaderOperation
  299. {
  300. internal ResourceUnpackerOperation(DownloadManager downloadMgr, string packageName, List<BundleInfo> downloadList, int downloadingMaxNumber, int failedTryAgain, int timeout)
  301. : base(downloadMgr, packageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout)
  302. {
  303. }
  304. /// <summary>
  305. /// 创建空的解压器
  306. /// </summary>
  307. internal static ResourceUnpackerOperation CreateEmptyUnpacker(DownloadManager downloadMgr, string packageName, int upackingMaxNumber, int failedTryAgain, int timeout)
  308. {
  309. List<BundleInfo> downloadList = new List<BundleInfo>();
  310. var operation = new ResourceUnpackerOperation(downloadMgr, packageName, downloadList, upackingMaxNumber, failedTryAgain, int.MaxValue);
  311. return operation;
  312. }
  313. }
  314. public sealed class ResourceImporterOperation : DownloaderOperation
  315. {
  316. internal ResourceImporterOperation(DownloadManager downloadMgr, string packageName, List<BundleInfo> downloadList, int downloadingMaxNumber, int failedTryAgain, int timeout)
  317. : base(downloadMgr, packageName, downloadList, downloadingMaxNumber, failedTryAgain, timeout)
  318. {
  319. }
  320. /// <summary>
  321. /// 创建空的导入器
  322. /// </summary>
  323. internal static ResourceImporterOperation CreateEmptyImporter(DownloadManager downloadMgr, string packageName, int upackingMaxNumber, int failedTryAgain, int timeout)
  324. {
  325. List<BundleInfo> downloadList = new List<BundleInfo>();
  326. var operation = new ResourceImporterOperation(downloadMgr, packageName, downloadList, upackingMaxNumber, failedTryAgain, int.MaxValue);
  327. return operation;
  328. }
  329. }
  330. }