Compare commits
21 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1c3b8963ac | |||
| e915892fa2 | |||
| ab1aefd619 | |||
| 459b3f09f9 | |||
| 9bcdfd88e6 | |||
| 2dc472c85a | |||
| 2087c14285 | |||
| ef36fb5584 | |||
| d6bd7b9ef0 | |||
| 23195bd7c7 | |||
| 5e439ee8d5 | |||
| cbfd5f8da8 | |||
| da58c11e59 | |||
| 23ec6dd194 | |||
| 679d89b4b0 | |||
| 228b3bc55f | |||
| 7882bb9bfd | |||
| 968ff99987 | |||
| e5deb3f3d4 | |||
| 2c780afea8 | |||
| d141ec23dc |
@ -1,5 +1,6 @@
|
||||
using Mlaumcherb.Client.Avalonia.зримое;
|
||||
using Mlaumcherb.Client.Avalonia.классы;
|
||||
using Mlaumcherb.Client.Avalonia.сеть.Update;
|
||||
using Mlaumcherb.Client.Avalonia.холопы;
|
||||
|
||||
namespace Mlaumcherb.Client.Avalonia;
|
||||
@ -20,21 +21,28 @@ 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 = "Тимериховое", url = "https://timerix.ddns.net/minecraft/catalog.json" },
|
||||
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" }
|
||||
];
|
||||
|
||||
public UpdateHelper.GiteaConfig gitea { get; set; } = new()
|
||||
{
|
||||
serverUrl = "https://timerix.ddns.net/git/",
|
||||
user = "Timerix",
|
||||
repo = "mlaumcherb",
|
||||
};
|
||||
|
||||
|
||||
[JsonIgnore] private static IOPath _filePath = "млаумчерб.json";
|
||||
|
||||
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 +75,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}");
|
||||
|
||||
@ -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,94 +26,33 @@ 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, null);
|
||||
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)
|
||||
{
|
||||
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 NetworkHelper.DownloadFile(props.RemoteDescriptorUrl, 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);
|
||||
WorkingDirectory = GetVersionDir(_descriptor.id);
|
||||
JavaExecutableFilePath = GetJavaExecutablePath(_descriptor.javaVersion.component, LauncherApp.Config.debug);
|
||||
JavaExecutableFilePath = GetJavaExecutablePath(
|
||||
_descriptor.javaVersion.component, LauncherApp.Config.redirect_game_output);
|
||||
}
|
||||
|
||||
public async Task UpdateFiles(bool checkHashes, Action<NetworkTask> networkTaskCreatedCallback)
|
||||
public async Task Download(bool checkHashes, Action<NetworkTask> networkTaskCreatedCallback)
|
||||
{
|
||||
LauncherApp.Logger.LogInfo(Name, $"started updating version {Name}");
|
||||
LauncherApp.Logger.LogInfo(Id, $"started updating version {Id}");
|
||||
|
||||
List<INetworkTaskFactory> taskFactories =
|
||||
[
|
||||
new AssetsDownloadTaskFactory(_descriptor),
|
||||
new LibrariesDownloadTaskFactory(_descriptor, _libraries),
|
||||
new VersionFileDownloadTaskFactory(_descriptor),
|
||||
];
|
||||
if (LauncherApp.Config.download_java)
|
||||
{
|
||||
if (LauncherApp.Config.download_java && (!File.Exists(JavaExecutableFilePath) || checkHashes))
|
||||
taskFactories.Add(new JavaDownloadTaskFactory(_descriptor));
|
||||
}
|
||||
//TODO: modpack
|
||||
/*if (modpack != null)
|
||||
{
|
||||
taskFactories.Add(new ModpackDownloadTaskFactory(modpack));
|
||||
}*/
|
||||
if (_descriptor.modpack != null)
|
||||
taskFactories.Add(new ModpackDownloadTaskFactory(_descriptor));
|
||||
// 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++)
|
||||
@ -141,8 +79,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
|
||||
@ -171,12 +109,13 @@ public class GameVersion
|
||||
if (string.IsNullOrWhiteSpace(LauncherApp.Config.player_name))
|
||||
throw new Exception("invalid player name");
|
||||
|
||||
string classSeparator = PlatformHelper.GetOs() == "windows" ? ";" : ":";
|
||||
Directory.Create(WorkingDirectory);
|
||||
string uuid = GetPlayerUUID(LauncherApp.Config.player_name);
|
||||
Dictionary<string, string> placeholder_values = new() {
|
||||
{ "resolution_width", "1600" },
|
||||
{ "resolution_height", "900" },
|
||||
{ "xms", "2048" },
|
||||
{ "xms", LauncherApp.Config.max_memory.ToString() },
|
||||
{ "xmx", LauncherApp.Config.max_memory.ToString() },
|
||||
{ "auth_player_name", LauncherApp.Config.player_name },
|
||||
{ "auth_access_token", uuid },
|
||||
@ -190,12 +129,14 @@ public class GameVersion
|
||||
{ "launcher_version", "1.6.84-j" },
|
||||
{ "classpath", _libraries.Libs.Select(l => l.jarFilePath)
|
||||
.Append(GetVersionJarFilePath(_descriptor.id))
|
||||
.MergeToString(';') },
|
||||
.MergeToString(classSeparator) },
|
||||
{ "assets_index_name", _descriptor.assets },
|
||||
{ "assets_root", GetAssetsDir().ToString() },
|
||||
{ "game_assets", GetAssetsDir().ToString() },
|
||||
{ "game_directory", WorkingDirectory.ToString() },
|
||||
{ "natives_directory", GetNativeLibrariesDir(_descriptor.id).ToString() },
|
||||
{ "library_directory", GetLibrariesDir().ToString() },
|
||||
{ "classpath_separator", classSeparator},
|
||||
{ "path", GetLog4jConfigFilePath().ToString() },
|
||||
{ "version_name", _descriptor.id },
|
||||
{ "version_type", _descriptor.type },
|
||||
@ -221,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()
|
||||
@ -246,5 +187,5 @@ public class GameVersion
|
||||
}
|
||||
|
||||
|
||||
public override string ToString() => Name;
|
||||
public override string ToString() => Id;
|
||||
}
|
||||
@ -5,11 +5,12 @@ public class LauncherLogger : ILogger
|
||||
private CompositeLogger _compositeLogger;
|
||||
private FileLogger _fileLogger;
|
||||
public static readonly IOPath LogsDirectory = "launcher_logs";
|
||||
public IOPath LogfileName => _fileLogger.LogfileName;
|
||||
public IOPath LogFilePath => _fileLogger.LogfileName;
|
||||
|
||||
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
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<Version>1.1.2</Version>
|
||||
<OutputType Condition="'$(Configuration)' == 'Debug'">Exe</OutputType>
|
||||
<OutputType Condition="'$(Configuration)' != 'Debug'">WinExe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
@ -11,18 +12,19 @@
|
||||
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
|
||||
<ApplicationIcon>капитал\кубе.ico</ApplicationIcon>
|
||||
<AssemblyName>млаумчерб</AssemblyName>
|
||||
<Configurations>Release;Debug</Configurations>
|
||||
<Platforms>x64</Platforms>
|
||||
<!-- AXAML resource has no public constructor -->
|
||||
<NoWarn>AVLN3001</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia" Version="11.2.0" />
|
||||
<PackageReference Include="Avalonia.Desktop" Version="11.2.0" />
|
||||
<PackageReference Include="Avalonia.Themes.Simple" Version="11.2.0" />
|
||||
<PackageReference Condition="'$(Configuration)' == 'Debug'" Include="Avalonia.Diagnostics" Version="11.2.0" />
|
||||
<PackageReference Include="Avalonia.Labs.Gif" Version="11.2.0" />
|
||||
<PackageReference Include="CliWrap" Version="3.6.7" />
|
||||
<PackageReference Include="DTLib" Version="1.6.1" />
|
||||
<PackageReference Include="Avalonia" Version="11.2.*" />
|
||||
<PackageReference Include="Avalonia.Desktop" Version="11.2.*" />
|
||||
<PackageReference Include="Avalonia.Themes.Simple" Version="11.2.*" />
|
||||
<PackageReference Condition="'$(Configuration)' == 'Debug'" Include="Avalonia.Diagnostics" Version="11.2.*" />
|
||||
<PackageReference Include="Avalonia.Labs.Gif" Version="11.2.*" />
|
||||
<PackageReference Include="CliWrap" Version="3.7.0" />
|
||||
<PackageReference Include="DTLib" Version="1.7.3" />
|
||||
<PackageReference Include="LZMA-SDK" Version="22.1.1" />
|
||||
<PackageReference Include="MessageBox.Avalonia" Version="3.2.0" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.*" />
|
||||
|
||||
@ -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>
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
@ -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"/>
|
||||
|
||||
@ -1,13 +1,17 @@
|
||||
using Avalonia;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Markup.Xaml;
|
||||
using Mlaumcherb.Client.Avalonia.классы;
|
||||
using Mlaumcherb.Client.Avalonia.сеть.Update;
|
||||
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()
|
||||
{
|
||||
@ -16,10 +20,46 @@ public class LauncherApp : Application
|
||||
Logger.DebugLogEnabled = Config.debug;
|
||||
AvaloniaXamlLoader.Load(this);
|
||||
|
||||
// some file required by forge installer
|
||||
if (!File.Exists("launcher_profiles.json"))
|
||||
try
|
||||
{
|
||||
File.WriteAllText("launcher_profiles.json", "{}");
|
||||
SelfUpdateAsync();
|
||||
|
||||
// some file required by forge installer
|
||||
if (!File.Exists("launcher_profiles.json"))
|
||||
{
|
||||
File.WriteAllText("launcher_profiles.json", "{}");
|
||||
}
|
||||
|
||||
InstalledVersionCatalog = InstalledVersionCatalog.Load();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
ErrorHelper.ShowMessageBox(nameof(LauncherApp), e);
|
||||
}
|
||||
}
|
||||
|
||||
private async void SelfUpdateAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
Logger.LogInfo(nameof(LauncherApp), "checking for updates...");
|
||||
var upd = new UpdateHelper(Config.gitea);
|
||||
upd.DeleteBackupFiles();
|
||||
if (await upd.IsUpdateAvailable())
|
||||
{
|
||||
Logger.LogInfo(nameof(LauncherApp), "downloading update...");
|
||||
await upd.UpdateSelf();
|
||||
Logger.LogInfo(nameof(LauncherApp), "restarting...");
|
||||
upd.RestartSelf();
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogInfo(nameof(LauncherApp), "no updates found");
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
ErrorHelper.ShowMessageBox(nameof(LauncherApp), e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -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}">
|
||||
Скачивать джаву
|
||||
@ -170,6 +178,7 @@
|
||||
<Button Classes="menu_button button_no_border" Click="ОткрытьФайлЛогов">лог-файл</Button>
|
||||
</StackPanel>
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
|
||||
<TextBlock Name="LauncherVersionTextBox"/>
|
||||
<Button Classes="menu_button button_no_border" Click="ОткрытьРепозиторий">исходный код</Button>
|
||||
<gif:GifImage
|
||||
Width="30" Height="30" Stretch="Uniform"
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
using System.Reflection;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Data;
|
||||
@ -32,13 +33,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,38 +66,79 @@ public partial class MainWindow : Window
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
protected override async void OnLoaded(RoutedEventArgs e)
|
||||
protected override void OnLoaded(RoutedEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
LauncherApp.Logger.OnLogMessage += GuiLogMessage;
|
||||
LauncherVersionTextBox.Text = $"v{Assembly.GetExecutingAssembly().GetName().Version}";
|
||||
|
||||
PlayerName = LauncherApp.Config.player_name;
|
||||
MemoryLimit = LauncherApp.Config.max_memory;
|
||||
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 vc in LauncherApp.Config.version_catalogs)
|
||||
{
|
||||
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;
|
||||
RemoteVersionCatalogComboBox.Items.Add(vc);
|
||||
}
|
||||
RemoteVersionCatalogComboBox.SelectedIndex = 0;
|
||||
|
||||
foreach (var vc in LauncherApp.Config.version_catalogs)
|
||||
UpdateInstalledVersionsCatalogView(LauncherApp.Config.last_launched_version);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ErrorHelper.ShowMessageBox(nameof(MainWindow), ex);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnUnloaded(RoutedEventArgs e)
|
||||
{
|
||||
SaveGuiPropertiesToConfig();
|
||||
}
|
||||
|
||||
private void SaveGuiPropertiesToConfig()
|
||||
{
|
||||
LauncherApp.Config.player_name = PlayerName;
|
||||
LauncherApp.Config.max_memory = MemoryLimit;
|
||||
LauncherApp.Config.download_java = EnableJavaDownload;
|
||||
LauncherApp.Config.redirect_game_output = RedirectGameOutput;
|
||||
LauncherApp.Config.SaveToFile();
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
VersionCatalogComboBox.Items.Add(vc);
|
||||
InstalledVersionCatalogComboBox.SelectedItem = view;
|
||||
break;
|
||||
}
|
||||
VersionCatalogComboBox.SelectedIndex = 0;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
InstalledVersionCatalogComboBox.IsEnabled = true;
|
||||
}
|
||||
|
||||
private void RescanInstalledVersionsButton_OnClick(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
var selectedVersionView = InstalledVersionCatalogComboBox.SelectedItem as InstalledGameVersionItemView;
|
||||
UpdateInstalledVersionsCatalogView(selectedVersionView?.Props.Id);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@ -121,32 +163,35 @@ public partial class MainWindow : Window
|
||||
{
|
||||
try
|
||||
{
|
||||
Dispatcher.UIThread.Invoke(() => LaunchButton.IsEnabled = false);
|
||||
|
||||
var selectedVersionView = (VersionItemView?)InstalledVersionComboBox.SelectedItem;
|
||||
var selectedVersion = selectedVersionView?.Props;
|
||||
LauncherApp.Config.last_launched_version = selectedVersion?.Name;
|
||||
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)
|
||||
if (InstalledVersionCatalogComboBox.SelectedItem is not InstalledGameVersionItemView selectedVersionView)
|
||||
return;
|
||||
|
||||
var v = await GameVersion.CreateFromPropsAsync(selectedVersion);
|
||||
await v.UpdateFiles(CheckGameFiles, nt =>
|
||||
{
|
||||
Dispatcher.UIThread.Invoke(() =>
|
||||
Dispatcher.UIThread.Invoke(() => LaunchButton.IsEnabled = false);
|
||||
LauncherApp.Config.last_launched_version = selectedVersionView.Props.Id;
|
||||
SaveGuiPropertiesToConfig();
|
||||
|
||||
var v = await selectedVersionView.Props.LoadDescriptor(UpdateGameFiles);
|
||||
|
||||
try
|
||||
{
|
||||
await v.Download(UpdateGameFiles, nt =>
|
||||
{
|
||||
DownloadsPanel.Children.Add(new NetworkTaskView(nt,
|
||||
ntv => DownloadsPanel.Children.Remove(ntv)));
|
||||
});
|
||||
}
|
||||
);
|
||||
Dispatcher.UIThread.Invoke(() =>
|
||||
{
|
||||
DownloadsPanel.Children.Add(new NetworkTaskView(nt,
|
||||
ntv => DownloadsPanel.Children.Remove(ntv)));
|
||||
});
|
||||
}
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ErrorHelper.ShowMessageBox(nameof(MainWindow), ex);
|
||||
}
|
||||
|
||||
Dispatcher.UIThread.Invoke(() =>
|
||||
{
|
||||
CheckGameFiles = false;
|
||||
UpdateGameFiles = false;
|
||||
});
|
||||
await v.Launch();
|
||||
}
|
||||
@ -156,10 +201,7 @@ public partial class MainWindow : Window
|
||||
}
|
||||
finally
|
||||
{
|
||||
Dispatcher.UIThread.Invoke(() =>
|
||||
{
|
||||
LaunchButton.IsEnabled = true;
|
||||
});
|
||||
Dispatcher.UIThread.Invoke(() => LaunchButton.IsEnabled = true);
|
||||
}
|
||||
}
|
||||
|
||||
@ -167,7 +209,10 @@ public partial class MainWindow : Window
|
||||
{
|
||||
try
|
||||
{
|
||||
Launcher.LaunchDirectoryInfoAsync(new DirectoryInfo(Directory.GetCurrent().ToString()))
|
||||
string workingDir = Directory.GetCurrent().ToString();
|
||||
LauncherApp.Logger.LogDebug(nameof(MainWindow),
|
||||
$"opening working directory: {workingDir}");
|
||||
Launcher.LaunchDirectoryInfoAsync(new DirectoryInfo(workingDir))
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
@ -180,7 +225,10 @@ public partial class MainWindow : Window
|
||||
{
|
||||
try
|
||||
{
|
||||
Launcher.LaunchFileInfoAsync(new FileInfo(LauncherApp.Logger.LogfileName.ToString()))
|
||||
string logFilePath = LauncherApp.Logger.LogFilePath.ToString();
|
||||
LauncherApp.Logger.LogDebug(nameof(MainWindow),
|
||||
$"opening log file: {logFilePath}");
|
||||
Launcher.LaunchFileInfoAsync(new FileInfo(logFilePath))
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
@ -193,7 +241,10 @@ public partial class MainWindow : Window
|
||||
{
|
||||
try
|
||||
{
|
||||
Launcher.LaunchUriAsync(new Uri("https://timerix.ddns.net:3322/Timerix/mlaumcherb"))
|
||||
var sourcesUri = new Uri(LauncherApp.Config.gitea.GetRepoUrl());
|
||||
LauncherApp.Logger.LogDebug(nameof(MainWindow),
|
||||
$"opening in web browser: {sourcesUri}");
|
||||
Launcher.LaunchUriAsync(sourcesUri)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
@ -218,71 +269,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 +308,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)
|
||||
{
|
||||
|
||||
@ -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
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -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.id, r.url));
|
||||
_versionPropsList.Add(r);
|
||||
}
|
||||
return _versionPropsList;
|
||||
}
|
||||
|
||||
@ -10,13 +10,16 @@ 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;
|
||||
public JavaVersion javaVersion { get; set; } = new() { component = "jre-legacy", majorVersion = 8 };
|
||||
public string? minecraftArguments { get; set; }
|
||||
public ArgumentsNew? arguments { get; set; }
|
||||
|
||||
// my additions
|
||||
public MyModpackRemoteProps? modpack { get; set; }
|
||||
}
|
||||
|
||||
public class Artifact
|
||||
@ -64,7 +67,7 @@ public class Library
|
||||
public List<Rule>? rules { get; set; }
|
||||
public Natives? natives { get; set; }
|
||||
public Extract? extract { get; set; }
|
||||
[JsonRequired] public LibraryDownloads downloads { get; set; } = null!;
|
||||
public LibraryDownloads? downloads { get; set; }
|
||||
}
|
||||
|
||||
public class AssetIndexProperties
|
||||
|
||||
@ -5,9 +5,9 @@ namespace Mlaumcherb.Client.Avalonia.классы;
|
||||
|
||||
public class JavaVersionCatalog
|
||||
{
|
||||
[JsonProperty("linux")]
|
||||
public Dictionary<string, JavaVersionProps[]>? linux_x86 { get; set; }
|
||||
[JsonProperty("linux-i386")]
|
||||
public Dictionary<string, JavaVersionProps[]>? linux_x86 { get; set; }
|
||||
[JsonProperty("linux")]
|
||||
public Dictionary<string, JavaVersionProps[]>? linux_x64 { get; set; }
|
||||
[JsonProperty("mac-os")]
|
||||
public Dictionary<string, JavaVersionProps[]>? osx_x64 { get; set; }
|
||||
@ -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
|
||||
|
||||
@ -30,7 +30,7 @@ public class GameArguments : ArgumentsWithPlaceholders
|
||||
{
|
||||
foreach (var arg in av.value)
|
||||
{
|
||||
if(!_raw_args.Contains(arg))
|
||||
// if(!_raw_args.Contains(arg))
|
||||
_raw_args.Add(arg);
|
||||
}
|
||||
}
|
||||
|
||||
@ -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);
|
||||
@ -1,74 +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 string? RemoteDescriptorUrl { get; }
|
||||
private bool _isDownloaded;
|
||||
public bool IsDownloaded
|
||||
{
|
||||
get => _isDownloaded;
|
||||
set
|
||||
{
|
||||
if(_isDownloaded != value)
|
||||
{
|
||||
_isDownloaded = value;
|
||||
StatusChanged?.Invoke(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
public event Action<bool>? StatusChanged;
|
||||
|
||||
public GameVersionProps(string name, string? url)
|
||||
{
|
||||
Name = name;
|
||||
LocalDescriptorPath = PathHelper.GetVersionDescriptorPath(name);
|
||||
RemoteDescriptorUrl = url;
|
||||
IsDownloaded = File.Exists(PathHelper.GetVersionJarFilePath(name));
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,137 @@
|
||||
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, timerix-anarx-2 inherits from 1.12.2-forge-14.23.5.2860, which inherits from 1.12.2
|
||||
while (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}'");
|
||||
JObject parentDescriptorRaw = JObject.Parse(File.ReadAllText(parentDescriptorPath));
|
||||
|
||||
// Remove `inheritsFrom: parentDescriptor.Id` to prevent overriding of `parentDescriptor.inheritsFrom`
|
||||
descriptorRaw.Remove("inheritsFrom");
|
||||
// Merge child descriptor into its parent.
|
||||
// Child descriptor values override values of parent.
|
||||
// Array values are merged together.
|
||||
parentDescriptorRaw.Merge(descriptorRaw,
|
||||
new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Concat });
|
||||
descriptorRaw = parentDescriptorRaw;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,78 @@
|
||||
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();
|
||||
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.
|
||||
/// Calls <see cref="Save"/>
|
||||
/// </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)))
|
||||
{
|
||||
LauncherApp.Logger.LogWarn(nameof(CheckInstalledVersions),
|
||||
$"Can't find version descriptor file in directory '{subdir}'. " +
|
||||
$"Rename it as directory name.");
|
||||
continue;
|
||||
}
|
||||
|
||||
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)
|
||||
));
|
||||
|
||||
Save();
|
||||
}
|
||||
}
|
||||
@ -21,7 +21,6 @@ public class JavaArguments : ArgumentsWithPlaceholders
|
||||
"-Dminecraft.client.jar=${client_jar}",
|
||||
"-Dminecraft.launcher.brand=${launcher_name}",
|
||||
"-Dminecraft.launcher.version=${launcher_version}",
|
||||
"-cp", "${classpath}"
|
||||
];
|
||||
|
||||
private static readonly string[] _enabled_features =
|
||||
@ -39,11 +38,17 @@ public class JavaArguments : ArgumentsWithPlaceholders
|
||||
{
|
||||
foreach (var arg in av.value)
|
||||
{
|
||||
if(!_raw_args.Contains(arg))
|
||||
// if(!_raw_args.Contains(arg))
|
||||
_raw_args.Add(arg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!_raw_args.Contains("-cp"))
|
||||
{
|
||||
_raw_args.Add("-cp");
|
||||
_raw_args.Add("${classpath}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -7,13 +7,28 @@ public class Libraries
|
||||
{
|
||||
private static readonly string[] enabled_features = [];
|
||||
|
||||
public record JarLib(string name, IOPath jarFilePath, Artifact artifact);
|
||||
public record NativeLib(string name, IOPath jarFilePath, Artifact artifact, Extract? extractionOptions)
|
||||
public record JarLib(string name, IOPath jarFilePath, Artifact? artifact);
|
||||
public record NativeLib(string name, IOPath jarFilePath, Artifact? artifact, Extract? extractionOptions)
|
||||
: JarLib(name, jarFilePath, artifact);
|
||||
|
||||
public IReadOnlyCollection<JarLib> Libs { get; }
|
||||
|
||||
private IOPath GetJarFilePath(Artifact artifact)
|
||||
public static IOPath GetPathFromMavenName(string mavenName, string ext = "jar")
|
||||
{
|
||||
int sep_0 = mavenName.IndexOf(':');
|
||||
if (sep_0 == -1)
|
||||
throw new ArgumentException($"Invalid maven name: {mavenName}");
|
||||
int sep_1 = mavenName.IndexOf(':', sep_0 + 1);
|
||||
if (sep_1 == -1)
|
||||
throw new ArgumentException($"Invalid maven name: {mavenName}");
|
||||
var package = mavenName.Substring(0, sep_0).Replace('.', '/');
|
||||
var artifact = mavenName.Substring(sep_0 + 1, sep_1 - sep_0 - 1);
|
||||
var version = mavenName.Substring(sep_1 + 1);
|
||||
string file_name = $"{artifact}-{version}.{ext}";
|
||||
return Path.Concat(PathHelper.GetLibrariesDir(), package, artifact, version, file_name);
|
||||
}
|
||||
|
||||
private static IOPath GetPathFromArtifact(Artifact artifact)
|
||||
{
|
||||
string relativePath;
|
||||
if (!string.IsNullOrEmpty(artifact.path))
|
||||
@ -60,26 +75,30 @@ public class Libraries
|
||||
}
|
||||
|
||||
Artifact artifact = null!;
|
||||
if(l.downloads.classifiers != null && !l.downloads.classifiers.TryGetValue(nativesKey, out artifact!))
|
||||
if(l.downloads?.classifiers != null && !l.downloads.classifiers.TryGetValue(nativesKey, out artifact!))
|
||||
throw new Exception($"can't find artifact for '{l.name}' with nativesKey '{nativesKey}'");
|
||||
|
||||
// skipping duplicates (WHO THE HELL CREATES THIS DISCRIPTORS AAAAAAAAA)
|
||||
if(!libHashes.Add(artifact.sha1))
|
||||
continue;
|
||||
|
||||
libs.Add(new NativeLib(l.name, GetJarFilePath(artifact), artifact, l.extract));
|
||||
libs.Add(new NativeLib(l.name, GetPathFromArtifact(artifact), artifact, l.extract));
|
||||
}
|
||||
else
|
||||
{
|
||||
Artifact? artifact = l.downloads.artifact;
|
||||
if (artifact == null)
|
||||
throw new NullReferenceException($"artifact for '{l.name}' is null");
|
||||
Artifact? artifact = l.downloads?.artifact;
|
||||
if (artifact is null)
|
||||
{
|
||||
libs.Add(new JarLib(l.name, GetPathFromMavenName(l.name), artifact));
|
||||
}
|
||||
else
|
||||
{
|
||||
// skipping duplicates
|
||||
if (!libHashes.Add(artifact.sha1))
|
||||
continue;
|
||||
|
||||
// skipping duplicates
|
||||
if(!libHashes.Add(artifact.sha1))
|
||||
continue;
|
||||
|
||||
libs.Add(new JarLib(l.name, GetJarFilePath(artifact), artifact));
|
||||
libs.Add(new JarLib(l.name, GetPathFromArtifact(artifact), artifact));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -0,0 +1,7 @@
|
||||
namespace Mlaumcherb.Client.Avalonia.классы;
|
||||
|
||||
public class MyModpackRemoteProps
|
||||
{
|
||||
[JsonRequired] public int format_version { get; set; }
|
||||
[JsonRequired] public Artifact artifact { get; set; } = null!;
|
||||
}
|
||||
47
Mlaumcherb.Client.Avalonia/классы/Пролетариат/MyModpackV2.cs
Normal file
47
Mlaumcherb.Client.Avalonia/классы/Пролетариат/MyModpackV2.cs
Normal file
@ -0,0 +1,47 @@
|
||||
using Mlaumcherb.Client.Avalonia.холопы;
|
||||
|
||||
namespace Mlaumcherb.Client.Avalonia.классы;
|
||||
|
||||
public class MyModpackV2
|
||||
{
|
||||
// 2
|
||||
[JsonRequired] public int format_version { get; set; }
|
||||
[JsonRequired] public string name { get; set; } = "";
|
||||
/// relative_path, props
|
||||
// ReSharper disable once CollectionNeverUpdated.Global
|
||||
[JsonRequired] public Dictionary<string, FileProps> files { get; set; } = new();
|
||||
|
||||
|
||||
public class FileProps
|
||||
{
|
||||
[JsonRequired] public Artifact artifact { get; set; } = null!;
|
||||
// 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 record FileCheckResult(FileProps props, IOPath relativePath, IOPath absolutePath);
|
||||
public List<FileCheckResult> CheckFiles(IOPath basedir, bool checkHashes, bool downloadOptionalFiles)
|
||||
{
|
||||
List<FileCheckResult> unmatchedFiles = new();
|
||||
IOPath launcherRoot = PathHelper.GetRootFullPath();
|
||||
foreach (var p in files)
|
||||
{
|
||||
if(!downloadOptionalFiles && p.Value.optional)
|
||||
continue;
|
||||
|
||||
IOPath relativePath = new IOPath(p.Key);
|
||||
// libraries can be in modpacks, they are placed in global libraries directory
|
||||
var absolutePath = Path.Concat(relativePath.StartsWith("libraries")
|
||||
? launcherRoot : basedir, relativePath);
|
||||
if (!HashHelper.CheckFileSHA1(absolutePath, p.Value.artifact.sha1, checkHashes && !p.Value.allow_edit))
|
||||
{
|
||||
unmatchedFiles.Add(new FileCheckResult(p.Value, relativePath, absolutePath));
|
||||
}
|
||||
}
|
||||
|
||||
return unmatchedFiles;
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,5 @@
|
||||
using System.Net.Http;
|
||||
using Mlaumcherb.Client.Avalonia.зримое;
|
||||
using Mlaumcherb.Client.Avalonia.классы;
|
||||
using Mlaumcherb.Client.Avalonia.холопы;
|
||||
|
||||
namespace Mlaumcherb.Client.Avalonia.сеть;
|
||||
|
||||
@ -13,6 +12,7 @@ public static class NetworkHelper
|
||||
// thanks for Sashok :3
|
||||
// https://github.com/new-sashok724/Launcher/blob/23485c3f7de6620d2c6b7b2dd9339c3beb6a0366/Launcher/source/helper/IOHelper.java#L259
|
||||
_http.DefaultRequestHeaders.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
|
||||
_http.Timeout = TimeSpan.FromSeconds(4);
|
||||
}
|
||||
|
||||
public static Task<string> GetString(string url, CancellationToken ct = default) => _http.GetStringAsync(url, ct);
|
||||
@ -41,4 +41,27 @@ public static class NetworkHelper
|
||||
?? throw new Exception($"can't deserialize {typeof(T).Name}");
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/// <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), false);
|
||||
|
||||
string txt = await NetworkHelper.GetString(url);
|
||||
File.WriteAllText(filePath, txt);
|
||||
return (txt, true);
|
||||
}
|
||||
|
||||
/// <returns>(file_content, didDownload)</returns>
|
||||
public static async Task<(T, bool)> ReadOrDownloadAndDeserialize<T>(IOPath filePath, string url,
|
||||
string? sha1, bool 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, didDownload);
|
||||
}
|
||||
}
|
||||
@ -1,7 +1,5 @@
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Security.Cryptography;
|
||||
using DTLib.Extensions;
|
||||
using Mlaumcherb.Client.Avalonia.зримое;
|
||||
using Mlaumcherb.Client.Avalonia.классы;
|
||||
using Mlaumcherb.Client.Avalonia.холопы;
|
||||
@ -13,42 +11,37 @@ public class AssetsDownloadTaskFactory : INetworkTaskFactory
|
||||
{
|
||||
private const string ASSET_SERVER_URL = "https://resources.download.minecraft.net/";
|
||||
private GameVersionDescriptor _descriptor;
|
||||
private SHA1 _hasher;
|
||||
private IOPath _indexFilePath;
|
||||
List<AssetDownloadProperties> _assetsToDownload = new();
|
||||
|
||||
public AssetsDownloadTaskFactory(GameVersionDescriptor descriptor)
|
||||
{
|
||||
_descriptor = descriptor;
|
||||
_hasher = SHA1.Create();
|
||||
_indexFilePath = PathHelper.GetAssetIndexFilePath(_descriptor.assetIndex.id);
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
if(!File.Exists(_indexFilePath))
|
||||
{
|
||||
LauncherApp.Logger.LogInfo(nameof(NetworkHelper), $"started downloading asset index to '{_indexFilePath}'");
|
||||
await DownloadFile(_descriptor.assetIndex.url, _indexFilePath);
|
||||
LauncherApp.Logger.LogInfo(nameof(NetworkHelper), "finished downloading asset index");
|
||||
}
|
||||
(AssetIndex assetIndex, _) = await ReadOrDownloadAndDeserialize<AssetIndex>(
|
||||
_indexFilePath,
|
||||
_descriptor.assetIndex.url,
|
||||
_descriptor.assetIndex.sha1,
|
||||
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)
|
||||
HashSet<string> assetHashes = new HashSet<string>();
|
||||
foreach (var pair in assetIndex.objects)
|
||||
@ -56,17 +49,10 @@ public class AssetsDownloadTaskFactory : INetworkTaskFactory
|
||||
if (assetHashes.Add(pair.Value.hash))
|
||||
{
|
||||
var a = new AssetDownloadProperties(pair.Key, pair.Value);
|
||||
if (!File.Exists(a.filePath))
|
||||
if (!HashHelper.CheckFileSHA1(a.filePath, a.hash, checkHashes))
|
||||
{
|
||||
_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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1,6 +1,4 @@
|
||||
using System.Security.Cryptography;
|
||||
using DTLib.Extensions;
|
||||
using Mlaumcherb.Client.Avalonia.зримое;
|
||||
using Mlaumcherb.Client.Avalonia.зримое;
|
||||
using Mlaumcherb.Client.Avalonia.классы;
|
||||
using Mlaumcherb.Client.Avalonia.холопы;
|
||||
using static Mlaumcherb.Client.Avalonia.сеть.NetworkHelper;
|
||||
@ -13,7 +11,6 @@ public class JavaDownloadTaskFactory : INetworkTaskFactory
|
||||
"https://launchermeta.mojang.com/v1/products/java-runtime/2ec0cc96c44e5a76b9c8b7c39df7210883d12871/all.json";
|
||||
private GameVersionDescriptor _descriptor;
|
||||
private IOPath _javaVersionDir;
|
||||
private SHA1 _hasher;
|
||||
private JavaDistributiveManifest? _distributiveManifest;
|
||||
private List<(IOPath path, JavaDistributiveElementProps props)> _filesToDownload = new();
|
||||
|
||||
@ -21,7 +18,6 @@ public class JavaDownloadTaskFactory : INetworkTaskFactory
|
||||
{
|
||||
_descriptor = descriptor;
|
||||
_javaVersionDir = PathHelper.GetJavaRuntimeDir(_descriptor.javaVersion.component);
|
||||
_hasher = SHA1.Create();
|
||||
}
|
||||
|
||||
public async Task<NetworkTask?> CreateAsync(bool checkHashes)
|
||||
@ -32,11 +28,14 @@ public class JavaDownloadTaskFactory : INetworkTaskFactory
|
||||
|
||||
NetworkTask? networkTask = null;
|
||||
if (!CheckFiles(checkHashes))
|
||||
networkTask = new(
|
||||
$"java runtime '{_descriptor.javaVersion.component}'",
|
||||
GetTotalSize(),
|
||||
Download
|
||||
);
|
||||
{
|
||||
networkTask = new NetworkTask(
|
||||
$"java runtime '{_descriptor.javaVersion.component}'",
|
||||
GetTotalSize(),
|
||||
Download
|
||||
);
|
||||
}
|
||||
|
||||
return networkTask;
|
||||
}
|
||||
|
||||
@ -52,18 +51,10 @@ public class JavaDownloadTaskFactory : INetworkTaskFactory
|
||||
{
|
||||
var artifact = pair.Value.downloads;
|
||||
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));
|
||||
}
|
||||
else if(checkHashes)
|
||||
{
|
||||
using var fs = File.OpenRead(file_path);
|
||||
if (_hasher.ComputeHash(fs).HashToString() != artifact.raw.sha1)
|
||||
{
|
||||
_filesToDownload.Add((file_path, pair.Value));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1,6 +1,4 @@
|
||||
using System.IO.Compression;
|
||||
using System.Security.Cryptography;
|
||||
using DTLib.Extensions;
|
||||
using Mlaumcherb.Client.Avalonia.зримое;
|
||||
using Mlaumcherb.Client.Avalonia.классы;
|
||||
using Mlaumcherb.Client.Avalonia.холопы;
|
||||
@ -12,7 +10,6 @@ public class LibrariesDownloadTaskFactory : INetworkTaskFactory
|
||||
{
|
||||
private GameVersionDescriptor _descriptor;
|
||||
private Libraries _libraries;
|
||||
private SHA1 _hasher;
|
||||
private List<Libraries.JarLib> _libsToDownload = new();
|
||||
private IOPath _nativesDir;
|
||||
|
||||
@ -20,7 +17,6 @@ public class LibrariesDownloadTaskFactory : INetworkTaskFactory
|
||||
{
|
||||
_descriptor = descriptor;
|
||||
_libraries = libraries;
|
||||
_hasher = SHA1.Create();
|
||||
_nativesDir = PathHelper.GetNativeLibrariesDir(descriptor.id);
|
||||
}
|
||||
|
||||
@ -28,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,20 +42,20 @@ public class LibrariesDownloadTaskFactory : INetworkTaskFactory
|
||||
|
||||
foreach (var l in _libraries.Libs)
|
||||
{
|
||||
if (!File.Exists(l.jarFilePath))
|
||||
if (l is Libraries.NativeLib native)
|
||||
{
|
||||
_libsToDownload.Add(l);
|
||||
}
|
||||
else if (!nativeDirExists && l is Libraries.NativeLib)
|
||||
{
|
||||
_libsToDownload.Add(l);
|
||||
}
|
||||
else if (checkHashes)
|
||||
{
|
||||
using var fs = File.OpenRead(l.jarFilePath);
|
||||
string hash = _hasher.ComputeHash(fs).HashToString();
|
||||
if(hash != l.artifact.sha1)
|
||||
//TODO: replace with actual native libraries check
|
||||
if(!nativeDirExists || checkHashes)
|
||||
{
|
||||
_libsToDownload.Add(l);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!HashHelper.CheckFileSHA1(l.jarFilePath, l.artifact?.sha1, checkHashes))
|
||||
{
|
||||
_libsToDownload.Add(l);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -67,7 +66,7 @@ public class LibrariesDownloadTaskFactory : INetworkTaskFactory
|
||||
{
|
||||
long total = 0;
|
||||
foreach (var l in _libsToDownload)
|
||||
total += l.artifact.size;
|
||||
total += l.artifact?.size ?? 0;
|
||||
return total;
|
||||
}
|
||||
|
||||
@ -83,23 +82,21 @@ public class LibrariesDownloadTaskFactory : INetworkTaskFactory
|
||||
await Parallel.ForEachAsync(_libsToDownload, opt, async (l, _ct) =>
|
||||
{
|
||||
LauncherApp.Logger.LogDebug(nameof(NetworkHelper), $"downloading library '{l.name}' to '{l.jarFilePath}'");
|
||||
if(string.IsNullOrEmpty(l.artifact.url))
|
||||
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);
|
||||
if (l is Libraries.NativeLib n)
|
||||
{
|
||||
var zipf = File.OpenRead(n.jarFilePath);
|
||||
ZipFile.ExtractToDirectory(zipf, _nativesDir.ToString(), true);
|
||||
if (n.extractionOptions?.exclude != null)
|
||||
await using var zipf = File.OpenRead(n.jarFilePath);
|
||||
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);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@ -0,0 +1,25 @@
|
||||
using Mlaumcherb.Client.Avalonia.классы;
|
||||
|
||||
namespace Mlaumcherb.Client.Avalonia.сеть.TaskFactories;
|
||||
|
||||
public class ModpackDownloadTaskFactory : INetworkTaskFactory
|
||||
{
|
||||
INetworkTaskFactory _implementationVersion;
|
||||
|
||||
public ModpackDownloadTaskFactory(GameVersionDescriptor descriptor)
|
||||
{
|
||||
if(descriptor.modpack is null)
|
||||
throw new ArgumentNullException(nameof(descriptor.modpack));
|
||||
|
||||
_implementationVersion = descriptor.modpack.format_version switch
|
||||
{
|
||||
2 => new MyModpackV2DownloadTaskFactory(descriptor),
|
||||
_ => throw new Exception($"Unknown Modpack format_version: {descriptor.modpack.format_version}")
|
||||
};
|
||||
}
|
||||
|
||||
public Task<NetworkTask?> CreateAsync(bool checkHashes)
|
||||
{
|
||||
return _implementationVersion.CreateAsync(checkHashes);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,71 @@
|
||||
using System.Linq;
|
||||
using Mlaumcherb.Client.Avalonia.зримое;
|
||||
using Mlaumcherb.Client.Avalonia.классы;
|
||||
using Mlaumcherb.Client.Avalonia.холопы;
|
||||
|
||||
namespace Mlaumcherb.Client.Avalonia.сеть.TaskFactories;
|
||||
|
||||
public class MyModpackV2DownloadTaskFactory : INetworkTaskFactory
|
||||
{
|
||||
private readonly GameVersionDescriptor _descriptor;
|
||||
private IOPath _modpackDescriptorPath;
|
||||
private IOPath _versionDir;
|
||||
private MyModpackV2? _modpack;
|
||||
// relative, absolute
|
||||
private List<MyModpackV2.FileCheckResult> _filesToDownload = new();
|
||||
|
||||
public MyModpackV2DownloadTaskFactory(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<MyModpackV2>(
|
||||
_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;
|
||||
_filesToDownload = _modpack.CheckFiles(_versionDir, checkHashes, didDownloadModpackDescriptor);
|
||||
if(_filesToDownload.Count > 0)
|
||||
{
|
||||
networkTask = new NetworkTask(
|
||||
$"modpack '{_modpack.name}'",
|
||||
_filesToDownload.Sum(f => f.props.artifact.size),
|
||||
Download
|
||||
);
|
||||
}
|
||||
|
||||
return networkTask;
|
||||
}
|
||||
|
||||
private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
|
||||
{
|
||||
LauncherApp.Logger.LogInfo(nameof(NetworkHelper), $"started downloading modpack '{_modpack!.name}'");
|
||||
|
||||
ParallelOptions opt = new()
|
||||
{
|
||||
MaxDegreeOfParallelism = LauncherApp.Config.max_parallel_downloads,
|
||||
CancellationToken = ct
|
||||
};
|
||||
await Parallel.ForEachAsync(_filesToDownload, opt, async (f, _ct) =>
|
||||
{
|
||||
LauncherApp.Logger.LogDebug(nameof(NetworkHelper), $"downloading file '{f.relativePath}'");
|
||||
if(string.IsNullOrEmpty(f.props.artifact.url))
|
||||
throw new Exception($"file '{f.relativePath}' doesn't have a url to download");
|
||||
await NetworkHelper.DownloadFile(f.props.artifact.url, f.absolutePath, _ct, pr.AddBytesCount);
|
||||
});
|
||||
|
||||
LauncherApp.Logger.LogInfo(nameof(NetworkHelper), $"finished downloading modpack '{_modpack.name}'");
|
||||
}
|
||||
}
|
||||
@ -1,51 +1,39 @@
|
||||
using System.Security.Cryptography;
|
||||
using DTLib.Extensions;
|
||||
using Mlaumcherb.Client.Avalonia.зримое;
|
||||
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 VersionFileDownloadTaskFactory : INetworkTaskFactory
|
||||
public class VersionJarDownloadTaskFactory : INetworkTaskFactory
|
||||
{
|
||||
private GameVersionDescriptor _descriptor;
|
||||
private IOPath _filePath;
|
||||
private SHA1 _hasher;
|
||||
|
||||
public VersionFileDownloadTaskFactory(GameVersionDescriptor descriptor)
|
||||
public VersionJarDownloadTaskFactory(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
|
||||
);
|
||||
$"game version jar '{_descriptor.id}'",
|
||||
GetTotalSize(),
|
||||
Download
|
||||
);
|
||||
}
|
||||
|
||||
return Task.FromResult(networkTask);
|
||||
}
|
||||
|
||||
private bool CheckFiles(bool checkHashes)
|
||||
{
|
||||
if (!File.Exists(_filePath))
|
||||
return false;
|
||||
|
||||
if (!checkHashes)
|
||||
return true;
|
||||
|
||||
if (_descriptor.downloads is null)
|
||||
return true;
|
||||
|
||||
using var fs = File.OpenRead(_filePath);
|
||||
string hash = _hasher.ComputeHash(fs).HashToString();
|
||||
return hash == _descriptor.downloads.client.sha1;
|
||||
return HashHelper.CheckFileSHA1(_filePath, _descriptor.downloads?.client.sha1, checkHashes);
|
||||
}
|
||||
|
||||
private long GetTotalSize()
|
||||
@ -58,10 +46,10 @@ public class VersionFileDownloadTaskFactory : INetworkTaskFactory
|
||||
private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
|
||||
{
|
||||
if (_descriptor.downloads is null)
|
||||
throw new Exception($"can't download version file '{_descriptor.id}' because it has no download url");
|
||||
throw new Exception($"can't download game version jar '{_descriptor.id}' because it has no download url");
|
||||
|
||||
LauncherApp.Logger.LogInfo(nameof(NetworkHelper), $"started downloading version file '{_descriptor.id}'");
|
||||
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 version file '{_descriptor.id}'");
|
||||
LauncherApp.Logger.LogInfo(nameof(NetworkHelper), $"finished downloading game version jar '{_descriptor.id}'");
|
||||
}
|
||||
}
|
||||
38
Mlaumcherb.Client.Avalonia/сеть/Update/Gitea.cs
Normal file
38
Mlaumcherb.Client.Avalonia/сеть/Update/Gitea.cs
Normal file
@ -0,0 +1,38 @@
|
||||
using System.Linq;
|
||||
|
||||
namespace Mlaumcherb.Client.Avalonia.сеть.Update;
|
||||
|
||||
public class Release
|
||||
{
|
||||
[JsonRequired] public int id { get; set; }
|
||||
[JsonRequired] public string tag_name { get; set; } = "";
|
||||
[JsonRequired] public DateTime created_at { get; set; }
|
||||
// ReSharper disable once CollectionNeverUpdated.Global
|
||||
public List<Asset> assets { get; set; } = new();
|
||||
|
||||
public class Asset
|
||||
{
|
||||
[JsonRequired] public int id { get; set; }
|
||||
[JsonRequired] public string name { get; set; } = "";
|
||||
[JsonRequired] public int size { get; set; }
|
||||
[JsonRequired] public DateTime created_at { get; set; }
|
||||
[JsonRequired] public string browser_download_url { get; set; } = "";
|
||||
|
||||
public async Task Download(IOPath localPath)
|
||||
{
|
||||
await NetworkHelper.DownloadFile(browser_download_url, localPath);
|
||||
}
|
||||
}
|
||||
|
||||
public Asset? FindAssetByName(string name) =>
|
||||
assets.FirstOrDefault(a => a.name == name);
|
||||
}
|
||||
|
||||
public class GiteaClient(string ServerUrl)
|
||||
{
|
||||
public async Task<Release> GetLatestRelease(string user, string repo)
|
||||
{
|
||||
string url = $"{ServerUrl}/api/v1/repos/{user}/{repo}/releases/latest";
|
||||
return await NetworkHelper.DownloadStringAndDeserialize<Release>(url);
|
||||
}
|
||||
}
|
||||
76
Mlaumcherb.Client.Avalonia/сеть/Update/UpdateHelper.cs
Normal file
76
Mlaumcherb.Client.Avalonia/сеть/Update/UpdateHelper.cs
Normal file
@ -0,0 +1,76 @@
|
||||
using System.Diagnostics;
|
||||
using System.Reflection;
|
||||
|
||||
namespace Mlaumcherb.Client.Avalonia.сеть.Update;
|
||||
|
||||
public class UpdateHelper
|
||||
{
|
||||
private readonly string _executableName = "млаумчерб.exe";
|
||||
private readonly IOPath executablePathActual;
|
||||
private readonly IOPath executablePathOld;
|
||||
private readonly IOPath executablePathNew;
|
||||
|
||||
private readonly GiteaConfig _giteaConfig;
|
||||
|
||||
public class GiteaConfig
|
||||
{
|
||||
[JsonRequired] public required string serverUrl { get; set; }
|
||||
[JsonRequired] public required string user { get; set; }
|
||||
[JsonRequired] public required string repo { get; set; }
|
||||
|
||||
public string GetRepoUrl() => $"{serverUrl}/{user}/{repo}";
|
||||
}
|
||||
|
||||
|
||||
public UpdateHelper(GiteaConfig giteaConfig)
|
||||
{
|
||||
_giteaConfig = giteaConfig;
|
||||
executablePathActual = _executableName;
|
||||
executablePathOld = _executableName + ".old";
|
||||
executablePathNew = _executableName + ".new";
|
||||
Gitea = new GiteaClient(giteaConfig.serverUrl);
|
||||
}
|
||||
|
||||
public GiteaClient Gitea { get; }
|
||||
|
||||
public void DeleteBackupFiles()
|
||||
{
|
||||
if(File.Exists(executablePathOld))
|
||||
File.Delete(executablePathOld);
|
||||
}
|
||||
|
||||
public async Task<bool> IsUpdateAvailable()
|
||||
{
|
||||
var latest = await Gitea.GetLatestRelease(_giteaConfig.user, _giteaConfig.repo);
|
||||
if (!Version.TryParse(latest.tag_name, out var latestVersion))
|
||||
throw new Exception($"Can't parse version of latest release: {latest.tag_name}");
|
||||
|
||||
Version? currentVersion = Assembly.GetExecutingAssembly().GetName().Version;
|
||||
if(currentVersion is null)
|
||||
throw new Exception($"Can't get current version from {Assembly.GetExecutingAssembly().GetName()}");
|
||||
|
||||
return currentVersion < latestVersion;
|
||||
}
|
||||
|
||||
public async Task UpdateSelf()
|
||||
{
|
||||
if(File.Exists(executablePathNew))
|
||||
File.Delete(executablePathNew);
|
||||
|
||||
var latest = await Gitea.GetLatestRelease(_giteaConfig.user, _giteaConfig.repo);
|
||||
var asset = latest.FindAssetByName(_executableName);
|
||||
if(asset == null)
|
||||
throw new Exception($"Can't find updated executable on gitea: {_executableName}");
|
||||
await asset.Download(executablePathNew);
|
||||
|
||||
File.Move(executablePathActual, executablePathOld, true);
|
||||
File.Move(executablePathNew, executablePathActual, true);
|
||||
}
|
||||
|
||||
public void RestartSelf()
|
||||
{
|
||||
Process.Start(executablePathActual.ToString());
|
||||
Thread.Sleep(500);
|
||||
Environment.Exit(0);
|
||||
}
|
||||
}
|
||||
32
Mlaumcherb.Client.Avalonia/холопы/HashHelper.cs
Normal file
32
Mlaumcherb.Client.Avalonia/холопы/HashHelper.cs
Normal 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 && sha1 is not null)
|
||||
return HashFileSHA1(f) == sha1;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@ -11,7 +11,7 @@ public static class PathHelper
|
||||
Path.Concat(GetRootFullPath(), "assets");
|
||||
|
||||
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) =>
|
||||
Path.Concat(GetVersionDir(id), id + ".json");
|
||||
@ -40,18 +40,29 @@ public static class PathHelper
|
||||
|
||||
public static IOPath GetJavaBinDir(string id) =>
|
||||
Path.Concat(GetJavaRuntimeDir(id), "bin");
|
||||
public static IOPath GetJavaExecutablePath(string id, bool debug)
|
||||
public static IOPath GetJavaExecutablePath(string id, bool redirectOutput)
|
||||
{
|
||||
string executable_name = "java";
|
||||
if (debug)
|
||||
executable_name += "w";
|
||||
if (!redirectOutput)
|
||||
executable_name = "javaw";
|
||||
if(OperatingSystem.IsWindows())
|
||||
executable_name += ".exe";
|
||||
return Path.Concat(GetJavaBinDir(id), executable_name);
|
||||
var path = Path.Concat(GetJavaBinDir(id), executable_name);
|
||||
if(!redirectOutput && !File.Exists(path))
|
||||
return GetJavaExecutablePath(id, true);
|
||||
return path;
|
||||
}
|
||||
|
||||
public static string GetLog4jConfigFileName() => "log4j.xml";
|
||||
|
||||
public static IOPath GetLog4jConfigFilePath() =>
|
||||
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");
|
||||
}
|
||||
|
||||
12
Mlaumcherb.Client.Avalonia/холопы/ReverseComparer.cs
Normal file
12
Mlaumcherb.Client.Avalonia/холопы/ReverseComparer.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
14
README.md
Normal file
14
README.md
Normal file
@ -0,0 +1,14 @@
|
||||
# Mlaumcherb - a minecraft laumcherb
|
||||
|
||||
<img src="./images/cheems.png" alt="silly-dog-picture" style="width:200px;"/>
|
||||
|
||||
## Features
|
||||
- Downloads minecraft from mojang server or any other
|
||||
- Downloads java or uses whatever you specified in config
|
||||
- Downloads modpacks of my custom format
|
||||
- Automatic launcher updates from git releases
|
||||
|
||||
## How to build
|
||||
```sh
|
||||
./build.sh selfcontained
|
||||
```
|
||||
@ -29,19 +29,21 @@ case "$mode" in
|
||||
args="$args_selfcontained"
|
||||
;;
|
||||
*)
|
||||
echo "ПОЛЬЗОВАНИЕ: ./собрать.sh [способ]"
|
||||
echo "ПОЛЬЗОВАНИЕ: ./build.sh [способ]"
|
||||
echo " СПОСОБЫ:"
|
||||
echo " бинарное - компилирует промежуточный (управляемый) код в машинный вместе с рантаймом"
|
||||
echo " небинарное - приделывает промежуточный (управляемый) код к рантайму"
|
||||
echo " Оба способа собирают программу в один файл, который не является 80-мегабайтовым умственно отсталым кубом. Он 20-мегабайтовый >w<"
|
||||
echo " aot, native, бинарное - компилирует промежуточный (управляемый) код в машинный вместе с рантаймом"
|
||||
echo " self-contained, selfcontained, небинарное - приделывает промежуточный (управляемый) код к рантайму"
|
||||
echo " Оба способа собирают программу в один файл, который не является 80-мегабайтовым умственно отсталым кубом.\
|
||||
Он 20-мегабайтовый >w<"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
rm -rf "$outdir"
|
||||
# when internet breaks again add --source /mnt/c/Users/User/.nuget/packages/
|
||||
command="dotnet publish -c Release -o $outdir $args"
|
||||
echo "$command"
|
||||
$command
|
||||
|
||||
find "$outdir" -name '*.pdb' -delete -printf "deleted '%p'\n"
|
||||
ls -shk "$outdir" | sort -h
|
||||
tree -sh "$outdir"
|
||||
BIN
images/cheems.png
Normal file
BIN
images/cheems.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 19 KiB |
@ -5,6 +5,8 @@ EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SolutionFolder", "SolutionFolder", "{A3217C18-CC0D-4CE8-9C48-1BDEC1E1B333}"
|
||||
ProjectSection(SolutionItems) = preProject
|
||||
.gitignore = .gitignore
|
||||
README.md = README.md
|
||||
build.sh = build.sh
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Global
|
||||
|
||||
Loading…
Reference in New Issue
Block a user