wabbajack/Wabbajack.Lib/AInstaller.cs

466 lines
18 KiB
C#
Raw Normal View History

2020-08-07 08:29:12 +00:00
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Threading.Tasks;
using Wabbajack.Common;
using Wabbajack.Lib.Downloaders;
using Wabbajack.VirtualFileSystem;
using Path = Alphaleonis.Win32.Filesystem.Path;
namespace Wabbajack.Lib
{
public abstract class AInstaller : ABatchProcessor
{
public bool IgnoreMissingFiles { get; internal set; } = false;
2020-03-25 12:47:25 +00:00
public AbsolutePath OutputFolder { get; private set; }
public AbsolutePath DownloadFolder { get; private set; }
public abstract ModManager ModManager { get; }
2020-03-26 21:15:44 +00:00
public AbsolutePath ModListArchive { get; private set; }
public ModList ModList { get; private set; }
public Dictionary<Hash, AbsolutePath> HashedArchives { get; } = new Dictionary<Hash, AbsolutePath>();
2020-01-07 13:50:11 +00:00
public GameMetaData Game { get; }
2020-04-10 01:29:53 +00:00
public SystemParameters? SystemParameters { get; set; }
2020-08-05 22:01:45 +00:00
public bool UseCompression { get; set; }
public TempFolder? ExtractedModlistFolder { get; set; } = null;
public AInstaller(AbsolutePath archive, ModList modList, AbsolutePath outputFolder, AbsolutePath downloadFolder, SystemParameters? parameters, int steps, Game game)
: base(steps)
{
ModList = modList;
ModListArchive = archive;
OutputFolder = outputFolder;
DownloadFolder = downloadFolder;
2020-01-07 13:50:11 +00:00
SystemParameters = parameters;
Game = game.MetaData();
}
public async Task ExtractModlist()
{
ExtractedModlistFolder = await TempFolder.Create();
await FileExtractor2.ExtractAll(Queue, ModListArchive, ExtractedModlistFolder.Dir);
}
public void Info(string msg)
{
Utils.Log(msg);
}
public void Status(string msg)
{
2020-02-08 04:35:08 +00:00
Queue.Report(msg, Percent.Zero);
}
public void Error(string msg)
{
Utils.Log(msg);
throw new Exception(msg);
}
2020-03-25 22:30:43 +00:00
public async Task<byte[]> LoadBytesFromPath(RelativePath path)
{
2020-09-05 19:36:44 +00:00
var fullPath = ExtractedModlistFolder!.Dir.Combine(path);
if (!fullPath.IsFile)
throw new Exception($"Cannot load inlined data {path} file does not exist");
return await fullPath.ReadAllBytesAsync();
}
2020-03-26 21:15:44 +00:00
public static ModList LoadFromFile(AbsolutePath path)
{
2020-03-26 21:15:44 +00:00
using var fs = new FileStream((string)path, FileMode.Open, FileAccess.Read, FileShare.Read);
using var ar = new ZipArchive(fs, ZipArchiveMode.Read);
var entry = ar.GetEntry("modlist");
if (entry == null)
{
2020-03-26 21:15:44 +00:00
entry = ar.GetEntry("modlist.json");
2021-01-01 00:06:56 +00:00
if (entry == null)
throw new Exception("Invalid Wabbajack Installer");
using var e = entry.Open();
return e.FromJson<ModList>();
}
2020-03-26 21:15:44 +00:00
using (var e = entry.Open())
return e.FromJson<ModList>();
}
/// <summary>
/// We don't want to make the installer index all the archives, that's just a waste of time, so instead
/// we'll pass just enough information to VFS to let it know about the files we have.
/// </summary>
2020-03-25 12:47:25 +00:00
protected async Task PrimeVFS()
{
2020-03-25 12:47:25 +00:00
VFS.AddKnown(ModList.Directives.OfType<FromArchive>().Select(d => d.ArchiveHashPath), HashedArchives);
2019-12-07 02:54:27 +00:00
await VFS.BackfillMissing();
}
public void BuildFolderStructure()
{
Info("Building Folder Structure");
ModList.Directives
2020-03-25 12:47:25 +00:00
.Select(d => OutputFolder.Combine(d.To.Parent))
2020-01-07 13:50:11 +00:00
.Distinct()
2020-03-28 02:54:14 +00:00
.Do(f => f.CreateDirectory());
}
public async Task InstallArchives()
{
var grouped = ModList.Directives
.OfType<FromArchive>()
.Select(a => new {VF = VFS.Index.FileForArchiveHashPath(a.ArchiveHashPath), Directive = a})
.GroupBy(a => a.VF)
.ToDictionary(a => a.Key);
if (grouped.Count == 0) return;
await VFS.Extract(Queue, grouped.Keys.ToHashSet(), async (vf, sf) =>
{
foreach (var directive in grouped[vf])
{
2020-09-06 03:28:31 +00:00
var file = directive.Directive;
2020-09-05 19:36:44 +00:00
2020-09-06 03:28:31 +00:00
switch (file)
2020-09-05 19:36:44 +00:00
{
case PatchedFromArchive pfa:
{
await using var s = await sf.GetStream();
s.Position = 0;
2020-09-05 19:36:44 +00:00
var patchData = await LoadBytesFromPath(pfa.PatchID);
2020-09-06 03:28:31 +00:00
var toFile = file.To.RelativeTo(OutputFolder);
{
await using var os = await toFile.Create();
Utils.ApplyPatch(s, () => new MemoryStream(patchData), os);
}
2020-09-06 03:28:31 +00:00
if (await VirusScanner.ShouldScan(toFile) &&
await ClientAPI.GetVirusScanResult(toFile) == VirusScanner.Result.Malware)
{
await toFile.DeleteAsync();
Utils.ErrorThrow(new Exception($"Virus scan of patched executable reported possible malware: {toFile.ToString()} ({(long)await toFile.FileHashCachedAsync()})"));
}
2020-09-05 19:36:44 +00:00
}
break;
case FromArchive _:
if (grouped[vf].Count() == 1)
{
await sf.Move(directive.Directive.To.RelativeTo(OutputFolder));
}
else
{
await using var s = await sf.GetStream();
await directive.Directive.To.RelativeTo(OutputFolder).WriteAllAsync(s, false);
}
2020-09-05 19:36:44 +00:00
break;
default:
throw new Exception($"No handler for {directive}");
}
2020-05-14 11:28:29 +00:00
2020-08-07 11:24:30 +00:00
if (file is PatchedFromArchive)
{
await file.To.RelativeTo(OutputFolder).FileHashAsync();
}
else
{
file.To.RelativeTo(OutputFolder).FileHashWriteCache(file.Hash);
}
if (UseCompression)
2020-08-05 22:01:45 +00:00
{
Utils.Status($"Compacting {file.To}");
await file.To.RelativeTo(OutputFolder).Compact(FileCompaction.Algorithm.XPRESS16K);
}
}
2020-11-03 14:45:08 +00:00
}, tempFolder: OutputFolder, updateTracker: UpdateTracker);
}
public async Task DownloadArchives()
{
var missing = ModList.Archives.Where(a => !HashedArchives.ContainsKey(a.Hash)).ToList();
Info($"Missing {missing.Count} archives");
Info("Getting Nexus API Key, if a browser appears, please accept");
var dispatchers = missing.Select(m => m.State.GetDownloader()).Distinct();
2019-12-07 02:45:13 +00:00
await Task.WhenAll(dispatchers.Select(d => d.Prepare()));
2020-02-06 05:30:31 +00:00
2020-11-05 21:30:00 +00:00
var nexusDownloader = dispatchers.OfType<NexusDownloader>().FirstOrDefault();
if (nexusDownloader != null && !await nexusDownloader.HaveEnoughAPICalls(missing))
{
throw new Exception($"Not enough Nexus API calls to download this list, please try again after midnight GMT when your API limits reset");
}
await DownloadMissingArchives(missing);
}
public async Task DownloadMissingArchives(List<Archive> missing, bool download = true)
{
if (download)
{
2020-11-24 22:14:09 +00:00
var result = SendDownloadMetrics(missing);
foreach (var a in missing.Where(a => a.State.GetType() == typeof(ManualDownloader.State)))
{
2020-03-25 22:49:32 +00:00
var outputPath = DownloadFolder.Combine(a.Name);
await a.State.Download(a, outputPath);
}
}
2020-09-12 20:23:03 +00:00
DesiredThreads.OnNext(DownloadThreads);
2020-11-05 21:30:00 +00:00
await missing.Where(a => a.State.GetType() != typeof(ManualDownloader.State))
2020-11-03 14:45:08 +00:00
.PMap(Queue, UpdateTracker, async archive =>
{
Info($"Downloading {archive.Name}");
2020-03-25 22:49:32 +00:00
var outputPath = DownloadFolder.Combine(archive.Name);
if (download)
{
2020-03-25 22:49:32 +00:00
if (outputPath.Exists)
{
2020-03-25 22:49:32 +00:00
var origName = Path.GetFileNameWithoutExtension(archive.Name);
var ext = Path.GetExtension(archive.Name);
2020-03-25 22:49:32 +00:00
var uniqueKey = archive.State.PrimaryKeyString.StringSha256Hex();
outputPath = DownloadFolder.Combine(origName + "_" + uniqueKey + "_" + ext);
2020-05-26 11:31:11 +00:00
await outputPath.DeleteAsync();
}
}
return await DownloadArchive(archive, download, outputPath);
});
2020-09-12 20:23:03 +00:00
DesiredThreads.OnNext(DiskThreads);
}
2020-11-24 22:14:09 +00:00
private async Task SendDownloadMetrics(List<Archive> missing)
{
var grouped = missing.GroupBy(m => m.State.GetType());
foreach (var group in grouped)
{
2020-11-25 00:22:24 +00:00
await Metrics.Send($"downloading_{group.Key.FullName!.Split(".").Last().Split("+").First()}", group.Sum(g => g.Size).ToString());
2020-11-24 22:14:09 +00:00
}
}
2020-03-25 22:49:32 +00:00
public async Task<bool> DownloadArchive(Archive archive, bool download, AbsolutePath? destination = null)
{
try
{
2020-08-20 22:02:50 +00:00
destination ??= DownloadFolder.Combine(archive.Name);
var result = await DownloadDispatcher.DownloadWithPossibleUpgrade(archive, destination.Value);
if (result == DownloadDispatcher.DownloadResult.Update)
{
await destination.Value.MoveToAsync(destination.Value.Parent.Combine(archive.Hash.ToHex()));
}
}
catch (Exception ex)
{
Utils.Log($"Download error for file {archive.Name}");
Utils.Log(ex.ToString());
return false;
}
return false;
}
public async Task HashArchives()
{
Utils.Log("Looking for files to hash");
// Enumerate all files.
var allFiles = DownloadFolder.EnumerateFiles()
.Concat(Game.GameLocation().EnumerateFiles())
.ToList();
// Create a Dictionary with filesize as the key.
var hashDict = new Dictionary<long, List<AbsolutePath>>();
// Populate the Dictionary with all files we found, using a list for the paths to allow for duplicated filesizes.
allFiles.ForEach(o =>
{
if (hashDict.ContainsKey(o.Size))
{
hashDict[o.Size].Add(o);
}
else
{
hashDict.Add(o.Size, new List<AbsolutePath> { o });
}
});
// Create a list for the files we filter.
var toHash = new List<AbsolutePath>();
// Iterate through required archives, adding any files we have that match filesize.
ModList.Archives.ForEach(o => {
if (hashDict.ContainsKey(o.Size))
{
hashDict[o.Size].ForEach(o => toHash.Add(o));
}
});
Utils.Log($"Found {allFiles.Count} total files, {toHash.Count} matching filesize");
// Hash all the files we added.
var hashResults = await
toHash
2020-11-03 14:45:08 +00:00
.PMap(Queue, UpdateTracker,async e => (await e.FileHashCachedAsync(), e));
2020-04-12 18:18:08 +00:00
HashedArchives.SetTo(hashResults
2020-03-25 22:49:32 +00:00
.OrderByDescending(e => e.Item2.LastModified)
.GroupBy(e => e.Item1)
.Select(e => e.First())
.Select(e => new KeyValuePair<Hash, AbsolutePath>(e.Item1, e.Item2)));
}
/// <summary>
/// Disabled
/// </summary>
public void ValidateFreeSpace()
{
return;
// Disabled, caused more problems than it was worth.
/*
DiskSpaceInfo DriveInfo(string path)
{
return Volume.GetDiskFreeSpace(Volume.GetUniqueVolumeNameForPath(path));
}
var paths = new[] {(OutputFolder, ModList.InstallSize),
(DownloadFolder, ModList.DownloadSize),
(Directory.GetCurrentDirectory(), ModList.ScratchSpaceSize)};
paths.GroupBy(f => DriveInfo(f.Item1).DriveName)
.Do(g =>
{
var required = g.Sum(i => i.Item2);
var contains = g.Sum(folder =>
Directory.EnumerateFiles(folder.Item1, "*", DirectoryEnumerationOptions.Recursive)
.Sum(file => new FileInfo(file).Length));
var available = DriveInfo(g.Key).FreeBytesAvailable;
if (required - contains > available)
throw new NotEnoughDiskSpaceException(
2020-01-13 21:11:07 +00:00
$"This ModList requires {required.ToFileSizeString()} on {g.Key} but only {available.ToFileSizeString()} is available.");
});
*/
}
/// <summary>
/// The user may already have some files in the OutputFolder. If so we can go through these and
/// figure out which need to be updated, deleted, or left alone
/// </summary>
public async Task OptimizeModlist()
{
2020-01-13 21:11:07 +00:00
Utils.Log("Optimizing ModList directives");
2020-01-13 21:11:07 +00:00
// Clone the ModList so our changes don't modify the original data
ModList = ModList.Clone();
var indexed = ModList.Directives.ToDictionary(d => d.To);
var profileFolder = OutputFolder.Combine("profiles");
var savePath = (RelativePath)"saves";
2019-11-24 23:03:36 +00:00
UpdateTracker.NextStep("Looking for files to delete");
2020-03-25 23:15:19 +00:00
await OutputFolder.EnumerateFiles()
2020-05-26 11:31:11 +00:00
.PMap(Queue, UpdateTracker, async f =>
{
2020-03-28 02:54:14 +00:00
var relativeTo = f.RelativeTo(OutputFolder);
if (indexed.ContainsKey(relativeTo) || f.InFolder(DownloadFolder))
return;
if (f.InFolder(profileFolder) && f.Parent.FileName == savePath) return;
2020-03-28 02:54:14 +00:00
Utils.Log($"Deleting {relativeTo} it's not part of this ModList");
2020-05-26 11:31:11 +00:00
await f.DeleteAsync();
});
Utils.Log("Cleaning empty folders");
2020-01-07 04:46:36 +00:00
var expectedFolders = indexed.Keys
2020-03-25 23:15:19 +00:00
.Select(f => f.RelativeTo(OutputFolder))
2020-01-07 04:46:36 +00:00
// We ignore the last part of the path, so we need a dummy file name
2020-03-25 23:15:19 +00:00
.Append(DownloadFolder.Combine("_"))
2020-03-28 02:54:14 +00:00
.Where(f => f.InFolder(OutputFolder))
2020-01-07 04:46:36 +00:00
.SelectMany(path =>
{
// Get all the folders and all the folder parents
// so for foo\bar\baz\qux.txt this emits ["foo", "foo\\bar", "foo\\bar\\baz"]
2020-03-25 23:15:19 +00:00
var split = ((string)path.RelativeTo(OutputFolder)).Split('\\');
return Enumerable.Range(1, split.Length - 1).Select(t => string.Join("\\", split.Take(t)));
})
.Distinct()
2020-03-25 23:15:19 +00:00
.Select(p => OutputFolder.Combine(p))
.ToHashSet();
try
{
2020-03-28 04:33:26 +00:00
var toDelete = OutputFolder.EnumerateDirectories(true)
.Where(p => !expectedFolders.Contains(p))
2020-03-28 04:33:26 +00:00
.OrderByDescending(p => ((string)p).Length)
.ToList();
foreach (var dir in toDelete)
{
await dir.DeleteDirectory(dontDeleteIfNotEmpty:true);
2020-03-28 04:33:26 +00:00
}
}
catch (Exception)
{
// ignored because it's not worth throwing a fit over
Utils.Log("Error when trying to clean empty folders. This doesn't really matter.");
}
2020-09-11 01:22:07 +00:00
var existingfiles = OutputFolder.EnumerateFiles().ToHashSet();
UpdateTracker.NextStep("Looking for unmodified files");
2020-03-25 23:15:19 +00:00
(await indexed.Values.PMap(Queue, UpdateTracker, async d =>
{
// Bit backwards, but we want to return null for
// all files we *want* installed. We return the files
// to remove from the install list.
2020-03-25 23:15:19 +00:00
var path = OutputFolder.Combine(d.To);
2020-09-11 01:22:07 +00:00
if (!existingfiles.Contains(path)) return null;
return await path.FileHashCachedAsync() == d.Hash ? d : null;
}))
.Do(d =>
{
if (d != null)
{
indexed.Remove(d.To);
}
});
2020-01-13 21:11:07 +00:00
UpdateTracker.NextStep("Updating ModList");
Utils.Log($"Optimized {ModList.Directives.Count} directives to {indexed.Count} required");
var requiredArchives = indexed.Values.OfType<FromArchive>()
2020-03-25 23:15:19 +00:00
.GroupBy(d => d.ArchiveHashPath.BaseHash)
.Select(d => d.Key)
.ToHashSet();
ModList.Archives = ModList.Archives.Where(a => requiredArchives.Contains(a.Hash)).ToList();
ModList.Directives = indexed.Values.ToList();
}
}
public class NotEnoughDiskSpaceException : Exception
{
public NotEnoughDiskSpaceException(string s) : base(s)
{
}
}
}