MainWindow.xaml.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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. // Install Pismo
  226. try
  227. {
  228. InstallPismo();
  229. }
  230. catch (Exception e)
  231. {
  232. SystemClose("Error Installing Pismo - "+e.GetType().FullName+"\n\n"+e.Message);
  233. return;
  234. }
  235. // And run
  236. try
  237. {
  238. Process.Start(fullPath);
  239. }
  240. catch (Exception e)
  241. {
  242. SystemClose("Error Executing - "+fullPath+ " "+e.GetType().FullName+"\n\n"+e.Message);
  243. return;
  244. }
  245. SystemClose();
  246. }
  247. private void InstallPismo()
  248. {
  249. // Kick off the Pismo installer and wait for it to end
  250. var pismo = new Process();
  251. pismo.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  252. pismo.StartInfo.FileName = Path.Combine(RootPath, "Pismo", "pfminst.exe");
  253. pismo.StartInfo.Arguments = "install";
  254. pismo.Start();
  255. pismo.WaitForExit();
  256. }
  257. protected async Task<PackageVersionInfo> GetPackageVersion()
  258. {
  259. try
  260. {
  261. // get the package information for the server
  262. var json = await MainClient.DownloadStringTaskAsync("http://www.mb3admin.com/admin/service/package/retrieveAll?name=" + PackageName);
  263. var packages = JsonSerializer.DeserializeFromString<List<PackageInfo>>(json);
  264. var version = packages[0].versions.Where(v => v.classification <= PackageClass).OrderByDescending(v => v.version).FirstOrDefault(v => v.version <= RequestedVersion);
  265. if (version == null)
  266. {
  267. SystemClose("Could not locate download package. Aborting.");
  268. return null;
  269. }
  270. return version;
  271. }
  272. catch (Exception e)
  273. {
  274. SystemClose(e.GetType().FullName + "\n\n" + e.Message);
  275. }
  276. return null;
  277. }
  278. /// <summary>
  279. /// Download our specified package to an archive in a temp location
  280. /// </summary>
  281. /// <returns>The fully qualified name of the downloaded package</returns>
  282. protected async Task<string> DownloadPackage(PackageVersionInfo version)
  283. {
  284. try
  285. {
  286. var archiveFile = Path.Combine(PrepareTempLocation(), version.targetFilename);
  287. // setup download progress and download the package
  288. MainClient.DownloadProgressChanged += DownloadProgressChanged;
  289. try
  290. {
  291. await MainClient.DownloadFileTaskAsync(version.sourceUrl, archiveFile);
  292. }
  293. catch (WebException e)
  294. {
  295. if (e.Status == WebExceptionStatus.RequestCanceled)
  296. {
  297. return null;
  298. }
  299. throw;
  300. }
  301. return archiveFile;
  302. }
  303. catch (Exception e)
  304. {
  305. SystemClose(e.GetType().FullName + "\n\n" + e.Message);
  306. }
  307. return "";
  308. }
  309. void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
  310. {
  311. rectProgress.Width = (this.Width * e.ProgressPercentage)/100f;
  312. }
  313. /// <summary>
  314. /// Extract the provided archive to our program root
  315. /// It is assumed the archive is a zip file relative to that root (with all necessary sub-folders)
  316. /// </summary>
  317. /// <param name="archive"></param>
  318. protected void ExtractPackage(string archive)
  319. {
  320. // Delete old content of system
  321. var systemDir = Path.Combine(RootPath, "system");
  322. if (Directory.Exists(systemDir))
  323. {
  324. try
  325. {
  326. Directory.Delete(systemDir, true);
  327. }
  328. catch
  329. {
  330. // we tried...
  331. }
  332. }
  333. // And extract
  334. using (var fileStream = File.OpenRead(archive))
  335. {
  336. using (var zipFile = ZipFile.Read(fileStream))
  337. {
  338. zipFile.ExtractAll(RootPath, ExtractExistingFileAction.OverwriteSilently);
  339. }
  340. }
  341. }
  342. /// <summary>
  343. /// Create a shortcut in the current user's start menu
  344. /// Only do current user to avoid need for admin elevation
  345. /// </summary>
  346. /// <param name="targetExe"></param>
  347. protected void CreateShortcuts(string targetExe)
  348. {
  349. // get path to all users start menu
  350. var startMenu = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu),"Media Browser 3");
  351. if (!Directory.Exists(startMenu)) Directory.CreateDirectory(startMenu);
  352. var product = new ShellShortcut(Path.Combine(startMenu, FriendlyName+".lnk")) {Path = targetExe, Description = "Run " + FriendlyName};
  353. product.Save();
  354. if (PackageName == "MBServer")
  355. {
  356. var path = Path.Combine(startMenu, "MB Dashboard.lnk");
  357. var dashboard = new ShellShortcut(path)
  358. {Path = @"http://localhost:8096/mediabrowser/dashboard/dashboard.html", Description = "Open the Media Browser Server Dashboard (configuration)"};
  359. dashboard.Save();
  360. }
  361. CreateUninstaller(Path.Combine(Path.GetDirectoryName(targetExe) ?? "", "MediaBrowser.Uninstaller.exe")+ " "+ (PackageName == "MBServer" ? "server" : "mbt"), targetExe);
  362. }
  363. /// <summary>
  364. /// Create uninstall entry in add/remove
  365. /// </summary>
  366. /// <param name="uninstallPath"></param>
  367. /// <param name="targetExe"></param>
  368. private void CreateUninstaller(string uninstallPath, string targetExe)
  369. {
  370. using (var parent = Registry.CurrentUser.OpenSubKey(
  371. @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", true))
  372. {
  373. if (parent == null)
  374. {
  375. MessageBox.Show("Uninstall registry key not found.");
  376. return;
  377. }
  378. try
  379. {
  380. RegistryKey key = null;
  381. try
  382. {
  383. const string guidText = "{4E76DB4E-1BB9-4A7B-860C-7940779CF7A0}";
  384. key = parent.OpenSubKey(guidText, true) ??
  385. parent.CreateSubKey(guidText);
  386. if (key == null)
  387. {
  388. MessageBox.Show(String.Format("Unable to create uninstaller entry'{0}\\{1}'", @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", guidText));
  389. return;
  390. }
  391. key.SetValue("DisplayName", FriendlyName);
  392. key.SetValue("ApplicationVersion", ActualVersion);
  393. key.SetValue("Publisher", "Media Browser Team");
  394. key.SetValue("DisplayIcon", targetExe);
  395. key.SetValue("DisplayVersion", ActualVersion.ToString(2));
  396. key.SetValue("URLInfoAbout", "http://www.mediabrowser3.com");
  397. key.SetValue("Contact", "http://community.mediabrowser.tv");
  398. key.SetValue("InstallDate", DateTime.Now.ToString("yyyyMMdd"));
  399. key.SetValue("UninstallString", uninstallPath);
  400. }
  401. finally
  402. {
  403. if (key != null)
  404. {
  405. key.Close();
  406. }
  407. }
  408. }
  409. catch (Exception ex)
  410. {
  411. MessageBox.Show("An error occurred writing uninstall information to the registry.");
  412. }
  413. }
  414. }
  415. /// <summary>
  416. /// Prepare a temporary location to download to
  417. /// </summary>
  418. /// <returns>The path to the temporary location</returns>
  419. protected string PrepareTempLocation()
  420. {
  421. ClearTempLocation(TempLocation);
  422. Directory.CreateDirectory(TempLocation);
  423. return TempLocation;
  424. }
  425. /// <summary>
  426. /// Clear out (delete recursively) the supplied temp location
  427. /// </summary>
  428. /// <param name="location"></param>
  429. protected void ClearTempLocation(string location)
  430. {
  431. if (Directory.Exists(location))
  432. {
  433. Directory.Delete(location, true);
  434. }
  435. }
  436. }
  437. }