308 lines
12 KiB
C#
308 lines
12 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.IO;
|
||
using System.IO.Compression;
|
||
using System.Linq;
|
||
using System.Reflection;
|
||
using System.Runtime.InteropServices;
|
||
using System.Security.Cryptography;
|
||
using System.Text;
|
||
using System.Threading;
|
||
using System.Xml.Linq;
|
||
using Microsoft.Win32;
|
||
|
||
namespace CasinoSetup;
|
||
|
||
public sealed class PackageInstaller
|
||
{
|
||
private readonly SetupPackage package;
|
||
|
||
public string IntegrationWarning { get; private set; }
|
||
|
||
public PackageInstaller(SetupPackage package)
|
||
{
|
||
this.package = package;
|
||
}
|
||
|
||
public void Install(string target, bool model, bool shortcut, bool integration, Action<InstallProgress> report, CancellationToken token)
|
||
{
|
||
target = InstallPaths.Normalize(target);
|
||
IntegrationWarning = null;
|
||
InstallPaths.ValidateTarget(target, package.FileName);
|
||
long required = package.RequiredBytes(model);
|
||
if (new DriveInfo(Path.GetPathRoot(target)).AvailableFreeSpace < required + 134217728)
|
||
{
|
||
throw new IOException("Недостаточно свободного места для распаковки и безопасной замены файлов.");
|
||
}
|
||
Directory.CreateDirectory(target);
|
||
InstallPaths.NoLinks(Path.Combine(target, ".casino-install.lock"));
|
||
using (new FileStream(Path.Combine(target, ".casino-install.lock"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, 1, FileOptions.DeleteOnClose))
|
||
{
|
||
List<XElement> old = ReadReceipt(target);
|
||
string stage = Path.Combine(target, ".casino-stage-" + Guid.NewGuid().ToString("N"));
|
||
Directory.CreateDirectory(stage);
|
||
try
|
||
{
|
||
package.Verify(package.Game, report, token);
|
||
if (model)
|
||
{
|
||
package.Verify(package.Model, report, token);
|
||
}
|
||
List<XElement> records = new List<XElement>();
|
||
HashSet<string> paths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||
long done = 0L;
|
||
Action<Stream, string, long> action = (Stream input, string relative, long length) =>
|
||
{
|
||
token.ThrowIfCancellationRequested();
|
||
if (!paths.Add(relative) || relative.Equals("casino-install.xml", StringComparison.OrdinalIgnoreCase) || relative.Split('/').Any((string p) => p.StartsWith(".casino-", StringComparison.OrdinalIgnoreCase)))
|
||
{
|
||
throw new InvalidDataException("Повторяющийся или служебный путь в пакете.");
|
||
}
|
||
string path = InstallPaths.SafeFile(stage, relative);
|
||
string path2 = InstallPaths.SafeFile(target, relative);
|
||
XElement xElement = old.FirstOrDefault((XElement e) => string.Equals((string)e.Attribute("path"), relative, StringComparison.OrdinalIgnoreCase));
|
||
if (File.Exists(path2) && (xElement == null || !InstallPaths.HashFile(path2).Equals((string)xElement.Attribute("sha256"), StringComparison.OrdinalIgnoreCase)))
|
||
{
|
||
throw new IOException("Файл уже существует и не принадлежит этой установке либо изменён:\n" + relative + "\nВыберите другую папку.");
|
||
}
|
||
Directory.CreateDirectory(Path.GetDirectoryName(path));
|
||
using FileStream fileStream = File.Create(path);
|
||
using SHA256 sHA = SHA256.Create();
|
||
byte[] array = new byte[1048576];
|
||
long num2 = 0L;
|
||
int num3;
|
||
while ((num3 = input.Read(array, 0, array.Length)) != 0)
|
||
{
|
||
token.ThrowIfCancellationRequested();
|
||
num2 += num3;
|
||
if (num2 > length)
|
||
{
|
||
throw new InvalidDataException("Неверный размер файла.");
|
||
}
|
||
fileStream.Write(array, 0, num3);
|
||
sHA.TransformBlock(array, 0, num3, null, 0);
|
||
done += num3;
|
||
report(new InstallProgress(15 + (int)(done * 78 / Math.Max(1L, required)), "Установка: " + relative));
|
||
}
|
||
if (num2 != length)
|
||
{
|
||
throw new EndOfStreamException("Неполный файл в пакете.");
|
||
}
|
||
sHA.TransformFinalBlock(array, 0, 0);
|
||
records.Add(new XElement("file", new XAttribute("path", relative), new XAttribute("sha256", InstallPaths.Hex(sHA.Hash))));
|
||
};
|
||
using (SliceStream stream = package.OpenBlock(package.Game))
|
||
{
|
||
using ZipArchive zipArchive = new ZipArchive(stream, ZipArchiveMode.Read);
|
||
long num = 0L;
|
||
foreach (ZipArchiveEntry entry in zipArchive.Entries)
|
||
{
|
||
if (string.IsNullOrEmpty(entry.Name))
|
||
{
|
||
throw new InvalidDataException("Неожиданная запись каталога.");
|
||
}
|
||
num = checked(num + entry.Length);
|
||
if (num > InstallPaths.Number(package.Game, "bytes"))
|
||
{
|
||
throw new InvalidDataException("Неверный размер архива.");
|
||
}
|
||
using Stream arg = entry.Open();
|
||
action(arg, entry.FullName, entry.Length);
|
||
}
|
||
if (num != InstallPaths.Number(package.Game, "bytes"))
|
||
{
|
||
throw new InvalidDataException("Неполный архив игры.");
|
||
}
|
||
}
|
||
if (model)
|
||
{
|
||
using (SliceStream arg2 = package.OpenBlock(package.Model))
|
||
{
|
||
action(arg2, (string)package.Model.Attribute("path"), InstallPaths.Number(package.Model, "bytes"));
|
||
}
|
||
if (!records.Last().Attribute("sha256").Value.Equals((string)package.Model.Attribute("sha256"), StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
throw new InvalidDataException("Контрольная сумма модели не совпадает.");
|
||
}
|
||
}
|
||
records.AddRange(from e in old
|
||
where !paths.Contains((string)e.Attribute("path"))
|
||
select new XElement(e));
|
||
XDocument xDocument = new XDocument(new XElement("casino-install", new XAttribute("version", "2"), new XAttribute("root", target), new XAttribute("id", Guid.NewGuid().ToString("N")), records));
|
||
xDocument.Save(Path.Combine(stage, "casino-install.xml"));
|
||
token.ThrowIfCancellationRequested();
|
||
report(new InstallProgress(94, "Сохранение файлов установки…"));
|
||
Commit(target, stage, paths.Concat(new string[1] { "casino-install.xml" }).ToArray());
|
||
InstallPaths.NoLinks(Path.Combine(target, "runtime"));
|
||
Directory.CreateDirectory(Path.Combine(target, "runtime"));
|
||
if (integration)
|
||
{
|
||
try
|
||
{
|
||
Register(target, required);
|
||
if (shortcut)
|
||
{
|
||
CreateShortcut(target);
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
IntegrationWarning = "Игра установлена, но настройка Windows завершена не полностью:\n" + ex.Message;
|
||
}
|
||
}
|
||
report(new InstallProgress(100, "Казино готово к открытию"));
|
||
}
|
||
finally
|
||
{
|
||
if (Directory.Exists(stage) && !File.Exists(Path.Combine(stage, ".preserve-backup")))
|
||
{
|
||
Directory.Delete(stage, recursive: true);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
public static List<XElement> ReadReceipt(string target)
|
||
{
|
||
string path = InstallPaths.SafeFile(target, "casino-install.xml");
|
||
if (!File.Exists(path))
|
||
{
|
||
return new List<XElement>();
|
||
}
|
||
XDocument xDocument;
|
||
using (FileStream stream = File.OpenRead(path))
|
||
{
|
||
xDocument = InstallPaths.ReadXml(stream);
|
||
}
|
||
if (xDocument.Root.Name != "casino-install" || (string)xDocument.Root.Attribute("version") != "2" || !target.Equals((string)xDocument.Root.Attribute("root"), StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
throw new InvalidDataException("Неизвестный список установленных файлов.");
|
||
}
|
||
HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||
List<XElement> list = xDocument.Root.Elements("file").ToList();
|
||
foreach (XElement item in list)
|
||
{
|
||
string text = (string)item.Attribute("path");
|
||
InstallPaths.SafeFile(target, text);
|
||
InstallPaths.CheckHash((string)item.Attribute("sha256"));
|
||
if (!hashSet.Add(text))
|
||
{
|
||
throw new InvalidDataException("Повторяющийся путь в списке установки.");
|
||
}
|
||
}
|
||
return list;
|
||
}
|
||
|
||
private static void Commit(string target, string stage, string[] paths)
|
||
{
|
||
string text = Path.Combine(stage, ".backup");
|
||
List<string> list = new List<string>();
|
||
List<string> list2 = new List<string>();
|
||
try
|
||
{
|
||
foreach (string relative in paths)
|
||
{
|
||
string path = InstallPaths.SafeFile(target, relative);
|
||
if (File.Exists(path))
|
||
{
|
||
using (new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
|
||
{
|
||
}
|
||
}
|
||
}
|
||
foreach (string text2 in paths)
|
||
{
|
||
string text3 = InstallPaths.SafeFile(target, text2);
|
||
string sourceFileName = InstallPaths.SafeFile(stage, text2);
|
||
string text4 = InstallPaths.SafeFile(text, text2);
|
||
Directory.CreateDirectory(Path.GetDirectoryName(text3));
|
||
if (File.Exists(text3))
|
||
{
|
||
Directory.CreateDirectory(Path.GetDirectoryName(text4));
|
||
File.Move(text3, text4);
|
||
list2.Add(text2);
|
||
}
|
||
File.Move(sourceFileName, text3);
|
||
list.Add(text2);
|
||
}
|
||
}
|
||
catch
|
||
{
|
||
try
|
||
{
|
||
foreach (string item in list.AsEnumerable().Reverse())
|
||
{
|
||
File.Delete(InstallPaths.SafeFile(target, item));
|
||
}
|
||
foreach (string item2 in list2.AsEnumerable().Reverse())
|
||
{
|
||
File.Move(InstallPaths.SafeFile(text, item2), InstallPaths.SafeFile(target, item2));
|
||
}
|
||
}
|
||
catch (Exception innerException)
|
||
{
|
||
File.WriteAllText(Path.Combine(stage, ".preserve-backup"), "Rollback incomplete. Preserve this backup.");
|
||
throw new IOException("Не удалось восстановить прежнюю установку. Резервные файлы оставлены: " + text, innerException);
|
||
}
|
||
throw;
|
||
}
|
||
}
|
||
|
||
private static void CreateShortcut(string target)
|
||
{
|
||
Type typeFromProgID = Type.GetTypeFromProgID("WScript.Shell");
|
||
if (typeFromProgID == null)
|
||
{
|
||
throw new IOException("Windows Script Host недоступен: ярлык не создан.");
|
||
}
|
||
object obj = Activator.CreateInstance(typeFromProgID);
|
||
object obj2 = null;
|
||
try
|
||
{
|
||
string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
|
||
string text = Path.Combine(folderPath, "Assembler Casino.lnk");
|
||
obj2 = typeFromProgID.InvokeMember("CreateShortcut", BindingFlags.InvokeMethod, null, obj, new object[1] { text });
|
||
Type type = obj2.GetType();
|
||
if (File.Exists(text))
|
||
{
|
||
string text2 = (string)type.InvokeMember("TargetPath", BindingFlags.GetProperty, null, obj2, null);
|
||
if (!text2.Equals(Path.Combine(target, "Assembler Casino.exe"), StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
throw new IOException("Файлы игры установлены; чужой ярлык с таким именем не изменён.");
|
||
}
|
||
}
|
||
type.InvokeMember("TargetPath", BindingFlags.SetProperty, null, obj2, new object[1] { Path.Combine(target, "Assembler Casino.exe") });
|
||
type.InvokeMember("WorkingDirectory", BindingFlags.SetProperty, null, obj2, new object[1] { target });
|
||
type.InvokeMember("IconLocation", BindingFlags.SetProperty, null, obj2, new object[1] { Path.Combine(target, "assets\\icons\\casino.ico") });
|
||
type.InvokeMember("Save", BindingFlags.InvokeMethod, null, obj2, null);
|
||
}
|
||
finally
|
||
{
|
||
if (obj2 != null)
|
||
{
|
||
Marshal.FinalReleaseComObject(obj2);
|
||
}
|
||
Marshal.FinalReleaseComObject(obj);
|
||
}
|
||
}
|
||
|
||
public static string RegistryKey(string target)
|
||
{
|
||
using SHA256 sHA = SHA256.Create();
|
||
return "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\AssemblerCasino-" + InstallPaths.Hex(sHA.ComputeHash(Encoding.UTF8.GetBytes(target.ToLowerInvariant()))).Substring(0, 16);
|
||
}
|
||
|
||
private static void Register(string target, long bytes)
|
||
{
|
||
using RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(RegistryKey(target));
|
||
registryKey.SetValue("DisplayName", "Assembler Casino");
|
||
registryKey.SetValue("DisplayVersion", "2.0");
|
||
registryKey.SetValue("Publisher", "Assembler Casino");
|
||
registryKey.SetValue("InstallLocation", target);
|
||
registryKey.SetValue("DisplayIcon", Path.Combine(target, "Assembler Casino.exe"));
|
||
registryKey.SetValue("UninstallString", "\"" + Path.Combine(target, "Uninstall Assembler Casino.exe") + "\"");
|
||
registryKey.SetValue("EstimatedSize", (int)Math.Min(2147483647L, bytes / 1024), RegistryValueKind.DWord);
|
||
registryKey.SetValue("NoModify", 1, RegistryValueKind.DWord);
|
||
registryKey.SetValue("NoRepair", 1, RegistryValueKind.DWord);
|
||
}
|
||
}
|