MultiThreadDownloader.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace Masuit.Tools.Core.Net
  10. {
  11. public delegate void FileMergeProgressChangedEventHandler(object sender, int e);
  12. public class MultiThreadDownloader
  13. {
  14. #region Variables
  15. public event EventHandler TotalProgressChanged;
  16. public event FileMergeProgressChangedEventHandler FileMergeProgressChanged;
  17. private readonly AsyncOperation _aop;
  18. #endregion
  19. #region DownloadManager
  20. public MultiThreadDownloader(string sourceUrl, string tempDir, string savePath, int numOfParts)
  21. {
  22. _url = sourceUrl;
  23. NumberOfParts = numOfParts;
  24. TempFileDirectory = tempDir;
  25. PartialDownloaderList = new List<PartialDownloader>();
  26. _aop = AsyncOperationManager.CreateOperation(null);
  27. FilePath = savePath;
  28. }
  29. public MultiThreadDownloader(string sourceUrl, string savePath, int numOfParts) : this(sourceUrl, null, savePath, numOfParts)
  30. {
  31. TempFileDirectory = Environment.GetEnvironmentVariable("temp");
  32. }
  33. public MultiThreadDownloader(string sourceUrl, int numOfParts) : this(sourceUrl, null, numOfParts)
  34. {
  35. }
  36. #endregion
  37. #region Events
  38. private void temp_DownloadPartCompleted(object sender, EventArgs e)
  39. {
  40. WaitOrResumeAll(PartialDownloaderList, true);
  41. if (TotalBytesReceived == Size)
  42. {
  43. UpdateProgress();
  44. MergeParts();
  45. return;
  46. }
  47. OrderByRemaining(PartialDownloaderList);
  48. int rem = PartialDownloaderList[0].RemainingBytes;
  49. if (rem < 50 * 1024)
  50. {
  51. WaitOrResumeAll(PartialDownloaderList, false);
  52. return;
  53. }
  54. int from = PartialDownloaderList[0].CurrentPosition + rem / 2;
  55. int to = PartialDownloaderList[0].To;
  56. if (from > to)
  57. {
  58. WaitOrResumeAll(PartialDownloaderList, false);
  59. return;
  60. }
  61. PartialDownloaderList[0].To = from - 1;
  62. WaitOrResumeAll(PartialDownloaderList, false);
  63. PartialDownloader temp = new PartialDownloader(_url, TempFileDirectory, Guid.NewGuid().ToString(), from, to, true);
  64. temp.DownloadPartCompleted += temp_DownloadPartCompleted;
  65. temp.DownloadPartProgressChanged += temp_DownloadPartProgressChanged;
  66. PartialDownloaderList.Add(temp);
  67. temp.Start();
  68. }
  69. void temp_DownloadPartProgressChanged(object sender, EventArgs e)
  70. {
  71. UpdateProgress();
  72. }
  73. void UpdateProgress()
  74. {
  75. int pr = (int)(TotalBytesReceived * 1d / Size * 100);
  76. if (TotalProgress != pr)
  77. {
  78. TotalProgress = pr;
  79. if (TotalProgressChanged != null)
  80. {
  81. _aop.Post(state => TotalProgressChanged(this, EventArgs.Empty), null);
  82. }
  83. }
  84. }
  85. #endregion
  86. #region Helpers
  87. void CreateFirstPartitions()
  88. {
  89. Size = GetContentLength(_url, ref _rangeAllowed, ref _url);
  90. int maximumPart = (int)(Size / (25 * 1024));
  91. maximumPart = maximumPart == 0 ? 1 : maximumPart;
  92. if (!_rangeAllowed)
  93. NumberOfParts = 1;
  94. else if (NumberOfParts > maximumPart)
  95. NumberOfParts = maximumPart;
  96. for (int i = 0; i < NumberOfParts; i++)
  97. {
  98. PartialDownloader temp = CreateNewPd(i, NumberOfParts, Size);
  99. temp.DownloadPartProgressChanged += temp_DownloadPartProgressChanged;
  100. temp.DownloadPartCompleted += temp_DownloadPartCompleted;
  101. PartialDownloaderList.Add(temp);
  102. temp.Start();
  103. }
  104. }
  105. void MergeParts()
  106. {
  107. List<PartialDownloader> mergeOrderedList = SortPDsByFrom(PartialDownloaderList);
  108. using (var fs = new FileStream(FilePath, FileMode.Create, FileAccess.ReadWrite))
  109. {
  110. long totalBytesWritten = 0;
  111. int mergeProgress = 0;
  112. foreach (var item in mergeOrderedList)
  113. {
  114. using (FileStream pds = new FileStream(item.FullPath, FileMode.Open, FileAccess.Read))
  115. {
  116. byte[] buffer = new byte[4096];
  117. int read;
  118. while ((read = pds.Read(buffer, 0, buffer.Length)) > 0)
  119. {
  120. fs.Write(buffer, 0, read);
  121. totalBytesWritten += read;
  122. int temp = (int)(totalBytesWritten * 1d / Size * 100);
  123. if (temp != mergeProgress && FileMergeProgressChanged != null)
  124. {
  125. mergeProgress = temp;
  126. _aop.Post(state => FileMergeProgressChanged(this, temp), null);
  127. }
  128. }
  129. }
  130. File.Delete(item.FullPath);
  131. }
  132. }
  133. }
  134. PartialDownloader CreateNewPd(int order, int parts, long contentLength)
  135. {
  136. int division = (int)contentLength / parts;
  137. int remaining = (int)contentLength % parts;
  138. int start = division * order;
  139. int end = start + division - 1;
  140. end += (order == parts - 1) ? remaining : 0;
  141. return new PartialDownloader(_url, TempFileDirectory, Guid.NewGuid().ToString(), start, end, true);
  142. }
  143. public static void WaitOrResumeAll(List<PartialDownloader> list, bool wait)
  144. {
  145. foreach (PartialDownloader item in list)
  146. {
  147. if (wait)
  148. item.Wait();
  149. else
  150. item.ResumeAfterWait();
  151. }
  152. }
  153. private static void BubbleSort(List<PartialDownloader> list)
  154. {
  155. bool switched = true;
  156. while (switched)
  157. {
  158. switched = false;
  159. for (int i = 0; i < list.Count - 1; i++)
  160. {
  161. if (list[i].RemainingBytes < list[i + 1].RemainingBytes)
  162. {
  163. PartialDownloader temp = list[i];
  164. list[i] = list[i + 1];
  165. list[i + 1] = temp;
  166. switched = true;
  167. }
  168. }
  169. }
  170. }
  171. //Sorts the downloader by From property to merge the parts
  172. public static List<PartialDownloader> SortPDsByFrom(List<PartialDownloader> list)
  173. {
  174. return list.OrderBy(x => x.From).ToList();
  175. }
  176. public static void OrderByRemaining(List<PartialDownloader> list)
  177. {
  178. BubbleSort(list);
  179. }
  180. public static long GetContentLength(string url, ref bool rangeAllowed, ref string redirectedUrl)
  181. {
  182. HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
  183. req.UserAgent = "Mozilla/4.0 (compatible; MSIE 11.0; Windows NT 6.2; .NET CLR 1.0.3705;)";
  184. req.ServicePoint.ConnectionLimit = 4;
  185. HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
  186. redirectedUrl = resp.ResponseUri.OriginalString;
  187. long ctl = resp.ContentLength;
  188. rangeAllowed = resp.Headers.AllKeys.Select((v, i) => new { HeaderName = v, HeaderValue = resp.Headers[i] }).Any(k => k.HeaderName.ToLower().Contains("range") && k.HeaderValue.ToLower().Contains("byte"));
  189. resp.Close();
  190. req.Abort();
  191. return ctl;
  192. }
  193. #endregion
  194. #region Public Methods
  195. public void Pause()
  196. {
  197. foreach (var t in PartialDownloaderList)
  198. {
  199. if (!t.Completed)
  200. t.Stop();
  201. }
  202. //Setting a Thread.Sleep ensures all downloads are stopped and exit from loop.
  203. Thread.Sleep(200);
  204. }
  205. public void Start()
  206. {
  207. Task th = new Task(CreateFirstPartitions);
  208. th.Start();
  209. }
  210. public void Resume()
  211. {
  212. int count = PartialDownloaderList.Count;
  213. for (int i = 0; i < count; i++)
  214. {
  215. if (PartialDownloaderList[i].Stopped)
  216. {
  217. int from = PartialDownloaderList[i].CurrentPosition + 1;
  218. int to = PartialDownloaderList[i].To;
  219. if (from > to) continue;
  220. PartialDownloader temp = new PartialDownloader(_url, TempFileDirectory, Guid.NewGuid().ToString(), from, to, _rangeAllowed);
  221. temp.DownloadPartProgressChanged += temp_DownloadPartProgressChanged;
  222. temp.DownloadPartCompleted += temp_DownloadPartCompleted;
  223. PartialDownloaderList.Add(temp);
  224. PartialDownloaderList[i].To = PartialDownloaderList[i].CurrentPosition;
  225. temp.Start();
  226. }
  227. }
  228. }
  229. #endregion
  230. #region Property Variables
  231. private string _url;
  232. private bool _rangeAllowed;
  233. #endregion
  234. #region Properties
  235. public bool RangeAllowed
  236. {
  237. get => _rangeAllowed;
  238. set => _rangeAllowed = value;
  239. }
  240. public string TempFileDirectory { get; set; }
  241. public string Url
  242. {
  243. get => _url;
  244. set => _url = value;
  245. }
  246. public int NumberOfParts { get; set; }
  247. public long TotalBytesReceived => PartialDownloaderList.Where(t => t != null).Sum(t => t.TotalBytesRead);
  248. public int TotalProgress { get; private set; }
  249. public long Size { get; private set; }
  250. public int TotalSpeedInBytes => PartialDownloaderList.Sum(t => t.SpeedInBytes);
  251. public List<PartialDownloader> PartialDownloaderList { get; }
  252. public string FilePath { get; set; }
  253. #endregion
  254. }
  255. }