DownloadManager.DownloadAgent.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. //------------------------------------------------------------
  2. // Game Framework
  3. // Copyright © 2013-2021 loyalsoft. All rights reserved.
  4. // Homepage: http://www.game7000.com/
  5. // Feedback: http://www.game7000.com/
  6. //------------------------------------------------------------
  7. using System;
  8. using System.IO;
  9. namespace GameFramework.Download
  10. {
  11. internal sealed partial class DownloadManager : GameFrameworkModule, IDownloadManager
  12. {
  13. /// <summary>
  14. /// 下载代理。
  15. /// </summary>
  16. private sealed class DownloadAgent : ITaskAgent<DownloadTask>, IDisposable
  17. {
  18. private readonly IDownloadAgentHelper m_Helper;
  19. private DownloadTask m_Task;
  20. private FileStream m_FileStream;
  21. private int m_WaitFlushSize;
  22. private float m_WaitTime;
  23. private long m_StartLength;
  24. private long m_DownloadedLength;
  25. private long m_SavedLength;
  26. private bool m_Disposed;
  27. public GameFrameworkAction<DownloadAgent> DownloadAgentStart;
  28. public GameFrameworkAction<DownloadAgent, int> DownloadAgentUpdate;
  29. public GameFrameworkAction<DownloadAgent, long> DownloadAgentSuccess;
  30. public GameFrameworkAction<DownloadAgent, string> DownloadAgentFailure;
  31. /// <summary>
  32. /// 初始化下载代理的新实例。
  33. /// </summary>
  34. /// <param name="downloadAgentHelper">下载代理辅助器。</param>
  35. public DownloadAgent(IDownloadAgentHelper downloadAgentHelper)
  36. {
  37. if (downloadAgentHelper == null)
  38. {
  39. throw new GameFrameworkException("Download agent helper is invalid.");
  40. }
  41. m_Helper = downloadAgentHelper;
  42. m_Task = null;
  43. m_FileStream = null;
  44. m_WaitFlushSize = 0;
  45. m_WaitTime = 0f;
  46. m_StartLength = 0L;
  47. m_DownloadedLength = 0L;
  48. m_SavedLength = 0L;
  49. m_Disposed = false;
  50. DownloadAgentStart = null;
  51. DownloadAgentUpdate = null;
  52. DownloadAgentSuccess = null;
  53. DownloadAgentFailure = null;
  54. }
  55. /// <summary>
  56. /// 获取下载任务。
  57. /// </summary>
  58. public DownloadTask Task
  59. {
  60. get
  61. {
  62. return m_Task;
  63. }
  64. }
  65. /// <summary>
  66. /// 获取已经等待时间。
  67. /// </summary>
  68. public float WaitTime
  69. {
  70. get
  71. {
  72. return m_WaitTime;
  73. }
  74. }
  75. /// <summary>
  76. /// 获取开始下载时已经存在的大小。
  77. /// </summary>
  78. public long StartLength
  79. {
  80. get
  81. {
  82. return m_StartLength;
  83. }
  84. }
  85. /// <summary>
  86. /// 获取本次已经下载的大小。
  87. /// </summary>
  88. public long DownloadedLength
  89. {
  90. get
  91. {
  92. return m_DownloadedLength;
  93. }
  94. }
  95. /// <summary>
  96. /// 获取当前的大小。
  97. /// </summary>
  98. public long CurrentLength
  99. {
  100. get
  101. {
  102. return m_StartLength + m_DownloadedLength;
  103. }
  104. }
  105. /// <summary>
  106. /// 获取已经存盘的大小。
  107. /// </summary>
  108. public long SavedLength
  109. {
  110. get
  111. {
  112. return m_SavedLength;
  113. }
  114. }
  115. /// <summary>
  116. /// 初始化下载代理。
  117. /// </summary>
  118. public void Initialize()
  119. {
  120. m_Helper.DownloadAgentHelperUpdateBytes += OnDownloadAgentHelperUpdateBytes;
  121. m_Helper.DownloadAgentHelperUpdateLength += OnDownloadAgentHelperUpdateLength;
  122. m_Helper.DownloadAgentHelperComplete += OnDownloadAgentHelperComplete;
  123. m_Helper.DownloadAgentHelperError += OnDownloadAgentHelperError;
  124. }
  125. /// <summary>
  126. /// 下载代理轮询。
  127. /// </summary>
  128. /// <param name="elapseSeconds">逻辑流逝时间,以秒为单位。</param>
  129. /// <param name="realElapseSeconds">真实流逝时间,以秒为单位。</param>
  130. public void Update(float elapseSeconds, float realElapseSeconds)
  131. {
  132. if (m_Task.Status == DownloadTaskStatus.Doing)
  133. {
  134. m_WaitTime += realElapseSeconds;
  135. if (m_WaitTime >= m_Task.Timeout)
  136. {
  137. DownloadAgentHelperErrorEventArgs downloadAgentHelperErrorEventArgs = DownloadAgentHelperErrorEventArgs.Create(false, "Timeout");
  138. OnDownloadAgentHelperError(this, downloadAgentHelperErrorEventArgs);
  139. ReferencePool.Release(downloadAgentHelperErrorEventArgs);
  140. }
  141. }
  142. }
  143. /// <summary>
  144. /// 关闭并清理下载代理。
  145. /// </summary>
  146. public void Shutdown()
  147. {
  148. Dispose();
  149. m_Helper.DownloadAgentHelperUpdateBytes -= OnDownloadAgentHelperUpdateBytes;
  150. m_Helper.DownloadAgentHelperUpdateLength -= OnDownloadAgentHelperUpdateLength;
  151. m_Helper.DownloadAgentHelperComplete -= OnDownloadAgentHelperComplete;
  152. m_Helper.DownloadAgentHelperError -= OnDownloadAgentHelperError;
  153. }
  154. /// <summary>
  155. /// 开始处理下载任务。
  156. /// </summary>
  157. /// <param name="task">要处理的下载任务。</param>
  158. /// <returns>开始处理任务的状态。</returns>
  159. public StartTaskStatus Start(DownloadTask task)
  160. {
  161. if (task == null)
  162. {
  163. throw new GameFrameworkException("Task is invalid.");
  164. }
  165. m_Task = task;
  166. m_Task.Status = DownloadTaskStatus.Doing;
  167. string downloadFile = Utility.Text.Format("{0}.download", m_Task.DownloadPath);
  168. try
  169. {
  170. if (File.Exists(downloadFile))
  171. {
  172. m_FileStream = File.OpenWrite(downloadFile);
  173. m_FileStream.Seek(0L, SeekOrigin.End);
  174. m_StartLength = m_SavedLength = m_FileStream.Length;
  175. m_DownloadedLength = 0L;
  176. }
  177. else
  178. {
  179. string directory = Path.GetDirectoryName(m_Task.DownloadPath);
  180. if (!Directory.Exists(directory))
  181. {
  182. Directory.CreateDirectory(directory);
  183. }
  184. m_FileStream = new FileStream(downloadFile, FileMode.Create, FileAccess.Write);
  185. m_StartLength = m_SavedLength = m_DownloadedLength = 0L;
  186. }
  187. if (DownloadAgentStart != null)
  188. {
  189. DownloadAgentStart(this);
  190. }
  191. if (m_StartLength > 0L)
  192. {
  193. m_Helper.Download(m_Task.DownloadUri, m_StartLength, m_Task.UserData);
  194. }
  195. else
  196. {
  197. m_Helper.Download(m_Task.DownloadUri, m_Task.UserData);
  198. }
  199. return StartTaskStatus.CanResume;
  200. }
  201. catch (Exception exception)
  202. {
  203. DownloadAgentHelperErrorEventArgs downloadAgentHelperErrorEventArgs = DownloadAgentHelperErrorEventArgs.Create(false, exception.ToString());
  204. OnDownloadAgentHelperError(this, downloadAgentHelperErrorEventArgs);
  205. ReferencePool.Release(downloadAgentHelperErrorEventArgs);
  206. return StartTaskStatus.UnknownError;
  207. }
  208. }
  209. /// <summary>
  210. /// 重置下载代理。
  211. /// </summary>
  212. public void Reset()
  213. {
  214. m_Helper.Reset();
  215. if (m_FileStream != null)
  216. {
  217. m_FileStream.Close();
  218. m_FileStream = null;
  219. }
  220. m_Task = null;
  221. m_WaitFlushSize = 0;
  222. m_WaitTime = 0f;
  223. m_StartLength = 0L;
  224. m_DownloadedLength = 0L;
  225. m_SavedLength = 0L;
  226. }
  227. /// <summary>
  228. /// 释放资源。
  229. /// </summary>
  230. public void Dispose()
  231. {
  232. Dispose(true);
  233. GC.SuppressFinalize(this);
  234. }
  235. /// <summary>
  236. /// 释放资源。
  237. /// </summary>
  238. /// <param name="disposing">释放资源标记。</param>
  239. private void Dispose(bool disposing)
  240. {
  241. if (m_Disposed)
  242. {
  243. return;
  244. }
  245. if (disposing)
  246. {
  247. if (m_FileStream != null)
  248. {
  249. m_FileStream.Dispose();
  250. m_FileStream = null;
  251. }
  252. }
  253. m_Disposed = true;
  254. }
  255. private void OnDownloadAgentHelperUpdateBytes(object sender, DownloadAgentHelperUpdateBytesEventArgs e)
  256. {
  257. m_WaitTime = 0f;
  258. try
  259. {
  260. m_FileStream.Write(e.GetBytes(), e.Offset, e.Length);
  261. m_WaitFlushSize += e.Length;
  262. m_SavedLength += e.Length;
  263. if (m_WaitFlushSize >= m_Task.FlushSize)
  264. {
  265. m_FileStream.Flush();
  266. m_WaitFlushSize = 0;
  267. }
  268. }
  269. catch (Exception exception)
  270. {
  271. DownloadAgentHelperErrorEventArgs downloadAgentHelperErrorEventArgs = DownloadAgentHelperErrorEventArgs.Create(false, exception.ToString());
  272. OnDownloadAgentHelperError(this, downloadAgentHelperErrorEventArgs);
  273. ReferencePool.Release(downloadAgentHelperErrorEventArgs);
  274. }
  275. }
  276. private void OnDownloadAgentHelperUpdateLength(object sender, DownloadAgentHelperUpdateLengthEventArgs e)
  277. {
  278. m_WaitTime = 0f;
  279. m_DownloadedLength += e.DeltaLength;
  280. if (DownloadAgentUpdate != null)
  281. {
  282. DownloadAgentUpdate(this, e.DeltaLength);
  283. }
  284. }
  285. private void OnDownloadAgentHelperComplete(object sender, DownloadAgentHelperCompleteEventArgs e)
  286. {
  287. m_WaitTime = 0f;
  288. m_DownloadedLength = e.Length;
  289. if (m_SavedLength != CurrentLength)
  290. {
  291. throw new GameFrameworkException("Internal download error.");
  292. }
  293. m_Helper.Reset();
  294. m_FileStream.Close();
  295. m_FileStream = null;
  296. if (File.Exists(m_Task.DownloadPath))
  297. {
  298. File.Delete(m_Task.DownloadPath);
  299. }
  300. File.Move(Utility.Text.Format("{0}.download", m_Task.DownloadPath), m_Task.DownloadPath);
  301. m_Task.Status = DownloadTaskStatus.Done;
  302. if (DownloadAgentSuccess != null)
  303. {
  304. DownloadAgentSuccess(this, e.Length);
  305. }
  306. m_Task.Done = true;
  307. }
  308. private void OnDownloadAgentHelperError(object sender, DownloadAgentHelperErrorEventArgs e)
  309. {
  310. m_Helper.Reset();
  311. if (m_FileStream != null)
  312. {
  313. m_FileStream.Close();
  314. m_FileStream = null;
  315. }
  316. if (e.DeleteDownloading)
  317. {
  318. File.Delete(Utility.Text.Format("{0}.download", m_Task.DownloadPath));
  319. }
  320. m_Task.Status = DownloadTaskStatus.Error;
  321. if (DownloadAgentFailure != null)
  322. {
  323. DownloadAgentFailure(this, e.ErrorMessage);
  324. }
  325. m_Task.Done = true;
  326. }
  327. }
  328. }
  329. }