11 Commits

Author SHA1 Message Date
679d89b4b0 removed symlink creation 2024-12-31 22:49:06 +05:00
228b3bc55f RemoteCatalog order changed 2024-12-31 21:53:54 +05:00
7882bb9bfd Fix for libraries in modpacks 2024-12-31 21:51:25 +05:00
968ff99987 ModpackManifest deleted 2024-12-31 20:03:31 +05:00
e5deb3f3d4 InstalledGameVersionCatalog 2024-12-31 17:55:30 +05:00
2c780afea8 added support for modpack defined in version descriptor 2024-12-29 12:15:51 +05:00
d141ec23dc bugfixes 2024-12-29 01:26:41 +05:00
e24ee815bc my version catalog 2024-12-28 00:26:38 +05:00
372fa5eda2 minor fixes 2024-12-28 00:22:28 +05:00
631f5c9126 forge support 2024-12-27 22:22:01 +05:00
cb85b132c3 Game version management 2024-12-27 21:11:19 +05:00
33 changed files with 1003 additions and 451 deletions

View File

@@ -1,10 +1,12 @@
using Mlaumcherb.Client.Avalonia.зримое; using Mlaumcherb.Client.Avalonia.зримое;
using Mlaumcherb.Client.Avalonia.классы;
using Mlaumcherb.Client.Avalonia.холопы; using Mlaumcherb.Client.Avalonia.холопы;
namespace Mlaumcherb.Client.Avalonia; namespace Mlaumcherb.Client.Avalonia;
public record Config public record Config
{ {
[JsonRequired] public string config_version { get; set; } = "1.0.0";
public bool debug { get; set; } = public bool debug { get; set; } =
#if DEBUG #if DEBUG
true; true;
@@ -15,17 +17,24 @@ public record Config
public int max_memory { get; set; } = 4096; public int max_memory { get; set; } = 4096;
public string minecraft_dir { get; set; } = "."; public string minecraft_dir { get; set; } = ".";
public bool download_java { get; set; } = true; public bool download_java { get; set; } = true;
public bool redirect_game_output { get; set; } = false;
public string? last_launched_version { get; set; } public string? last_launched_version { get; set; }
public int max_parallel_downloads { get; set; } = 16; public int max_parallel_downloads { get; set; } = 16;
public GameVersionCatalogProps[] version_catalogs { get; set; } =
[
new() { name = "Тимериховое", url = "https://timerix.ddns.net/minecraft/catalog.json" },
new() { name = "Mojang", url = "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json" },
];
[JsonIgnore] static IOPath _filePath = "config.json";
[JsonIgnore] private static IOPath _filePath = "млаумчерб.json";
public static Config LoadFromFile() 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)) 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(); return new Config();
} }
@@ -58,7 +67,7 @@ public record Config
public void SaveToFile() 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); var text = JsonConvert.SerializeObject(this, Formatting.Indented);
File.WriteAllText(_filePath, text); File.WriteAllText(_filePath, text);
LauncherApp.Logger.LogDebug(nameof(Config), $"config has been saved: {text}"); LauncherApp.Logger.LogDebug(nameof(Config), $"config has been saved: {text}");

View File

@@ -13,8 +13,8 @@ namespace Mlaumcherb.Client.Avalonia;
public class GameVersion public class GameVersion
{ {
private readonly GameVersionProps _props; private readonly InstalledGameVersionProps _props;
public string Name => _props.Name; public string Id => _props.Id;
public IOPath WorkingDirectory { get; } public IOPath WorkingDirectory { get; }
private IOPath JavaExecutableFilePath; private IOPath JavaExecutableFilePath;
@@ -26,52 +26,10 @@ public class GameVersion
private CancellationTokenSource? _gameCts; private CancellationTokenSource? _gameCts;
private CommandTask<CommandResult>? _commandTask; private CommandTask<CommandResult>? _commandTask;
public static async Task<List<GameVersionProps>> GetAllVersionsAsync() internal GameVersion(InstalledGameVersionProps props, GameVersionDescriptor descriptor)
{
var propsSet = new HashSet<GameVersionProps>();
// local descriptors
Directory.Create(GetVersionsDir());
foreach (IOPath subdir in Directory.GetDirectories(GetVersionsDir()))
{
string name = subdir.LastName().ToString();
var d = new GameVersionProps(name, null);
if(!File.Exists(d.LocalDescriptorPath))
throw new Exception("Can't find version descriptor file in directory '{subdir}'. Rename it as directory name.");
propsSet.Add(d);
}
// remote non-duplicating versions
foreach (var removeVersion in await Сеть.GetDownloadableVersions())
{
propsSet.Add(removeVersion);
}
// reverse sort
var propsList = propsSet.ToList();
propsList.Sort((a, b) => b.CompareTo(a));
return propsList;
}
public static async Task<GameVersion> CreateFromPropsAsync(GameVersionProps props)
{
if (!File.Exists(props.LocalDescriptorPath))
{
if (props.RemoteDescriptorUrl is null)
throw new NullReferenceException("can't download game version descriptor '"
+ props.Name + "', because RemoteDescriptorUrl is null");
await Сеть.DownloadFile(props.RemoteDescriptorUrl, props.LocalDescriptorPath);
}
return new GameVersion(props);
}
private GameVersion(GameVersionProps props)
{ {
_props = props; _props = props;
string descriptorText = File.ReadAllText(props.LocalDescriptorPath); _descriptor = descriptor;
_descriptor = JsonConvert.DeserializeObject<GameVersionDescriptor>(descriptorText)
?? throw new Exception($"can't parse descriptor file '{props.LocalDescriptorPath}'");
_javaArgs = new JavaArguments(_descriptor); _javaArgs = new JavaArguments(_descriptor);
_gameArgs = new GameArguments(_descriptor); _gameArgs = new GameArguments(_descriptor);
_libraries = new Libraries(_descriptor); _libraries = new Libraries(_descriptor);
@@ -79,30 +37,26 @@ public class GameVersion
JavaExecutableFilePath = GetJavaExecutablePath(_descriptor.javaVersion.component, LauncherApp.Config.debug); 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 = List<INetworkTaskFactory> taskFactories =
[ [
new AssetsDownloadTaskFactory(_descriptor), new AssetsDownloadTaskFactory(_descriptor),
new LibrariesDownloadTaskFactory(_descriptor, _libraries), new LibrariesDownloadTaskFactory(_descriptor, _libraries),
new VersionFileDownloadTaskFactory(_descriptor),
]; ];
if(LauncherApp.Config.download_java) if (LauncherApp.Config.download_java)
{
taskFactories.Add(new JavaDownloadTaskFactory(_descriptor)); taskFactories.Add(new JavaDownloadTaskFactory(_descriptor));
} if (_descriptor.modpack != null)
//TODO: modpack taskFactories.Add(new ModpackDownloadTaskFactory(_descriptor));
/*if (modpack != null) // has to be downloaded last because it is used to check if version is installed
{ taskFactories.Add(new VersionJarDownloadTaskFactory(_descriptor));
taskFactories.Add(new ModpackDownloadTaskFactory(modpack));
}*/
var networkTasks = new List<NetworkTask>(); var networkTasks = new List<NetworkTask>();
for (int i = 0; i < taskFactories.Count; i++) 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) if (nt != null)
{ {
networkTasks.Add(nt); networkTasks.Add(nt);
@@ -124,8 +78,8 @@ public class GameVersion
await res.CopyToAsync(file); await res.CopyToAsync(file);
} }
_props.IsDownloaded = true; _props.IsInstalled = true;
LauncherApp.Logger.LogInfo(Name, $"finished updating version {Name}"); LauncherApp.Logger.LogInfo(Id, $"finished updating version {Id}");
} }
//minecraft player uuid explanation //minecraft player uuid explanation
@@ -159,7 +113,7 @@ public class GameVersion
Dictionary<string, string> placeholder_values = new() { Dictionary<string, string> placeholder_values = new() {
{ "resolution_width", "1600" }, { "resolution_width", "1600" },
{ "resolution_height", "900" }, { "resolution_height", "900" },
{ "xms", "2048" }, { "xms", LauncherApp.Config.max_memory.ToString() },
{ "xmx", LauncherApp.Config.max_memory.ToString() }, { "xmx", LauncherApp.Config.max_memory.ToString() },
{ "auth_player_name", LauncherApp.Config.player_name }, { "auth_player_name", LauncherApp.Config.player_name },
{ "auth_access_token", uuid }, { "auth_access_token", uuid },
@@ -179,6 +133,8 @@ public class GameVersion
{ "game_assets", GetAssetsDir().ToString() }, { "game_assets", GetAssetsDir().ToString() },
{ "game_directory", WorkingDirectory.ToString() }, { "game_directory", WorkingDirectory.ToString() },
{ "natives_directory", GetNativeLibrariesDir(_descriptor.id).ToString() }, { "natives_directory", GetNativeLibrariesDir(_descriptor.id).ToString() },
{ "library_directory", GetLibrariesDir().ToString() },
{ "classpath_separator", ";"},
{ "path", GetLog4jConfigFilePath().ToString() }, { "path", GetLog4jConfigFilePath().ToString() },
{ "version_name", _descriptor.id }, { "version_name", _descriptor.id },
{ "version_type", _descriptor.type }, { "version_type", _descriptor.type },
@@ -197,26 +153,30 @@ public class GameVersion
var command = Cli.Wrap(JavaExecutableFilePath.ToString()) var command = Cli.Wrap(JavaExecutableFilePath.ToString())
.WithWorkingDirectory(WorkingDirectory.ToString()) .WithWorkingDirectory(WorkingDirectory.ToString())
.WithArguments(argsList) .WithArguments(argsList)
.WithStandardOutputPipe(PipeTarget.ToDelegate(LogGameOut))
.WithStandardErrorPipe(PipeTarget.ToDelegate(LogGameError))
.WithValidation(CommandResultValidation.None); .WithValidation(CommandResultValidation.None);
LauncherApp.Logger.LogInfo(Name, "launching the game"); if (LauncherApp.Config.redirect_game_output)
LauncherApp.Logger.LogDebug(Name, "java: " + command.TargetFilePath); {
LauncherApp.Logger.LogDebug(Name, "working_dir: " + command.WorkingDirPath); command = command
LauncherApp.Logger.LogDebug(Name, "arguments: \n\t" + argsList.MergeToString("\n\t")); .WithStandardOutputPipe(PipeTarget.ToDelegate(LogGameOut))
.WithStandardErrorPipe(PipeTarget.ToDelegate(LogGameError));
}
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(); _gameCts = new();
_commandTask = command.ExecuteAsync(_gameCts.Token); _commandTask = command.ExecuteAsync(_gameCts.Token);
var result = await _commandTask; 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) private void LogGameOut(string line)
{ {
LauncherApp.Logger.LogInfo(Name, line); LauncherApp.Logger.LogInfo(Id, line);
} }
private void LogGameError(string line) private void LogGameError(string line)
{ {
LauncherApp.Logger.LogWarn(Name, line); LauncherApp.Logger.LogWarn(Id, line);
} }
public void Close() public void Close()
@@ -225,5 +185,5 @@ public class GameVersion
} }
public override string ToString() => Name; public override string ToString() => Id;
} }

View File

@@ -1,6 +1,4 @@
using Mlaumcherb.Client.Avalonia.зримое; namespace Mlaumcherb.Client.Avalonia;
namespace Mlaumcherb.Client.Avalonia;
public class LauncherLogger : ILogger public class LauncherLogger : ILogger
{ {
@@ -12,6 +10,7 @@ public class LauncherLogger : ILogger
public LauncherLogger() public LauncherLogger()
{ {
_fileLogger = new FileLogger(LogsDirectory, "млаумчерб"); _fileLogger = new FileLogger(LogsDirectory, "млаумчерб");
_fileLogger.DebugLogEnabled = true;
ILogger[] loggers = ILogger[] loggers =
[ [
_fileLogger, _fileLogger,
@@ -56,7 +55,11 @@ public class LauncherLogger : ILogger
public bool DebugLogEnabled public bool DebugLogEnabled
{ {
get => _compositeLogger.DebugLogEnabled; get => _compositeLogger.DebugLogEnabled;
set => _compositeLogger.DebugLogEnabled = value; set
{
_compositeLogger.DebugLogEnabled = value;
_fileLogger.DebugLogEnabled = true;
}
} }
public bool InfoLogEnabled public bool InfoLogEnabled

View File

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

View File

@@ -4,6 +4,7 @@
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Mlaumcherb.Client.Avalonia" xmlns:local="clr-namespace:Mlaumcherb.Client.Avalonia"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450" 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"/> <TextBlock Name="text" Background="Transparent"/>
</UserControl> </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"/> <Setter Property="MinWidth" Value="50"/>
</Style> </Style>
<Style Selector="Button.button_dark">
<Setter Property="Background" Value="#65656070"/>
</Style>
<Style Selector="Border.menu_separator"> <Style Selector="Border.menu_separator">
<Setter Property="Background" Value="#ff505050"/> <Setter Property="Background" Value="#ff505050"/>
<Setter Property="Width" Value="1"/> <Setter Property="Width" Value="1"/>

View File

@@ -1,13 +1,15 @@
using Avalonia; using Avalonia;
using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml; using Avalonia.Markup.Xaml;
using Mlaumcherb.Client.Avalonia.классы;
namespace Mlaumcherb.Client.Avalonia.зримое; namespace Mlaumcherb.Client.Avalonia.зримое;
public class LauncherApp : Application public class LauncherApp : Application
{ {
public static LauncherLogger Logger = new(); public static LauncherLogger Logger = new();
public static Config Config = new(); public static Config Config = null!;
public static InstalledVersionCatalog InstalledVersionCatalog = null!;
public override void Initialize() public override void Initialize()
{ {
@@ -15,6 +17,14 @@ public class LauncherApp : Application
Config = Config.LoadFromFile(); Config = Config.LoadFromFile();
Logger.DebugLogEnabled = Config.debug; Logger.DebugLogEnabled = Config.debug;
AvaloniaXamlLoader.Load(this); AvaloniaXamlLoader.Load(this);
// some file required by forge installer
if (!File.Exists("launcher_profiles.json"))
{
File.WriteAllText("launcher_profiles.json", "{}");
}
InstalledVersionCatalog = InstalledVersionCatalog.Load();
} }
public override void OnFrameworkInitializationCompleted() public override void OnFrameworkInitializationCompleted()

View File

@@ -7,53 +7,104 @@
Title="млаумчерб" Title="млаумчерб"
Icon="avares://млаумчерб/капитал/кубе.ico" Icon="avares://млаумчерб/капитал/кубе.ico"
FontFamily="{StaticResource MonospaceFont}" FontSize="18" FontFamily="{StaticResource MonospaceFont}" FontSize="18"
MinWidth="1200" MinHeight="700" MinWidth="800" MinHeight="400"
Width="800" Height="500" Width="800" Height="600"
WindowStartupLocation="CenterScreen"> WindowStartupLocation="CenterScreen">
<Grid> <Grid RowDefinitions="* 30">
<Grid.RowDefinitions>* 30</Grid.RowDefinitions>
<Image Grid.RowSpan="2" Stretch="UniformToFill" <Image Grid.RowSpan="2" Stretch="UniformToFill"
Source="avares://млаумчерб/капитал/фоне.png"/> Source="avares://млаумчерб/капитал/фоне.png"/>
<Grid Grid.Row="0" Margin="10"> <Grid Grid.Row="0" Margin="10">
<Grid.ColumnDefinitions>* 300 *</Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
<ColumnDefinition MinWidth="150"/>
<ColumnDefinition Width="2" />
<ColumnDefinition MinWidth="300"/>
<ColumnDefinition Width="2" />
<ColumnDefinition MinWidth="150"/>
</Grid.ColumnDefinitions>
<GridSplitter Grid.Column="1" Background="Transparent" ResizeDirection="Columns" />
<GridSplitter Grid.Column="3" Background="Transparent" ResizeDirection="Columns"/>
<!-- Central panel --> <!-- Central panel -->
<Border Grid.Column="1" <Border Grid.Column="2"
Classes="dark_tr_bg white_border" Classes="dark_tr_bg white_border">
Margin="10 0">
<Grid> <Grid>
<Grid.RowDefinitions>* 60</Grid.RowDefinitions> <Grid.RowDefinitions>* 60</Grid.RowDefinitions>
<StackPanel Orientation="Vertical" Margin="10" Spacing="10"> <ScrollViewer Grid.Row="0"
<TextBlock>Версия:</TextBlock> HorizontalScrollBarVisibility="Disabled"
<ComboBox Name="VersionComboBox"/> VerticalScrollBarVisibility="Auto">
<StackPanel Margin="10" Spacing="6">
<TextBlock>Ник:</TextBlock>
<TextBox Background="Transparent"
Text="{Binding #window.PlayerName}"/>
<TextBlock>Ник:</TextBlock> <TextBlock>Версия игры:</TextBlock>
<TextBox Background="Transparent" <ComboBox Name="InstalledVersionCatalogComboBox"/>
Text="{Binding #window.PlayerName}"/> <Button Name="RescanInstalledVersionsButton"
Click="RescanInstalledVersionsButton_OnClick"
Classes="button_dark">
Обновить список
</Button>
<Button Name="DeleteVersionButton"
Click="DeleteVersionButton_OnClick"
Classes="button_dark">
Удалить версию
</Button>
<TextBlock> <Expander Header="Добавление версий"
<Run>Выделенная память:</Run> BorderThickness="1" BorderBrush="Gray"
<TextBox Background="Transparent" Padding="0" Padding="4">
BorderThickness="1" <StackPanel Spacing="6">
BorderBrush="#777777" <TextBlock>Источник:</TextBlock>
Text="{Binding #window.MemoryLimit}"> <ComboBox Name="RemoteVersionCatalogComboBox"/>
</TextBox> <WrapPanel>
<Run>Мб</Run> <CheckBox Name="ReleaseVersionTypeCheckBox" IsChecked="True">релиз</CheckBox>
</TextBlock> <CheckBox Name="SnapshotVersionTypeCheckBox">снапшот</CheckBox>
<Slider Minimum="2048" Maximum="8192" <CheckBox Name="OldVersionTypeCheckBox">старое</CheckBox>
Value="{Binding #window.MemoryLimit}"> <CheckBox Name="OtherVersionTypeAlphaCheckBox">другое</CheckBox>
</Slider> </WrapPanel>
<Button Name="SearchVersionsButton"
Click="SearchVersionsButton_OnClick"
Classes="button_dark">
Поиск
</Button>
<TextBlock>Доступные версии:</TextBlock>
<ComboBox Name="RemoteVersionCatalogItemsComboBox"/>
<Button Name="AddVersionButton" IsEnabled="False"
Click="AddVersionButton_OnClick"
Classes="button_dark">
Добавить
</Button>
</StackPanel>
</Expander>
<CheckBox IsChecked="{Binding #window.CheckGameFiles}"> <TextBlock>
Проверять файлы игры <Run>Выделенная память:</Run>
</CheckBox> <TextBox Background="Transparent" Padding="0"
<CheckBox IsChecked="{Binding #window.EnableJavaDownload}"> BorderThickness="1"
Скачивать джаву BorderBrush="#777777"
</CheckBox> Text="{Binding #window.MemoryLimit}">
</StackPanel> </TextBox>
<Run>Мб</Run>
</TextBlock>
<Slider Minimum="2048" Maximum="8192"
Value="{Binding #window.MemoryLimit}">
</Slider>
<CheckBox IsChecked="{Binding #window.UpdateGameFiles}">
Обновить файлы игры
</CheckBox>
<CheckBox IsChecked="{Binding #window.EnableJavaDownload}">
Скачивать джаву
</CheckBox>
<CheckBox IsChecked="{Binding #window.RedirectGameOutput}">
Выводить лог игры в лаунчер
</CheckBox>
</StackPanel>
</ScrollViewer>
<Button Name="LaunchButton" Grid.Row="1" <Button Name="LaunchButton" Grid.Row="1"
Margin="10" Padding="0 0 0 4" Margin="10" Padding="4"
Classes="button_no_border" Classes="button_no_border"
Background="#BBfd7300" Background="#BBfd7300"
Click="Запуск"> Click="Запуск">
@@ -65,8 +116,7 @@
<!-- Left panel --> <!-- Left panel -->
<Border Grid.Column="0" <Border Grid.Column="0"
Classes="dark_tr_bg white_border"> Classes="dark_tr_bg white_border">
<Grid> <Grid RowDefinitions="36 *">
<Grid.RowDefinitions>36 *</Grid.RowDefinitions>
<Border Classes="white_border" Margin="-1" Padding="4"> <Border Classes="white_border" Margin="-1" Padding="4">
<DockPanel> <DockPanel>
<TextBlock FontWeight="Bold" <TextBlock FontWeight="Bold"
@@ -92,9 +142,9 @@
</Border> </Border>
<!-- Right panel --> <!-- Right panel -->
<Border Grid.Column="2" Classes="dark_tr_bg white_border"> <Border Grid.Column="4"
<Grid> Classes="dark_tr_bg white_border">
<Grid.RowDefinitions>36 *</Grid.RowDefinitions> <Grid RowDefinitions="36 *">
<Border Classes="white_border" Margin="-1" Padding="4"> <Border Classes="white_border" Margin="-1" Padding="4">
<DockPanel> <DockPanel>
<TextBlock FontWeight="Bold" <TextBlock FontWeight="Bold"

View File

@@ -6,6 +6,9 @@ using Avalonia.Platform.Storage;
using Avalonia.Threading; using Avalonia.Threading;
using Mlaumcherb.Client.Avalonia.классы; using Mlaumcherb.Client.Avalonia.классы;
using Mlaumcherb.Client.Avalonia.холопы; using Mlaumcherb.Client.Avalonia.холопы;
using MsBox.Avalonia;
using MsBox.Avalonia.Dto;
using MsBox.Avalonia.Models;
namespace Mlaumcherb.Client.Avalonia.зримое; namespace Mlaumcherb.Client.Avalonia.зримое;
@@ -29,13 +32,13 @@ public partial class MainWindow : Window
set => SetValue(MemoryLimitProperty, value); set => SetValue(MemoryLimitProperty, value);
} }
public static readonly StyledProperty<bool> CheckGameFilesProperty = public static readonly StyledProperty<bool> UpdateGameFilesProperty =
AvaloniaProperty.Register<MainWindow, bool>(nameof(CheckGameFiles), AvaloniaProperty.Register<MainWindow, bool>(nameof(UpdateGameFiles),
defaultBindingMode: BindingMode.TwoWay, defaultValue: false); defaultBindingMode: BindingMode.TwoWay, defaultValue: false);
public bool CheckGameFiles public bool UpdateGameFiles
{ {
get => GetValue(CheckGameFilesProperty); get => GetValue(UpdateGameFilesProperty);
set => SetValue(CheckGameFilesProperty, value); set => SetValue(UpdateGameFilesProperty, value);
} }
@@ -48,12 +51,21 @@ public partial class MainWindow : Window
set => SetValue(EnableJavaDownloadProperty, value); set => SetValue(EnableJavaDownloadProperty, value);
} }
public static readonly StyledProperty<bool> RedirectGameOutputProperty =
AvaloniaProperty.Register<MainWindow, bool>(nameof(RedirectGameOutput),
defaultBindingMode: BindingMode.TwoWay, defaultValue: false);
public bool RedirectGameOutput
{
get => GetValue(RedirectGameOutputProperty);
set => SetValue(RedirectGameOutputProperty, value);
}
public MainWindow() public MainWindow()
{ {
InitializeComponent(); InitializeComponent();
} }
protected override async void OnLoaded(RoutedEventArgs e) protected override void OnLoaded(RoutedEventArgs e)
{ {
try try
{ {
@@ -62,21 +74,15 @@ public partial class MainWindow : Window
PlayerName = LauncherApp.Config.player_name; PlayerName = LauncherApp.Config.player_name;
MemoryLimit = LauncherApp.Config.max_memory; MemoryLimit = LauncherApp.Config.max_memory;
EnableJavaDownload = LauncherApp.Config.download_java; EnableJavaDownload = LauncherApp.Config.download_java;
RedirectGameOutput = LauncherApp.Config.redirect_game_output;
VersionComboBox.SelectedIndex = 0; foreach (var vc in LauncherApp.Config.version_catalogs)
VersionComboBox.IsEnabled = false;
var versions = await GameVersion.GetAllVersionsAsync();
Dispatcher.UIThread.Invoke(() =>
{ {
foreach (var p in versions) RemoteVersionCatalogComboBox.Items.Add(vc);
{ }
VersionComboBox.Items.Add(new VersionItemView(p)); RemoteVersionCatalogComboBox.SelectedIndex = 0;
if (LauncherApp.Config.last_launched_version != null &&
p.Name == LauncherApp.Config.last_launched_version) UpdateInstalledVersionsCatalogView(LauncherApp.Config.last_launched_version);
VersionComboBox.SelectedIndex = VersionComboBox.Items.Count - 1;
}
VersionComboBox.IsEnabled = true;
});
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -84,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) private void GuiLogMessage(LauncherLogger.LogMessage msg)
{ {
if (msg.severity == LogSeverity.Debug) return; if (msg.severity == LogSeverity.Debug) return;
@@ -101,20 +140,19 @@ public partial class MainWindow : Window
{ {
try try
{ {
Dispatcher.UIThread.Invoke(() => LaunchButton.IsEnabled = false); if (InstalledVersionCatalogComboBox.SelectedItem is not InstalledGameVersionItemView selectedVersionView)
return;
var selectedVersionView = (VersionItemView?)VersionComboBox.SelectedItem; Dispatcher.UIThread.Invoke(() => LaunchButton.IsEnabled = false);
var selectedVersion = selectedVersionView?.Props; LauncherApp.Config.last_launched_version = selectedVersionView.Props.Id;
LauncherApp.Config.last_launched_version = selectedVersion?.Name;
LauncherApp.Config.player_name = PlayerName; LauncherApp.Config.player_name = PlayerName;
LauncherApp.Config.max_memory = MemoryLimit; LauncherApp.Config.max_memory = MemoryLimit;
LauncherApp.Config.download_java = EnableJavaDownload; LauncherApp.Config.download_java = EnableJavaDownload;
LauncherApp.Config.redirect_game_output = RedirectGameOutput;
LauncherApp.Config.SaveToFile(); LauncherApp.Config.SaveToFile();
if (selectedVersion == null)
return;
var v = await GameVersion.CreateFromPropsAsync(selectedVersion); var v = await selectedVersionView.Props.LoadDescriptor(UpdateGameFiles);
await v.UpdateFiles(CheckGameFiles, nt => await v.Download(UpdateGameFiles, nt =>
{ {
Dispatcher.UIThread.Invoke(() => Dispatcher.UIThread.Invoke(() =>
{ {
@@ -125,7 +163,7 @@ public partial class MainWindow : Window
); );
Dispatcher.UIThread.Invoke(() => Dispatcher.UIThread.Invoke(() =>
{ {
CheckGameFiles = false; UpdateGameFiles = false;
}); });
await v.Launch(); await v.Launch();
} }
@@ -135,10 +173,7 @@ public partial class MainWindow : Window
} }
finally finally
{ {
Dispatcher.UIThread.Invoke(() => Dispatcher.UIThread.Invoke(() => LaunchButton.IsEnabled = true);
{
LaunchButton.IsEnabled = true;
});
} }
} }
@@ -196,4 +231,101 @@ public partial class MainWindow : Window
} }
DownloadsPanel.Children.Clear(); DownloadsPanel.Children.Clear();
} }
private async void SearchVersionsButton_OnClick(object? sender, RoutedEventArgs e)
{
try
{
if(RemoteVersionCatalogComboBox.SelectedItem is not GameVersionCatalogProps catalogProps)
return;
var catalog = await catalogProps.GetVersionCatalogAsync();
var searchParams = new VersionSearchParams
{
ReleaseTypeAllowed = ReleaseVersionTypeCheckBox.IsChecked ?? false,
SnapshotTypeAllowed = SnapshotVersionTypeCheckBox.IsChecked ?? false,
OldTypeAllowed = OldVersionTypeCheckBox.IsChecked ?? false,
OtherTypeAllowed = OtherVersionTypeAlphaCheckBox.IsChecked ?? false
};
var versions = catalog.GetDownloadableVersions(searchParams);
Dispatcher.UIThread.Invoke(() =>
{
RemoteVersionCatalogItemsComboBox.IsEnabled = false;
RemoteVersionCatalogItemsComboBox.Items.Clear();
foreach (var p in versions)
{
RemoteVersionCatalogItemsComboBox.Items.Add(new RemoteGameVersionItemView(p));
}
RemoteVersionCatalogItemsComboBox.IsEnabled = true;
AddVersionButton.IsEnabled = versions.Count > 0;
});
}
catch (Exception ex)
{
ErrorHelper.ShowMessageBox(nameof(MainWindow), ex);
}
}
private void AddVersionButton_OnClick(object? sender, RoutedEventArgs e)
{
try
{
if(RemoteVersionCatalogComboBox.SelectedItem is not GameVersionCatalogProps catalogProps)
return;
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)
{
ErrorHelper.ShowMessageBox(nameof(MainWindow), ex);
}
}
} }

View File

@@ -1,31 +0,0 @@
using Avalonia.Controls;
using Avalonia.Media;
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.OnDownloadCompleted += UpdateBackground;
UpdateBackground();
}
private void UpdateBackground()
{
Background = Props.IsDownloaded ? _avaliableColor : _unavaliableColor;
}
}

View File

@@ -1,8 +1,35 @@
namespace Mlaumcherb.Client.Avalonia.классы; namespace Mlaumcherb.Client.Avalonia.классы;
public record VersionSearchParams
{
public bool ReleaseTypeAllowed;
public bool SnapshotTypeAllowed;
public bool OldTypeAllowed;
public bool OtherTypeAllowed;
}
public class GameVersionCatalog 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<RemoteVersionDescriptorProps> GetDownloadableVersions(VersionSearchParams p)
{
var _versionPropsList = new List<RemoteVersionDescriptorProps>();
foreach (var r in versions)
{
bool match = r.type switch
{
"release" => p.ReleaseTypeAllowed,
"snapshot" => p.SnapshotTypeAllowed,
"old_alpha" or "old_beta" => p.OldTypeAllowed,
_ => p.OtherTypeAllowed
};
if(match)
_versionPropsList.Add(r);
}
return _versionPropsList;
}
} }
public class AssetProperties public class AssetProperties
@@ -19,9 +46,9 @@ public class AssetIndex
public class RemoteVersionDescriptorProps public class RemoteVersionDescriptorProps
{ {
[JsonRequired] public string id { get; set; } = ""; [JsonRequired] public string id { get; set; } = "";
[JsonRequired] public string type { get; set; } = "";
[JsonRequired] public string url { get; set; } = ""; [JsonRequired] public string url { get; set; } = "";
[JsonRequired] public string sha1 { get; set; } = ""; [JsonRequired] public string type { get; set; } = "";
[JsonRequired] public DateTime time { get; set; } public string sha1 { get; set; } = "";
[JsonRequired] public DateTime releaseTime { get; set; } public DateTime time { get; set; }
public DateTime releaseTime { get; set; }
} }

View File

@@ -10,17 +10,21 @@ public class GameVersionDescriptor
[JsonRequired] public DateTime releaseTime { get; set; } [JsonRequired] public DateTime releaseTime { get; set; }
[JsonRequired] public string type { get; set; } = ""; [JsonRequired] public string type { get; set; } = "";
[JsonRequired] public string mainClass { get; set; } = ""; [JsonRequired] public string mainClass { get; set; } = "";
[JsonRequired] public Downloads downloads { get; set; } = null!; [JsonRequired] public List<Library> libraries { get; set; } = new();
[JsonRequired] public List<Library> libraries { get; set; } = null!;
[JsonRequired] public AssetIndexProperties assetIndex { get; set; } = null!; [JsonRequired] public AssetIndexProperties assetIndex { get; set; } = null!;
[JsonRequired] public string assets { get; set; } = ""; [JsonRequired] public string assets { get; set; } = "";
public Downloads? downloads { get; set; } = null;
public JavaVersion javaVersion { get; set; } = new() { component = "jre-legacy", majorVersion = 8 }; public JavaVersion javaVersion { get; set; } = new() { component = "jre-legacy", majorVersion = 8 };
public string? minecraftArguments { get; set; } public string? minecraftArguments { get; set; }
public ArgumentsNew? arguments { get; set; } public ArgumentsNew? arguments { get; set; }
// my additions
public MyModpackRemoteProps? modpack { get; set; }
} }
public class Artifact public class Artifact
{ {
public string? path = null;
[JsonRequired] public string url { get; set; } = ""; [JsonRequired] public string url { get; set; } = "";
[JsonRequired] public string sha1 { get; set; } = ""; [JsonRequired] public string sha1 { get; set; } = "";
[JsonRequired] public int size { get; set; } [JsonRequired] public int size { get; set; }

View File

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

View File

@@ -30,7 +30,7 @@ public class GameArguments : ArgumentsWithPlaceholders
{ {
foreach (var arg in av.value) foreach (var arg in av.value)
{ {
if(!_raw_args.Contains(arg)) // if(!_raw_args.Contains(arg))
_raw_args.Add(arg); _raw_args.Add(arg);
} }
} }

View File

@@ -0,0 +1,17 @@
using Mlaumcherb.Client.Avalonia.сеть;
namespace Mlaumcherb.Client.Avalonia.классы;
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,62 +0,0 @@
using Mlaumcherb.Client.Avalonia.холопы;
namespace Mlaumcherb.Client.Avalonia.классы;
public class GameVersionProps : IComparable<GameVersionProps>, IEquatable<GameVersionProps>
{
public string Name { get; }
public IOPath LocalDescriptorPath { get; }
public string? RemoteDescriptorUrl { get; }
private bool _isDownloaded;
public bool IsDownloaded
{
get => _isDownloaded;
set
{
bool downloadCompleted = value && !_isDownloaded;
_isDownloaded = value;
if(downloadCompleted)
OnDownloadCompleted?.Invoke();
}
}
public event Action? OnDownloadCompleted;
public GameVersionProps(string name, string? url)
{
Name = name;
LocalDescriptorPath = PathHelper.GetVersionDescriptorPath(name);
RemoteDescriptorUrl = url;
IsDownloaded = File.Exists(PathHelper.GetVersionJarFilePath(name));
}
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

@@ -21,7 +21,6 @@ public class JavaArguments : ArgumentsWithPlaceholders
"-Dminecraft.client.jar=${client_jar}", "-Dminecraft.client.jar=${client_jar}",
"-Dminecraft.launcher.brand=${launcher_name}", "-Dminecraft.launcher.brand=${launcher_name}",
"-Dminecraft.launcher.version=${launcher_version}", "-Dminecraft.launcher.version=${launcher_version}",
"-cp", "${classpath}"
]; ];
private static readonly string[] _enabled_features = private static readonly string[] _enabled_features =
@@ -39,11 +38,17 @@ public class JavaArguments : ArgumentsWithPlaceholders
{ {
foreach (var arg in av.value) foreach (var arg in av.value)
{ {
if(!_raw_args.Contains(arg)) // if(!_raw_args.Contains(arg))
_raw_args.Add(arg); _raw_args.Add(arg);
} }
} }
} }
} }
if (!_raw_args.Contains("-cp"))
{
_raw_args.Add("-cp");
_raw_args.Add("${classpath}");
}
} }
} }

View File

@@ -13,6 +13,18 @@ public class Libraries
public IReadOnlyCollection<JarLib> Libs { get; } public IReadOnlyCollection<JarLib> Libs { get; }
private IOPath GetJarFilePath(Artifact artifact)
{
string relativePath;
if (!string.IsNullOrEmpty(artifact.path))
relativePath = artifact.path;
else if (!string.IsNullOrEmpty(artifact.url))
relativePath = artifact.url.AsSpan().After("://").After('/').ToString();
else throw new ArgumentException("Artifact must have a path or url");
return Path.Concat(PathHelper.GetLibrariesDir(), relativePath);
}
public Libraries(GameVersionDescriptor descriptor) public Libraries(GameVersionDescriptor descriptor)
{ {
List<JarLib> libs = new(); List<JarLib> libs = new();
@@ -55,9 +67,7 @@ public class Libraries
if(!libHashes.Add(artifact.sha1)) if(!libHashes.Add(artifact.sha1))
continue; continue;
string urlTail = artifact.url.AsSpan().After("://").After('/').ToString(); libs.Add(new NativeLib(l.name, GetJarFilePath(artifact), artifact, l.extract));
IOPath jarFilePath = Path.Concat(PathHelper.GetLibrariesDir(), urlTail);
libs.Add(new NativeLib(l.name, jarFilePath, artifact, l.extract));
} }
else else
{ {
@@ -69,9 +79,7 @@ public class Libraries
if(!libHashes.Add(artifact.sha1)) if(!libHashes.Add(artifact.sha1))
continue; continue;
string urlTail = artifact.url.AsSpan().After("://").After('/').ToString(); libs.Add(new JarLib(l.name, GetJarFilePath(artifact), artifact));
IOPath jarFilePath = Path.Concat(PathHelper.GetLibrariesDir(), urlTail);
libs.Add(new JarLib(l.name, jarFilePath, artifact));
} }
} }

View File

@@ -0,0 +1,53 @@
using Mlaumcherb.Client.Avalonia.холопы;
namespace Mlaumcherb.Client.Avalonia.классы;
public class MyModpackRemoteProps
{
[JsonRequired] public int format_version { get; set; }
[JsonRequired] public Artifact artifact { get; set; } = null!;
}
public class MyModpackV1
{
// 1
[JsonRequired] public int format_version { get; set; }
[JsonRequired] public string name { get; set; } = "";
// zip archive with all files
[JsonRequired] public Artifact zip { 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; }
}
/// <param name="unmatchedFilesLocalPaths">relative, absolute</param>
public Dictionary<IOPath, IOPath> CheckFiles(IOPath basedir, bool checkHashes, bool downloadOptionalFiles)
{
Dictionary<IOPath, IOPath> unmatchedFiles = new();
IOPath launcherRoot = PathHelper.GetRootFullPath();
foreach (var p in files)
{
if(!downloadOptionalFiles && p.Value.optional)
continue;
IOPath relativePath = new IOPath(p.Key);
var absolutePath = Path.Concat(relativePath.StartsWith("libraries")
? launcherRoot : basedir, relativePath);
if (!HashHelper.CheckFileSHA1(absolutePath, p.Value.sha1, checkHashes && !p.Value.allow_edit))
{
unmatchedFiles.Add(relativePath, absolutePath);
}
}
return unmatchedFiles;
}
}

View File

@@ -1,14 +1,13 @@
using System.Net.Http; using System.Net.Http;
using Mlaumcherb.Client.Avalonia.зримое; using Mlaumcherb.Client.Avalonia.холопы;
using Mlaumcherb.Client.Avalonia.классы;
namespace Mlaumcherb.Client.Avalonia.сеть; namespace Mlaumcherb.Client.Avalonia.сеть;
public static class Сеть public static class NetworkHelper
{ {
private static HttpClient _http = new(); private static HttpClient _http = new();
static Сеть() static NetworkHelper()
{ {
// thanks for Sashok :3 // thanks for Sashok :3
// https://github.com/new-sashok724/Launcher/blob/23485c3f7de6620d2c6b7b2dd9339c3beb6a0366/Launcher/source/helper/IOHelper.java#L259 // https://github.com/new-sashok724/Launcher/blob/23485c3f7de6620d2c6b7b2dd9339c3beb6a0366/Launcher/source/helper/IOHelper.java#L259
@@ -36,52 +35,32 @@ public static class Сеть
public static async Task<T> DownloadStringAndDeserialize<T>(string url) public static async Task<T> DownloadStringAndDeserialize<T>(string url)
{ {
var text = await _http.GetStringAsync(url); var text = await GetString(url);
var result = JsonConvert.DeserializeObject<T>(text) var result = JsonConvert.DeserializeObject<T>(text)
?? throw new Exception($"can't deserialize {typeof(T).Name}"); ?? throw new Exception($"can't deserialize {typeof(T).Name}");
return result; return result;
} }
private static readonly string[] VERSION_MANIFEST_URLS =
{
"https://piston-meta.mojang.com/mc/game/version_manifest_v2.json"
};
private static async Task<List<RemoteVersionDescriptorProps>> GetRemoteVersionDescriptorsAsync() /// <returns>(file_content, didDownload)</returns>
public static async Task<(string, bool)> ReadOrDownload(IOPath filePath, string url,
string? sha1, bool checkHashes)
{ {
List<RemoteVersionDescriptorProps> descriptors = new(); if (HashHelper.CheckFileSHA1(filePath, sha1, checkHashes))
foreach (var url in VERSION_MANIFEST_URLS) return (File.ReadAllText(filePath), false);
{
try
{
var catalog = await DownloadStringAndDeserialize<GameVersionCatalog>(url);
descriptors.AddRange(catalog.versions);
}
catch (Exception ex)
{
LauncherApp.Logger.LogWarn(nameof(Сеть), ex);
}
}
return descriptors; string txt = await NetworkHelper.GetString(url);
File.WriteAllText(filePath, txt);
return (txt, true);
} }
private static List<GameVersionProps>? _versionPropsList; /// <returns>(file_content, didDownload)</returns>
public static async Task<(T, bool)> ReadOrDownloadAndDeserialize<T>(IOPath filePath, string url,
/// <returns>empty list if couldn't find any remote versions</returns> string? sha1, bool checkHashes)
public static async Task<IReadOnlyList<GameVersionProps>> GetDownloadableVersions()
{ {
if (_versionPropsList == null) (string text, bool didDownload) = await ReadOrDownload(filePath, url, sha1, checkHashes);
{ var result = JsonConvert.DeserializeObject<T>(text)
_versionPropsList = new(); ?? throw new Exception($"can't deserialize {typeof(T).Name}");
var rvdlist = await GetRemoteVersionDescriptorsAsync(); return (result, didDownload);
foreach (var r in rvdlist)
{
if (r.type == "release")
_versionPropsList.Add(new GameVersionProps(r.id, r.url));
}
}
return _versionPropsList;
} }
} }

View File

@@ -1,11 +1,9 @@
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Security.Cryptography;
using DTLib.Extensions;
using Mlaumcherb.Client.Avalonia.зримое; using Mlaumcherb.Client.Avalonia.зримое;
using Mlaumcherb.Client.Avalonia.классы; using Mlaumcherb.Client.Avalonia.классы;
using Mlaumcherb.Client.Avalonia.холопы; using Mlaumcherb.Client.Avalonia.холопы;
using static Mlaumcherb.Client.Avalonia.сеть.Сеть; using static Mlaumcherb.Client.Avalonia.сеть.NetworkHelper;
namespace Mlaumcherb.Client.Avalonia.сеть.TaskFactories; namespace Mlaumcherb.Client.Avalonia.сеть.TaskFactories;
@@ -13,42 +11,37 @@ public class AssetsDownloadTaskFactory : INetworkTaskFactory
{ {
private const string ASSET_SERVER_URL = "https://resources.download.minecraft.net/"; private const string ASSET_SERVER_URL = "https://resources.download.minecraft.net/";
private GameVersionDescriptor _descriptor; private GameVersionDescriptor _descriptor;
private SHA1 _hasher;
private IOPath _indexFilePath; private IOPath _indexFilePath;
List<AssetDownloadProperties> _assetsToDownload = new(); List<AssetDownloadProperties> _assetsToDownload = new();
public AssetsDownloadTaskFactory(GameVersionDescriptor descriptor) public AssetsDownloadTaskFactory(GameVersionDescriptor descriptor)
{ {
_descriptor = descriptor; _descriptor = descriptor;
_hasher = SHA1.Create();
_indexFilePath = PathHelper.GetAssetIndexFilePath(_descriptor.assetIndex.id); _indexFilePath = PathHelper.GetAssetIndexFilePath(_descriptor.assetIndex.id);
} }
public async Task<NetworkTask?> CreateAsync(bool checkHashes) public async Task<NetworkTask?> CreateAsync(bool checkHashes)
{ {
NetworkTask? networkTask = null;
if (!await CheckFilesAsync(checkHashes)) if (!await CheckFilesAsync(checkHashes))
return new NetworkTask( {
networkTask = new NetworkTask(
$"assets '{_descriptor.assetIndex.id}'", $"assets '{_descriptor.assetIndex.id}'",
GetTotalSize(), GetTotalSize(),
Download Download
); );
}
return null; return networkTask;
} }
private async Task<bool> CheckFilesAsync(bool checkHashes) private async Task<bool> CheckFilesAsync(bool checkHashes)
{ {
if(!File.Exists(_indexFilePath)) (AssetIndex assetIndex, _) = await ReadOrDownloadAndDeserialize<AssetIndex>(
{ _indexFilePath,
LauncherApp.Logger.LogInfo(nameof(Сеть), $"started downloading asset index to '{_indexFilePath}'"); _descriptor.assetIndex.url,
await DownloadFile(_descriptor.assetIndex.url, _indexFilePath); _descriptor.assetIndex.sha1,
LauncherApp.Logger.LogInfo(nameof(Сеть), "finished downloading asset index"); checkHashes);
}
string indexFileText = File.ReadAllText(_indexFilePath);
var assetIndex = JsonConvert.DeserializeObject<AssetIndex>(indexFileText)
?? throw new Exception($"can't deserialize asset index file '{_indexFilePath}'");
_assetsToDownload.Clear();
// removing duplicates for Dictionary (idk how can it be possible, but Newtonsoft.Json creates them) // removing duplicates for Dictionary (idk how can it be possible, but Newtonsoft.Json creates them)
HashSet<string> assetHashes = new HashSet<string>(); HashSet<string> assetHashes = new HashSet<string>();
foreach (var pair in assetIndex.objects) foreach (var pair in assetIndex.objects)
@@ -56,17 +49,10 @@ public class AssetsDownloadTaskFactory : INetworkTaskFactory
if (assetHashes.Add(pair.Value.hash)) if (assetHashes.Add(pair.Value.hash))
{ {
var a = new AssetDownloadProperties(pair.Key, pair.Value); var a = new AssetDownloadProperties(pair.Key, pair.Value);
if (!File.Exists(a.filePath)) if (!HashHelper.CheckFileSHA1(a.filePath, a.hash, checkHashes))
{ {
_assetsToDownload.Add(a); _assetsToDownload.Add(a);
} }
else if(checkHashes)
{
await using var fs = File.OpenRead(a.filePath);
string hash = _hasher.ComputeHash(fs).HashToString();
if (hash != a.hash)
_assetsToDownload.Add(a);
}
} }
} }
@@ -102,7 +88,7 @@ public class AssetsDownloadTaskFactory : INetworkTaskFactory
private async Task Download(NetworkProgressReporter pr, CancellationToken ct) private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
{ {
LauncherApp.Logger.LogInfo(nameof(Сеть), $"started downloading assets '{_descriptor.assetIndex.id}'"); LauncherApp.Logger.LogInfo(nameof(NetworkHelper), $"started downloading assets '{_descriptor.assetIndex.id}'");
ParallelOptions opt = new() ParallelOptions opt = new()
{ {
MaxDegreeOfParallelism = LauncherApp.Config.max_parallel_downloads, MaxDegreeOfParallelism = LauncherApp.Config.max_parallel_downloads,
@@ -114,7 +100,7 @@ public class AssetsDownloadTaskFactory : INetworkTaskFactory
bool completed = false; bool completed = false;
while(!completed) while(!completed)
{ {
LauncherApp.Logger.LogDebug(nameof(Сеть), $"downloading asset '{a.name}' {a.hash}"); LauncherApp.Logger.LogDebug(nameof(NetworkHelper), $"downloading asset '{a.name}' {a.hash}");
try try
{ {
await DownloadFile(a.url, a.filePath, _ct, pr.AddBytesCount); await DownloadFile(a.url, a.filePath, _ct, pr.AddBytesCount);
@@ -125,13 +111,13 @@ public class AssetsDownloadTaskFactory : INetworkTaskFactory
// wait on rate limit // wait on rate limit
if(httpException.StatusCode == HttpStatusCode.TooManyRequests) if(httpException.StatusCode == HttpStatusCode.TooManyRequests)
{ {
LauncherApp.Logger.LogDebug(nameof(Сеть), "rate limit hit"); LauncherApp.Logger.LogDebug(nameof(NetworkHelper), "rate limit hit");
await Task.Delay(1000, _ct); await Task.Delay(1000, _ct);
} }
else throw; else throw;
} }
} }
}); });
LauncherApp.Logger.LogInfo(nameof(Сеть), $"finished downloading assets '{_descriptor.assetIndex.id}'"); LauncherApp.Logger.LogInfo(nameof(NetworkHelper), $"finished downloading assets '{_descriptor.assetIndex.id}'");
} }
} }

View File

@@ -1,9 +1,7 @@
using System.Security.Cryptography; using Mlaumcherb.Client.Avalonia.зримое;
using DTLib.Extensions;
using Mlaumcherb.Client.Avalonia.зримое;
using Mlaumcherb.Client.Avalonia.классы; using Mlaumcherb.Client.Avalonia.классы;
using Mlaumcherb.Client.Avalonia.холопы; using Mlaumcherb.Client.Avalonia.холопы;
using static Mlaumcherb.Client.Avalonia.сеть.Сеть; using static Mlaumcherb.Client.Avalonia.сеть.NetworkHelper;
namespace Mlaumcherb.Client.Avalonia.сеть.TaskFactories; namespace Mlaumcherb.Client.Avalonia.сеть.TaskFactories;
@@ -13,7 +11,6 @@ public class JavaDownloadTaskFactory : INetworkTaskFactory
"https://launchermeta.mojang.com/v1/products/java-runtime/2ec0cc96c44e5a76b9c8b7c39df7210883d12871/all.json"; "https://launchermeta.mojang.com/v1/products/java-runtime/2ec0cc96c44e5a76b9c8b7c39df7210883d12871/all.json";
private GameVersionDescriptor _descriptor; private GameVersionDescriptor _descriptor;
private IOPath _javaVersionDir; private IOPath _javaVersionDir;
private SHA1 _hasher;
private JavaDistributiveManifest? _distributiveManifest; private JavaDistributiveManifest? _distributiveManifest;
private List<(IOPath path, JavaDistributiveElementProps props)> _filesToDownload = new(); private List<(IOPath path, JavaDistributiveElementProps props)> _filesToDownload = new();
@@ -21,7 +18,6 @@ public class JavaDownloadTaskFactory : INetworkTaskFactory
{ {
_descriptor = descriptor; _descriptor = descriptor;
_javaVersionDir = PathHelper.GetJavaRuntimeDir(_descriptor.javaVersion.component); _javaVersionDir = PathHelper.GetJavaRuntimeDir(_descriptor.javaVersion.component);
_hasher = SHA1.Create();
} }
public async Task<NetworkTask?> CreateAsync(bool checkHashes) public async Task<NetworkTask?> CreateAsync(bool checkHashes)
@@ -32,11 +28,14 @@ public class JavaDownloadTaskFactory : INetworkTaskFactory
NetworkTask? networkTask = null; NetworkTask? networkTask = null;
if (!CheckFiles(checkHashes)) if (!CheckFiles(checkHashes))
networkTask = new( {
$"java runtime '{_descriptor.javaVersion.component}'", networkTask = new NetworkTask(
GetTotalSize(), $"java runtime '{_descriptor.javaVersion.component}'",
Download GetTotalSize(),
); Download
);
}
return networkTask; return networkTask;
} }
@@ -52,18 +51,10 @@ public class JavaDownloadTaskFactory : INetworkTaskFactory
{ {
var artifact = pair.Value.downloads; var artifact = pair.Value.downloads;
IOPath file_path = Path.Concat(_javaVersionDir, pair.Key); IOPath file_path = Path.Concat(_javaVersionDir, pair.Key);
if (!File.Exists(file_path)) if (!HashHelper.CheckFileSHA1(file_path, artifact.raw.sha1, checkHashes))
{ {
_filesToDownload.Add((file_path, pair.Value)); _filesToDownload.Add((file_path, pair.Value));
} }
else if(checkHashes)
{
using var fs = File.OpenRead(file_path);
if (_hasher.ComputeHash(fs).HashToString() != artifact.raw.sha1)
{
_filesToDownload.Add((file_path, pair.Value));
}
}
} }
} }
@@ -84,7 +75,7 @@ public class JavaDownloadTaskFactory : INetworkTaskFactory
private async Task Download(NetworkProgressReporter pr, CancellationToken ct) private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
{ {
LauncherApp.Logger.LogInfo(nameof(Сеть), "started downloading java runtime " + LauncherApp.Logger.LogInfo(nameof(NetworkHelper), "started downloading java runtime " +
$"{_descriptor.javaVersion.majorVersion} '{_descriptor.javaVersion.component}'"); $"{_descriptor.javaVersion.majorVersion} '{_descriptor.javaVersion.component}'");
ParallelOptions opt = new() ParallelOptions opt = new()
@@ -96,7 +87,7 @@ public class JavaDownloadTaskFactory : INetworkTaskFactory
{ {
if (f.props.downloads!.lzma != null) if (f.props.downloads!.lzma != null)
{ {
LauncherApp.Logger.LogDebug(nameof(Сеть), $"downloading lzma-compressed file '{f.path}'"); LauncherApp.Logger.LogDebug(nameof(NetworkHelper), $"downloading lzma-compressed file '{f.path}'");
await using var pipe = new TransformStream(await GetStream(f.props.downloads.lzma.url, _ct)); await using var pipe = new TransformStream(await GetStream(f.props.downloads.lzma.url, _ct));
pipe.AddTransform(pr.AddBytesCount); pipe.AddTransform(pr.AddBytesCount);
await using var fs = File.OpenWrite(f.path); await using var fs = File.OpenWrite(f.path);
@@ -104,18 +95,18 @@ public class JavaDownloadTaskFactory : INetworkTaskFactory
} }
else else
{ {
LauncherApp.Logger.LogDebug(nameof(Сеть), $"downloading raw file '{f.path}'"); LauncherApp.Logger.LogDebug(nameof(NetworkHelper), $"downloading raw file '{f.path}'");
await DownloadFile(f.props.downloads.raw.url, f.path, _ct, pr.AddBytesCount); await DownloadFile(f.props.downloads.raw.url, f.path, _ct, pr.AddBytesCount);
} }
if(!OperatingSystem.IsWindows() && f.props.executable is true) if(!OperatingSystem.IsWindows() && f.props.executable is true)
{ {
LauncherApp.Logger.LogDebug(nameof(Сеть), $"adding execute rights to file '{f.path}'"); LauncherApp.Logger.LogDebug(nameof(NetworkHelper), $"adding execute rights to file '{f.path}'");
System.IO.File.SetUnixFileMode(f.path.ToString(), UnixFileMode.UserExecute); System.IO.File.SetUnixFileMode(f.path.ToString(), UnixFileMode.UserExecute);
} }
}); });
LauncherApp.Logger.LogInfo(nameof(Сеть), "finished downloading java runtime " + LauncherApp.Logger.LogInfo(nameof(NetworkHelper), "finished downloading java runtime " +
$"{_descriptor.javaVersion.majorVersion} '{_descriptor.javaVersion.component}'"); $"{_descriptor.javaVersion.majorVersion} '{_descriptor.javaVersion.component}'");
} }

View File

@@ -1,10 +1,8 @@
using System.IO.Compression; using System.IO.Compression;
using System.Security.Cryptography;
using DTLib.Extensions;
using Mlaumcherb.Client.Avalonia.зримое; using Mlaumcherb.Client.Avalonia.зримое;
using Mlaumcherb.Client.Avalonia.классы; using Mlaumcherb.Client.Avalonia.классы;
using Mlaumcherb.Client.Avalonia.холопы; using Mlaumcherb.Client.Avalonia.холопы;
using static Mlaumcherb.Client.Avalonia.сеть.Сеть; using static Mlaumcherb.Client.Avalonia.сеть.NetworkHelper;
namespace Mlaumcherb.Client.Avalonia.сеть.TaskFactories; namespace Mlaumcherb.Client.Avalonia.сеть.TaskFactories;
@@ -12,7 +10,6 @@ public class LibrariesDownloadTaskFactory : INetworkTaskFactory
{ {
private GameVersionDescriptor _descriptor; private GameVersionDescriptor _descriptor;
private Libraries _libraries; private Libraries _libraries;
private SHA1 _hasher;
private List<Libraries.JarLib> _libsToDownload = new(); private List<Libraries.JarLib> _libsToDownload = new();
private IOPath _nativesDir; private IOPath _nativesDir;
@@ -20,7 +17,6 @@ public class LibrariesDownloadTaskFactory : INetworkTaskFactory
{ {
_descriptor = descriptor; _descriptor = descriptor;
_libraries = libraries; _libraries = libraries;
_hasher = SHA1.Create();
_nativesDir = PathHelper.GetNativeLibrariesDir(descriptor.id); _nativesDir = PathHelper.GetNativeLibrariesDir(descriptor.id);
} }
@@ -28,11 +24,14 @@ public class LibrariesDownloadTaskFactory : INetworkTaskFactory
{ {
NetworkTask? networkTask = null; NetworkTask? networkTask = null;
if (!CheckFiles(checkHashes)) if (!CheckFiles(checkHashes))
{
networkTask = new NetworkTask( networkTask = new NetworkTask(
$"libraries '{_descriptor.id}'", $"libraries '{_descriptor.id}'",
GetTotalSize(), GetTotalSize(),
Download Download
); );
}
return Task.FromResult(networkTask); return Task.FromResult(networkTask);
} }
@@ -43,21 +42,15 @@ public class LibrariesDownloadTaskFactory : INetworkTaskFactory
foreach (var l in _libraries.Libs) foreach (var l in _libraries.Libs)
{ {
if (!File.Exists(l.jarFilePath)) if (!HashHelper.CheckFileSHA1(l.jarFilePath, l.artifact.sha1, checkHashes))
{ {
_libsToDownload.Add(l); _libsToDownload.Add(l);
} }
//TODO: replace with actual native libraries check
else if (!nativeDirExists && l is Libraries.NativeLib) else if (!nativeDirExists && l is Libraries.NativeLib)
{ {
_libsToDownload.Add(l); _libsToDownload.Add(l);
} }
else if (checkHashes)
{
using var fs = File.OpenRead(l.jarFilePath);
string hash = _hasher.ComputeHash(fs).HashToString();
if(hash != l.artifact.sha1)
_libsToDownload.Add(l);
}
} }
return _libsToDownload.Count == 0; return _libsToDownload.Count == 0;
@@ -73,7 +66,7 @@ public class LibrariesDownloadTaskFactory : INetworkTaskFactory
private async Task Download(NetworkProgressReporter pr, CancellationToken ct) private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
{ {
LauncherApp.Logger.LogInfo(nameof(Сеть), $"started downloading libraries '{_descriptor.id}'"); LauncherApp.Logger.LogInfo(nameof(NetworkHelper), $"started downloading libraries '{_descriptor.id}'");
ParallelOptions opt = new() ParallelOptions opt = new()
{ {
@@ -82,26 +75,26 @@ public class LibrariesDownloadTaskFactory : INetworkTaskFactory
}; };
await Parallel.ForEachAsync(_libsToDownload, opt, async (l, _ct) => await Parallel.ForEachAsync(_libsToDownload, opt, async (l, _ct) =>
{ {
LauncherApp.Logger.LogDebug(nameof(Сеть), $"downloading library '{l.name}' to '{l.jarFilePath}'"); LauncherApp.Logger.LogDebug(nameof(NetworkHelper), $"downloading library '{l.name}' to '{l.jarFilePath}'");
if(string.IsNullOrEmpty(l.artifact.url))
throw new Exception($"library '{l.name}' doesn't have a url to download");
await DownloadFile(l.artifact.url, l.jarFilePath, _ct, pr.AddBytesCount); await DownloadFile(l.artifact.url, l.jarFilePath, _ct, pr.AddBytesCount);
if (l is Libraries.NativeLib n) if (l is Libraries.NativeLib n)
{ {
var zipf = File.OpenRead(n.jarFilePath); await using var zipf = File.OpenRead(n.jarFilePath);
ZipFile.ExtractToDirectory(zipf, _nativesDir.ToString(), true); using var archive = new ZipArchive(zipf);
if (n.extractionOptions?.exclude != null) foreach (var entry in archive.Entries)
{ {
foreach (var excluded in n.extractionOptions.exclude) if (n.extractionOptions?.exclude?.Contains(entry.FullName) is true or null)
{ continue;
IOPath path = Path.Concat(_nativesDir, excluded);
if(Directory.Exists(path)) var real_path = Path.Concat(_nativesDir, entry.FullName);
Directory.Delete(path); Directory.Create(real_path.ParentDir());
if(File.Exists(path)) entry.ExtractToFile(real_path.ToString(), true);
File.Delete(path);
}
} }
} }
}); });
LauncherApp.Logger.LogInfo(nameof(Сеть), $"finished downloading libraries '{_descriptor.id}'"); LauncherApp.Logger.LogInfo(nameof(NetworkHelper), $"finished downloading libraries '{_descriptor.id}'");
} }
} }

View File

@@ -0,0 +1,27 @@
using Mlaumcherb.Client.Avalonia.классы;
namespace Mlaumcherb.Client.Avalonia.сеть.TaskFactories;
public class ModpackDownloadTaskFactory : INetworkTaskFactory
{
INetworkTaskFactory _implementationVersion;
private GameVersionDescriptor _descriptor;
public ModpackDownloadTaskFactory(GameVersionDescriptor descriptor)
{
if(descriptor.modpack is null)
throw new ArgumentNullException(nameof(descriptor.modpack));
_descriptor = descriptor;
_implementationVersion = descriptor.modpack.format_version switch
{
1 => new MyModpackV1DownloadTaskFactory(descriptor),
_ => throw new Exception($"Unknown Modpack format_version: {descriptor.modpack.format_version}")
};
}
public Task<NetworkTask?> CreateAsync(bool checkHashes)
{
return _implementationVersion.CreateAsync(checkHashes);
}
}

View File

@@ -0,0 +1,75 @@
using System.IO.Compression;
using Mlaumcherb.Client.Avalonia.зримое;
using Mlaumcherb.Client.Avalonia.классы;
using Mlaumcherb.Client.Avalonia.холопы;
namespace Mlaumcherb.Client.Avalonia.сеть.TaskFactories;
public class MyModpackV1DownloadTaskFactory : INetworkTaskFactory
{
private readonly GameVersionDescriptor _descriptor;
private IOPath _modpackDescriptorPath;
private IOPath _versionDir;
private MyModpackV1? _modpack;
// relative, absolute
private Dictionary<IOPath, IOPath> _filesToDosnload = new();
public MyModpackV1DownloadTaskFactory(GameVersionDescriptor descriptor)
{
_descriptor = descriptor;
_modpackDescriptorPath = PathHelper.GetModpackDescriptorPath(_descriptor.id);
_versionDir = PathHelper.GetVersionDir(_descriptor.id);
}
public async Task<NetworkTask?> CreateAsync(bool checkHashes)
{
if(_descriptor.modpack is null)
throw new ArgumentNullException(nameof(_descriptor.modpack));
(_modpack, bool didDownloadModpackDescriptor) = await NetworkHelper.ReadOrDownloadAndDeserialize<MyModpackV1>(
_modpackDescriptorPath,
_descriptor.modpack.artifact.url,
_descriptor.modpack.artifact.sha1,
checkHashes);
if (_modpack.format_version != _descriptor.modpack.format_version)
throw new Exception($"Modpack.format_version mismatches descriptor.modpack.version: " +
$"{_modpack.format_version} != {_descriptor.modpack.format_version}");
NetworkTask? networkTask = null;
_filesToDosnload = _modpack.CheckFiles(_versionDir, checkHashes, didDownloadModpackDescriptor);
if(_filesToDosnload.Count > 0)
{
networkTask = new NetworkTask(
$"modpack '{_modpack.name}'",
_modpack.zip.size,
Download
);
}
return networkTask;
}
private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
{
LauncherApp.Logger.LogInfo(nameof(NetworkHelper), $"started downloading modpack '{_modpack!.name}'");
if(string.IsNullOrEmpty(_modpack.zip.url))
throw new Exception($"modpack '{_modpack.name}' doesn't have a url to download");
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);
using var archive = new ZipArchive(zipf);
foreach (var entry in archive.Entries)
{
IOPath relativePath = new(entry.FullName);
if(_filesToDosnload.TryGetValue(relativePath, out var absolutePath))
{
Directory.Create(absolutePath.ParentDir());
entry.ExtractToFile(absolutePath.ToString(), true);
}
}
LauncherApp.Logger.LogInfo(nameof(NetworkHelper), $"finished downloading modpack '{_modpack.name}'");
}
}

View File

@@ -1,57 +0,0 @@
using System.Security.Cryptography;
using DTLib.Extensions;
using Mlaumcherb.Client.Avalonia.зримое;
using Mlaumcherb.Client.Avalonia.классы;
using Mlaumcherb.Client.Avalonia.холопы;
using static Mlaumcherb.Client.Avalonia.сеть.Сеть;
namespace Mlaumcherb.Client.Avalonia.сеть.TaskFactories;
public class VersionFileDownloadTaskFactory : INetworkTaskFactory
{
private GameVersionDescriptor _descriptor;
private IOPath _filePath;
private SHA1 _hasher;
public VersionFileDownloadTaskFactory(GameVersionDescriptor descriptor)
{
_descriptor = descriptor;
_filePath = PathHelper.GetVersionJarFilePath(_descriptor.id);
_hasher = SHA1.Create();
}
public Task<NetworkTask?> CreateAsync(bool checkHashes)
{
NetworkTask? networkTask = null;
if (!CheckFiles(checkHashes))
networkTask = new NetworkTask(
$"version file '{_descriptor.id}'",
GetTotalSize(),
Download
);
return Task.FromResult(networkTask);
}
private bool CheckFiles(bool checkHashes)
{
if (!File.Exists(_filePath))
return false;
if (!checkHashes)
return true;
using var fs = File.OpenRead(_filePath);
string hash = _hasher.ComputeHash(fs).HashToString();
return hash == _descriptor.downloads.client.sha1;
}
private long GetTotalSize()
{
return _descriptor.downloads.client.size;
}
private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
{
LauncherApp.Logger.LogInfo(nameof(Сеть), $"started downloading version file '{_descriptor.id}'");
await DownloadFile(_descriptor.downloads.client.url, _filePath, ct, pr.AddBytesCount);
LauncherApp.Logger.LogInfo(nameof(Сеть), $"finished downloading version file '{_descriptor.id}'");
}
}

View File

@@ -0,0 +1,55 @@
using Mlaumcherb.Client.Avalonia.зримое;
using Mlaumcherb.Client.Avalonia.классы;
using Mlaumcherb.Client.Avalonia.холопы;
using static Mlaumcherb.Client.Avalonia.сеть.NetworkHelper;
namespace Mlaumcherb.Client.Avalonia.сеть.TaskFactories;
public class VersionJarDownloadTaskFactory : INetworkTaskFactory
{
private GameVersionDescriptor _descriptor;
private IOPath _filePath;
public VersionJarDownloadTaskFactory(GameVersionDescriptor descriptor)
{
_descriptor = descriptor;
_filePath = PathHelper.GetVersionJarFilePath(_descriptor.id);
}
public Task<NetworkTask?> CreateAsync(bool checkHashes)
{
NetworkTask? networkTask = null;
if (!CheckFiles(checkHashes))
{
networkTask = new NetworkTask(
$"game version jar '{_descriptor.id}'",
GetTotalSize(),
Download
);
}
return Task.FromResult(networkTask);
}
private bool CheckFiles(bool checkHashes)
{
return HashHelper.CheckFileSHA1(_filePath, _descriptor.downloads?.client.sha1, checkHashes);
}
private long GetTotalSize()
{
if(_descriptor.downloads is null)
return 0;
return _descriptor.downloads.client.size;
}
private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
{
if (_descriptor.downloads is null)
throw new Exception($"can't download game version jar '{_descriptor.id}' because it has no download url");
LauncherApp.Logger.LogInfo(nameof(NetworkHelper), $"started downloading game version jar '{_descriptor.id}'");
await DownloadFile(_descriptor.downloads.client.url, _filePath, ct, pr.AddBytesCount);
LauncherApp.Logger.LogInfo(nameof(NetworkHelper), $"finished downloading game version jar '{_descriptor.id}'");
}
}

View File

@@ -0,0 +1,32 @@
using System.Security.Cryptography;
using DTLib.Extensions;
namespace Mlaumcherb.Client.Avalonia.холопы;
public static class HashHelper
{
private static SHA1 _hasher;
static HashHelper()
{
_hasher = SHA1.Create();
}
public static string HashFileSHA1(IOPath f)
{
using var fs = File.OpenRead(f);
byte[] hash = _hasher.ComputeHash(fs);
return hash.HashToString();
}
public static bool CheckFileSHA1(IOPath f, string? sha1, bool checkHash)
{
if (!File.Exists(f))
return false;
if(checkHash)
return sha1 is not null && HashFileSHA1(f) == sha1;
return true;
}
}

View File

@@ -11,7 +11,7 @@ public static class PathHelper
Path.Concat(GetRootFullPath(), "assets"); Path.Concat(GetRootFullPath(), "assets");
public static IOPath GetAssetIndexFilePath(string id) => public static IOPath GetAssetIndexFilePath(string id) =>
Path.Concat(GetAssetsDir(), $"assets/indexes/{id}.json"); Path.Concat(GetAssetsDir(), $"indexes/{id}.json"); // this path is hardcoded in the game
public static IOPath GetVersionDescriptorPath(string id) => public static IOPath GetVersionDescriptorPath(string id) =>
Path.Concat(GetVersionDir(id), id + ".json"); Path.Concat(GetVersionDir(id), id + ".json");
@@ -54,4 +54,12 @@ public static class PathHelper
public static IOPath GetLog4jConfigFilePath() => public static IOPath GetLog4jConfigFilePath() =>
Path.Concat(GetAssetsDir(), GetLog4jConfigFileName()); Path.Concat(GetAssetsDir(), GetLog4jConfigFileName());
public static IOPath GetModpackDescriptorPath(string game_version) =>
Path.Concat(GetVersionDir(game_version), "timerix_modpack.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);
}
}