MainWindow.xaml.cs 8.8 KB

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