downloadpackage.task 11 KB

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