MainWindow.xaml.cs 12 KB

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