MainWindow.xaml.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Net;
  7. using System.Threading.Tasks;
  8. using System.Windows;
  9. using System.Linq;
  10. using Ionic.Zip;
  11. using MediaBrowser.Installer.Code;
  12. using ServiceStack.Text;
  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(4,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. protected WebClient MainClient = new WebClient();
  30. public MainWindow()
  31. {
  32. GetArgs();
  33. InitializeComponent();
  34. DoInstall();
  35. }
  36. private void btnCancel_Click(object sender, RoutedEventArgs e)
  37. {
  38. this.Close();
  39. }
  40. protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
  41. {
  42. if (!SystemClosing && MessageBox.Show("Cancel Installation - Are you sure?", "Cancel", MessageBoxButton.YesNo) == MessageBoxResult.No)
  43. {
  44. e.Cancel = true;
  45. }
  46. if (MainClient.IsBusy)
  47. {
  48. MainClient.CancelAsync();
  49. while (MainClient.IsBusy)
  50. {
  51. // wait to finish
  52. }
  53. }
  54. MainClient.Dispose();
  55. ClearTempLocation(TempLocation);
  56. base.OnClosing(e);
  57. }
  58. protected void SystemClose(string message = null)
  59. {
  60. if (message != null)
  61. {
  62. MessageBox.Show(message, "Error");
  63. }
  64. SystemClosing = true;
  65. this.Close();
  66. }
  67. protected void GetArgs()
  68. {
  69. var product = ConfigurationManager.AppSettings["product"] ?? "server";
  70. PackageClass = (PackageVersionClass) Enum.Parse(typeof (PackageVersionClass), ConfigurationManager.AppSettings["class"] ?? "Release");
  71. switch (product.ToLower())
  72. {
  73. case "mbt":
  74. PackageName = "MBTheater";
  75. RootSuffix = "-UI";
  76. TargetExe = "MediaBrowser.UI.exe";
  77. FriendlyName = "Media Browser Theater";
  78. break;
  79. default:
  80. PackageName = "MBServer";
  81. RootSuffix = "-Server";
  82. TargetExe = "MediaBrowser.ServerApplication.exe";
  83. FriendlyName = "Media Browser Server";
  84. break;
  85. }
  86. RootPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MediaBrowser" + RootSuffix);
  87. }
  88. /// <summary>
  89. /// Execute the install process
  90. /// </summary>
  91. /// <returns></returns>
  92. protected async Task DoInstall()
  93. {
  94. lblStatus.Content = string.Format("Downloading {0}...", FriendlyName);
  95. dlAnimation.StartAnimation();
  96. prgProgress.Value = 0;
  97. prgProgress.Visibility = Visibility.Visible;
  98. // Determine Package version
  99. var version = await GetPackageVersion();
  100. lblStatus.Content = string.Format("Downloading {0} (version {1})...", FriendlyName, version.versionStr);
  101. // Now try and shut down the server if that is what we are installing and it is running
  102. if (PackageName == "MBServer" && Process.GetProcessesByName("mediabrowser.serverapplication").Length != 0)
  103. {
  104. using (var client = new WebClient())
  105. {
  106. try
  107. {
  108. client.UploadString("http://localhost:8096/mediabrowser/System/Shutdown", "");
  109. }
  110. catch (WebException e)
  111. {
  112. if (e.GetStatus() == HttpStatusCode.NotFound || e.Message.StartsWith("Unable to connect",StringComparison.OrdinalIgnoreCase)) return; // just wasn't running
  113. MessageBox.Show("Error shutting down server. Please be sure it is not running before hitting OK.\n\n" + e.GetStatus() + "\n\n" + e.Message);
  114. }
  115. }
  116. }
  117. else
  118. {
  119. if (PackageName == "MBTheater")
  120. {
  121. // Uninstalling MBT - shut it down if it is running
  122. var processes = Process.GetProcessesByName("mediabrowser.ui");
  123. if (processes.Length > 0)
  124. {
  125. try
  126. {
  127. processes[0].CloseMainWindow();
  128. }
  129. catch (Exception ex)
  130. {
  131. MessageBox.Show("Unable to shutdown Media Browser Theater. Please ensure it is not running before hitting OK.\n\n" + ex.Message, "Error");
  132. }
  133. }
  134. }
  135. }
  136. // Download
  137. var archive = await DownloadPackage(version);
  138. dlAnimation.StopAnimation();
  139. prgProgress.Visibility = btnCancel.Visibility = Visibility.Hidden;
  140. if (archive == null) return; //we canceled or had an error that was already reported
  141. // Extract
  142. lblStatus.Content = "Extracting Package...";
  143. try
  144. {
  145. ExtractPackage(archive);
  146. }
  147. catch (Exception e)
  148. {
  149. SystemClose("Error Extracting - " + e.GetType().FullName + "\n\n" + e.Message);
  150. }
  151. // Create shortcut
  152. var fullPath = Path.Combine(RootPath, "System", TargetExe);
  153. try
  154. {
  155. CreateShortcuts(fullPath);
  156. }
  157. catch (Exception e)
  158. {
  159. SystemClose("Error Creating Shortcut - "+e.GetType().FullName+"\n\n"+e.Message);
  160. }
  161. // And run
  162. try
  163. {
  164. Process.Start(fullPath);
  165. }
  166. catch (Exception e)
  167. {
  168. SystemClose("Error Executing - "+fullPath+ " "+e.GetType().FullName+"\n\n"+e.Message);
  169. }
  170. SystemClose();
  171. }
  172. protected async Task<PackageVersionInfo> GetPackageVersion()
  173. {
  174. try
  175. {
  176. // get the package information for the server
  177. var json = await MainClient.DownloadStringTaskAsync("http://www.mb3admin.com/admin/service/package/retrieveAll?name=" + PackageName);
  178. var packages = JsonSerializer.DeserializeFromString<List<PackageInfo>>(json);
  179. var version = packages[0].versions.Where(v => v.classification <= PackageClass).OrderByDescending(v => v.version).FirstOrDefault(v => v.version <= PackageVersion);
  180. if (version == null)
  181. {
  182. SystemClose("Could not locate download package. Aborting.");
  183. return null;
  184. }
  185. return version;
  186. }
  187. catch (Exception e)
  188. {
  189. SystemClose(e.GetType().FullName + "\n\n" + e.Message);
  190. }
  191. return null;
  192. }
  193. /// <summary>
  194. /// Download our specified package to an archive in a temp location
  195. /// </summary>
  196. /// <returns>The fully qualified name of the downloaded package</returns>
  197. protected async Task<string> DownloadPackage(PackageVersionInfo version)
  198. {
  199. try
  200. {
  201. var archiveFile = Path.Combine(PrepareTempLocation(), version.targetFilename);
  202. // setup download progress and download the package
  203. MainClient.DownloadProgressChanged += DownloadProgressChanged;
  204. try
  205. {
  206. await MainClient.DownloadFileTaskAsync(version.sourceUrl, archiveFile);
  207. }
  208. catch (WebException e)
  209. {
  210. if (e.Status == WebExceptionStatus.RequestCanceled)
  211. {
  212. return null;
  213. }
  214. throw;
  215. }
  216. return archiveFile;
  217. }
  218. catch (Exception e)
  219. {
  220. SystemClose(e.GetType().FullName + "\n\n" + e.Message);
  221. }
  222. return "";
  223. }
  224. void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
  225. {
  226. prgProgress.Value = e.ProgressPercentage;
  227. }
  228. /// <summary>
  229. /// Extract the provided archive to our program root
  230. /// It is assumed the archive is a zip file relative to that root (with all necessary sub-folders)
  231. /// </summary>
  232. /// <param name="archive"></param>
  233. protected void ExtractPackage(string archive)
  234. {
  235. using (var fileStream = System.IO.File.OpenRead(archive))
  236. {
  237. using (var zipFile = ZipFile.Read(fileStream))
  238. {
  239. zipFile.ExtractAll(RootPath, ExtractExistingFileAction.OverwriteSilently);
  240. }
  241. }
  242. }
  243. /// <summary>
  244. /// Create a shortcut in the current user's start menu
  245. /// Only do current user to avoid need for admin elevation
  246. /// </summary>
  247. /// <param name="targetExe"></param>
  248. protected void CreateShortcuts(string targetExe)
  249. {
  250. // get path to all users start menu
  251. var startMenu = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu),"Media Browser 3");
  252. if (!Directory.Exists(startMenu)) Directory.CreateDirectory(startMenu);
  253. var product = new ShellShortcut(Path.Combine(startMenu, FriendlyName+".lnk")) {Path = targetExe, Description = "Run " + FriendlyName};
  254. product.Save();
  255. if (PackageName == "MBServer")
  256. {
  257. var path = Path.Combine(startMenu, "MB Dashboard.lnk");
  258. var dashboard = new ShellShortcut(path)
  259. {Path = @"http://localhost:8096/mediabrowser/dashboard/dashboard.html", Description = "Open the Media Browser Server Dashboard (configuration)"};
  260. dashboard.Save();
  261. }
  262. var uninstall = new ShellShortcut(Path.Combine(startMenu, "Uninstall " + FriendlyName + ".lnk"))
  263. {Path = Path.Combine(Path.GetDirectoryName(targetExe), "MediaBrowser.Uninstaller.exe"), Arguments = (PackageName == "MBServer" ? "server" : "mbt"), Description = "Uninstall " + FriendlyName};
  264. uninstall.Save();
  265. }
  266. /// <summary>
  267. /// Prepare a temporary location to download to
  268. /// </summary>
  269. /// <returns>The path to the temporary location</returns>
  270. protected string PrepareTempLocation()
  271. {
  272. ClearTempLocation(TempLocation);
  273. Directory.CreateDirectory(TempLocation);
  274. return TempLocation;
  275. }
  276. /// <summary>
  277. /// Clear out (delete recursively) the supplied temp location
  278. /// </summary>
  279. /// <param name="location"></param>
  280. protected void ClearTempLocation(string location)
  281. {
  282. if (Directory.Exists(location))
  283. {
  284. Directory.Delete(location, true);
  285. }
  286. }
  287. }
  288. }