MainWindow.xaml.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Net;
  6. using System.Threading.Tasks;
  7. using System.Windows;
  8. using System.Linq;
  9. using Ionic.Zip;
  10. using MediaBrowser.Installer.Code;
  11. using ServiceStack.Text;
  12. using IWshRuntimeLibrary;
  13. namespace MediaBrowser.Installer
  14. {
  15. /// <summary>
  16. /// Interaction logic for MainWindow.xaml
  17. /// </summary>
  18. public partial class MainWindow : Window
  19. {
  20. protected PackageVersionClass PackageClass = PackageVersionClass.Release;
  21. protected Version PackageVersion = new Version(10,0,0,0);
  22. protected string PackageName = "MBServer";
  23. protected string RootSuffix = "-Server";
  24. protected string TargetExe = "MediaBrowser.ServerApplication.exe";
  25. protected string FriendlyName = "Media Browser Server";
  26. protected string RootPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MediaBrowser-Server");
  27. protected bool SystemClosing = false;
  28. protected string TempLocation = Path.Combine(Path.GetTempPath(), "MediaBrowser");
  29. public MainWindow()
  30. {
  31. GetArgs();
  32. InitializeComponent();
  33. DoInstall();
  34. }
  35. private void btnCancel_Click(object sender, RoutedEventArgs e)
  36. {
  37. this.Close();
  38. }
  39. protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
  40. {
  41. if (!SystemClosing && MessageBox.Show("Cancel Installation - Are you sure?", "Cancel", MessageBoxButton.YesNo) == MessageBoxResult.No)
  42. {
  43. e.Cancel = true;
  44. }
  45. ClearTempLocation(TempLocation);
  46. base.OnClosing(e);
  47. }
  48. protected void SystemClose(string message = null)
  49. {
  50. if (message != null)
  51. {
  52. MessageBox.Show(message, "Error");
  53. }
  54. SystemClosing = true;
  55. this.Close();
  56. }
  57. protected void GetArgs()
  58. {
  59. var args = Environment.GetCommandLineArgs();
  60. var parameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  61. foreach (var arg in args)
  62. {
  63. var nameValue = arg.Split('=');
  64. try
  65. {
  66. parameters[nameValue[0]] = nameValue[1];
  67. }
  68. catch // let it default below
  69. {
  70. }
  71. }
  72. // fill in our arguments if there
  73. PackageName = parameters.GetValueOrDefault("package","MBServer");
  74. PackageClass = (PackageVersionClass)Enum.Parse(typeof(PackageVersionClass), parameters.GetValueOrDefault("class","Release"));
  75. PackageVersion = new Version(parameters.GetValueOrDefault("version","10.0.0.0"));
  76. RootSuffix = parameters.GetValueOrDefault("suffix", "-Server");
  77. TargetExe = parameters.GetValueOrDefault("target", "MediaBrowser.ServerApplication.exe");
  78. FriendlyName = parameters.GetValueOrDefault("name", PackageName);
  79. RootPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MediaBrowser" + RootSuffix);
  80. }
  81. /// <summary>
  82. /// Execute the install process
  83. /// </summary>
  84. /// <returns></returns>
  85. protected async Task DoInstall()
  86. {
  87. lblStatus.Content = "Downloading "+FriendlyName+"...";
  88. dlAnimation.StartAnimation();
  89. prgProgress.Value = 0;
  90. prgProgress.Visibility = Visibility.Visible;
  91. // Download
  92. var archive = await DownloadPackage();
  93. dlAnimation.StopAnimation();
  94. prgProgress.Visibility = btnCancel.Visibility = Visibility.Hidden;
  95. // Extract
  96. lblStatus.Content = "Extracting Package...";
  97. try
  98. {
  99. ExtractPackage(archive);
  100. }
  101. catch (Exception e)
  102. {
  103. SystemClose("Error Extracting - " + e.GetType().FullName + "\n\n" + e.Message);
  104. }
  105. // Create shortcut
  106. var fullPath = Path.Combine(RootPath, "System", TargetExe);
  107. try
  108. {
  109. CreateShortcut(fullPath);
  110. }
  111. catch (Exception e)
  112. {
  113. SystemClose("Error Creating Shortcut - "+e.GetType().FullName+"\n\n"+e.Message);
  114. }
  115. // And run
  116. try
  117. {
  118. Process.Start(fullPath);
  119. }
  120. catch (Exception e)
  121. {
  122. SystemClose("Error Executing - "+fullPath+ " "+e.GetType().FullName+"\n\n"+e.Message);
  123. }
  124. SystemClose();
  125. }
  126. /// <summary>
  127. /// Download our specified package to an archive in a temp location
  128. /// </summary>
  129. /// <returns>The fully qualified name of the downloaded package</returns>
  130. protected async Task<string> DownloadPackage()
  131. {
  132. using (var client = new WebClient())
  133. {
  134. try
  135. {
  136. // get the package information for the server
  137. var json = await client.DownloadStringTaskAsync("http://www.mb3admin.com/admin/service/package/retrieveAll?name="+PackageName);
  138. var packages = JsonSerializer.DeserializeFromString<List<PackageInfo>>(json);
  139. var version = packages[0].versions.Where(v => v.classification == PackageClass).OrderByDescending(v => v.version).FirstOrDefault(v => v.version <= PackageVersion);
  140. if (version == null)
  141. {
  142. SystemClose("Could not locate download package. Aborting.");
  143. return null;
  144. }
  145. var archiveFile = Path.Combine(PrepareTempLocation(), version.targetFilename);
  146. // setup download progress and download the package
  147. client.DownloadProgressChanged += DownloadProgressChanged;
  148. await client.DownloadFileTaskAsync(version.sourceUrl, archiveFile);
  149. return archiveFile;
  150. }
  151. catch (Exception e)
  152. {
  153. SystemClose(e.GetType().FullName + "\n\n" + e.Message);
  154. }
  155. }
  156. return "";
  157. }
  158. void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
  159. {
  160. prgProgress.Value = e.ProgressPercentage;
  161. }
  162. /// <summary>
  163. /// Extract the provided archive to our program root
  164. /// It is assumed the archive is a zip file relative to that root (with all necessary sub-folders)
  165. /// </summary>
  166. /// <param name="archive"></param>
  167. protected void ExtractPackage(string archive)
  168. {
  169. using (var fileStream = System.IO.File.OpenRead(archive))
  170. {
  171. using (var zipFile = ZipFile.Read(fileStream))
  172. {
  173. zipFile.ExtractAll(RootPath, ExtractExistingFileAction.OverwriteSilently);
  174. }
  175. }
  176. }
  177. /// <summary>
  178. /// Create a shortcut in the current user's start menu
  179. /// Only do current user to avoid need for admin elevation
  180. /// </summary>
  181. /// <param name="targetExe"></param>
  182. protected void CreateShortcut(string targetExe)
  183. {
  184. // get path to all users start menu
  185. var shell = new WshShell();
  186. var startMenu = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu),"Media Browser");
  187. if (!Directory.Exists(startMenu)) Directory.CreateDirectory(startMenu);
  188. var product = (IWshShortcut)shell.CreateShortcut(Path.Combine(startMenu, FriendlyName+".lnk"));
  189. product.TargetPath = targetExe;
  190. product.Description = "Run " + FriendlyName;
  191. product.Save();
  192. var uninstall = (IWshShortcut)shell.CreateShortcut(Path.Combine(startMenu, "Uninstall " + FriendlyName + ".lnk"));
  193. uninstall.TargetPath = Path.Combine(Path.GetDirectoryName(targetExe),"MediaBrowser.Uninstaller.exe");
  194. uninstall.Arguments = (PackageName == "MBServer" ? "server" : "mbt");
  195. uninstall.Description = "Uninstall " + FriendlyName;
  196. uninstall.Save();
  197. }
  198. /// <summary>
  199. /// Prepare a temporary location to download to
  200. /// </summary>
  201. /// <returns>The path to the temporary location</returns>
  202. protected string PrepareTempLocation()
  203. {
  204. ClearTempLocation(TempLocation);
  205. Directory.CreateDirectory(TempLocation);
  206. return TempLocation;
  207. }
  208. /// <summary>
  209. /// Clear out (delete recursively) the supplied temp location
  210. /// </summary>
  211. /// <param name="location"></param>
  212. protected void ClearTempLocation(string location)
  213. {
  214. if (Directory.Exists(location))
  215. {
  216. Directory.Delete(location, true);
  217. }
  218. }
  219. }
  220. }