MainWindow.xaml.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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 Archive = null;
  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. protected WebClient MainClient = new WebClient();
  31. public MainWindow()
  32. {
  33. GetArgs();
  34. InitializeComponent();
  35. DoInstall(Archive);
  36. }
  37. private void btnCancel_Click(object sender, RoutedEventArgs e)
  38. {
  39. this.Close();
  40. }
  41. protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
  42. {
  43. if (!SystemClosing && MessageBox.Show("Cancel Installation - Are you sure?", "Cancel", MessageBoxButton.YesNo) == MessageBoxResult.No)
  44. {
  45. e.Cancel = true;
  46. }
  47. if (MainClient.IsBusy)
  48. {
  49. MainClient.CancelAsync();
  50. while (MainClient.IsBusy)
  51. {
  52. // wait to finish
  53. }
  54. }
  55. MainClient.Dispose();
  56. ClearTempLocation(TempLocation);
  57. base.OnClosing(e);
  58. }
  59. protected void SystemClose(string message = null)
  60. {
  61. if (message != null)
  62. {
  63. MessageBox.Show(message, "Error");
  64. }
  65. SystemClosing = true;
  66. this.Close();
  67. }
  68. protected void GetArgs()
  69. {
  70. //cmd line args should be name/value pairs like: product=server archive="c:\.." caller=34552
  71. var cmdArgs = Environment.GetCommandLineArgs();
  72. var args = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  73. foreach (var pair in cmdArgs)
  74. {
  75. var nameValue = pair.Split('=');
  76. if (nameValue.Length == 2)
  77. {
  78. args[nameValue[0]] = nameValue[1];
  79. }
  80. }
  81. Archive = args.GetValueOrDefault("archive", null);
  82. var product = args.GetValueOrDefault("product", null) ?? ConfigurationManager.AppSettings["product"] ?? "server";
  83. PackageClass = (PackageVersionClass) Enum.Parse(typeof (PackageVersionClass), args.GetValueOrDefault("class", null) ?? ConfigurationManager.AppSettings["class"] ?? "Release");
  84. PackageVersion = new Version(args.GetValueOrDefault("version", "4.0"));
  85. var callerId = args.GetValueOrDefault("caller", null);
  86. if (callerId != null)
  87. {
  88. // Wait for our caller to exit
  89. try
  90. {
  91. var process = Process.GetProcessById(Convert.ToInt32(callerId));
  92. process.WaitForExit();
  93. }
  94. catch (ArgumentException)
  95. {
  96. // wasn't running
  97. }
  98. }
  99. switch (product.ToLower())
  100. {
  101. case "mbt":
  102. PackageName = "MBTheater";
  103. RootSuffix = "-UI";
  104. TargetExe = "MediaBrowser.UI.exe";
  105. FriendlyName = "Media Browser Theater";
  106. break;
  107. default:
  108. PackageName = "MBServer";
  109. RootSuffix = "-Server";
  110. TargetExe = "MediaBrowser.ServerApplication.exe";
  111. FriendlyName = "Media Browser Server";
  112. break;
  113. }
  114. RootPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MediaBrowser" + RootSuffix);
  115. }
  116. /// <summary>
  117. /// Execute the install process
  118. /// </summary>
  119. /// <returns></returns>
  120. protected async Task DoInstall(string archive)
  121. {
  122. lblStatus.Text = string.Format("Installing {0}...", FriendlyName);
  123. // Determine Package version
  124. var version = await GetPackageVersion();
  125. // Now try and shut down the server if that is what we are installing and it is running
  126. var procs = Process.GetProcessesByName("mediabrowser.serverapplication");
  127. var server = procs.Length > 0 ? procs[0] : null;
  128. if (PackageName == "MBServer" && server != null)
  129. {
  130. lblStatus.Text = "Shutting Down Media Browser Server...";
  131. using (var client = new WebClient())
  132. {
  133. try
  134. {
  135. client.UploadString("http://localhost:8096/mediabrowser/System/Shutdown", "");
  136. try
  137. {
  138. server.WaitForExit();
  139. }
  140. catch (ArgumentException)
  141. {
  142. // already gone
  143. }
  144. }
  145. catch (WebException e)
  146. {
  147. if (e.GetStatus() == HttpStatusCode.NotFound || e.Message.StartsWith("Unable to connect",StringComparison.OrdinalIgnoreCase)) return; // just wasn't running
  148. MessageBox.Show("Error shutting down server. Please be sure it is not running before hitting OK.\n\n" + e.GetStatus() + "\n\n" + e.Message);
  149. }
  150. }
  151. }
  152. else
  153. {
  154. if (PackageName == "MBTheater")
  155. {
  156. // Uninstalling MBT - shut it down if it is running
  157. var processes = Process.GetProcessesByName("mediabrowser.ui");
  158. if (processes.Length > 0)
  159. {
  160. lblStatus.Text = "Shutting Down Media Browser Theater...";
  161. try
  162. {
  163. processes[0].Kill();
  164. }
  165. catch (Exception ex)
  166. {
  167. MessageBox.Show("Unable to shutdown Media Browser Theater. Please ensure it is not running before hitting OK.\n\n" + ex.Message, "Error");
  168. }
  169. }
  170. }
  171. }
  172. // Download if we don't already have it
  173. if (archive == null)
  174. {
  175. lblStatus.Text = string.Format("Downloading {0} (version {1})...", FriendlyName, version.versionStr);
  176. try
  177. {
  178. archive = await DownloadPackage(version);
  179. }
  180. catch (Exception e)
  181. {
  182. SystemClose("Error Downloading Package - " + e.GetType().FullName + "\n\n" + e.Message);
  183. }
  184. }
  185. if (archive == null) return; //we canceled or had an error that was already reported
  186. // Extract
  187. lblStatus.Text = "Extracting Package...";
  188. try
  189. {
  190. ExtractPackage(archive);
  191. }
  192. catch (Exception e)
  193. {
  194. SystemClose("Error Extracting - " + e.GetType().FullName + "\n\n" + e.Message);
  195. }
  196. // Create shortcut
  197. var fullPath = Path.Combine(RootPath, "System", TargetExe);
  198. try
  199. {
  200. CreateShortcuts(fullPath);
  201. }
  202. catch (Exception e)
  203. {
  204. SystemClose("Error Creating Shortcut - "+e.GetType().FullName+"\n\n"+e.Message);
  205. }
  206. // And run
  207. try
  208. {
  209. Process.Start(fullPath);
  210. }
  211. catch (Exception e)
  212. {
  213. SystemClose("Error Executing - "+fullPath+ " "+e.GetType().FullName+"\n\n"+e.Message);
  214. }
  215. SystemClose();
  216. }
  217. protected async Task<PackageVersionInfo> GetPackageVersion()
  218. {
  219. try
  220. {
  221. // get the package information for the server
  222. var json = await MainClient.DownloadStringTaskAsync("http://www.mb3admin.com/admin/service/package/retrieveAll?name=" + PackageName);
  223. var packages = JsonSerializer.DeserializeFromString<List<PackageInfo>>(json);
  224. var version = packages[0].versions.Where(v => v.classification <= PackageClass).OrderByDescending(v => v.version).FirstOrDefault(v => v.version <= PackageVersion);
  225. if (version == null)
  226. {
  227. SystemClose("Could not locate download package. Aborting.");
  228. return null;
  229. }
  230. return version;
  231. }
  232. catch (Exception e)
  233. {
  234. SystemClose(e.GetType().FullName + "\n\n" + e.Message);
  235. }
  236. return null;
  237. }
  238. /// <summary>
  239. /// Download our specified package to an archive in a temp location
  240. /// </summary>
  241. /// <returns>The fully qualified name of the downloaded package</returns>
  242. protected async Task<string> DownloadPackage(PackageVersionInfo version)
  243. {
  244. try
  245. {
  246. var archiveFile = Path.Combine(PrepareTempLocation(), version.targetFilename);
  247. // setup download progress and download the package
  248. MainClient.DownloadProgressChanged += DownloadProgressChanged;
  249. try
  250. {
  251. await MainClient.DownloadFileTaskAsync(version.sourceUrl, archiveFile);
  252. }
  253. catch (WebException e)
  254. {
  255. if (e.Status == WebExceptionStatus.RequestCanceled)
  256. {
  257. return null;
  258. }
  259. throw;
  260. }
  261. return archiveFile;
  262. }
  263. catch (Exception e)
  264. {
  265. SystemClose(e.GetType().FullName + "\n\n" + e.Message);
  266. }
  267. return "";
  268. }
  269. void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
  270. {
  271. rectProgress.Width = (this.Width * e.ProgressPercentage)/100f;
  272. }
  273. /// <summary>
  274. /// Extract the provided archive to our program root
  275. /// It is assumed the archive is a zip file relative to that root (with all necessary sub-folders)
  276. /// </summary>
  277. /// <param name="archive"></param>
  278. protected void ExtractPackage(string archive)
  279. {
  280. // Delete old content of system
  281. var systemDir = Path.Combine(RootPath, "system");
  282. if (Directory.Exists(systemDir))
  283. {
  284. try
  285. {
  286. Directory.Delete(systemDir, true);
  287. }
  288. catch
  289. {
  290. // we tried...
  291. }
  292. }
  293. // And extract
  294. using (var fileStream = File.OpenRead(archive))
  295. {
  296. using (var zipFile = ZipFile.Read(fileStream))
  297. {
  298. zipFile.ExtractAll(RootPath, ExtractExistingFileAction.OverwriteSilently);
  299. }
  300. }
  301. }
  302. /// <summary>
  303. /// Create a shortcut in the current user's start menu
  304. /// Only do current user to avoid need for admin elevation
  305. /// </summary>
  306. /// <param name="targetExe"></param>
  307. protected void CreateShortcuts(string targetExe)
  308. {
  309. // get path to all users start menu
  310. var startMenu = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu),"Media Browser 3");
  311. if (!Directory.Exists(startMenu)) Directory.CreateDirectory(startMenu);
  312. var product = new ShellShortcut(Path.Combine(startMenu, FriendlyName+".lnk")) {Path = targetExe, Description = "Run " + FriendlyName};
  313. product.Save();
  314. if (PackageName == "MBServer")
  315. {
  316. var path = Path.Combine(startMenu, "MB Dashboard.lnk");
  317. var dashboard = new ShellShortcut(path)
  318. {Path = @"http://localhost:8096/mediabrowser/dashboard/dashboard.html", Description = "Open the Media Browser Server Dashboard (configuration)"};
  319. dashboard.Save();
  320. }
  321. var uninstall = new ShellShortcut(Path.Combine(startMenu, "Uninstall " + FriendlyName + ".lnk"))
  322. {Path = Path.Combine(Path.GetDirectoryName(targetExe), "MediaBrowser.Uninstaller.exe"), Arguments = (PackageName == "MBServer" ? "server" : "mbt"), Description = "Uninstall " + FriendlyName};
  323. uninstall.Save();
  324. }
  325. /// <summary>
  326. /// Prepare a temporary location to download to
  327. /// </summary>
  328. /// <returns>The path to the temporary location</returns>
  329. protected string PrepareTempLocation()
  330. {
  331. ClearTempLocation(TempLocation);
  332. Directory.CreateDirectory(TempLocation);
  333. return TempLocation;
  334. }
  335. /// <summary>
  336. /// Clear out (delete recursively) the supplied temp location
  337. /// </summary>
  338. /// <param name="location"></param>
  339. protected void ClearTempLocation(string location)
  340. {
  341. if (Directory.Exists(location))
  342. {
  343. Directory.Delete(location, true);
  344. }
  345. }
  346. }
  347. }