MainWindow.xaml.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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. using IWshRuntimeLibrary;
  14. namespace MediaBrowser.Installer
  15. {
  16. /// <summary>
  17. /// Interaction logic for MainWindow.xaml
  18. /// </summary>
  19. public partial class MainWindow : Window
  20. {
  21. protected PackageVersionClass PackageClass = PackageVersionClass.Release;
  22. protected Version PackageVersion = new Version(4,0,0,0);
  23. protected string PackageName = "MBServer";
  24. protected string RootSuffix = "-Server";
  25. protected string TargetExe = "MediaBrowser.ServerApplication.exe";
  26. protected string FriendlyName = "Media Browser Server";
  27. protected string RootPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MediaBrowser-Server");
  28. protected bool SystemClosing = false;
  29. protected string TempLocation = Path.Combine(Path.GetTempPath(), "MediaBrowser");
  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. ClearTempLocation(TempLocation);
  47. base.OnClosing(e);
  48. }
  49. protected void SystemClose(string message = null)
  50. {
  51. if (message != null)
  52. {
  53. MessageBox.Show(message, "Error");
  54. }
  55. SystemClosing = true;
  56. this.Close();
  57. }
  58. protected void GetArgs()
  59. {
  60. var product = ConfigurationManager.AppSettings["product"] ?? "server";
  61. PackageClass = (PackageVersionClass) Enum.Parse(typeof (PackageVersionClass), ConfigurationManager.AppSettings["class"] ?? "Release");
  62. switch (product.ToLower())
  63. {
  64. case "mbt":
  65. PackageName = "MBTheater";
  66. RootSuffix = "-UI";
  67. TargetExe = "MediaBrowser.UI.exe";
  68. FriendlyName = "Media Browser Theater";
  69. break;
  70. default:
  71. PackageName = "MBServer";
  72. RootSuffix = "-Server";
  73. TargetExe = "MediaBrowser.ServerApplication.exe";
  74. FriendlyName = "Media Browser Server";
  75. break;
  76. }
  77. RootPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MediaBrowser" + RootSuffix);
  78. }
  79. /// <summary>
  80. /// Execute the install process
  81. /// </summary>
  82. /// <returns></returns>
  83. protected async Task DoInstall()
  84. {
  85. lblStatus.Content = string.Format("Downloading {0}...", FriendlyName);
  86. dlAnimation.StartAnimation();
  87. prgProgress.Value = 0;
  88. prgProgress.Visibility = Visibility.Visible;
  89. // Determine Package version
  90. var version = await GetPackageVersion().ConfigureAwait(false);
  91. lblStatus.Content = string.Format("Downloading {0} (version {1})...", FriendlyName, version.versionStr);
  92. // Download
  93. var archive = await DownloadPackage(version).ConfigureAwait(false);
  94. dlAnimation.StopAnimation();
  95. prgProgress.Visibility = btnCancel.Visibility = Visibility.Hidden;
  96. // Extract
  97. lblStatus.Content = "Extracting Package...";
  98. try
  99. {
  100. ExtractPackage(archive);
  101. }
  102. catch (Exception e)
  103. {
  104. SystemClose("Error Extracting - " + e.GetType().FullName + "\n\n" + e.Message);
  105. }
  106. // Create shortcut
  107. var fullPath = Path.Combine(RootPath, "System", TargetExe);
  108. try
  109. {
  110. CreateShortcut(fullPath);
  111. }
  112. catch (Exception e)
  113. {
  114. SystemClose("Error Creating Shortcut - "+e.GetType().FullName+"\n\n"+e.Message);
  115. }
  116. // And run
  117. try
  118. {
  119. Process.Start(fullPath);
  120. }
  121. catch (Exception e)
  122. {
  123. SystemClose("Error Executing - "+fullPath+ " "+e.GetType().FullName+"\n\n"+e.Message);
  124. }
  125. SystemClose();
  126. }
  127. protected async Task<PackageVersionInfo> GetPackageVersion()
  128. {
  129. using (var client = new WebClient())
  130. {
  131. try
  132. {
  133. // get the package information for the server
  134. var json = await client.DownloadStringTaskAsync("http://www.mb3admin.com/admin/service/package/retrieveAll?name=" + PackageName).ConfigureAwait(false);
  135. var packages = JsonSerializer.DeserializeFromString<List<PackageInfo>>(json);
  136. var version = packages[0].versions.Where(v => v.classification == PackageClass).OrderByDescending(v => v.version).FirstOrDefault(v => v.version <= PackageVersion);
  137. if (version == null)
  138. {
  139. SystemClose("Could not locate download package. Aborting.");
  140. return null;
  141. }
  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).ConfigureAwait(false);
  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 CreateShortcut(string targetExe)
  198. {
  199. // get path to all users start menu
  200. var shell = new WshShell();
  201. var startMenu = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu),"Media Browser");
  202. if (!Directory.Exists(startMenu)) Directory.CreateDirectory(startMenu);
  203. var product = (IWshShortcut)shell.CreateShortcut(Path.Combine(startMenu, FriendlyName+".lnk"));
  204. product.TargetPath = targetExe;
  205. product.Description = "Run " + FriendlyName;
  206. product.Save();
  207. var uninstall = (IWshShortcut)shell.CreateShortcut(Path.Combine(startMenu, "Uninstall " + FriendlyName + ".lnk"));
  208. uninstall.TargetPath = Path.Combine(Path.GetDirectoryName(targetExe),"MediaBrowser.Uninstaller.exe");
  209. uninstall.Arguments = (PackageName == "MBServer" ? "server" : "mbt");
  210. uninstall.Description = "Uninstall " + FriendlyName;
  211. uninstall.Save();
  212. }
  213. /// <summary>
  214. /// Prepare a temporary location to download to
  215. /// </summary>
  216. /// <returns>The path to the temporary location</returns>
  217. protected string PrepareTempLocation()
  218. {
  219. ClearTempLocation(TempLocation);
  220. Directory.CreateDirectory(TempLocation);
  221. return TempLocation;
  222. }
  223. /// <summary>
  224. /// Clear out (delete recursively) the supplied temp location
  225. /// </summary>
  226. /// <param name="location"></param>
  227. protected void ClearTempLocation(string location)
  228. {
  229. if (Directory.Exists(location))
  230. {
  231. Directory.Delete(location, true);
  232. }
  233. }
  234. }
  235. }