MainWindow.xaml.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. // Now try and shut down the server if that is what we are installing and it is running
  101. if (PackageName == "MBServer" && Process.GetProcessesByName("mediabrowser.serverapplication").Length != 0)
  102. {
  103. lblStatus.Content = "Shutting Down Media Browser Server...";
  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. lblStatus.Content = "Shutting Down Media Browser Theater...";
  126. try
  127. {
  128. processes[0].Kill();
  129. }
  130. catch (Exception ex)
  131. {
  132. MessageBox.Show("Unable to shutdown Media Browser Theater. Please ensure it is not running before hitting OK.\n\n" + ex.Message, "Error");
  133. }
  134. }
  135. }
  136. }
  137. // Download
  138. lblStatus.Content = string.Format("Downloading {0} (version {1})...", FriendlyName, version.versionStr);
  139. var archive = await DownloadPackage(version);
  140. dlAnimation.StopAnimation();
  141. prgProgress.Visibility = btnCancel.Visibility = Visibility.Hidden;
  142. if (archive == null) return; //we canceled or had an error that was already reported
  143. // Extract
  144. lblStatus.Content = "Extracting Package...";
  145. try
  146. {
  147. ExtractPackage(archive);
  148. }
  149. catch (Exception e)
  150. {
  151. SystemClose("Error Extracting - " + e.GetType().FullName + "\n\n" + e.Message);
  152. }
  153. // Create shortcut
  154. var fullPath = Path.Combine(RootPath, "System", TargetExe);
  155. try
  156. {
  157. CreateShortcuts(fullPath);
  158. }
  159. catch (Exception e)
  160. {
  161. SystemClose("Error Creating Shortcut - "+e.GetType().FullName+"\n\n"+e.Message);
  162. }
  163. // And run
  164. try
  165. {
  166. Process.Start(fullPath);
  167. }
  168. catch (Exception e)
  169. {
  170. SystemClose("Error Executing - "+fullPath+ " "+e.GetType().FullName+"\n\n"+e.Message);
  171. }
  172. SystemClose();
  173. }
  174. protected async Task<PackageVersionInfo> GetPackageVersion()
  175. {
  176. try
  177. {
  178. // get the package information for the server
  179. var json = await MainClient.DownloadStringTaskAsync("http://www.mb3admin.com/admin/service/package/retrieveAll?name=" + PackageName);
  180. var packages = JsonSerializer.DeserializeFromString<List<PackageInfo>>(json);
  181. var version = packages[0].versions.Where(v => v.classification <= PackageClass).OrderByDescending(v => v.version).FirstOrDefault(v => v.version <= PackageVersion);
  182. if (version == null)
  183. {
  184. SystemClose("Could not locate download package. Aborting.");
  185. return null;
  186. }
  187. return version;
  188. }
  189. catch (Exception e)
  190. {
  191. SystemClose(e.GetType().FullName + "\n\n" + e.Message);
  192. }
  193. return null;
  194. }
  195. /// <summary>
  196. /// Download our specified package to an archive in a temp location
  197. /// </summary>
  198. /// <returns>The fully qualified name of the downloaded package</returns>
  199. protected async Task<string> DownloadPackage(PackageVersionInfo version)
  200. {
  201. try
  202. {
  203. var archiveFile = Path.Combine(PrepareTempLocation(), version.targetFilename);
  204. // setup download progress and download the package
  205. MainClient.DownloadProgressChanged += DownloadProgressChanged;
  206. try
  207. {
  208. await MainClient.DownloadFileTaskAsync(version.sourceUrl, archiveFile);
  209. }
  210. catch (WebException e)
  211. {
  212. if (e.Status == WebExceptionStatus.RequestCanceled)
  213. {
  214. return null;
  215. }
  216. throw;
  217. }
  218. return archiveFile;
  219. }
  220. catch (Exception e)
  221. {
  222. SystemClose(e.GetType().FullName + "\n\n" + e.Message);
  223. }
  224. return "";
  225. }
  226. void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
  227. {
  228. prgProgress.Value = e.ProgressPercentage;
  229. }
  230. /// <summary>
  231. /// Extract the provided archive to our program root
  232. /// It is assumed the archive is a zip file relative to that root (with all necessary sub-folders)
  233. /// </summary>
  234. /// <param name="archive"></param>
  235. protected void ExtractPackage(string archive)
  236. {
  237. using (var fileStream = System.IO.File.OpenRead(archive))
  238. {
  239. using (var zipFile = ZipFile.Read(fileStream))
  240. {
  241. zipFile.ExtractAll(RootPath, ExtractExistingFileAction.OverwriteSilently);
  242. }
  243. }
  244. }
  245. /// <summary>
  246. /// Create a shortcut in the current user's start menu
  247. /// Only do current user to avoid need for admin elevation
  248. /// </summary>
  249. /// <param name="targetExe"></param>
  250. protected void CreateShortcuts(string targetExe)
  251. {
  252. // get path to all users start menu
  253. var startMenu = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu),"Media Browser 3");
  254. if (!Directory.Exists(startMenu)) Directory.CreateDirectory(startMenu);
  255. var product = new ShellShortcut(Path.Combine(startMenu, FriendlyName+".lnk")) {Path = targetExe, Description = "Run " + FriendlyName};
  256. product.Save();
  257. if (PackageName == "MBServer")
  258. {
  259. var path = Path.Combine(startMenu, "MB Dashboard.lnk");
  260. var dashboard = new ShellShortcut(path)
  261. {Path = @"http://localhost:8096/mediabrowser/dashboard/dashboard.html", Description = "Open the Media Browser Server Dashboard (configuration)"};
  262. dashboard.Save();
  263. }
  264. var uninstall = new ShellShortcut(Path.Combine(startMenu, "Uninstall " + FriendlyName + ".lnk"))
  265. {Path = Path.Combine(Path.GetDirectoryName(targetExe), "MediaBrowser.Uninstaller.exe"), Arguments = (PackageName == "MBServer" ? "server" : "mbt"), Description = "Uninstall " + FriendlyName};
  266. uninstall.Save();
  267. }
  268. /// <summary>
  269. /// Prepare a temporary location to download to
  270. /// </summary>
  271. /// <returns>The path to the temporary location</returns>
  272. protected string PrepareTempLocation()
  273. {
  274. ClearTempLocation(TempLocation);
  275. Directory.CreateDirectory(TempLocation);
  276. return TempLocation;
  277. }
  278. /// <summary>
  279. /// Clear out (delete recursively) the supplied temp location
  280. /// </summary>
  281. /// <param name="location"></param>
  282. protected void ClearTempLocation(string location)
  283. {
  284. if (Directory.Exists(location))
  285. {
  286. Directory.Delete(location, true);
  287. }
  288. }
  289. }
  290. }