downloadpackage.task 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  3. <ImportGroup Label="PropertySheets">
  4. <Import Project="basedir.props" Condition=" '$(BaseDirImported)' == ''"/>
  5. </ImportGroup>
  6. <UsingTask TaskName="DownloadPackageTask"
  7. TaskFactory="CodeTaskFactory"
  8. AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll" >
  9. <ParameterGroup>
  10. <package Required="true" />
  11. <expectfileordirectory Required="true" />
  12. <outputfolder />
  13. <outputfilename />
  14. <extractto />
  15. </ParameterGroup>
  16. <Task>
  17. <Reference Include="Microsoft.Build" />
  18. <Reference Include="Microsoft.Build.Framework" />
  19. <Reference Include="Microsoft.Build.Utilities.Core" />
  20. <Code Type="Class" Language="cs">
  21. <![CDATA[
  22. using System;
  23. using System.IO;
  24. using System.Threading;
  25. using Microsoft.Build.Framework;
  26. using System.Reflection;
  27. using Microsoft.Build.Execution;
  28. using System.Net;
  29. using System.ComponentModel;
  30. using System.Diagnostics;
  31. public class DownloadPackageTask : Microsoft.Build.Utilities.Task, Microsoft.Build.Framework.ICancelableTask
  32. {
  33. public class State
  34. {
  35. public string filename;
  36. public int progress;
  37. }
  38. protected ManualResetEvent TaskCanceled { get; private set; }
  39. public void Cancel()
  40. {
  41. TaskCanceled.Set();
  42. }
  43. private string basedir;
  44. [Required]
  45. public string package { get; set; }
  46. [Required]
  47. public string expectfileordirectory { get; set; }
  48. public string outputfolder { get; set; }
  49. public string outputfilename { get; set; }
  50. public string extractto { get; set; }
  51. internal static bool FileOrDirectoryExists(string name)
  52. {
  53. return (Directory.Exists(name) || File.Exists(name));
  54. }
  55. public override bool Execute()
  56. {
  57. basedir = Path.GetFullPath(@"$(BaseDir)");
  58. TaskCanceled = new ManualResetEvent(false);
  59. Log.LogMessage(MessageImportance.High,
  60. "Checking for package \"" + package + "\".");
  61. //Log.LogMessage(MessageImportance.High,
  62. // "BaseDir \"" + basedir + "\"");
  63. //Log.LogMessage(MessageImportance.High,
  64. // "expectfileordirectory \"" + expectfileordirectory + "\"");
  65. string librarypath = basedir;
  66. Mutex m = new Mutex(false, Path.Combine(librarypath, package).Replace(":", "/").Replace("\\","/"));
  67. m.WaitOne();
  68. if (FileOrDirectoryExists(expectfileordirectory))
  69. {
  70. Log.LogMessage(MessageImportance.High,
  71. "Package \"" + package + "\" exists. Do nothing.");
  72. }
  73. else
  74. {
  75. Log.LogMessage(MessageImportance.High,
  76. "Start downloading package \"" + package + "\".");
  77. using (var client = new System.Net.WebClient())
  78. {
  79. Uri uri = new Uri(package);
  80. string urifilename = Path.GetFileName(uri.LocalPath);
  81. string output = Path.Combine(outputfolder ?? librarypath, (outputfilename ?? urifilename));
  82. //if (!File.Exists(output)) // Uncomment to skip download if exists
  83. {
  84. var syncObject = new State
  85. {
  86. filename = urifilename,
  87. progress = -1
  88. };
  89. lock (syncObject)
  90. {
  91. client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFileCompleted);
  92. client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);
  93. client.DownloadFileAsync(uri, output, syncObject);
  94. Log.LogMessage(MessageImportance.High,
  95. "uri: \"" + uri + "\".");
  96. Log.LogMessage(MessageImportance.High,
  97. "output: \"" + output + "\".");
  98. while (!Monitor.Wait(syncObject, 1000))
  99. {
  100. if (TaskCanceled.WaitOne(0))
  101. {
  102. client.CancelAsync();
  103. Monitor.Wait(syncObject);
  104. if (File.Exists(output))
  105. {
  106. Log.LogMessage(MessageImportance.High,
  107. "Deleting incomplete file " + output + " for package \"" + package + "\".");
  108. File.Delete(output);
  109. }
  110. Log.LogMessage(MessageImportance.High,
  111. "Downloading canceled for package \"" + package + "\".");
  112. break;
  113. }
  114. }
  115. }
  116. }
  117. if (File.Exists(output))
  118. {
  119. // Successful download.
  120. if (Path.GetExtension(output) != ".exe")
  121. {
  122. Extract(output);
  123. string filename = Path.Combine(Path.GetDirectoryName(output), Path.GetFileNameWithoutExtension(output));
  124. Log.LogMessage(MessageImportance.High,
  125. "Filename \"" + filename + "\".");
  126. if (File.Exists(filename))
  127. {
  128. Extract(filename);
  129. File.Delete(filename);
  130. }
  131. }
  132. }
  133. }
  134. if (!TaskCanceled.WaitOne(0))
  135. {
  136. Log.LogMessage(MessageImportance.High,
  137. "Downloading finished for package \"" + package + "\".");
  138. }
  139. }
  140. m.ReleaseMutex();
  141. return true;
  142. }
  143. private void Extract(string filename)
  144. {
  145. string extracttofolder = Path.GetFullPath((extractto ?? Path.GetDirectoryName(filename)) + "/");
  146. string arctool = Path.Combine(new string[] { basedir, "7za1701.exe" });
  147. string args = " x \"" + filename + "\" -y -o\"" + extracttofolder + "\"";
  148. Log.LogMessage(MessageImportance.High,
  149. "arctool : " + arctool);
  150. Log.LogMessage(MessageImportance.High,
  151. "args : " + args);
  152. Log.LogMessage(MessageImportance.High,
  153. "WorkingDirectory : " + Path.GetDirectoryName(arctool));
  154. var proc = new Process
  155. {
  156. StartInfo = new ProcessStartInfo
  157. {
  158. FileName = arctool,
  159. Arguments = args,
  160. UseShellExecute = false,
  161. RedirectStandardOutput = true,
  162. CreateNoWindow = true,
  163. WorkingDirectory = Path.GetDirectoryName(arctool)
  164. }
  165. };
  166. proc.Start();
  167. while (!proc.StandardOutput.EndOfStream)
  168. {
  169. string line = proc.StandardOutput.ReadLine();
  170. Log.LogMessage(MessageImportance.High,
  171. Path.GetFileName(filename) + " : " + line);
  172. if (TaskCanceled.WaitOne(0))
  173. {
  174. proc.Kill();
  175. break;
  176. }
  177. }
  178. proc.WaitForExit();
  179. }
  180. private void DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
  181. {
  182. lock (e.UserState)
  183. {
  184. //releases blocked thread
  185. Monitor.Pulse(e.UserState);
  186. }
  187. }
  188. private string humanSize(double len)
  189. {
  190. string[] sizes = { "B", "KB", "MB", "GB", "TB" };
  191. int order = 0;
  192. while (len >= 1024 && order < sizes.Length - 1)
  193. {
  194. order++;
  195. len = len / 1024;
  196. }
  197. return String.Format("{0:0.##} {1}", len, sizes[order]);
  198. }
  199. private void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
  200. {
  201. if (((State)e.UserState).progress < e.ProgressPercentage)
  202. {
  203. ((State)e.UserState).progress = e.ProgressPercentage;
  204. // Displays the transfer progress.
  205. Log.LogMessage(MessageImportance.High, ((State)e.UserState).filename + " : downloaded " + humanSize(e.BytesReceived) + " of " + humanSize(e.TotalBytesToReceive) + " " + e.ProgressPercentage + " % complete...");
  206. }
  207. }
  208. }
  209. ]]>
  210. </Code>
  211. </Task>
  212. </UsingTask>
  213. <Target Name="7za" BeforeTargets="Build">
  214. <DownloadPackageTask
  215. package="http://files.freeswitch.org/downloads/win32/7za1701.exe"
  216. expectfileordirectory="$(BaseDir)7za1701.exe"
  217. outputfolder="$(BaseDir)"
  218. outputfilename="7za1701.exe"
  219. extractto=""
  220. />
  221. </Target>
  222. <PropertyGroup>
  223. <downloadpackagetask_Imported>true</downloadpackagetask_Imported>
  224. </PropertyGroup>
  225. </Project>