MainWindow.xaml.cs 12 KB

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