MainWindow.xaml.cs 17 KB

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