Compare commits

..

2 Commits

Author SHA1 Message Date
968ff99987 ModpackManifest deleted 2024-12-31 20:03:31 +05:00
e5deb3f3d4 InstalledGameVersionCatalog 2024-12-31 17:55:30 +05:00
28 changed files with 551 additions and 412 deletions

View File

@ -20,7 +20,7 @@ public record Config
public bool redirect_game_output { get; set; } = false;
public string? last_launched_version { get; set; }
public int max_parallel_downloads { get; set; } = 16;
public VersionCatalogProps[] version_catalogs { get; set; } =
public GameVersionCatalogProps[] version_catalogs { get; set; } =
[
new() { name = "Mojang", url = "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json" },
new() { name = "Тимериховое", url = "https://timerix.ddns.net/minecraft/catalog.json" }
@ -31,10 +31,10 @@ public record Config
public static Config LoadFromFile()
{
LauncherApp.Logger.LogInfo(nameof(Config), $"loading config from file '{_filePath}'");
LauncherApp.Logger.LogDebug(nameof(Config), $"loading config from file '{_filePath}'");
if(!File.Exists(_filePath))
{
LauncherApp.Logger.LogInfo(nameof(Config), "file doesn't exist");
LauncherApp.Logger.LogDebug(nameof(Config), "file doesn't exist");
return new Config();
}
@ -67,7 +67,7 @@ public record Config
public void SaveToFile()
{
LauncherApp.Logger.LogInfo(nameof(Config), $"saving config to file '{_filePath}'");
LauncherApp.Logger.LogDebug(nameof(Config), $"saving config to file '{_filePath}'");
var text = JsonConvert.SerializeObject(this, Formatting.Indented);
File.WriteAllText(_filePath, text);
LauncherApp.Logger.LogDebug(nameof(Config), $"config has been saved: {text}");

View File

@ -7,15 +7,14 @@ using Mlaumcherb.Client.Avalonia.классы;
using Mlaumcherb.Client.Avalonia.сеть;
using Mlaumcherb.Client.Avalonia.сеть.TaskFactories;
using Mlaumcherb.Client.Avalonia.холопы;
using Newtonsoft.Json.Linq;
using static Mlaumcherb.Client.Avalonia.холопы.PathHelper;
namespace Mlaumcherb.Client.Avalonia;
public class GameVersion
{
private readonly GameVersionProps _props;
public string Name => _props.Name;
private readonly InstalledGameVersionProps _props;
public string Id => _props.Id;
public IOPath WorkingDirectory { get; }
private IOPath JavaExecutableFilePath;
@ -27,69 +26,10 @@ public class GameVersion
private CancellationTokenSource? _gameCts;
private CommandTask<CommandResult>? _commandTask;
public static Task<List<GameVersionProps>> GetAllVersionsAsync()
{
var propsList = new List<GameVersionProps>();
// local descriptors
Directory.Create(GetVersionsDir());
foreach (IOPath subdir in Directory.GetDirectories(GetVersionsDir()))
{
string name = subdir.LastName().ToString();
var d = new GameVersionProps(name);
if(!File.Exists(d.LocalDescriptorPath))
throw new Exception("Can't find version descriptor file in directory '{subdir}'. Rename it as directory name.");
propsList.Add(d);
}
// reverse sort
propsList.Sort((a, b) => b.CompareTo(a));
return Task.FromResult(propsList);
}
public static async Task<GameVersion> CreateFromPropsAsync(GameVersionProps props, bool checkHash)
{
//TODO: refresh version descriptor from server
if (!File.Exists(props.LocalDescriptorPath))
{
if (props.RemoteProps is null)
throw new NullReferenceException("can't download game version descriptor '"
+ props.Name + "', because RemoteDescriptorUrl is null");
await NetworkHelper.DownloadFile(props.RemoteProps.url, props.LocalDescriptorPath);
}
return new GameVersion(props);
}
private GameVersion(GameVersionProps props)
internal GameVersion(InstalledGameVersionProps props, GameVersionDescriptor descriptor)
{
_props = props;
string descriptorText = File.ReadAllText(props.LocalDescriptorPath);
JObject descriptorRaw = JObject.Parse(descriptorText);
// Descriptors can inherit from other descriptors.
// For example, 1.12.2-forge-14.23.5.2860 inherits from 1.12.2
if (descriptorRaw.TryGetValue("inheritsFrom", out var v))
{
string parentDescriptorId = v.Value<string>()
?? throw new Exception("inheritsFrom is null");
LauncherApp.Logger.LogInfo(Name, $"merging descriptor '{parentDescriptorId}' with '{Name}'");
IOPath parentDescriptorPath = GetVersionDescriptorPath(parentDescriptorId);
if (!File.Exists(parentDescriptorPath))
throw new Exception($"Версия '{Name} требует установить версию '{parentDescriptorId}'");
string parentDescriptorText = File.ReadAllText(parentDescriptorPath);
JObject parentDescriptorRaw = JObject.Parse(parentDescriptorText);
parentDescriptorRaw.Merge(descriptorRaw,
new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Concat });
descriptorRaw = parentDescriptorRaw;
// removing dependency
descriptorRaw.Remove("inheritsFrom");
File.WriteAllText(props.LocalDescriptorPath, descriptorRaw.ToString());
}
_descriptor = descriptorRaw.ToObject<GameVersionDescriptor>()
?? throw new Exception($"can't parse descriptor file '{props.LocalDescriptorPath}'");
_descriptor = descriptor;
_javaArgs = new JavaArguments(_descriptor);
_gameArgs = new GameArguments(_descriptor);
_libraries = new Libraries(_descriptor);
@ -97,9 +37,11 @@ public class GameVersion
JavaExecutableFilePath = GetJavaExecutablePath(_descriptor.javaVersion.component, LauncherApp.Config.debug);
}
public async Task UpdateFiles(bool checkHashes, Action<NetworkTask> networkTaskCreatedCallback)
public async Task Download(bool update, Action<NetworkTask> networkTaskCreatedCallback)
{
LauncherApp.Logger.LogInfo(Name, $"started updating version {Name}");
LauncherApp.Logger.LogInfo(Id, $"started updating version {Id}");
List<INetworkTaskFactory> taskFactories =
[
@ -107,20 +49,16 @@ public class GameVersion
new LibrariesDownloadTaskFactory(_descriptor, _libraries),
];
if (LauncherApp.Config.download_java)
{
taskFactories.Add(new JavaDownloadTaskFactory(_descriptor));
}
if (_descriptor.modpack != null)
{
taskFactories.Add(new ModpackDownloadTaskFactory(_descriptor));
}
// has to be downloaded last because it is used by GameVersionProps to check if version is installed
// has to be downloaded last because it is used to check if version is installed
taskFactories.Add(new VersionJarDownloadTaskFactory(_descriptor));
var networkTasks = new List<NetworkTask>();
for (int i = 0; i < taskFactories.Count; i++)
{
var nt = await taskFactories[i].CreateAsync(checkHashes);
var nt = await taskFactories[i].CreateAsync(update);
if (nt != null)
{
networkTasks.Add(nt);
@ -142,8 +80,8 @@ public class GameVersion
await res.CopyToAsync(file);
}
_props.IsDownloaded = true;
LauncherApp.Logger.LogInfo(Name, $"finished updating version {Name}");
_props.IsInstalled = true;
LauncherApp.Logger.LogInfo(Id, $"finished updating version {Id}");
}
//minecraft player uuid explanation
@ -224,23 +162,23 @@ public class GameVersion
.WithStandardOutputPipe(PipeTarget.ToDelegate(LogGameOut))
.WithStandardErrorPipe(PipeTarget.ToDelegate(LogGameError));
}
LauncherApp.Logger.LogInfo(Name, "launching the game");
LauncherApp.Logger.LogDebug(Name, "java: " + command.TargetFilePath);
LauncherApp.Logger.LogDebug(Name, "working_dir: " + command.WorkingDirPath);
LauncherApp.Logger.LogDebug(Name, "arguments: \n\t" + argsList.MergeToString("\n\t"));
LauncherApp.Logger.LogInfo(Id, "launching the game");
LauncherApp.Logger.LogDebug(Id, "java: " + command.TargetFilePath);
LauncherApp.Logger.LogDebug(Id, "working_dir: " + command.WorkingDirPath);
LauncherApp.Logger.LogDebug(Id, "arguments: \n\t" + argsList.MergeToString("\n\t"));
_gameCts = new();
_commandTask = command.ExecuteAsync(_gameCts.Token);
var result = await _commandTask;
LauncherApp.Logger.LogInfo(Name, $"game exited with code {result.ExitCode}");
LauncherApp.Logger.LogInfo(Id, $"game exited with code {result.ExitCode}");
}
private void LogGameOut(string line)
{
LauncherApp.Logger.LogInfo(Name, line);
LauncherApp.Logger.LogInfo(Id, line);
}
private void LogGameError(string line)
{
LauncherApp.Logger.LogWarn(Name, line);
LauncherApp.Logger.LogWarn(Id, line);
}
public void Close()
@ -249,5 +187,5 @@ public class GameVersion
}
public override string ToString() => Name;
public override string ToString() => Id;
}

View File

@ -10,6 +10,7 @@ public class LauncherLogger : ILogger
public LauncherLogger()
{
_fileLogger = new FileLogger(LogsDirectory, "млаумчерб");
_fileLogger.DebugLogEnabled = true;
ILogger[] loggers =
[
_fileLogger,
@ -54,7 +55,11 @@ public class LauncherLogger : ILogger
public bool DebugLogEnabled
{
get => _compositeLogger.DebugLogEnabled;
set => _compositeLogger.DebugLogEnabled = value;
set
{
_compositeLogger.DebugLogEnabled = value;
_fileLogger.DebugLogEnabled = true;
}
}
public bool InfoLogEnabled

View File

@ -13,6 +13,8 @@
<AssemblyName>млаумчерб</AssemblyName>
<Configurations>Release;Debug</Configurations>
<Platforms>x64</Platforms>
<!-- AXAML resource has no public constructor -->
<NoWarn>AVLN3001</NoWarn>
</PropertyGroup>
<ItemGroup>

View File

@ -4,7 +4,7 @@
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Mlaumcherb.Client.Avalonia"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
x:Class="Mlaumcherb.Client.Avalonia.зримое.VersionItemView"
x:Class="Mlaumcherb.Client.Avalonia.зримое.GameVersionItemView"
Padding="2">
<TextBlock Name="text" Background="Transparent"/>
</UserControl>

View File

@ -0,0 +1,48 @@
using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Threading;
using Mlaumcherb.Client.Avalonia.классы;
namespace Mlaumcherb.Client.Avalonia.зримое;
public abstract partial class GameVersionItemView : ListBoxItem
{
private static readonly SolidColorBrush _avaliableColor = new(Color.FromRgb(30, 130, 40));
private static readonly SolidColorBrush _unavaliableColor = new(Color.FromRgb(170, 70, 70));
protected GameVersionItemView(string name, bool initialStatus)
{
InitializeComponent();
text.Text = name;
UpdateBackground(initialStatus);
}
protected void UpdateBackground(bool isInstalled)
{
Dispatcher.UIThread.Invoke(() => Background = isInstalled ? _avaliableColor : _unavaliableColor);
}
}
// Background changes when props status changes
public class InstalledGameVersionItemView : GameVersionItemView
{
public readonly InstalledGameVersionProps Props;
public InstalledGameVersionItemView(InstalledGameVersionProps props) : base(props.Id, props.IsInstalled)
{
Props = props;
props.StatusChanged += UpdateBackground;
}
}
// Background is set once by checking if the version is present in InstalledVersionsCatalog
public class RemoteGameVersionItemView : GameVersionItemView
{
public readonly RemoteVersionDescriptorProps Props;
public RemoteGameVersionItemView(RemoteVersionDescriptorProps props)
: base(props.id, LauncherApp.InstalledVersionCatalog.versions.ContainsKey(props.id))
{
Props = props;
}
}

View File

@ -25,6 +25,10 @@
<Setter Property="MinWidth" Value="50"/>
</Style>
<Style Selector="Button.button_dark">
<Setter Property="Background" Value="#65656070"/>
</Style>
<Style Selector="Border.menu_separator">
<Setter Property="Background" Value="#ff505050"/>
<Setter Property="Width" Value="1"/>

View File

@ -1,13 +1,15 @@
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using Mlaumcherb.Client.Avalonia.классы;
namespace Mlaumcherb.Client.Avalonia.зримое;
public class LauncherApp : Application
{
public static LauncherLogger Logger = new();
public static Config Config = new();
public static Config Config = null!;
public static InstalledVersionCatalog InstalledVersionCatalog = null!;
public override void Initialize()
{
@ -21,6 +23,8 @@ public class LauncherApp : Application
{
File.WriteAllText("launcher_profiles.json", "{}");
}
InstalledVersionCatalog = InstalledVersionCatalog.Load();
}
public override void OnFrameworkInitializationCompleted()

View File

@ -34,20 +34,30 @@
<ScrollViewer Grid.Row="0"
HorizontalScrollBarVisibility="Disabled"
VerticalScrollBarVisibility="Auto">
<StackPanel Margin="10" Spacing="10">
<TextBlock>Версия:</TextBlock>
<ComboBox Name="InstalledVersionComboBox"/>
<StackPanel Margin="10" Spacing="6">
<TextBlock>Ник:</TextBlock>
<TextBox Background="Transparent"
Text="{Binding #window.PlayerName}"/>
<TextBlock>Версия игры:</TextBlock>
<ComboBox Name="InstalledVersionCatalogComboBox"/>
<Button Name="RescanInstalledVersionsButton"
Click="RescanInstalledVersionsButton_OnClick"
Classes="button_dark">
Обновить список
</Button>
<Button Name="DeleteVersionButton"
Click="DeleteVersionButton_OnClick">
Click="DeleteVersionButton_OnClick"
Classes="button_dark">
Удалить версию
</Button>
<Expander Header="Добавление версий"
BorderThickness="1" BorderBrush="Gray"
Padding="4">
<StackPanel>
<StackPanel Spacing="6">
<TextBlock>Источник:</TextBlock>
<ComboBox Name="VersionCatalogComboBox"/>
<ComboBox Name="RemoteVersionCatalogComboBox"/>
<WrapPanel>
<CheckBox Name="ReleaseVersionTypeCheckBox" IsChecked="True">релиз</CheckBox>
<CheckBox Name="SnapshotVersionTypeCheckBox">снапшот</CheckBox>
@ -55,22 +65,20 @@
<CheckBox Name="OtherVersionTypeAlphaCheckBox">другое</CheckBox>
</WrapPanel>
<Button Name="SearchVersionsButton"
Click="SearchVersionsButton_OnClick">
Click="SearchVersionsButton_OnClick"
Classes="button_dark">
Поиск
</Button>
<TextBlock>Доступные версии:</TextBlock>
<ComboBox Name="VersionCatalogItemsComboBox"/>
<ComboBox Name="RemoteVersionCatalogItemsComboBox"/>
<Button Name="AddVersionButton" IsEnabled="False"
Click="AddVersionButton_OnClick">
Click="AddVersionButton_OnClick"
Classes="button_dark">
Добавить
</Button>
</StackPanel>
</Expander>
<TextBlock>Ник:</TextBlock>
<TextBox Background="Transparent"
Text="{Binding #window.PlayerName}"/>
<TextBlock>
<Run>Выделенная память:</Run>
<TextBox Background="Transparent" Padding="0"
@ -84,8 +92,8 @@
Value="{Binding #window.MemoryLimit}">
</Slider>
<CheckBox IsChecked="{Binding #window.CheckGameFiles}">
Проверять файлы игры
<CheckBox IsChecked="{Binding #window.UpdateGameFiles}">
Обновить файлы игры
</CheckBox>
<CheckBox IsChecked="{Binding #window.EnableJavaDownload}">
Скачивать джаву

View File

@ -32,13 +32,13 @@ public partial class MainWindow : Window
set => SetValue(MemoryLimitProperty, value);
}
public static readonly StyledProperty<bool> CheckGameFilesProperty =
AvaloniaProperty.Register<MainWindow, bool>(nameof(CheckGameFiles),
public static readonly StyledProperty<bool> UpdateGameFilesProperty =
AvaloniaProperty.Register<MainWindow, bool>(nameof(UpdateGameFiles),
defaultBindingMode: BindingMode.TwoWay, defaultValue: false);
public bool CheckGameFiles
public bool UpdateGameFiles
{
get => GetValue(CheckGameFilesProperty);
set => SetValue(CheckGameFilesProperty, value);
get => GetValue(UpdateGameFilesProperty);
set => SetValue(UpdateGameFilesProperty, value);
}
@ -65,7 +65,7 @@ public partial class MainWindow : Window
InitializeComponent();
}
protected override async void OnLoaded(RoutedEventArgs e)
protected override void OnLoaded(RoutedEventArgs e)
{
try
{
@ -76,27 +76,13 @@ public partial class MainWindow : Window
EnableJavaDownload = LauncherApp.Config.download_java;
RedirectGameOutput = LauncherApp.Config.redirect_game_output;
InstalledVersionComboBox.SelectedIndex = 0;
InstalledVersionComboBox.IsEnabled = false;
var versions = await GameVersion.GetAllVersionsAsync();
Dispatcher.UIThread.Invoke(() =>
{
foreach (var p in versions)
{
InstalledVersionComboBox.Items.Add(new VersionItemView(p));
// select last played version
if (LauncherApp.Config.last_launched_version != null &&
p.Name == LauncherApp.Config.last_launched_version)
InstalledVersionComboBox.SelectedIndex = InstalledVersionComboBox.Items.Count - 1;
}
InstalledVersionComboBox.IsEnabled = true;
foreach (var vc in LauncherApp.Config.version_catalogs)
{
VersionCatalogComboBox.Items.Add(vc);
RemoteVersionCatalogComboBox.Items.Add(vc);
}
VersionCatalogComboBox.SelectedIndex = 0;
});
RemoteVersionCatalogComboBox.SelectedIndex = 0;
UpdateInstalledVersionsCatalogView(LauncherApp.Config.last_launched_version);
}
catch (Exception ex)
{
@ -104,6 +90,39 @@ public partial class MainWindow : Window
}
}
private void UpdateInstalledVersionsCatalogView(string? selectVersion)
{
LauncherApp.InstalledVersionCatalog.CheckInstalledVersions();
InstalledVersionCatalogComboBox.IsEnabled = false;
InstalledVersionCatalogComboBox.Items.Clear();
foreach (var p in LauncherApp.InstalledVersionCatalog.versions)
{
InstalledVersionCatalogComboBox.Items.Add(new InstalledGameVersionItemView(p.Value));
}
InstalledVersionCatalogComboBox.SelectedItem = null;
if(selectVersion is not null
&& LauncherApp.InstalledVersionCatalog.versions.TryGetValue(selectVersion, out var props))
{
foreach (InstalledGameVersionItemView? view in InstalledVersionCatalogComboBox.Items)
{
if (view?.Props.Id == props.Id)
{
InstalledVersionCatalogComboBox.SelectedItem = view;
break;
}
}
}
InstalledVersionCatalogComboBox.IsEnabled = true;
}
private void RescanInstalledVersionsButton_OnClick(object? sender, RoutedEventArgs e)
{
var selectedVersionView = InstalledVersionCatalogComboBox.SelectedItem as InstalledGameVersionItemView;
UpdateInstalledVersionsCatalogView(selectedVersionView?.Props.Id);
}
private void GuiLogMessage(LauncherLogger.LogMessage msg)
{
if (msg.severity == LogSeverity.Debug) return;
@ -121,21 +140,19 @@ public partial class MainWindow : Window
{
try
{
Dispatcher.UIThread.Invoke(() => LaunchButton.IsEnabled = false);
if (InstalledVersionCatalogComboBox.SelectedItem is not InstalledGameVersionItemView selectedVersionView)
return;
var selectedVersionView = (VersionItemView?)InstalledVersionComboBox.SelectedItem;
var selectedVersion = selectedVersionView?.Props;
LauncherApp.Config.last_launched_version = selectedVersion?.Name;
Dispatcher.UIThread.Invoke(() => LaunchButton.IsEnabled = false);
LauncherApp.Config.last_launched_version = selectedVersionView.Props.Id;
LauncherApp.Config.player_name = PlayerName;
LauncherApp.Config.max_memory = MemoryLimit;
LauncherApp.Config.download_java = EnableJavaDownload;
LauncherApp.Config.redirect_game_output = RedirectGameOutput;
LauncherApp.Config.SaveToFile();
if (selectedVersion == null)
return;
var v = await GameVersion.CreateFromPropsAsync(selectedVersion, CheckGameFiles);
await v.UpdateFiles(CheckGameFiles, nt =>
var v = await selectedVersionView.Props.LoadDescriptor(UpdateGameFiles);
await v.Download(UpdateGameFiles, nt =>
{
Dispatcher.UIThread.Invoke(() =>
{
@ -146,7 +163,7 @@ public partial class MainWindow : Window
);
Dispatcher.UIThread.Invoke(() =>
{
CheckGameFiles = false;
UpdateGameFiles = false;
});
await v.Launch();
}
@ -156,10 +173,7 @@ public partial class MainWindow : Window
}
finally
{
Dispatcher.UIThread.Invoke(() =>
{
LaunchButton.IsEnabled = true;
});
Dispatcher.UIThread.Invoke(() => LaunchButton.IsEnabled = true);
}
}
@ -218,71 +232,32 @@ public partial class MainWindow : Window
DownloadsPanel.Children.Clear();
}
private async void DeleteVersionButton_OnClick(object? sender, RoutedEventArgs e)
{
try
{
VersionItemView? sel = InstalledVersionComboBox.SelectedItem as VersionItemView;
if(sel is null)
return;
var box = MessageBoxManager.GetMessageBoxCustom(new MessageBoxCustomParams
{
ButtonDefinitions = new List<ButtonDefinition> { new() { Name = "Да" }, new() { Name = "Нет" } },
ContentTitle = $"Удаление версии {sel.Props.Name}",
ContentMessage = $"Вы уверены, что хотите удалить версию {sel.Props.Name}? Все файлы, включая сохранения, будут удалены!",
Icon = MsBox.Avalonia.Enums.Icon.Question,
WindowStartupLocation = WindowStartupLocation.CenterOwner,
SizeToContent = SizeToContent.WidthAndHeight,
ShowInCenter = true,
Topmost = true
}
);
var result = await box.ShowAsync().ConfigureAwait(false);
if (result != "Да")
return;
sel.Props.DeleteFiles();
Dispatcher.UIThread.Invoke(() =>
{
InstalledVersionComboBox.Items.Remove(sel);
});
}
catch (Exception ex)
{
ErrorHelper.ShowMessageBox(nameof(MainWindow), ex);
}
}
private async void SearchVersionsButton_OnClick(object? sender, RoutedEventArgs e)
{
try
{
var catalogProps = VersionCatalogComboBox.SelectedItem as VersionCatalogProps;
if(catalogProps is null)
if(RemoteVersionCatalogComboBox.SelectedItem is not GameVersionCatalogProps catalogProps)
return;
var catalog = await catalogProps.GetVersionCatalogAsync();
var searchParams = new VersionSearchParams();
Dispatcher.UIThread.Invoke(() =>
var searchParams = new VersionSearchParams
{
searchParams.ReleaseTypeAllowed = ReleaseVersionTypeCheckBox.IsChecked ?? false;
searchParams.SnapshotTypeAllowed = SnapshotVersionTypeCheckBox.IsChecked ?? false;
searchParams.OldTypeAllowed = OldVersionTypeCheckBox.IsChecked ?? false;
searchParams.OtherTypeAllowed = OtherVersionTypeAlphaCheckBox.IsChecked ?? false;
});
ReleaseTypeAllowed = ReleaseVersionTypeCheckBox.IsChecked ?? false,
SnapshotTypeAllowed = SnapshotVersionTypeCheckBox.IsChecked ?? false,
OldTypeAllowed = OldVersionTypeCheckBox.IsChecked ?? false,
OtherTypeAllowed = OtherVersionTypeAlphaCheckBox.IsChecked ?? false
};
var versions = catalog.GetDownloadableVersions(searchParams);
Dispatcher.UIThread.Invoke(() =>
{
VersionCatalogItemsComboBox.IsEnabled = false;
VersionCatalogItemsComboBox.Items.Clear();
RemoteVersionCatalogItemsComboBox.IsEnabled = false;
RemoteVersionCatalogItemsComboBox.Items.Clear();
foreach (var p in versions)
{
VersionCatalogItemsComboBox.Items.Add(new VersionItemView(p));
RemoteVersionCatalogItemsComboBox.Items.Add(new RemoteGameVersionItemView(p));
}
VersionCatalogItemsComboBox.SelectedIndex = 0;
VersionCatalogItemsComboBox.IsEnabled = true;
RemoteVersionCatalogItemsComboBox.IsEnabled = true;
AddVersionButton.IsEnabled = versions.Count > 0;
});
}
@ -296,12 +271,57 @@ public partial class MainWindow : Window
{
try
{
var selectedVersionView = VersionCatalogItemsComboBox.SelectedItem as VersionItemView;
if(selectedVersionView is null)
if(RemoteVersionCatalogComboBox.SelectedItem is not GameVersionCatalogProps catalogProps)
return;
InstalledVersionComboBox.Items.Insert(0, new VersionItemView(selectedVersionView.Props));
InstalledVersionComboBox.SelectedIndex = 0;
if(RemoteVersionCatalogItemsComboBox.SelectedItem is not RemoteGameVersionItemView sel)
return;
var installedProps = new InstalledGameVersionProps(sel.Props.id, catalogProps, sel.Props);
if (!LauncherApp.InstalledVersionCatalog.versions.TryAdd(sel.Props.id, installedProps))
throw new Exception("Версия уже была добавлена");
LauncherApp.InstalledVersionCatalog.Save();
var propsView = new InstalledGameVersionItemView(installedProps);
InstalledVersionCatalogComboBox.Items.Insert(0, propsView);
InstalledVersionCatalogComboBox.SelectedItem = propsView;
}
catch (Exception ex)
{
ErrorHelper.ShowMessageBox(nameof(MainWindow), ex);
}
}
private async void DeleteVersionButton_OnClick(object? sender, RoutedEventArgs e)
{
try
{
if(InstalledVersionCatalogComboBox.SelectedItem is not InstalledGameVersionItemView sel)
return;
var box = MessageBoxManager.GetMessageBoxCustom(new MessageBoxCustomParams
{
ButtonDefinitions = new List<ButtonDefinition> { new() { Name = "Да" }, new() { Name = "Нет" } },
ContentTitle = $"Удаление версии {sel.Props.Id}",
ContentMessage = $"Вы уверены, что хотите удалить версию {sel.Props.Id}? Все файлы, включая сохранения, будут удалены!",
Icon = MsBox.Avalonia.Enums.Icon.Question,
WindowStartupLocation = WindowStartupLocation.CenterOwner,
SizeToContent = SizeToContent.WidthAndHeight,
ShowInCenter = true,
Topmost = true
}
);
var result = await box.ShowAsync().ConfigureAwait(false);
if (result != "Да")
return;
sel.Props.Delete();
Dispatcher.UIThread.Invoke(() =>
{
InstalledVersionCatalogComboBox.Items.Remove(sel);
LauncherApp.InstalledVersionCatalog.versions.Remove(sel.Props.Id);
LauncherApp.InstalledVersionCatalog.Save();
});
}
catch (Exception ex)
{

View File

@ -1,34 +0,0 @@
using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Threading;
using Mlaumcherb.Client.Avalonia.классы;
namespace Mlaumcherb.Client.Avalonia.зримое;
public partial class VersionItemView : ListBoxItem
{
public GameVersionProps Props { get; }
private SolidColorBrush _avaliableColor = new(Color.FromRgb(30, 130, 40));
private SolidColorBrush _unavaliableColor = new(Color.FromRgb(170, 70, 70));
public VersionItemView()
{
throw new Exception();
}
public VersionItemView(GameVersionProps props)
{
Props = props;
InitializeComponent();
text.Text = props.Name;
props.StatusChanged += UpdateBackground;
UpdateBackground(props.IsDownloaded);
}
private void UpdateBackground(bool isDownloaded)
{
Dispatcher.UIThread.Invoke(() =>
Background = isDownloaded ? _avaliableColor : _unavaliableColor
);
}
}

View File

@ -10,12 +10,12 @@ public record VersionSearchParams
public class GameVersionCatalog
{
[JsonRequired] public List<RemoteVersionDescriptorProps> versions { get; set; } = null!;
[JsonRequired] public List<RemoteVersionDescriptorProps> versions { get; set; } = new();
/// <returns>empty list if couldn't find any remote versions</returns>
public List<GameVersionProps> GetDownloadableVersions(VersionSearchParams p)
public List<RemoteVersionDescriptorProps> GetDownloadableVersions(VersionSearchParams p)
{
var _versionPropsList = new List<GameVersionProps>();
var _versionPropsList = new List<RemoteVersionDescriptorProps>();
foreach (var r in versions)
{
bool match = r.type switch
@ -26,7 +26,7 @@ public class GameVersionCatalog
_ => p.OtherTypeAllowed
};
if(match)
_versionPropsList.Add(new GameVersionProps(r));
_versionPropsList.Add(r);
}
return _versionPropsList;
}

View File

@ -10,7 +10,7 @@ public class GameVersionDescriptor
[JsonRequired] public DateTime releaseTime { get; set; }
[JsonRequired] public string type { get; set; } = "";
[JsonRequired] public string mainClass { get; set; } = "";
[JsonRequired] public List<Library> libraries { get; set; } = null!;
[JsonRequired] public List<Library> libraries { get; set; } = new();
[JsonRequired] public AssetIndexProperties assetIndex { get; set; } = null!;
[JsonRequired] public string assets { get; set; } = "";
public Downloads? downloads { get; set; } = null;

View File

@ -67,7 +67,7 @@ public class JavaVersionProps
public class JavaDistributiveManifest
{
[JsonRequired] public Dictionary<string, JavaDistributiveElementProps> files { get; set; } = null!;
[JsonRequired] public Dictionary<string, JavaDistributiveElementProps> files { get; set; } = new();
}
public class JavaDistributiveElementProps

View File

@ -1,30 +0,0 @@
using Mlaumcherb.Client.Avalonia.холопы;
namespace Mlaumcherb.Client.Avalonia.классы;
public class ModpackFilesManifest
{
public class FileProps
{
[JsonRequired] public string sha1 { get; set; }
public bool allow_edit { get; set; } = false;
}
/// relative_path, hash
[JsonRequired] public Dictionary<string, FileProps> files { get; set; } = new();
public bool CheckFiles(IOPath basedir, bool checkHashes, HashSet<IOPath> unmatchedFilesLocalPaths)
{
foreach (var p in files)
{
var localPath = new IOPath(p.Key);
var realPath = Path.Concat(basedir, localPath);
if (!HashHelper.CheckFileSHA1(realPath, p.Value.sha1, checkHashes && !p.Value.allow_edit))
{
unmatchedFilesLocalPaths.Add(localPath);
}
}
return unmatchedFilesLocalPaths.Count == 0;
}
}

View File

@ -3,14 +3,13 @@
namespace Mlaumcherb.Client.Avalonia.классы;
public class VersionCatalogProps
public class GameVersionCatalogProps
{
[JsonRequired] public required string name { get; init; }
[JsonRequired] public required string url { get; init; }
public override string ToString() => name;
public async Task<GameVersionCatalog> GetVersionCatalogAsync()
{
return await NetworkHelper.DownloadStringAndDeserialize<GameVersionCatalog>(url);

View File

@ -1,83 +0,0 @@
using Mlaumcherb.Client.Avalonia.зримое;
using Mlaumcherb.Client.Avalonia.холопы;
namespace Mlaumcherb.Client.Avalonia.классы;
public class GameVersionProps : IComparable<GameVersionProps>, IEquatable<GameVersionProps>
{
public string Name { get; }
public IOPath LocalDescriptorPath { get; }
public RemoteVersionDescriptorProps? RemoteProps { get; }
private bool _isDownloaded;
public bool IsDownloaded
{
get => _isDownloaded;
set
{
if(_isDownloaded != value)
{
_isDownloaded = value;
StatusChanged?.Invoke(value);
}
}
}
public event Action<bool>? StatusChanged;
private GameVersionProps(string name, RemoteVersionDescriptorProps? remoteProps)
{
Name = name;
RemoteProps = remoteProps;
LocalDescriptorPath = PathHelper.GetVersionDescriptorPath(name);
IsDownloaded = File.Exists(PathHelper.GetVersionJarFilePath(name));
}
public GameVersionProps(string name)
: this(name, null)
{ }
public GameVersionProps(RemoteVersionDescriptorProps remoteProps)
: this(remoteProps.id, remoteProps)
{ }
public void DeleteFiles()
{
IsDownloaded = false;
LauncherApp.Logger.LogInfo(Name, "Deleting files...");
var verdir = PathHelper.GetVersionDir(Name);
if(Directory.Exists(verdir))
Directory.Delete(verdir);
LauncherApp.Logger.LogInfo(Name, "Files deleted");
}
public override string ToString() => Name;
public override int GetHashCode() => Name.GetHashCode();
public int CompareTo(GameVersionProps? other)
{
if (ReferenceEquals(this, other)) return 0;
if (other is null) return 1;
if (Version.TryParse(Name, out var version1) && Version.TryParse(other.Name, out var version2))
{
return version1.CompareTo(version2);
}
return String.Compare(Name, other.Name, StringComparison.InvariantCulture);
}
public bool Equals(GameVersionProps? other)
{
if (other is null) return false;
if (ReferenceEquals(this, other)) return true;
return Name == other.Name;
}
public override bool Equals(object? obj)
{
if (obj is GameVersionProps other) return Equals(other);
if (ReferenceEquals(this, obj)) return true;
return false;
}
}

View File

@ -0,0 +1,134 @@
using Mlaumcherb.Client.Avalonia.зримое;
using Mlaumcherb.Client.Avalonia.сеть;
using Mlaumcherb.Client.Avalonia.холопы;
using Newtonsoft.Json.Linq;
namespace Mlaumcherb.Client.Avalonia.классы;
public class InstalledGameVersionProps : IComparable<InstalledGameVersionProps>, IEquatable<InstalledGameVersionProps>
{
[JsonRequired] public string Id { get; }
public GameVersionCatalogProps? CatalogProps { get; set; }
public RemoteVersionDescriptorProps? DescriptorProps { get; set; }
private bool _isInstalled;
[JsonIgnore]
public bool IsInstalled
{
get => _isInstalled;
set
{
_isInstalled = value;
StatusChanged?.Invoke(value);
}
}
[JsonIgnore] public IOPath DescriptorPath { get; }
public event Action<bool>? StatusChanged;
public InstalledGameVersionProps(string id, GameVersionCatalogProps? catalogProps, RemoteVersionDescriptorProps? descriptorProps)
{
this.Id = id;
this.CatalogProps = catalogProps;
this.DescriptorProps = descriptorProps;
DescriptorPath = PathHelper.GetVersionDescriptorPath(id);
IsInstalled = File.Exists(PathHelper.GetVersionJarFilePath(id));
}
public async Task<GameVersion> LoadDescriptor(bool checkForUpdates)
{
// check if DescriptorProps had been changed on on remote version catalog server
if (checkForUpdates && CatalogProps is not null && DescriptorProps is not null)
{
var remoteCatalog = await NetworkHelper.DownloadStringAndDeserialize<GameVersionCatalog>(CatalogProps.url);
DescriptorProps = remoteCatalog.versions.Find(remoteProps => remoteProps.id == Id);
if(DescriptorProps is null)
LauncherApp.Logger.LogWarn(nameof(InstalledGameVersionProps),
$"Game version '{Id}' was deleted from remote catalog '{CatalogProps.name}'."
+ "It is kept locally, but can't be updated anymore.");
}
// Descriptor is downloaded here
if (!HashHelper.CheckFileSHA1(DescriptorPath, DescriptorProps?.sha1, checkForUpdates))
{
if (DescriptorProps is null)
throw new NullReferenceException(
$"can't download game version descriptor '{Id}', because RemoteDescriptor is null");
// download descriptor
await NetworkHelper.DownloadFile(DescriptorProps.url, DescriptorPath);
}
string descriptorText = File.ReadAllText(DescriptorPath);
JObject descriptorRaw = JObject.Parse(descriptorText);
// Descriptors can inherit from other descriptors.
// For example, 1.12.2-forge-14.23.5.2860 inherits from 1.12.2
if (descriptorRaw.TryGetValue("inheritsFrom", out var v))
{
string parentDescriptorId = v.Value<string>()
?? throw new Exception("inheritsFrom is null");
LauncherApp.Logger.LogInfo(Id, $"merging descriptor '{parentDescriptorId}' with '{Id}'");
IOPath parentDescriptorPath = PathHelper.GetVersionDescriptorPath(parentDescriptorId);
if (!File.Exists(parentDescriptorPath))
throw new Exception($"Версия '{Id} требует установить версию '{parentDescriptorId}'");
string parentDescriptorText = File.ReadAllText(parentDescriptorPath);
JObject parentDescriptorRaw = JObject.Parse(parentDescriptorText);
parentDescriptorRaw.Merge(descriptorRaw,
new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Concat });
descriptorRaw = parentDescriptorRaw;
// removing dependency
descriptorRaw.Remove("inheritsFrom");
File.WriteAllText(DescriptorPath, descriptorRaw.ToString());
}
var descriptor = descriptorRaw.ToObject<GameVersionDescriptor>()
?? throw new Exception($"can't parse descriptor file '{DescriptorPath}'");
return new GameVersion(this, descriptor);
}
public void Delete()
{
if(!IsInstalled)
return;
LauncherApp.Logger.LogInfo(Id, "Deleting files...");
var verdir = PathHelper.GetVersionDir(Id);
if(Directory.Exists(verdir))
Directory.Delete(verdir);
LauncherApp.Logger.LogInfo(Id, "Files deleted");
IsInstalled = false;
}
public override string ToString() => Id;
public override int GetHashCode() => Id.GetHashCode();
public int CompareTo(InstalledGameVersionProps? other)
{
if (ReferenceEquals(this, other))
return 0;
if (other is null)
return 1;
return String.Compare(Id, other.Id, StringComparison.InvariantCulture);
}
public bool Equals(InstalledGameVersionProps? other)
{
if (other is null) return false;
if (ReferenceEquals(this, other)) return true;
return Id == other.Id;
}
public override bool Equals(object? obj)
{
if (obj is InstalledGameVersionProps other) return Equals(other);
if (ReferenceEquals(this, obj)) return true;
return false;
}
}

View File

@ -0,0 +1,77 @@
using System.Linq;
using Mlaumcherb.Client.Avalonia.зримое;
using Mlaumcherb.Client.Avalonia.холопы;
namespace Mlaumcherb.Client.Avalonia.классы;
public class InstalledVersionCatalog
{
/// version_id, props
[JsonRequired] public Dictionary<string, InstalledGameVersionProps> versions { get; set; } = new();
private IComparer<InstalledGameVersionProps> reverseComparer = new ReverseComparer<InstalledGameVersionProps>();
public static InstalledVersionCatalog Load()
{
InstalledVersionCatalog catalog;
var installedCatalogPath = PathHelper.GetInstalledVersionCatalogPath();
if (!File.Exists(installedCatalogPath))
{
LauncherApp.Logger.LogDebug(nameof(InstalledVersionCatalog), "creating new catalog");
catalog = new InstalledVersionCatalog();
}
else
{
LauncherApp.Logger.LogDebug(nameof(InstalledVersionCatalog), "loading catalog from file");
catalog = JsonConvert.DeserializeObject<InstalledVersionCatalog>(
File.ReadAllText(installedCatalogPath))
?? throw new NullReferenceException($"can't deserialize {installedCatalogPath}");
}
catalog.CheckInstalledVersions();
catalog.Save();
return catalog;
}
public void Save()
{
var installedCatalogPath = PathHelper.GetInstalledVersionCatalogPath();
LauncherApp.Logger.LogDebug(nameof(InstalledVersionCatalog), "saving catalog to file");
var text = JsonConvert.SerializeObject(this, Formatting.Indented);
File.WriteAllText(installedCatalogPath, text);
LauncherApp.Logger.LogDebug(nameof(InstalledVersionCatalog), "catalog has been saved");
}
/// <summary>
/// Check if any versions were installed or deleted manually.
/// </summary>
public void CheckInstalledVersions()
{
var versionsUpdated = new List<InstalledGameVersionProps>();
Directory.Create(PathHelper.GetVersionsDir());
foreach (var subdir in Directory.GetDirectories(PathHelper.GetVersionsDir()))
{
string id = subdir.LastName().ToString();
if (!File.Exists(PathHelper.GetVersionDescriptorPath(id)))
throw new Exception(
$"Can't find version descriptor file in directory '{subdir}'. Rename it as directory name.");
if (versions.TryGetValue(id, out var foundProps))
{
versionsUpdated.Add(foundProps);
}
else
{
versionsUpdated.Add(new InstalledGameVersionProps(id, null, null));
}
}
// reverse sort
versionsUpdated.Sort(reverseComparer);
// create dictionary from list
versions = new Dictionary<string, InstalledGameVersionProps>(
versionsUpdated.Select(props =>
new KeyValuePair<string, InstalledGameVersionProps>(props.Id, props)
));
}
}

View File

@ -1,4 +1,6 @@
namespace Mlaumcherb.Client.Avalonia.классы;
using Mlaumcherb.Client.Avalonia.холопы;
namespace Mlaumcherb.Client.Avalonia.классы;
public class MyModpackRemoteProps
{
@ -8,12 +10,40 @@ public class MyModpackRemoteProps
public class MyModpackV1
{
// 1
[JsonRequired] public int format_version { get; set; }
[JsonRequired] public string name { get; set; }
[JsonRequired] public string name { get; set; } = "";
// zip archive with all files
[JsonRequired] public Artifact zip { get; set; } = null!;
// ModpackFilesManifest
[JsonRequired] public Artifact manifest { get; set; } = null!;
/// relative_path, hash
// ReSharper disable once CollectionNeverUpdated.Global
[JsonRequired] public Dictionary<string, FileProps> files { get; set; } = new();
public class FileProps
{
[JsonRequired] public string sha1 { get; set; } = "";
// disable hash validation, allowing users to edit this file
public bool allow_edit { get; set; }
// don't re-download file if it was deleted by user
public bool optional { get; set; }
}
public bool CheckFiles(IOPath basedir, bool checkHashes, bool downloadOptionalFiles, HashSet<IOPath> unmatchedFilesLocalPaths)
{
foreach (var p in files)
{
if(!downloadOptionalFiles && p.Value.optional)
continue;
var localPath = new IOPath(p.Key);
var realPath = Path.Concat(basedir, localPath);
if (!HashHelper.CheckFileSHA1(realPath, p.Value.sha1, checkHashes && !p.Value.allow_edit))
{
unmatchedFilesLocalPaths.Add(localPath);
}
}
return unmatchedFilesLocalPaths.Count == 0;
}
}

View File

@ -42,23 +42,25 @@ public static class NetworkHelper
}
public static async Task<string> ReadOrDownload(IOPath filePath, string url,
/// <returns>(file_content, didDownload)</returns>
public static async Task<(string, bool)> ReadOrDownload(IOPath filePath, string url,
string? sha1, bool checkHashes)
{
if (HashHelper.CheckFileSHA1(filePath, sha1, checkHashes))
return File.ReadAllText(filePath);
return (File.ReadAllText(filePath), false);
string txt = await NetworkHelper.GetString(url);
File.WriteAllText(filePath, txt);
return txt;
return (txt, true);
}
public static async Task<T> ReadOrDownloadAndDeserialize<T>(IOPath filePath, string url,
/// <returns>(file_content, didDownload)</returns>
public static async Task<(T, bool)> ReadOrDownloadAndDeserialize<T>(IOPath filePath, string url,
string? sha1, bool checkHashes)
{
string text = await ReadOrDownload(filePath, url, sha1, checkHashes);
(string text, bool didDownload) = await ReadOrDownload(filePath, url, sha1, checkHashes);
var result = JsonConvert.DeserializeObject<T>(text)
?? throw new Exception($"can't deserialize {typeof(T).Name}");
return result;
return (result, didDownload);
}
}

View File

@ -22,24 +22,26 @@ public class AssetsDownloadTaskFactory : INetworkTaskFactory
public async Task<NetworkTask?> CreateAsync(bool checkHashes)
{
NetworkTask? networkTask = null;
if (!await CheckFilesAsync(checkHashes))
return new NetworkTask(
{
networkTask = new NetworkTask(
$"assets '{_descriptor.assetIndex.id}'",
GetTotalSize(),
Download
);
}
return null;
return networkTask;
}
private async Task<bool> CheckFilesAsync(bool checkHashes)
{
var assetIndex = await ReadOrDownloadAndDeserialize<AssetIndex>(
(AssetIndex assetIndex, _) = await ReadOrDownloadAndDeserialize<AssetIndex>(
_indexFilePath,
_descriptor.assetIndex.url,
_descriptor.assetIndex.sha1,
checkHashes);
_assetsToDownload.Clear();
// removing duplicates for Dictionary (idk how can it be possible, but Newtonsoft.Json creates them)
HashSet<string> assetHashes = new HashSet<string>();
foreach (var pair in assetIndex.objects)

View File

@ -28,11 +28,14 @@ public class JavaDownloadTaskFactory : INetworkTaskFactory
NetworkTask? networkTask = null;
if (!CheckFiles(checkHashes))
networkTask = new(
{
networkTask = new NetworkTask(
$"java runtime '{_descriptor.javaVersion.component}'",
GetTotalSize(),
Download
);
}
return networkTask;
}

View File

@ -24,11 +24,14 @@ public class LibrariesDownloadTaskFactory : INetworkTaskFactory
{
NetworkTask? networkTask = null;
if (!CheckFiles(checkHashes))
{
networkTask = new NetworkTask(
$"libraries '{_descriptor.id}'",
GetTotalSize(),
Download
);
}
return Task.FromResult(networkTask);
}
@ -43,7 +46,7 @@ public class LibrariesDownloadTaskFactory : INetworkTaskFactory
{
_libsToDownload.Add(l);
}
//TODO: replace with actual native assets check
//TODO: replace with actual native libraries check
else if (!nativeDirExists && l is Libraries.NativeLib)
{
_libsToDownload.Add(l);
@ -79,18 +82,15 @@ public class LibrariesDownloadTaskFactory : INetworkTaskFactory
if (l is Libraries.NativeLib n)
{
await using var zipf = File.OpenRead(n.jarFilePath);
//TODO: replace following code with manual extraction
ZipFile.ExtractToDirectory(zipf, _nativesDir.ToString(), true);
if (n.extractionOptions?.exclude != null)
using var archive = new ZipArchive(zipf);
foreach (var entry in archive.Entries)
{
foreach (var excluded in n.extractionOptions.exclude)
{
IOPath path = Path.Concat(_nativesDir, excluded);
if(Directory.Exists(path))
Directory.Delete(path);
if(File.Exists(path))
File.Delete(path);
}
if (n.extractionOptions?.exclude?.Contains(entry.FullName) is true or null)
continue;
var real_path = Path.Concat(_nativesDir, entry.FullName);
Directory.Create(real_path.ParentDir());
entry.ExtractToFile(real_path.ToString(), true);
}
}
});

View File

@ -28,19 +28,16 @@ public class ModpackDownloadTaskFactory : INetworkTaskFactory
public class MyModpackV1DownloadTaskFactory : INetworkTaskFactory
{
private IOPath _modpackManifesPath;
private readonly GameVersionDescriptor _descriptor;
private IOPath _modpackDescriptorPath;
private IOPath _versionDir;
private MyModpackV1? _modpack;
private ModpackFilesManifest? _modpackManifest;
private HashSet<IOPath> _filesToDosnload = new();
public MyModpackV1DownloadTaskFactory(GameVersionDescriptor descriptor)
{
_descriptor = descriptor;
_modpackDescriptorPath = PathHelper.GetModpackDescriptorPath(_descriptor.id);
_modpackManifesPath = PathHelper.GetModpackManifestPath(_descriptor.id);
_versionDir = PathHelper.GetVersionDir(_descriptor.id);
}
@ -49,8 +46,7 @@ public class MyModpackV1DownloadTaskFactory : INetworkTaskFactory
if(_descriptor.modpack is null)
throw new ArgumentNullException(nameof(_descriptor.modpack));
_modpack = await NetworkHelper.ReadOrDownloadAndDeserialize<MyModpackV1>(
(_modpack, bool didDownloadModpackDescriptor) = await NetworkHelper.ReadOrDownloadAndDeserialize<MyModpackV1>(
_modpackDescriptorPath,
_descriptor.modpack.artifact.url,
_descriptor.modpack.artifact.sha1,
@ -59,20 +55,17 @@ public class MyModpackV1DownloadTaskFactory : INetworkTaskFactory
throw new Exception($"Modpack.format_version mismatches descriptor.modpack.version: " +
$"{_modpack.format_version} != {_descriptor.modpack.format_version}");
_modpackManifest = await NetworkHelper.ReadOrDownloadAndDeserialize<ModpackFilesManifest>(
_modpackManifesPath,
_modpack.manifest.url,
_modpack.manifest.sha1,
checkHashes);
if(!_modpackManifest.CheckFiles(_versionDir, checkHashes, _filesToDosnload))
return new NetworkTask(
NetworkTask? networkTask = null;
if(!_modpack.CheckFiles(_versionDir, checkHashes, didDownloadModpackDescriptor, _filesToDosnload))
{
networkTask = new NetworkTask(
$"modpack '{_descriptor.assetIndex.id}'",
_modpack.zip.size,
Download
);
}
return null;
return networkTask;
}
private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
@ -81,7 +74,7 @@ public class MyModpackV1DownloadTaskFactory : INetworkTaskFactory
if(string.IsNullOrEmpty(_modpack.zip.url))
throw new Exception($"modpack '{_modpack.name}' doesn't have a url to download");
var _archivePath = Path.Concat("downloads/modpacks", _modpack.name + ".zip");
var _archivePath = Path.Concat(PathHelper.GetCacheDir(), "modpacks", _modpack.name + ".zip");
await NetworkHelper.DownloadFile(_modpack.zip.url, _archivePath, ct, pr.AddBytesCount);
await using var zipf = File.OpenRead(_archivePath);

View File

@ -20,11 +20,14 @@ public class VersionJarDownloadTaskFactory : INetworkTaskFactory
{
NetworkTask? networkTask = null;
if (!CheckFiles(checkHashes))
{
networkTask = new NetworkTask(
$"game version jar '{_descriptor.id}'",
GetTotalSize(),
Download
);
}
return Task.FromResult(networkTask);
}

View File

@ -58,6 +58,8 @@ public static class PathHelper
public static IOPath GetModpackDescriptorPath(string game_version) =>
Path.Concat(GetVersionDir(game_version), "timerix_modpack.json");
public static IOPath GetModpackManifestPath(string game_version) =>
Path.Concat(GetVersionDir(game_version), "timerix_modpack_files.json");
public static IOPath GetCacheDir() =>
Path.Concat(GetRootFullPath(), "cache");
public static IOPath GetInstalledVersionCatalogPath() =>
Path.Concat(GetCacheDir(), "installed_versions.json");
}

View File

@ -0,0 +1,12 @@
namespace Mlaumcherb.Client.Avalonia.холопы;
// compares Y with X instead of X with Y
public class ReverseComparer<T> : IComparer<T> where T : IComparable<T>
{
public int Compare(T? x, T? y)
{
if (y is null)
return x is null ? 0 : -1;
return y.CompareTo(x);
}
}