MainWindow.xaml.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Net;
  6. using System.Threading.Tasks;
  7. using System.Windows;
  8. using System.Web;
  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(10,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 args = AppDomain.CurrentDomain.SetupInformation.ActivationArguments;
  61. if (args == null || args.ActivationData == null || args.ActivationData.Length <= 0) return;
  62. var url = new Uri(args.ActivationData[0], UriKind.Absolute);
  63. var parameters = HttpUtility.ParseQueryString(url.Query);
  64. // fill in our arguments if there
  65. PackageName = parameters["package"] ?? "MBServer";
  66. PackageClass = (PackageVersionClass)Enum.Parse(typeof(PackageVersionClass), parameters["class"] ?? "Release");
  67. PackageVersion = new Version(parameters["version"].ValueOrDefault("10.0.0.0"));
  68. RootSuffix = parameters["suffix"] ?? "-Server";
  69. TargetExe = parameters["target"] ?? "MediaBrowser.ServerApplication.exe";
  70. FriendlyName = parameters["name"] ?? PackageName;
  71. RootPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MediaBrowser" + RootSuffix);
  72. }
  73. /// <summary>
  74. /// Execute the install process
  75. /// </summary>
  76. /// <returns></returns>
  77. protected async Task DoInstall()
  78. {
  79. lblStatus.Content = "Downloading "+FriendlyName+"...";
  80. dlAnimation.StartAnimation();
  81. prgProgress.Value = 0;
  82. prgProgress.Visibility = Visibility.Visible;
  83. // Download
  84. var archive = await DownloadPackage();
  85. dlAnimation.StopAnimation();
  86. prgProgress.Visibility = btnCancel.Visibility = Visibility.Hidden;
  87. // Extract
  88. lblStatus.Content = "Extracting Package...";
  89. try
  90. {
  91. ExtractPackage(archive);
  92. }
  93. catch (Exception e)
  94. {
  95. SystemClose("Error Extracting - " + e.GetType().FullName + "\n\n" + e.Message);
  96. }
  97. // Create shortcut
  98. var fullPath = Path.Combine(RootPath, "System", TargetExe);
  99. try
  100. {
  101. CreateShortcut(fullPath);
  102. }
  103. catch (Exception e)
  104. {
  105. SystemClose("Error Creating Shortcut - "+e.GetType().FullName+"\n\n"+e.Message);
  106. }
  107. // And run
  108. try
  109. {
  110. Process.Start(fullPath);
  111. }
  112. catch (Exception e)
  113. {
  114. SystemClose("Error Executing - "+fullPath+ " "+e.GetType().FullName+"\n\n"+e.Message);
  115. }
  116. SystemClose();
  117. }
  118. /// <summary>
  119. /// Download our specified package to an archive in a temp location
  120. /// </summary>
  121. /// <returns>The fully qualified name of the downloaded package</returns>
  122. protected async Task<string> DownloadPackage()
  123. {
  124. using (var client = new WebClient())
  125. {
  126. try
  127. {
  128. // get the package information for the server
  129. var json = await client.DownloadStringTaskAsync("http://www.mb3admin.com/admin/service/package/retrieveAll?name="+PackageName);
  130. var packages = JsonSerializer.DeserializeFromString<List<PackageInfo>>(json);
  131. var version = packages[0].versions.Where(v => v.classification == PackageClass).OrderByDescending(v => v.version).FirstOrDefault(v => v.version <= PackageVersion);
  132. if (version == null)
  133. {
  134. SystemClose("Could not locate download package. Aborting.");
  135. return null;
  136. }
  137. var archiveFile = Path.Combine(PrepareTempLocation(), version.targetFilename);
  138. // setup download progress and download the package
  139. client.DownloadProgressChanged += DownloadProgressChanged;
  140. await client.DownloadFileTaskAsync(version.sourceUrl, archiveFile);
  141. return archiveFile;
  142. }
  143. catch (Exception e)
  144. {
  145. SystemClose(e.GetType().FullName + "\n\n" + e.Message);
  146. }
  147. }
  148. return "";
  149. }
  150. void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
  151. {
  152. prgProgress.Value = e.ProgressPercentage;
  153. }
  154. /// <summary>
  155. /// Extract the provided archive to our program root
  156. /// It is assumed the archive is a zip file relative to that root (with all necessary sub-folders)
  157. /// </summary>
  158. /// <param name="archive"></param>
  159. protected void ExtractPackage(string archive)
  160. {
  161. using (var fileStream = System.IO.File.OpenRead(archive))
  162. {
  163. using (var zipFile = ZipFile.Read(fileStream))
  164. {
  165. zipFile.ExtractAll(RootPath, ExtractExistingFileAction.OverwriteSilently);
  166. }
  167. }
  168. }
  169. /// <summary>
  170. /// Create a shortcut in the current user's start menu
  171. /// Only do current user to avoid need for admin elevation
  172. /// </summary>
  173. /// <param name="targetExe"></param>
  174. protected void CreateShortcut(string targetExe)
  175. {
  176. // get path to all users start menu
  177. var shell = new WshShell();
  178. var startMenu = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu),"Media Browser");
  179. if (!Directory.Exists(startMenu)) Directory.CreateDirectory(startMenu);
  180. var product = (IWshShortcut)shell.CreateShortcut(Path.Combine(startMenu, FriendlyName+".lnk"));
  181. product.TargetPath = targetExe;
  182. product.Description = "Run " + FriendlyName;
  183. product.Save();
  184. var uninstall = (IWshShortcut)shell.CreateShortcut(Path.Combine(startMenu, "Uninstall " + FriendlyName + ".lnk"));
  185. uninstall.TargetPath = Path.Combine(Path.GetDirectoryName(targetExe),"MediaBrowser.Uninstall.exe "+(PackageName == "MBServer" ? "server" : "mbt"));
  186. uninstall.Description = "Uninstall " + FriendlyName;
  187. uninstall.Save();
  188. }
  189. /// <summary>
  190. /// Prepare a temporary location to download to
  191. /// </summary>
  192. /// <returns>The path to the temporary location</returns>
  193. protected string PrepareTempLocation()
  194. {
  195. ClearTempLocation(TempLocation);
  196. Directory.CreateDirectory(TempLocation);
  197. return TempLocation;
  198. }
  199. /// <summary>
  200. /// Clear out (delete recursively) the supplied temp location
  201. /// </summary>
  202. /// <param name="location"></param>
  203. protected void ClearTempLocation(string location)
  204. {
  205. if (Directory.Exists(location))
  206. {
  207. Directory.Delete(location, true);
  208. }
  209. }
  210. }
  211. }