MainWindow.xaml.cs 9.7 KB

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