MainWindow.xaml.cs 18 KB

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