星火微课系统客户端
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

DownloadManager.cs 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. using Common.Model;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading;
  7. namespace Common.system
  8. {
  9. /// <summary>
  10. /// 下载方法
  11. /// 创建人:赵耀
  12. /// 创建时间:2018年10月30日
  13. /// </summary>
  14. public class DownloadManager
  15. {
  16. private long fromIndex = 0;//开始下载的位置
  17. private bool isRun = false;//是否正在进行
  18. private DownloadInfoModel dlInfo;
  19. private List<DownloadService> dls = new List<DownloadService>();
  20. /// <summary>
  21. /// 开始下载
  22. /// </summary>
  23. public event Action OnStart;
  24. /// <summary>
  25. /// 停止下载
  26. /// </summary>
  27. public event Action OnStop;
  28. /// <summary>
  29. /// 下载进度
  30. /// </summary>
  31. public event Action<long, long, string> OnDownload;
  32. /// <summary>
  33. /// 下载完成
  34. /// </summary>
  35. public event Action<string> OnFinsh;
  36. /// <summary>
  37. /// 断开网络连接
  38. /// </summary>
  39. public event Action<string> OnDisconnect;
  40. public DownloadManager(DownloadInfoModel dlInfo)
  41. {
  42. this.dlInfo = dlInfo;
  43. }
  44. /// <summary>
  45. /// 暂停
  46. /// </summary>
  47. public void Stop()
  48. {
  49. this.isRun = false;
  50. dls.ForEach(dl => dl.Stop());
  51. OnStopHandler();
  52. }
  53. /// <summary>
  54. /// 开始下载
  55. /// </summary>
  56. public void Start()
  57. {
  58. this.dlInfo.isReStart = false;
  59. WorkStart();
  60. }
  61. /// <summary>
  62. /// 重新下载
  63. /// </summary>
  64. public void ReStart()
  65. {
  66. this.dlInfo.isReStart = true;
  67. WorkStart();
  68. }
  69. /// <summary>
  70. /// 下载
  71. /// </summary>
  72. private void WorkStart()
  73. {
  74. new Action(() =>
  75. {
  76. if (dlInfo.isReStart)
  77. {
  78. this.Stop();
  79. }
  80. while (dls.Where(dl => !dl.isStopped).Count() > 0)
  81. {
  82. if (dlInfo.isReStart) Thread.Sleep(100);
  83. else return;
  84. }
  85. this.isRun = true;
  86. OnStartHandler();
  87. //首次任务或者不支持断点续传的进入
  88. if (dlInfo.isNewTask || (!dlInfo.isNewTask && !dlInfo.IsSupportMultiThreading))
  89. {
  90. try
  91. {
  92. //第一次请求获取一小块数据,根据返回的情况判断是否支持断点续传
  93. using (var rsp = HttpHelper.Download(dlInfo.downloadUrlList[0], 0, 0, dlInfo.method))
  94. {
  95. //获取文件名,如果包含附件名称则取下附件,否则从url获取名称
  96. var Disposition = rsp.Headers["Content-Disposition"];
  97. try
  98. {
  99. if (Disposition != null)
  100. dlInfo.fileName = Disposition.Split('=')[1];
  101. else
  102. dlInfo.fileName = Path.GetFileName(rsp.ResponseUri.AbsolutePath);
  103. }
  104. catch (Exception)//无法获取文件名时 使用传入保存名称
  105. {
  106. dlInfo.fileName = dlInfo.saveFileName;
  107. }
  108. //默认给流总数
  109. dlInfo.count = rsp.ContentLength;
  110. //尝试获取 Content-Range 头部,不为空说明支持断点续传
  111. var contentRange = rsp.Headers["Content-Range"];
  112. if (contentRange != null)
  113. {
  114. //支持断点续传的话,就取range 这里的总数
  115. dlInfo.count = long.Parse(rsp.Headers["Content-Range"].Split('/')[1]);
  116. dlInfo.IsSupportMultiThreading = true;
  117. //生成一个临时文件名
  118. //var tempFileName = Convert.ToBase64String(Encoding.UTF8.GetBytes(dlInfo.fileName)).ToUpper();
  119. //tempFileName = tempFileName.Length > 32 ? tempFileName.Substring(0, 32) : tempFileName;
  120. //dlInfo.tempFileName = "test"; //tempFileName + DateTime.Now.ToString("yyyyMMddHHmmssfff");
  121. ///创建线程信息
  122. ///
  123. GetTaskInfo(dlInfo);
  124. }
  125. else
  126. {
  127. //不支持断点续传则一开始就直接读完整流
  128. Save(GetRealFileName(dlInfo), rsp.GetResponseStream());
  129. OnFineshHandler();
  130. }
  131. }
  132. }
  133. catch (Exception ex)
  134. {
  135. string ErrMessage = "【下载】(DownloadManager):" + ex.Message;
  136. LogHelper.WriteErrLog(ErrMessage, ex);
  137. OnDisconnectHandler();
  138. return;
  139. }
  140. dlInfo.isNewTask = false;
  141. }
  142. //如果支持断点续传采用这个
  143. if (dlInfo.IsSupportMultiThreading)
  144. {
  145. StartTask(dlInfo);
  146. //等待合并
  147. while (this.dls.Where(td => !td.isFinish).Count() > 0 && this.isRun)
  148. {
  149. Thread.Sleep(100);
  150. }
  151. if ((this.dls.Where(td => !td.isFinish).Count() == 0))
  152. {
  153. CombineFiles(dlInfo);
  154. OnFineshHandler();
  155. }
  156. }
  157. }).BeginInvoke(null, null);
  158. }
  159. /// <summary>
  160. /// 合成文件
  161. /// </summary>
  162. /// <param name="dlInfo"></param>
  163. private void CombineFiles(DownloadInfoModel dlInfo)
  164. {
  165. string realFilePath = GetRealFileName(dlInfo);
  166. //合并数据
  167. byte[] buffer = new Byte[2048];
  168. int length = 0;
  169. using (var fileStream = File.Open(realFilePath, FileMode.CreateNew))
  170. {
  171. for (int i = 0; i < dlInfo.TaskInfoList.Count; i++)
  172. {
  173. var tempFile = dlInfo.TaskInfoList[i].filePath;
  174. using (var tempStream = File.Open(tempFile, FileMode.Open))
  175. {
  176. while ((length = tempStream.Read(buffer, 0, buffer.Length)) > 0)
  177. {
  178. fileStream.Write(buffer, 0, length);
  179. }
  180. tempStream.Flush();
  181. }
  182. //File.Delete(tempFile);
  183. }
  184. }
  185. }
  186. /// <summary>
  187. /// 创建文件
  188. /// </summary>
  189. /// <param name="dlInfo"></param>
  190. /// <returns></returns>
  191. private static string GetRealFileName(DownloadInfoModel dlInfo)
  192. {
  193. //创建正式文件名,如果已存在则加数字序号创建,避免覆盖
  194. var fileIndex = 0;
  195. var realFilePath = Path.Combine(dlInfo.saveDir, dlInfo.saveFileName);
  196. while (File.Exists(realFilePath))
  197. {
  198. realFilePath = Path.Combine(dlInfo.saveDir, string.Format("{0}_{1}", fileIndex++, dlInfo.fileName));
  199. }
  200. return realFilePath;
  201. }
  202. private void StartTask(DownloadInfoModel dlInfo)
  203. {
  204. this.dls = new List<DownloadService>();
  205. if (dlInfo.TaskInfoList != null)
  206. {
  207. foreach (var item in dlInfo.TaskInfoList)
  208. {
  209. var dl = new DownloadService();
  210. dl.OnDownload += OnDownloadHandler;
  211. dl.OnDisconnect += OnDisconnectHandler;
  212. dls.Add(dl);
  213. try
  214. {
  215. dl.Start(item, dlInfo.isReStart);
  216. }
  217. catch (Exception ex)
  218. {
  219. string ErrMessage = "【下载】(DownloadManager):" + ex.Message;
  220. LogHelper.WriteErrLog(ErrMessage, ex);
  221. }
  222. }
  223. }
  224. }
  225. /// <summary>
  226. /// 创建下载任务
  227. /// </summary>
  228. /// <param name="dlInfo"></param>
  229. private void GetTaskInfo(DownloadInfoModel dlInfo)
  230. {
  231. var pieceSize = (dlInfo.count) / dlInfo.taskCount;
  232. dlInfo.TaskInfoList = new List<TaskInfoModel>();
  233. var rand = new Random();
  234. var urlIndex = 0;
  235. for (int i = 0; i <= dlInfo.taskCount + 1; i++)
  236. {
  237. var from = (i * pieceSize);
  238. if (from >= dlInfo.count) break;
  239. var to = from + pieceSize;
  240. if (to >= dlInfo.count) to = dlInfo.count;
  241. dlInfo.TaskInfoList.Add(
  242. new TaskInfoModel
  243. {
  244. method = dlInfo.method,
  245. downloadUrl = dlInfo.downloadUrlList[urlIndex++],
  246. filePath = Path.Combine(dlInfo.saveDir, dlInfo.tempFileName + ".temp" + i),
  247. fromIndex = from,
  248. toIndex = to
  249. });
  250. if (urlIndex >= dlInfo.downloadUrlList.Count) urlIndex = 0;
  251. }
  252. }
  253. /// <summary>
  254. /// 保存内容
  255. /// </summary>
  256. /// <param name="filePath"></param>
  257. /// <param name="stream"></param>
  258. private void Save(string filePath, Stream stream)
  259. {
  260. try
  261. {
  262. using (var writer = File.Open(filePath, FileMode.Append))
  263. {
  264. using (stream)
  265. {
  266. var repeatTimes = 0;
  267. byte[] buffer = new byte[1024];
  268. var length = 0;
  269. while ((length = stream.Read(buffer, 0, buffer.Length)) > 0 && this.isRun)
  270. {
  271. writer.Write(buffer, 0, length);
  272. this.fromIndex += length;
  273. if (repeatTimes % 5 == 0)
  274. {
  275. writer.Flush();//一定大小就刷一次缓冲区
  276. OnDownloadHandler();
  277. }
  278. repeatTimes++;
  279. }
  280. writer.Flush();
  281. OnDownloadHandler();
  282. }
  283. }
  284. }
  285. catch (Exception)
  286. {
  287. //异常也不影响
  288. }
  289. }
  290. /// <summary>
  291. /// 开始下载
  292. /// </summary>
  293. private void OnStartHandler()
  294. {
  295. new Action(() =>
  296. {
  297. this.OnStart.Invoke();
  298. }).BeginInvoke(null, null);
  299. }
  300. /// <summary>
  301. /// 暂停下载
  302. /// </summary>
  303. private void OnStopHandler()
  304. {
  305. new Action(() =>
  306. {
  307. this.OnStop.Invoke();
  308. }).BeginInvoke(null, null);
  309. }
  310. /// <summary>
  311. /// 下载完成
  312. /// </summary>
  313. private void OnFineshHandler()
  314. {
  315. new Action(() =>
  316. {
  317. for (int i = 0; i < dlInfo.TaskInfoList.Count; i++)
  318. {
  319. var tempFile = dlInfo.TaskInfoList[i].filePath;
  320. File.Delete(tempFile);
  321. }
  322. this.OnFinsh.Invoke(dlInfo.saveFileName);
  323. }).BeginInvoke(null, null);
  324. }
  325. /// <summary>
  326. /// 下载进度
  327. /// </summary>
  328. private void OnDownloadHandler()
  329. {
  330. new Action(() =>
  331. {
  332. long current = GetDownloadLength();
  333. this.OnDownload.Invoke(current, dlInfo.count, dlInfo.saveFileName);
  334. }).BeginInvoke(null, null);
  335. }
  336. /// <summary>
  337. /// 断开网络连接
  338. /// </summary>
  339. private void OnDisconnectHandler()
  340. {
  341. new Action(() =>
  342. {
  343. this.OnDisconnect.Invoke(dlInfo.saveFileName);
  344. }).BeginInvoke(null, null);
  345. }
  346. /// <summary>
  347. /// 当前下载进度
  348. /// </summary>
  349. /// <returns></returns>
  350. public long GetDownloadLength()
  351. {
  352. if (dlInfo.IsSupportMultiThreading) return dls.Sum(dl => dl.GetDownloadedCount());
  353. else return this.fromIndex;
  354. }
  355. /// <summary>
  356. /// 获取保存文件名
  357. /// </summary>
  358. /// <returns></returns>
  359. public DownloadInfoModel GetFileInfo
  360. {
  361. get { return dlInfo; }
  362. }
  363. }
  364. }