Files
minecraft-modpack-updater/ModpackUpdater.Manager/ModpackInstaller.cs

262 lines
10 KiB
C#

using Newtonsoft.Json;
using System.IO.Compression;
using FileMode = System.IO.FileMode;
namespace ModpackUpdater.Manager;
public class ModpackInstaller(ModpackConfig updateConfig, ModpackInfo modpackInfo)
{
private class LocalZipCacheEntry
{
public string DownloadUrl { get; set; }
public string ExtractedZipPath { get; set; }
}
public event InstallProgessUpdatedEventHandler InstallProgessUpdated;
public delegate void InstallProgessUpdatedEventHandler(UpdateCheckResult result, int processedSyncs);
public event CheckingProgressUpdatedEventHandler CheckingProgressUpdated;
public delegate void CheckingProgressUpdatedEventHandler(int toCheck, int processed);
private readonly HttpClient http = new();
private readonly ModpackFactory factory = new();
~ModpackInstaller()
{
http.Dispose();
}
private async Task<UpdateInfos> DownloadUpdateInfos()
{
var content = await http.GetStringAsync(updateConfig.UpdateUrl);
return UpdateInfos.Parse(content);
}
private async Task<InstallInfos> DownloadInstallInfos()
{
var content = await http.GetStringAsync(updateConfig.InstallUrl);
return InstallInfos.Parse(content);
}
public async Task<UpdateCheckResult> Check(UpdateCheckOptions options)
{
InstallInfos installInfos = null;
UpdateInfos updateInfos = null;
var result = new UpdateCheckResult();
var exists = modpackInfo.Exists;
if (updateConfig.Maintenance && !options.IgnoreMaintenance)
{
result.IsInMaintenance = true;
return result;
}
if (modpackInfo == null || !Directory.Exists(modpackInfo.LocaLPath))
{
result.HasError = true;
return result;
}
installInfos = await DownloadInstallInfos();
// Check install actions
if (!exists)
{
if (installInfos is not null && installInfos.IsPublic && installInfos.Actions.Count != 0)
{
var actions = installInfos.Actions.Where(n => n.Side.IsSide(options.Side) && (!n.IsExtra || options.IncludeExtras));
if (actions.Any())
{
result.Actions.AddRange(actions);
result.LatestVersion = installInfos.Version;
result.CurrentVersion = installInfos.Version;
}
}
if (result.Actions.Count == 0)
result.HasError = true;
}
// Check update actions
if (exists || options.AllowUpdaterAfterInstall)
{
updateInfos = await DownloadUpdateInfos();
if (updateInfos is not null && updateInfos.Updates.Count != 0)
{
var updatesOrderes = updateInfos.Updates.Where(n => n.IsPublic || options.IncludeNonPublic).OrderByDescending(n => n.Version);
result.LatestVersion = updatesOrderes.First().Version;
if (exists)
result.CurrentVersion = modpackInfo.Version;
result.IsInstalled = true;
var checkingVersionIndex = 0;
var checkingVersion = updatesOrderes.ElementAtOrDefault(checkingVersionIndex);
var actionsZeroIndex = result.Actions.Count; // Ensure we insert update actions behind install actions
while (checkingVersion is not null && checkingVersion.Version > result.CurrentVersion)
{
var actionsToAdd = new List<UpdateAction>();
foreach (var action in checkingVersion.Actions)
{
// Resolve inherits
ResolveInherit(action, installInfos);
// Check & add
if (action.Side.IsSide(options.Side) && (!action.IsExtra || options.IncludeExtras) && !result.Actions.Any(n => n.DestPath == action.DestPath))
actionsToAdd.Add(action);
}
result.Actions.InsertRange(actionsZeroIndex, actionsToAdd);
checkingVersionIndex += 1;
checkingVersion = updatesOrderes.ElementAtOrDefault(checkingVersionIndex);
}
}
else
result.HasError = true;
}
return result;
}
public static void ResolveInherit(UpdateAction action, InstallInfos installInfos)
{
if (!string.IsNullOrWhiteSpace(action.InheritFrom) && installInfos.Actions.FirstOrDefault(a => a.Id == action.InheritFrom) is InstallAction iaction)
DuplicateTo(iaction, action);
}
public static void DuplicateTo(InstallAction source, InstallAction destination)
{
JsonConvert.PopulateObject(JsonConvert.SerializeObject(source), destination);
}
public async Task<bool?> Install(UpdateCheckResult checkResult)
{
var processed = 0;
var localZipCache = new List<LocalZipCacheEntry>();
foreach (InstallAction iaction in checkResult.Actions)
{
var destFilePath = Path.Combine(modpackInfo.LocaLPath, iaction.DestPath);
var sourceUrl = updateConfig.PreferDirectLinks && !string.IsNullOrWhiteSpace(iaction.SourceUrl)
? iaction.SourceUrl
: await factory.ResolveSourceUrl(iaction);
if (iaction is UpdateAction uaction)
{
switch (uaction.Type)
{
case UpdateActionType.Update:
await InstallFile(destFilePath, sourceUrl, uaction.IsZip, uaction.ZipPath, localZipCache);
break;
case UpdateActionType.Delete:
{
if (uaction.IsDirectory)
{
if (Directory.Exists(destFilePath))
Directory.Delete(destFilePath, true);
}
else if (File.Exists(destFilePath))
File.Delete(destFilePath);
}
break;
case UpdateActionType.Copy:
{
var srcFilePath = Path.Combine(modpackInfo.LocaLPath, uaction.SrcPath);
if (uaction.IsDirectory)
{
if (Directory.Exists(srcFilePath))
Extensions.CopyDirectory(srcFilePath, destFilePath, true);
}
else if (File.Exists(srcFilePath))
{
Directory.CreateDirectory(Path.GetDirectoryName(destFilePath));
File.Copy(srcFilePath, destFilePath, true);
}
}
break;
case UpdateActionType.Move:
{
var srcFilePath = Path.Combine(modpackInfo.LocaLPath, uaction.SrcPath);
if (uaction.IsDirectory)
{
if (Directory.Exists(srcFilePath))
Directory.Move(srcFilePath, destFilePath);
}
else if (File.Exists(srcFilePath))
{
Directory.CreateDirectory(Path.GetDirectoryName(destFilePath));
File.Move(srcFilePath, destFilePath, true);
}
}
break;
}
}
else
await InstallFile(destFilePath, sourceUrl, iaction.IsZip, iaction.ZipPath, localZipCache);
processed += 1;
InstallProgessUpdated?.Invoke(checkResult, processed);
}
// Save new modpack info
modpackInfo.Version = checkResult.LatestVersion;
modpackInfo.ConfigUrl = updateConfig.ConfigUrl;
modpackInfo.Save();
// Delete cached zip files
foreach (var task in localZipCache)
Directory.Delete(task.ExtractedZipPath, true);
return true;
}
private async Task InstallFile(string destFilePath, string sourceUrl, bool isZip, string zipPath, List<LocalZipCacheEntry> localZipCache)
{
Directory.CreateDirectory(Path.GetDirectoryName(destFilePath));
if (!isZip || localZipCache.FirstOrDefault(n => n.DownloadUrl == sourceUrl) is not LocalZipCacheEntry cachedZipInfo)
{
// Download
var fsDestinationPath = isZip ? Path.Combine(Path.GetTempPath(), $"mc_update_file_{DateTime.Now.ToBinary()}.zip") : destFilePath;
var sRemote = await http.GetStreamAsync(sourceUrl);
var fs = new FileStream(fsDestinationPath, FileMode.Create, FileAccess.ReadWrite);
await sRemote.CopyToAsync(fs);
await fs.FlushAsync();
sRemote.Close();
fs.Close();
// Extract
if (isZip)
{
// Extract files
var zipDir = Path.Combine(Path.GetDirectoryName(fsDestinationPath), Path.GetFileNameWithoutExtension(fsDestinationPath));
ZipFile.ExtractToDirectory(fsDestinationPath, zipDir);
// Create cache entry
cachedZipInfo = new()
{
DownloadUrl = sourceUrl,
ExtractedZipPath = zipDir
};
localZipCache.Add(cachedZipInfo);
// Remofe temp zip file
File.Delete(fsDestinationPath);
}
else
cachedZipInfo = null;
}
// Handle zip file content
if (cachedZipInfo != null)
{
// Copy content
var zipSrc = Path.Combine(cachedZipInfo.ExtractedZipPath, zipPath);
Extensions.CopyDirectory(zipSrc, destFilePath, true);
}
}
}