3 using System.Diagnostics;
\r
5 using NaGet.SubCommands;
\r
6 using System.Xml.Serialization;
\r
8 namespace NaGet.Packages.Install
\r
12 /// ダウンロード・インストール処理をカプセル化するクラス
\r
14 public class Installation
\r
16 private Package installedPackage;
\r
21 public Package InstalledPackage {
\r
22 get { return installedPackage; }
\r
24 installedPackage = value;
\r
26 installerIndex = getPreferInstallerIndex(value);
\r
27 installerFile = getArchiveFilePath();
\r
32 /// (保存される)ーインストーラのファイルのパス
\r
34 private string installerFile;
\r
37 /// インストールが完了されたか否かのフラグ
\r
39 private bool installed = false;
\r
42 /// サイレントインストールを行うか否か
\r
44 private bool silent = false;
\r
47 /// 起動するインストーラーのインデックス番号
\r
49 protected int installerIndex = 0;
\r
52 /// 外部アプリのエラー出力の受信ハンドラ
\r
54 public event EventHandler<NaGet.Utils.AnyDataEventArgs<string>> ErrorDataReceived;
\r
57 /// 外部アプリの標準出力の受信ハンドラ
\r
59 public event EventHandler<NaGet.Utils.AnyDataEventArgs<string>> OutputDataReceived;
\r
64 public Installation()
\r
71 /// <param name="package">インストールするパッケージ</param>
\r
72 public Installation(Package package)
\r
74 InstalledPackage = package;
\r
78 /// インストーラーファイルを取得する
\r
80 public string InstallerFile {
\r
81 get { return installerFile; }
\r
85 #region インストール状態チェック関連
\r
90 public bool IsInstallablePackage()
\r
92 return installerIndex >= 0;
\r
98 public bool Downloaded {
\r
100 return File.Exists(installerFile) && ((File.GetAttributes(installerFile) & FileAttributes.Hidden) != FileAttributes.Hidden);
\r
105 /// インストール作業済みであるか否か。実際にインストールされたかどうかではありません。
\r
107 public bool Installed {
\r
108 get { return installed; }
\r
112 /// インストーラーの処理が成功してインストールされたプログラムが確認できるか否か。
\r
114 public bool InstallSuccessed {
\r
116 switch (InstalledPackage.Type) {
\r
117 case InstallerType.ARCHIVE:
\r
118 case InstallerType.ITSELF:
\r
119 // アーカイブインストーラーおよび配布exeそれ自身が実行ファイルのとき、
\r
120 // (AppliStationの作る)プログラムフォルダーの存在のみで確認を行う。
\r
121 return Directory.Exists(Path.Combine(NaGet.Env.ArchiveProgramFiles, InstalledPackage.Name));
\r
122 case InstallerType.EXEC_INSTALLER:
\r
123 case InstallerType.MSI_PACKAGE:
\r
124 return RegistriedUninstallers.GetInstalledPackageFor(InstalledPackage) != null;
\r
132 /// サイレントインストールを行うかのフラグ。
\r
134 public bool Silent {
\r
136 return (SupportsSilentOnly)? true :
\r
137 (IsSupportsSilent)? silent :
\r
140 set { silent = value; }
\r
144 /// サイレントインストールをサポートしているか否か
\r
146 public bool IsSupportsSilent {
\r
148 switch (InstalledPackage.Type) {
\r
149 case InstallerType.ARCHIVE:
\r
150 case InstallerType.ITSELF:
\r
151 case InstallerType.MSI_PACKAGE:
\r
153 case InstallerType.EXEC_INSTALLER:
\r
154 return ! string.IsNullOrEmpty(InstalledPackage.SilentInstallArguments);
\r
162 /// サイレントインストールだけをサポートしているか否か
\r
164 public bool SupportsSilentOnly {
\r
166 return (InstalledPackage.Type == InstallerType.ARCHIVE)
\r
167 || (InstalledPackage.Type == InstallerType.ITSELF);
\r
172 /// 選択されたパッケージは、AppliStationではなくPCへのインストールをするのか否かを返す。
\r
174 /// <remark>RunAsが必要か否かの判断にしようされる</remark>
\r
175 public bool TargetPC {
\r
177 return (InstalledPackage.Type != InstallerType.ARCHIVE)
\r
178 && (InstalledPackage.Type != InstallerType.ITSELF);
\r
187 /// <param name="downloader">ダウンローダオブジェクト</param>
\r
188 public void Download(Downloader downloader)
\r
191 string url = InstalledPackage.Installer[installerIndex].Url.Href;
\r
192 downloader.Download(url, installerFile);
\r
194 // サーバ指定のファイル名に変更する
\r
195 if (! string.IsNullOrEmpty(downloader.DownloadedFileName)) {
\r
196 string newFile = Path.Combine(Path.GetDirectoryName(installerFile), downloader.DownloadedFileName);
\r
197 File.Move(installerFile, newFile);
\r
198 installerFile = newFile;
\r
203 string targetDir = Path.GetDirectoryName(installerFile);
\r
204 NaGet.Utils.SetAccessControlRecursive(targetDir, File.GetAccessControl(Path.GetDirectoryName(targetDir)));
\r
205 } catch (Exception) {} // 失敗時は何もしない
\r
210 /// インストーラーファイルをスキャンする
\r
212 /// <remarks>ウイルスのため退避・削除されたときも例外を投げずにあたかも正常かのように動作しえます。</remarks>
\r
213 /// <exception cref="ComException">スキャンで意図せぬ動作があったとき</exception>
\r
214 /// <param name="scanner">スキャナーオブジェクト</param>
\r
215 /// <returns>スキャン結果</returns>
\r
216 public DownloadScannerResult ScanInstallerFile(DownloadScanner scanner)
\r
218 DownloadScannerResult result;
\r
219 Exception e = null;
\r
221 result = scanner.Scan(installerFile, InstalledPackage.Installer[installerIndex].Url.Href);
\r
222 } catch (Exception ex) {
\r
223 result = DownloadScannerResult.ScannerNotFound;
\r
228 // ファイルが消されていないが例外が発生していたときは、その例外を投げる
\r
236 /// ハッシュ検証のためのハッシュの種類の数を返す
\r
238 /// <returns>ハッシュの個数</returns>
\r
239 public int GetRegisteredHashCount()
\r
241 HashValue[] hashValues = InstalledPackage.Installer[installerIndex].Hash;
\r
242 return (hashValues == null)? 0 : hashValues.Length;
\r
248 /// <returns>検証にパスしたらtrue、パスしなかったらfalse</returns>
\r
249 public bool VerifyHashValues()
\r
251 HashValue[] hashValues = InstalledPackage.Installer[installerIndex].Hash;
\r
252 if (hashValues != null) {
\r
253 foreach (HashValue hash in hashValues) {
\r
254 if (! hash.Validate(installerFile)) {
\r
263 private int invokeInstaller(string installerfile, InstallerType type)
\r
265 if (! File.Exists(installerfile)) {
\r
266 throw new FileNotFoundException(string.Format("{0} is not found, perhaps failed to download.", installerfile), installerfile);
\r
269 Process hProcess = null;
\r
272 case InstallerType.EXEC_INSTALLER:
\r
274 hProcess = Process.Start(installerfile, InstalledPackage.SilentInstallArguments);
\r
276 hProcess = Process.Start(installerfile);
\r
280 case InstallerType.MSI_PACKAGE:
\r
281 string msiexecArgs = string.Format("{0} /norestart /i \"{1}\" REBOOT=ReallySuppress",
\r
282 (Silent)? "/passive" : string.Empty,
\r
285 hProcess = Process.Start("msiexec", msiexecArgs);
\r
287 case InstallerType.ARCHIVE:
\r
288 case InstallerType.ITSELF:
\r
289 string argument = string.Format("-i \"{0}\" \"{1}\"", installerfile, this.InstalledPackage.Name);
\r
290 hProcess = createExtractArchiveProcess(argument,
\r
291 this.OutputDataReceived,
\r
292 this.ErrorDataReceived);
\r
293 // Note: ARCHIVEかITSELFの判断はarchive-instが行う
\r
296 throw new NotImplementedException("Not implemented archive installation yet");
\r
299 if (NaGet.Env.InstallProcessOnBackground) {
\r
301 hProcess.PriorityClass = ProcessPriorityClass.Idle;
\r
302 } catch (Exception) {}
\r
305 hProcess.WaitForExit();
\r
307 return hProcess.ExitCode;
\r
309 if (hProcess != null) {
\r
316 /// インストーラー等を起動してインストール作業を行う
\r
318 /// <returns>インストーラーの終了コード</returns>
\r
319 public int Install()
\r
321 string installerFile = this.installerFile;
\r
322 string tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
\r
324 // アーカイブされているなら一旦展開
\r
325 if (InstalledPackage.ArchivedInstaller) {
\r
326 Directory.CreateDirectory(tempDir);
\r
328 string argument = string.Format("-t \"{0}\" \"{1}\"", installerFile, tempDir);
\r
329 using (Process hProcess = createExtractArchiveProcess(argument,
\r
330 this.OutputDataReceived,
\r
331 this.ErrorDataReceived)) {
\r
332 if (NaGet.Env.InstallProcessOnBackground) {
\r
334 hProcess.PriorityClass = ProcessPriorityClass.Idle;
\r
335 } catch (Exception) {}
\r
338 hProcess.WaitForExit();
\r
340 if (hProcess.ExitCode != 0) {
\r
341 throw new ApplicationException("Extract error " + installerFile + " to " + tempDir);
\r
345 installerFile = seekInstallerFile(tempDir, InstalledPackage.Type);
\r
346 if (installerFile == null && Directory.GetDirectories(tempDir).Length == 1) {
\r
347 installerFile = seekInstallerFile(Path.Combine(tempDir, Directory.GetDirectories(tempDir)[0]), InstalledPackage.Type);
\r
351 int exitCode = invokeInstaller(installerFile, InstalledPackage.Type);
\r
358 #region インストーラーファイル設定時の処理
\r
361 /// もっともふさわしいインストーラー番号を返す
\r
363 /// <returns></returns>
\r
364 private static int getPreferInstallerIndex(Package InstalledPackage)
\r
366 if (InstalledPackage.Type == InstallerType.CANNOT_INSTALL) { // インストール不能パッケージ
\r
373 for (int i = 0; i < InstalledPackage.Installer.Length; i++) {
\r
374 Platform platform = InstalledPackage.Installer[i].Platform;
\r
377 if (platform != null) {
\r
378 pts = (platform.IsRunnable())? 10 : 0;
\r
379 pts += (platform.IsRunnableArchOnWow64() && platform.IsRunnableOS())? 1 : 0;
\r
380 } else { // if (platform == null) {
\r
381 pts = 1; // null の場合は動作プラットホーム扱い
\r
383 if (pts > bestVal) {
\r
393 /// インストーラーの保存先パスを生成
\r
395 /// <remarks>installerIndexが求まっているものとして仮定して処理する</remarks>
\r
396 private string getArchiveFilePath()
\r
398 Package package = this.InstalledPackage;
\r
400 string folderName = string.Format("{0}({1})", package.Name, package.Version);
\r
401 string subFolderName = string.Format("installer.{0}", (installerIndex >= 0)? installerIndex.ToString("D") : "X");
\r
402 string fileName = NaGet.Utils.Url2filename(new Uri(package.Installer[0].Url.Href));
\r
404 string folder = Path.Combine(NaGet.Env.ArchiveFolderPath, Path.Combine(folderName, subFolderName));
\r
406 if (! File.Exists(Path.Combine(folder, fileName))) {
\r
407 if (Directory.Exists(folder)) {
\r
408 if (! File.Exists(Path.Combine(folder, fileName))) {
\r
409 fileName = seekInstallerFile(folder, package.Type) ?? fileName;
\r
412 Directory.CreateDirectory(folder);
\r
416 Directory.SetAccessControl(folder, Directory.GetAccessControl(Path.GetDirectoryName(folder)));
\r
417 } catch (Exception) {} // 失敗時無視
\r
421 return Path.Combine(folder, fileName);
\r
429 /// <param name="basedir">探すフォルダー</param>
\r
430 /// <param name="type">インストーラーの種類</param>
\r
431 /// <returns>探し出されたインストーラーファイルのフルパス。存在しないならばnull</returns>
\r
432 private static string seekInstallerFile(string basedir, InstallerType type)
\r
434 if (! Directory.Exists(basedir)) {
\r
438 System.Collections.Generic.List<string> list = new System.Collections.Generic.List<string>();
\r
440 case InstallerType.MSI_PACKAGE:
\r
441 list.AddRange(Directory.GetFiles(basedir, "*.msi"));
\r
443 case InstallerType.EXEC_INSTALLER:
\r
444 list.AddRange(Directory.GetFiles(basedir, "*.exe"));
\r
446 case InstallerType.ARCHIVE:
\r
447 list.AddRange(Directory.GetFiles(basedir, "*.zip"));
\r
448 list.AddRange(Directory.GetFiles(basedir, "*.lzh"));
\r
449 list.AddRange(Directory.GetFiles(basedir, "*.cab"));
\r
450 list.AddRange(Directory.GetFiles(basedir, "*.7z"));
\r
451 list.AddRange(Directory.GetFiles(basedir, "*.tar*"));
\r
453 case InstallerType.ITSELF:
\r
454 list.AddRange(Directory.GetFiles(basedir, "*.exe"));
\r
462 delegate(string file) {
\r
463 return ! File.Exists(file);
\r
467 // "setup"の語が入ったファイルはインストーラとみなし、優先選択
\r
468 foreach (string path in list) {
\r
469 if (Path.GetFileName(path).ToLower().IndexOf("setup") >= 0) {
\r
475 return (list.Count > 0)? list[0] : null;
\r
480 /// アーカイブファイルの展開・インストールを行う
\r
482 /// <param name="archiveInstArgs">"archive-inst.exe"への引数</param>
\r
483 /// <param name="outputReceived">標準出力用リスナ(null可)</param>
\r
484 /// <param name="errorReceived">エラー出力用リスナ(null可)</param>
\r
485 /// <returns>実行プロセス</returns>
\r
486 private static Process createExtractArchiveProcess(string archiveInstArgs,
\r
487 EventHandler<NaGet.Utils.AnyDataEventArgs<string>> outputReceived,
\r
488 EventHandler<NaGet.Utils.AnyDataEventArgs<string>> errorReceived)
\r
490 string archiveInstExe = Path.GetFullPath("archive-inst.exe");
\r
491 if (! File.Exists(archiveInstExe)) {
\r
492 string errMsg = string.Format("\"{0}\" does not found!");
\r
493 throw new ApplicationException(errMsg,
\r
494 new FileNotFoundException(errMsg, archiveInstExe));
\r
499 ProcessStartInfo procInfo = new ProcessStartInfo(archiveInstExe, archiveInstArgs);
\r
500 procInfo.UseShellExecute = false;
\r
501 procInfo.CreateNoWindow = true;
\r
502 procInfo.WorkingDirectory = Environment.CurrentDirectory;
\r
504 return NaGet.Utils.ProcessStartWithOutputCapture(procInfo, outputReceived, errorReceived);
\r
508 /// ダウンロードしたインストーラファイルを削除する
\r
510 public virtual void RemoveDownloadedFile()
\r
512 if (Downloaded && File.Exists(installerFile)) {
\r
513 File.Delete(installerFile);
\r
517 public override string ToString()
\r
519 return string.Format("{0}({1})", InstalledPackage.Name, InstalledPackage.Version);
\r
522 public static string ToString(Installation[] installations)
\r
524 string[] strs = new string[installations.Length];
\r
525 for (int i = 0; i < installations.Length; i++) {
\r
526 strs[i] = installations[i].ToString();
\r
528 return string.Join(" ", strs);
\r
534 /// パッケージ配列をインストール処理配列に変換する便利メソッド
\r
536 /// <param name="pkgs">パッケージ配列</param>
\r
537 /// <returns>変換されたインストール処理配列</returns>
\r
538 public static Installation[] ConvertInstallations(Package[] pkgs)
\r
540 Installation[] insts = new Installation[pkgs.Length];
\r
541 for (int i = 0; i < pkgs.Length; i++) {
\r
542 insts[i] = new Installation(pkgs[i]);
\r
548 /// パッケージがインストール可能かを戻します。
\r
550 /// <param name="pkg">検査対象のパッケージ</param>
\r
551 /// <returns>インストール可能か否か</returns>
\r
552 public static bool IsInstallablePackage(Package pkg)
\r
554 int installerIndex = getPreferInstallerIndex(pkg);
\r
555 return installerIndex >= 0;
\r