MainWindow.xaml.cs 11 KB

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