MainWindow.xaml.cs 11 KB

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