its downloading!!!
This commit is contained in:
parent
ae7e5096fc
commit
612976dfe6
1
.gitignore
vendored
1
.gitignore
vendored
@ -17,6 +17,7 @@
|
|||||||
.idea/
|
.idea/
|
||||||
.editorconfig
|
.editorconfig
|
||||||
*.user
|
*.user
|
||||||
|
*.DotSettings
|
||||||
|
|
||||||
#backups
|
#backups
|
||||||
.old*/
|
.old*/
|
||||||
@ -1,7 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<configuration>
|
|
||||||
<packageSources>
|
|
||||||
<!-- avalonia nightly feed -->
|
|
||||||
<add key="avalonia-nightly" value="https://nuget-feed-nightly.avaloniaui.net/v3/index.json" protocolVersion="3" />
|
|
||||||
</packageSources>
|
|
||||||
</configuration>
|
|
||||||
26
Млаумчерб.Клиент/LZMACompressor.cs
Normal file
26
Млаумчерб.Клиент/LZMACompressor.cs
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
namespace Млаумчерб.Клиент;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// https://gist.github.com/ststeiger/cb9750664952f775a341
|
||||||
|
/// </summary>
|
||||||
|
public static class LZMACompressor
|
||||||
|
{
|
||||||
|
public static void Decompress(Stream inputStream, Stream outputStream)
|
||||||
|
{
|
||||||
|
var decoder = new SevenZip.Compression.LZMA.Decoder();
|
||||||
|
var properties = new byte[5];
|
||||||
|
// Read decoder properties
|
||||||
|
if (inputStream.Read(properties, 0, 5) != 5)
|
||||||
|
throw new Exception("lzma stream is too short");
|
||||||
|
decoder.SetDecoderProperties(properties);
|
||||||
|
|
||||||
|
// Read decompressed data size
|
||||||
|
var fileLengthBytes = new byte[8];
|
||||||
|
if(inputStream.Read(fileLengthBytes, 0, 8) != 8)
|
||||||
|
throw new Exception("lzma stream is too short");
|
||||||
|
long fileLength = BitConverter.ToInt64(fileLengthBytes, 0);
|
||||||
|
|
||||||
|
// Decode
|
||||||
|
decoder.Code(inputStream, outputStream, -1, fileLength, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -6,6 +6,7 @@ global using System.Text;
|
|||||||
global using System.Threading;
|
global using System.Threading;
|
||||||
global using System.Threading.Tasks;
|
global using System.Threading.Tasks;
|
||||||
global using Newtonsoft.Json;
|
global using Newtonsoft.Json;
|
||||||
|
global using DTLib;
|
||||||
global using DTLib.Logging;
|
global using DTLib.Logging;
|
||||||
global using DTLib.Filesystem;
|
global using DTLib.Filesystem;
|
||||||
global using File = DTLib.Filesystem.File;
|
global using File = DTLib.Filesystem.File;
|
||||||
@ -13,7 +14,7 @@ global using Directory = DTLib.Filesystem.Directory;
|
|||||||
global using Path = DTLib.Filesystem.Path;
|
global using Path = DTLib.Filesystem.Path;
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using Avalonia;
|
using Avalonia;
|
||||||
using Млаумчерб.Клиент.видимое;
|
using Млаумчерб.Клиент.зримое;
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент;
|
namespace Млаумчерб.Клиент;
|
||||||
|
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
using CliWrap;
|
using System.Linq;
|
||||||
|
using CliWrap;
|
||||||
using DTLib.Extensions;
|
using DTLib.Extensions;
|
||||||
using Млаумчерб.Клиент.видимое;
|
using Млаумчерб.Клиент.зримое;
|
||||||
using Млаумчерб.Клиент.классы;
|
using Млаумчерб.Клиент.классы;
|
||||||
using Млаумчерб.Клиент.сеть;
|
using Млаумчерб.Клиент.сеть;
|
||||||
using Млаумчерб.Клиент.сеть.NetworkTaskFactories;
|
using Млаумчерб.Клиент.сеть.NetworkTaskFactories;
|
||||||
@ -25,15 +26,24 @@ public class GameVersion
|
|||||||
|
|
||||||
public static async Task<List<GameVersionProps>> GetAllVersionsAsync()
|
public static async Task<List<GameVersionProps>> GetAllVersionsAsync()
|
||||||
{
|
{
|
||||||
var propsList = new List<GameVersionProps>();
|
var propsSet = new HashSet<GameVersionProps>();
|
||||||
foreach (IOPath f in Directory.GetFiles(GetVersionDescriptorDir()))
|
|
||||||
|
// local descriptors
|
||||||
|
foreach (IOPath f in Directory.GetFiles(GetVersionDescriptorsDir()))
|
||||||
{
|
{
|
||||||
string name = GetVersionDescriptorName(f);
|
string name = GetVersionDescriptorName(f);
|
||||||
propsList.Add(new GameVersionProps(name, null, f));
|
propsSet.Add(new GameVersionProps(name, null, f));
|
||||||
}
|
}
|
||||||
|
|
||||||
var remoteVersions = await Сеть.GetDownloadableVersions();
|
// remote non-duplicating versions
|
||||||
propsList.AddRange(remoteVersions);
|
foreach (var removeVersion in await Сеть.GetDownloadableVersions())
|
||||||
|
{
|
||||||
|
propsSet.Add(removeVersion);
|
||||||
|
}
|
||||||
|
|
||||||
|
// reverse sort
|
||||||
|
var propsList = propsSet.ToList();
|
||||||
|
propsList.Sort((a, b) => b.CompareTo(a));
|
||||||
return propsList;
|
return propsList;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -44,7 +54,7 @@ public class GameVersion
|
|||||||
if (props.RemoteDescriptorUrl is null)
|
if (props.RemoteDescriptorUrl is null)
|
||||||
throw new NullReferenceException("can't download game version descriptor '"
|
throw new NullReferenceException("can't download game version descriptor '"
|
||||||
+ props.Name + "', because RemoteDescriptorUrl is null");
|
+ props.Name + "', because RemoteDescriptorUrl is null");
|
||||||
await Сеть.DownloadFileHTTP(props.RemoteDescriptorUrl, props.LocalDescriptorPath);
|
await Сеть.DownloadFile(props.RemoteDescriptorUrl, props.LocalDescriptorPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
return new GameVersion(props);
|
return new GameVersion(props);
|
||||||
@ -63,44 +73,44 @@ public class GameVersion
|
|||||||
JavaExecutableFilePath = GetJavaExecutablePath(descriptor.javaVersion.component);
|
JavaExecutableFilePath = GetJavaExecutablePath(descriptor.javaVersion.component);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<List<NetworkTask>> CreateUpdateTasksAsync(bool checkHashes)
|
public async Task UpdateFiles(bool checkHashes, Action<NetworkTask> networkTaskCreatedCallback)
|
||||||
{
|
{
|
||||||
|
Приложение.Логгер.LogInfo(nameof(GameVersion), $"started updating version {Name}");
|
||||||
|
|
||||||
List<INetworkTaskFactory> taskFactories =
|
List<INetworkTaskFactory> taskFactories =
|
||||||
[
|
[
|
||||||
new AssetsDownloadTaskFactory(descriptor),
|
new AssetsDownloadTaskFactory(descriptor),
|
||||||
new LibrariesDownloadTaskFactory(descriptor, libraries),
|
new LibrariesDownloadTaskFactory(descriptor, libraries),
|
||||||
new VersionFileDownloadTaskFactory(descriptor),
|
new VersionFileDownloadTaskFactory(descriptor),
|
||||||
];
|
];
|
||||||
/*if(Приложение.Настройки.скачать_жабу)
|
if(Приложение.Настройки.скачивать_жабу)
|
||||||
{
|
{
|
||||||
taskFactories.Add(new JavaDownloadTaskFactory(descriptor));
|
taskFactories.Add(new JavaDownloadTaskFactory(descriptor));
|
||||||
}*/
|
}
|
||||||
|
//TODO: modpack
|
||||||
/*if (modpack != null)
|
/*if (modpack != null)
|
||||||
{
|
{
|
||||||
taskFactories.Add(new ModpackDownloadTaskFactory(modpack));
|
taskFactories.Add(new ModpackDownloadTaskFactory(modpack));
|
||||||
}*/
|
}*/
|
||||||
|
|
||||||
List<NetworkTask> tasks = new();
|
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(checkHashes);
|
||||||
if (nt != null)
|
if (nt != null)
|
||||||
tasks.Add(nt);
|
{
|
||||||
|
networkTasks.Add(nt);
|
||||||
|
networkTaskCreatedCallback.Invoke(nt);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (tasks.Count == 0)
|
foreach (var nt in networkTasks)
|
||||||
{
|
{
|
||||||
_props.IsDownloaded = true;
|
await nt.StartAsync();
|
||||||
}
|
}
|
||||||
else
|
|
||||||
{
|
|
||||||
tasks[^1].OnStop += status =>
|
|
||||||
{
|
|
||||||
if (status == NetworkTask.Status.Completed)
|
|
||||||
_props.IsDownloaded = true;
|
_props.IsDownloaded = true;
|
||||||
};
|
Приложение.Логгер.LogInfo(nameof(GameVersion), $"finished updating version {Name}");
|
||||||
}
|
|
||||||
return tasks;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task Launch()
|
public async Task Launch()
|
||||||
|
|||||||
@ -24,7 +24,9 @@ public class LauncherLogger : ILogger
|
|||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
public delegate void LogHandler(string context, LogSeverity severity, object message, ILogFormat format);
|
public record LogMessage(string context, LogSeverity severity, object message, ILogFormat format);
|
||||||
|
|
||||||
|
public delegate void LogHandler(LogMessage msg);
|
||||||
public event LogHandler? OnLogMessage;
|
public event LogHandler? OnLogMessage;
|
||||||
|
|
||||||
public void Log(string context, LogSeverity severity, object message, ILogFormat format)
|
public void Log(string context, LogSeverity severity, object message, ILogFormat format)
|
||||||
@ -39,7 +41,7 @@ public class LauncherLogger : ILogger
|
|||||||
_ => throw new ArgumentOutOfRangeException(nameof(severity), severity, null)
|
_ => throw new ArgumentOutOfRangeException(nameof(severity), severity, null)
|
||||||
};
|
};
|
||||||
if(isEnabled)
|
if(isEnabled)
|
||||||
OnLogMessage?.Invoke(context, severity, message, format);
|
OnLogMessage?.Invoke(new(context, severity, message, format));
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Dispose()
|
public void Dispose()
|
||||||
|
|||||||
@ -16,16 +16,16 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Avalonia" Version="11.*" />
|
<PackageReference Include="Avalonia" Version="11.2.0" />
|
||||||
<PackageReference Include="Avalonia.Desktop" Version="11.*" />
|
<PackageReference Include="Avalonia.Desktop" Version="11.2.0" />
|
||||||
<PackageReference Include="Avalonia.Themes.Simple" Version="11.*" />
|
<PackageReference Include="Avalonia.Themes.Simple" Version="11.2.0" />
|
||||||
<PackageReference Condition="'$(Configuration)' == 'Debug'" Include="Avalonia.Diagnostics" Version="11.*" />
|
<PackageReference Condition="'$(Configuration)' == 'Debug'" Include="Avalonia.Diagnostics" Version="11.2.0" />
|
||||||
<PackageReference Include="Avalonia.Labs.Gif" Version="11.2.999-cibuild-00051673"/>
|
<PackageReference Include="Avalonia.Labs.Gif" Version="11.2.0" />
|
||||||
<PackageReference Include="CliWrap" Version="3.6.*" />
|
<PackageReference Include="CliWrap" Version="3.6.7" />
|
||||||
<PackageReference Include="DTLib" Version="1.4.3" />
|
<PackageReference Include="DTLib" Version="1.6.1" />
|
||||||
<PackageReference Include="MessageBox.Avalonia" Version="3.1.*" />
|
<PackageReference Include="LZMA-SDK" Version="22.1.1" />
|
||||||
|
<PackageReference Include="MessageBox.Avalonia" Version="3.2.0" />
|
||||||
<PackageReference Include="Newtonsoft.Json" Version="13.*" />
|
<PackageReference Include="Newtonsoft.Json" Version="13.*" />
|
||||||
<PackageReference Include="EasyCompressor.LZMA" Version="2.0.2" />
|
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
@ -33,15 +33,15 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Compile Update="видимое\VersionItemView.axaml.cs">
|
<Compile Update="зримое\VersionItemView.axaml.cs">
|
||||||
<DependentUpon>VersionItemView.axaml</DependentUpon>
|
<DependentUpon>VersionItemView.axaml</DependentUpon>
|
||||||
<SubType>Code</SubType>
|
<SubType>Code</SubType>
|
||||||
</Compile>
|
</Compile>
|
||||||
<Compile Update="видимое\Окне.axaml.cs">
|
<Compile Update="зримое\Окне.axaml.cs">
|
||||||
<DependentUpon>Окне.axaml</DependentUpon>
|
<DependentUpon>Окне.axaml</DependentUpon>
|
||||||
<SubType>Code</SubType>
|
<SubType>Code</SubType>
|
||||||
</Compile>
|
</Compile>
|
||||||
<Compile Update="видимое\Приложение.axaml.cs">
|
<Compile Update="зримое\Приложение.axaml.cs">
|
||||||
<DependentUpon>Приложение.axaml</DependentUpon>
|
<DependentUpon>Приложение.axaml</DependentUpon>
|
||||||
<SubType>Code</SubType>
|
<SubType>Code</SubType>
|
||||||
</Compile>
|
</Compile>
|
||||||
|
|||||||
@ -1,5 +1,4 @@
|
|||||||
using DTLib.Extensions;
|
using Млаумчерб.Клиент.зримое;
|
||||||
using Млаумчерб.Клиент.видимое;
|
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент;
|
namespace Млаумчерб.Клиент;
|
||||||
|
|
||||||
@ -7,12 +6,11 @@ public record Настройки
|
|||||||
{
|
{
|
||||||
public string имя_пользователя { get; set; } = "";
|
public string имя_пользователя { get; set; } = "";
|
||||||
public int выделенная_память_мб { get; set; } = 4096;
|
public int выделенная_память_мб { get; set; } = 4096;
|
||||||
public bool открывать_на_весь_экран { get; set; }
|
|
||||||
public string путь_к_кубачу { get; set; } = ".";
|
public string путь_к_кубачу { get; set; } = ".";
|
||||||
public bool скачать_жабу { get; set; } = true;
|
public bool запускать_полноэкранное { get; set; } = false;
|
||||||
|
public bool скачивать_жабу { get; set; } = true;
|
||||||
public string? последняя_запущенная_версия { get; set; }
|
public string? последняя_запущенная_версия { get; set; }
|
||||||
|
public int максимум_параллельных_загрузок { get; set; } = 16;
|
||||||
[JsonIgnore] private Stream? fileWriteStream;
|
|
||||||
|
|
||||||
public static Настройки ЗагрузитьИзФайла(string имя_файла = "млаумчерб.настройки")
|
public static Настройки ЗагрузитьИзФайла(string имя_файла = "млаумчерб.настройки")
|
||||||
{
|
{
|
||||||
@ -43,10 +41,8 @@ public record Настройки
|
|||||||
{
|
{
|
||||||
//TODO: file backup and restore
|
//TODO: file backup and restore
|
||||||
Приложение.Логгер.LogDebug(nameof(Настройки), $"настройки сохраняются в файл '{имя_файла}'");
|
Приложение.Логгер.LogDebug(nameof(Настройки), $"настройки сохраняются в файл '{имя_файла}'");
|
||||||
fileWriteStream ??= File.OpenWrite(имя_файла);
|
|
||||||
var текст = JsonConvert.SerializeObject(this, Formatting.Indented);
|
var текст = JsonConvert.SerializeObject(this, Formatting.Indented);
|
||||||
fileWriteStream.Seek(0, SeekOrigin.Begin);
|
File.WriteAllText(имя_файла, текст);
|
||||||
fileWriteStream.FluentWriteString(текст).Flush();
|
|
||||||
Приложение.Логгер.LogDebug(nameof(Настройки), $"настройки сохранены: {текст}");
|
Приложение.Логгер.LogDebug(nameof(Настройки), $"настройки сохранены: {текст}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -4,7 +4,7 @@ using MsBox.Avalonia;
|
|||||||
using MsBox.Avalonia.Dto;
|
using MsBox.Avalonia.Dto;
|
||||||
using MsBox.Avalonia.Enums;
|
using MsBox.Avalonia.Enums;
|
||||||
using MsBox.Avalonia.Models;
|
using MsBox.Avalonia.Models;
|
||||||
using Млаумчерб.Клиент.видимое;
|
using Млаумчерб.Клиент.зримое;
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент;
|
namespace Млаумчерб.Клиент;
|
||||||
|
|
||||||
|
|||||||
@ -1,20 +0,0 @@
|
|||||||
<UserControl xmlns="https://github.com/avaloniaui"
|
|
||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
|
||||||
x:Class="Млаумчерб.Клиент.видимое.DownloadTaskView"
|
|
||||||
Padding="4" MaxHeight="60" MinWidth="200"
|
|
||||||
VerticalAlignment="Top"
|
|
||||||
HorizontalAlignment="Stretch"
|
|
||||||
BorderThickness="1" BorderBrush="#999999">
|
|
||||||
<Grid RowDefinitions="30 30" ColumnDefinitions="* 30">
|
|
||||||
<TextBlock Grid.Row="0" Grid.Column="0" Name="NameText"/>
|
|
||||||
<Button Grid.Row="0" Grid.Column="1"
|
|
||||||
Classes="button_no_border"
|
|
||||||
Background="Transparent"
|
|
||||||
Foreground="#FF4040"
|
|
||||||
FontSize="12"
|
|
||||||
Click="RemoveFromList">
|
|
||||||
[X]
|
|
||||||
</Button>
|
|
||||||
<TextBlock Grid.Row="1" Grid.Column="0" Name="DownloadedProgressText"/>
|
|
||||||
</Grid>
|
|
||||||
</UserControl>
|
|
||||||
@ -1,42 +0,0 @@
|
|||||||
using Avalonia.Controls;
|
|
||||||
using Avalonia.Interactivity;
|
|
||||||
using Avalonia.Threading;
|
|
||||||
using Млаумчерб.Клиент.сеть;
|
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент.видимое;
|
|
||||||
|
|
||||||
public partial class DownloadTaskView : UserControl
|
|
||||||
{
|
|
||||||
private readonly NetworkTask _task;
|
|
||||||
private readonly Action<DownloadTaskView> _removeFromList;
|
|
||||||
|
|
||||||
|
|
||||||
public DownloadTaskView()
|
|
||||||
{
|
|
||||||
throw new NotImplementedException();
|
|
||||||
}
|
|
||||||
|
|
||||||
public DownloadTaskView(NetworkTask task, Action<DownloadTaskView> removeFromList)
|
|
||||||
{
|
|
||||||
_task = task;
|
|
||||||
_removeFromList = removeFromList;
|
|
||||||
InitializeComponent();
|
|
||||||
NameText.Text = task.Name;
|
|
||||||
task.OnProgress += ReportProgress;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
void ReportProgress(DownloadProgress progress)
|
|
||||||
{
|
|
||||||
Dispatcher.UIThread.Invoke(() =>
|
|
||||||
{
|
|
||||||
DownloadedProgressText.Text = progress.ToString();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private void RemoveFromList(object? sender, RoutedEventArgs e)
|
|
||||||
{
|
|
||||||
_task.Cancel();
|
|
||||||
Dispatcher.UIThread.Invoke(() => _removeFromList.Invoke(this));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
26
Млаумчерб.Клиент/зримое/DownloadItemView.axaml
Normal file
26
Млаумчерб.Клиент/зримое/DownloadItemView.axaml
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
<UserControl xmlns="https://github.com/avaloniaui"
|
||||||
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
|
x:Class="Млаумчерб.Клиент.зримое.NetworkTaskView"
|
||||||
|
Padding="4" MinHeight="90" MinWidth="200"
|
||||||
|
VerticalAlignment="Top"
|
||||||
|
HorizontalAlignment="Stretch"
|
||||||
|
BorderThickness="1" BorderBrush="#999999">
|
||||||
|
<Grid RowDefinitions="* * *" ColumnDefinitions="* 30">
|
||||||
|
<TextBlock Name="NameText"
|
||||||
|
Grid.Row="0" Grid.Column="0" />
|
||||||
|
<Button Grid.Row="0" Grid.Column="1"
|
||||||
|
Classes="button_no_border"
|
||||||
|
Background="Transparent"
|
||||||
|
Foreground="#FF4040"
|
||||||
|
FontSize="12"
|
||||||
|
Click="RemoveFromList">
|
||||||
|
[X]
|
||||||
|
</Button>
|
||||||
|
<TextBlock Name="StatusText"
|
||||||
|
Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2"
|
||||||
|
FontSize="15"/>
|
||||||
|
<TextBlock Name="ProgressText"
|
||||||
|
Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2"
|
||||||
|
FontSize="14"/>
|
||||||
|
</Grid>
|
||||||
|
</UserControl>
|
||||||
66
Млаумчерб.Клиент/зримое/DownloadItemView.axaml.cs
Normal file
66
Млаумчерб.Клиент/зримое/DownloadItemView.axaml.cs
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
using Avalonia.Controls;
|
||||||
|
using Avalonia.Interactivity;
|
||||||
|
using Avalonia.Threading;
|
||||||
|
using Млаумчерб.Клиент.сеть;
|
||||||
|
|
||||||
|
namespace Млаумчерб.Клиент.зримое;
|
||||||
|
|
||||||
|
public partial class NetworkTaskView : UserControl
|
||||||
|
{
|
||||||
|
public readonly NetworkTask Task;
|
||||||
|
private readonly Action<NetworkTaskView> _removeFromList;
|
||||||
|
|
||||||
|
|
||||||
|
public NetworkTaskView()
|
||||||
|
{
|
||||||
|
throw new Exception();
|
||||||
|
}
|
||||||
|
|
||||||
|
public NetworkTaskView(NetworkTask task, Action<NetworkTaskView> removeFromList)
|
||||||
|
{
|
||||||
|
Task = task;
|
||||||
|
_removeFromList = removeFromList;
|
||||||
|
InitializeComponent();
|
||||||
|
NameText.Text = task.Name;
|
||||||
|
StatusText.Text = task.DownloadStatus.ToString();
|
||||||
|
task.OnStart += OnTaskOnStart;
|
||||||
|
task.OnProgress += ReportProgress;
|
||||||
|
task.OnStop += OnTaskStop;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnTaskOnStart()
|
||||||
|
{
|
||||||
|
Dispatcher.UIThread.Invoke(() =>
|
||||||
|
{
|
||||||
|
StatusText.Text = Task.DownloadStatus.ToString();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnTaskStop(NetworkTask.Status status)
|
||||||
|
{
|
||||||
|
Dispatcher.UIThread.Invoke(() =>
|
||||||
|
{
|
||||||
|
StatusText.Text = status.ToString();
|
||||||
|
if(!string.IsNullOrEmpty(ProgressText.Text))
|
||||||
|
{
|
||||||
|
int speedIndex = ProgressText.Text.IndexOf('(');
|
||||||
|
if(speedIndex > 0)
|
||||||
|
ProgressText.Text = ProgressText.Text.Remove(speedIndex);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void ReportProgress(DownloadProgress progress)
|
||||||
|
{
|
||||||
|
Dispatcher.UIThread.Invoke(() =>
|
||||||
|
{
|
||||||
|
ProgressText.Text = progress.ToString();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RemoveFromList(object? sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
Task.Cancel();
|
||||||
|
Dispatcher.UIThread.Invoke(() => _removeFromList.Invoke(this));
|
||||||
|
}
|
||||||
|
}
|
||||||
13
Млаумчерб.Клиент/зримое/LogMessageView.axaml
Normal file
13
Млаумчерб.Клиент/зримое/LogMessageView.axaml
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
<UserControl xmlns="https://github.com/avaloniaui"
|
||||||
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
|
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||||
|
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||||
|
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
|
||||||
|
x:Class="Млаумчерб.Клиент.зримое.LogMessageView"
|
||||||
|
FontSize="14">
|
||||||
|
<SelectableTextBlock Name="ContentTextBox"
|
||||||
|
FontSize="{Binding $parent.FontSize}"
|
||||||
|
TextWrapping="Wrap"
|
||||||
|
VerticalAlignment="Top"
|
||||||
|
Background="Transparent"/>
|
||||||
|
</UserControl>
|
||||||
24
Млаумчерб.Клиент/зримое/LogMessageView.axaml.cs
Normal file
24
Млаумчерб.Клиент/зримое/LogMessageView.axaml.cs
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
using Avalonia.Controls;
|
||||||
|
using DTLib;
|
||||||
|
|
||||||
|
namespace Млаумчерб.Клиент.зримое;
|
||||||
|
|
||||||
|
public partial class LogMessageView : UserControl
|
||||||
|
{
|
||||||
|
public static ILogFormat ShortLogFormat = new DefaultLogFormat
|
||||||
|
{
|
||||||
|
TimeStampFormat = MyTimeFormat.TimeOnly,
|
||||||
|
PrintContext = false
|
||||||
|
};
|
||||||
|
|
||||||
|
public LogMessageView()
|
||||||
|
{
|
||||||
|
throw new Exception();
|
||||||
|
}
|
||||||
|
|
||||||
|
public LogMessageView(LauncherLogger.LogMessage m)
|
||||||
|
{
|
||||||
|
InitializeComponent();
|
||||||
|
ContentTextBox.Text = ShortLogFormat.CreateMessage(m.context, m.severity, m.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -4,6 +4,6 @@
|
|||||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||||
xmlns:local="clr-namespace:Млаумчерб.Клиент"
|
xmlns:local="clr-namespace:Млаумчерб.Клиент"
|
||||||
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
|
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
|
||||||
x:Class="Млаумчерб.Клиент.видимое.VersionItemView">
|
x:Class="Млаумчерб.Клиент.зримое.VersionItemView">
|
||||||
<TextBlock Name="text" Background="Transparent"/>
|
<TextBlock Name="text" Background="Transparent"/>
|
||||||
</UserControl>
|
</UserControl>
|
||||||
@ -2,7 +2,7 @@
|
|||||||
using Avalonia.Media;
|
using Avalonia.Media;
|
||||||
using Млаумчерб.Клиент.классы;
|
using Млаумчерб.Клиент.классы;
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент.видимое;
|
namespace Млаумчерб.Клиент.зримое;
|
||||||
|
|
||||||
public partial class VersionItemView : ListBoxItem
|
public partial class VersionItemView : ListBoxItem
|
||||||
{
|
{
|
||||||
@ -2,7 +2,7 @@
|
|||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
xmlns:gif="clr-namespace:Avalonia.Labs.Gif;assembly=Avalonia.Labs.Gif"
|
xmlns:gif="clr-namespace:Avalonia.Labs.Gif;assembly=Avalonia.Labs.Gif"
|
||||||
xmlns:local="clr-namespace:Млаумчерб"
|
xmlns:local="clr-namespace:Млаумчерб"
|
||||||
x:Class="Млаумчерб.Клиент.видимое.Окне"
|
x:Class="Млаумчерб.Клиент.зримое.Окне"
|
||||||
Name="window"
|
Name="window"
|
||||||
Title="млаумчерб"
|
Title="млаумчерб"
|
||||||
Icon="avares://млаумчерб/капитал/кубе.ico"
|
Icon="avares://млаумчерб/капитал/кубе.ico"
|
||||||
@ -17,29 +17,8 @@
|
|||||||
|
|
||||||
<Grid Grid.Row="0" Margin="10">
|
<Grid Grid.Row="0" Margin="10">
|
||||||
<Grid.ColumnDefinitions>* 300 *</Grid.ColumnDefinitions>
|
<Grid.ColumnDefinitions>* 300 *</Grid.ColumnDefinitions>
|
||||||
<Border Grid.Column="0"
|
|
||||||
Classes="dark_tr_bg white_border">
|
<!-- Central panel -->
|
||||||
<Grid>
|
|
||||||
<Grid.RowDefinitions>30 *</Grid.RowDefinitions>
|
|
||||||
<Border Classes="white_border" Margin="-1" Padding="4">
|
|
||||||
<TextBlock FontWeight="Bold"
|
|
||||||
HorizontalAlignment="Center"
|
|
||||||
VerticalAlignment="Center">
|
|
||||||
Лог
|
|
||||||
</TextBlock>
|
|
||||||
</Border>
|
|
||||||
<ScrollViewer Name="LogScrollViewer" Grid.Row="1"
|
|
||||||
HorizontalScrollBarVisibility="Disabled"
|
|
||||||
VerticalScrollBarVisibility="Visible"
|
|
||||||
Background="Transparent">
|
|
||||||
<TextBox Name="LogTextBox"
|
|
||||||
FontSize="14"
|
|
||||||
IsReadOnly="True" TextWrapping="Wrap"
|
|
||||||
VerticalAlignment="Top"
|
|
||||||
Background="Transparent" BorderThickness="0"/>
|
|
||||||
</ScrollViewer>
|
|
||||||
</Grid>
|
|
||||||
</Border>
|
|
||||||
<Border Grid.Column="1"
|
<Border Grid.Column="1"
|
||||||
Classes="dark_tr_bg white_border"
|
Classes="dark_tr_bg white_border"
|
||||||
Margin="10 0">
|
Margin="10 0">
|
||||||
@ -67,14 +46,17 @@
|
|||||||
</Slider>
|
</Slider>
|
||||||
|
|
||||||
<CheckBox IsChecked="{Binding #window.Fullscreen}">
|
<CheckBox IsChecked="{Binding #window.Fullscreen}">
|
||||||
Запустить полноэкранное
|
Запускать полноэкранное
|
||||||
</CheckBox>
|
</CheckBox>
|
||||||
|
|
||||||
<CheckBox IsChecked="{Binding #window.CheckGameFiles}">
|
<CheckBox IsChecked="{Binding #window.CheckGameFiles}">
|
||||||
Проверить файлы игры
|
Проверять файлы игры
|
||||||
|
</CheckBox>
|
||||||
|
<CheckBox IsChecked="{Binding #window.EnableJavaDownload}">
|
||||||
|
Скачивать джаву
|
||||||
</CheckBox>
|
</CheckBox>
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
<Button Grid.Row="1" Margin="10" Padding="0 0 0 4"
|
<Button Name="LaunchButton" Grid.Row="1"
|
||||||
|
Margin="10" Padding="0 0 0 4"
|
||||||
Classes="button_no_border"
|
Classes="button_no_border"
|
||||||
Background="#BBfd7300"
|
Background="#BBfd7300"
|
||||||
Click="Запуск">
|
Click="Запуск">
|
||||||
@ -83,22 +65,60 @@
|
|||||||
</Grid>
|
</Grid>
|
||||||
</Border>
|
</Border>
|
||||||
|
|
||||||
|
<!-- Left panel -->
|
||||||
|
<Border Grid.Column="0"
|
||||||
|
Classes="dark_tr_bg white_border">
|
||||||
|
<Grid>
|
||||||
|
<Grid.RowDefinitions>36 *</Grid.RowDefinitions>
|
||||||
|
<Border Classes="white_border" Margin="-1" Padding="4">
|
||||||
|
<DockPanel>
|
||||||
|
<TextBlock FontWeight="Bold"
|
||||||
|
DockPanel.Dock="Left">
|
||||||
|
Лог
|
||||||
|
</TextBlock>
|
||||||
|
<Button Click="ClearLogPanel"
|
||||||
|
Classes="menu_button"
|
||||||
|
DockPanel.Dock="Right"
|
||||||
|
HorizontalAlignment="Right">
|
||||||
|
очистить
|
||||||
|
</Button>
|
||||||
|
</DockPanel>
|
||||||
|
</Border>
|
||||||
|
<ScrollViewer Name="LogScrollViewer" Grid.Row="1"
|
||||||
|
HorizontalScrollBarVisibility="Disabled"
|
||||||
|
VerticalScrollBarVisibility="Visible"
|
||||||
|
Background="Transparent">
|
||||||
|
<StackPanel Name="LogPanel"
|
||||||
|
VerticalAlignment="Top"/>
|
||||||
|
</ScrollViewer>
|
||||||
|
</Grid>
|
||||||
|
</Border>
|
||||||
|
|
||||||
|
<!-- Right panel -->
|
||||||
<Border Grid.Column="2" Classes="dark_tr_bg white_border">
|
<Border Grid.Column="2" Classes="dark_tr_bg white_border">
|
||||||
<Grid>
|
<Grid>
|
||||||
<Grid.RowDefinitions>30 *</Grid.RowDefinitions>
|
<Grid.RowDefinitions>36 *</Grid.RowDefinitions>
|
||||||
<Border Classes="white_border" Margin="-1" Padding="4">
|
<Border Classes="white_border" Margin="-1" Padding="4">
|
||||||
|
<DockPanel>
|
||||||
<TextBlock FontWeight="Bold"
|
<TextBlock FontWeight="Bold"
|
||||||
HorizontalAlignment="Center"
|
DockPanel.Dock="Left">
|
||||||
VerticalAlignment="Center">
|
|
||||||
Загрузки
|
Загрузки
|
||||||
</TextBlock>
|
</TextBlock>
|
||||||
|
<Button Click="ClearDownloadsPanel"
|
||||||
|
Classes="menu_button"
|
||||||
|
DockPanel.Dock="Right"
|
||||||
|
HorizontalAlignment="Right">
|
||||||
|
очистить
|
||||||
|
</Button>
|
||||||
|
</DockPanel>
|
||||||
</Border>
|
</Border>
|
||||||
<ScrollViewer Grid.Row="1"
|
<ScrollViewer Grid.Row="1"
|
||||||
HorizontalScrollBarVisibility="Disabled"
|
HorizontalScrollBarVisibility="Disabled"
|
||||||
VerticalScrollBarVisibility="Visible"
|
VerticalScrollBarVisibility="Visible"
|
||||||
Background="Transparent"
|
Background="Transparent"
|
||||||
Padding="1">
|
Padding="1">
|
||||||
<StackPanel Name="DownloadsPanel" VerticalAlignment="Top"/>
|
<StackPanel Name="DownloadsPanel"
|
||||||
|
VerticalAlignment="Top"/>
|
||||||
</ScrollViewer>
|
</ScrollViewer>
|
||||||
</Grid>
|
</Grid>
|
||||||
</Border>
|
</Border>
|
||||||
@ -106,7 +126,7 @@
|
|||||||
<Border Grid.Row="1" Background="#954808B0">
|
<Border Grid.Row="1" Background="#954808B0">
|
||||||
<Grid>
|
<Grid>
|
||||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
|
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
|
||||||
<Button Classes="menu_button button_no_border" Click="ОткрытьПапкуЛаунчера">директория лаунчера</Button>
|
<Button Classes="menu_button button_no_border" Click="ОткрытьПапкуЛаунчера">папка лаунчера</Button>
|
||||||
<Border Classes="menu_separator"/>
|
<Border Classes="menu_separator"/>
|
||||||
<Button Classes="menu_button button_no_border" Click="ОткрытьФайлЛогов">лог-файл</Button>
|
<Button Classes="menu_button button_no_border" Click="ОткрытьФайлЛогов">лог-файл</Button>
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
@ -6,7 +6,7 @@ using Avalonia.Platform.Storage;
|
|||||||
using Avalonia.Threading;
|
using Avalonia.Threading;
|
||||||
using Млаумчерб.Клиент.классы;
|
using Млаумчерб.Клиент.классы;
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент.видимое;
|
namespace Млаумчерб.Клиент.зримое;
|
||||||
|
|
||||||
public partial class Окне : Window
|
public partial class Окне : Window
|
||||||
{
|
{
|
||||||
@ -46,6 +46,16 @@ public partial class Окне : Window
|
|||||||
set => SetValue(CheckGameFilesProperty, value);
|
set => SetValue(CheckGameFilesProperty, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static readonly StyledProperty<bool> EnableJavaDownloadProperty =
|
||||||
|
AvaloniaProperty.Register<Окне, bool>(nameof(EnableJavaDownload),
|
||||||
|
defaultBindingMode: BindingMode.TwoWay, defaultValue: true);
|
||||||
|
public bool EnableJavaDownload
|
||||||
|
{
|
||||||
|
get => GetValue(EnableJavaDownloadProperty);
|
||||||
|
set => SetValue(EnableJavaDownloadProperty, value);
|
||||||
|
}
|
||||||
|
|
||||||
public Окне()
|
public Окне()
|
||||||
{
|
{
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
@ -55,34 +65,14 @@ public partial class Окне : Window
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
Приложение.Логгер.OnLogMessage += (context, severity, message, format) =>
|
Приложение.Логгер.OnLogMessage += GuiLogMessage;
|
||||||
{
|
|
||||||
if(severity == LogSeverity.Debug)
|
|
||||||
return;
|
|
||||||
|
|
||||||
StringBuilder b = new();
|
|
||||||
b.Append(DateTime.Now.ToString("[HH:mm:ss]["));
|
|
||||||
b.Append(severity);
|
|
||||||
b.Append("]: ");
|
|
||||||
b.Append(message);
|
|
||||||
b.Append('\n');
|
|
||||||
Dispatcher.UIThread.Invoke(() =>
|
|
||||||
{
|
|
||||||
double offsetFromBottom = LogScrollViewer.Extent.Height
|
|
||||||
- LogScrollViewer.Offset.Y
|
|
||||||
- LogScrollViewer.Viewport.Height;
|
|
||||||
bool is_scrolled_to_end = offsetFromBottom < 20.0; // scrolled less then one line up
|
|
||||||
LogTextBox.Text += b.ToString();
|
|
||||||
if (is_scrolled_to_end)
|
|
||||||
LogScrollViewer.ScrollToEnd();
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
Username = Приложение.Настройки.имя_пользователя;
|
Username = Приложение.Настройки.имя_пользователя;
|
||||||
MemoryLimit = Приложение.Настройки.выделенная_память_мб;
|
MemoryLimit = Приложение.Настройки.выделенная_память_мб;
|
||||||
Fullscreen = Приложение.Настройки.открывать_на_весь_экран;
|
Fullscreen = Приложение.Настройки.запускать_полноэкранное;
|
||||||
|
EnableJavaDownload = Приложение.Настройки.скачивать_жабу;
|
||||||
|
|
||||||
Directory.Create(Пути.GetVersionDescriptorDir());
|
Directory.Create(Пути.GetVersionDescriptorsDir());
|
||||||
VersionComboBox.SelectedIndex = 0;
|
VersionComboBox.SelectedIndex = 0;
|
||||||
VersionComboBox.IsEnabled = false;
|
VersionComboBox.IsEnabled = false;
|
||||||
var versions = await GameVersion.GetAllVersionsAsync();
|
var versions = await GameVersion.GetAllVersionsAsync();
|
||||||
@ -104,38 +94,62 @@ public partial class Окне : Window
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void GuiLogMessage(LauncherLogger.LogMessage msg)
|
||||||
|
{
|
||||||
|
if (msg.severity == LogSeverity.Debug) return;
|
||||||
|
|
||||||
|
Dispatcher.UIThread.Invoke(() =>
|
||||||
|
{
|
||||||
|
double offsetFromBottom = LogScrollViewer.Extent.Height - LogScrollViewer.Offset.Y - LogScrollViewer.Viewport.Height;
|
||||||
|
bool is_scrolled_to_end = offsetFromBottom < 20.0; // scrolled less then one line up
|
||||||
|
LogPanel.Children.Add(new LogMessageView(msg));
|
||||||
|
if (is_scrolled_to_end) LogScrollViewer.ScrollToEnd();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private async void Запуск(object? sender, RoutedEventArgs e)
|
private async void Запуск(object? sender, RoutedEventArgs e)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
Dispatcher.UIThread.Invoke(() => LaunchButton.IsEnabled = false);
|
||||||
|
|
||||||
var selectedVersionView = (VersionItemView?)VersionComboBox.SelectedItem;
|
var selectedVersionView = (VersionItemView?)VersionComboBox.SelectedItem;
|
||||||
var selectedVersion = selectedVersionView?.Props;
|
var selectedVersion = selectedVersionView?.Props;
|
||||||
Приложение.Настройки.последняя_запущенная_версия = selectedVersion?.Name;
|
Приложение.Настройки.последняя_запущенная_версия = selectedVersion?.Name;
|
||||||
Приложение.Настройки.имя_пользователя = Username;
|
Приложение.Настройки.имя_пользователя = Username;
|
||||||
Приложение.Настройки.выделенная_память_мб = MemoryLimit;
|
Приложение.Настройки.выделенная_память_мб = MemoryLimit;
|
||||||
Приложение.Настройки.открывать_на_весь_экран = Fullscreen;
|
Приложение.Настройки.запускать_полноэкранное = Fullscreen;
|
||||||
|
Приложение.Настройки.скачивать_жабу = EnableJavaDownload;
|
||||||
Приложение.Настройки.СохранитьВФайл();
|
Приложение.Настройки.СохранитьВФайл();
|
||||||
if (selectedVersion == null)
|
if (selectedVersion == null)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
var v = await GameVersion.CreateFromPropsAsync(selectedVersion);
|
var v = await GameVersion.CreateFromPropsAsync(selectedVersion);
|
||||||
var updateTasks = await v.CreateUpdateTasksAsync(CheckGameFiles);
|
await v.UpdateFiles(CheckGameFiles, nt =>
|
||||||
foreach (var t in updateTasks)
|
|
||||||
{
|
{
|
||||||
var updateTask = t.StartAsync();
|
|
||||||
Dispatcher.UIThread.Invoke(() =>
|
Dispatcher.UIThread.Invoke(() =>
|
||||||
{
|
{
|
||||||
var view = new DownloadTaskView(t, view => DownloadsPanel.Children.Remove(view));
|
DownloadsPanel.Children.Add(new NetworkTaskView(nt,
|
||||||
DownloadsPanel.Children.Add(view);
|
ntv => DownloadsPanel.Children.Remove(ntv)));
|
||||||
});
|
});
|
||||||
await updateTask;
|
|
||||||
}
|
}
|
||||||
Dispatcher.UIThread.Invoke(() => CheckGameFiles = false);
|
);
|
||||||
|
Dispatcher.UIThread.Invoke(() =>
|
||||||
|
{
|
||||||
|
CheckGameFiles = false;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Ошибки.ПоказатьСообщение(nameof(Окне), ex);
|
Ошибки.ПоказатьСообщение(nameof(Окне), ex);
|
||||||
}
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Dispatcher.UIThread.Invoke(() =>
|
||||||
|
{
|
||||||
|
LaunchButton.IsEnabled = true;
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ОткрытьПапкуЛаунчера(object? s, RoutedEventArgs e)
|
private void ОткрытьПапкуЛаунчера(object? s, RoutedEventArgs e)
|
||||||
@ -176,4 +190,20 @@ public partial class Окне : Window
|
|||||||
Ошибки.ПоказатьСообщение(nameof(Окне), ex);
|
Ошибки.ПоказатьСообщение(nameof(Окне), ex);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void ClearLogPanel(object? sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
LogPanel.Children.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private void ClearDownloadsPanel(object? sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
foreach (var control in DownloadsPanel.Children)
|
||||||
|
{
|
||||||
|
var nt = (NetworkTaskView)control;
|
||||||
|
nt.Task.Cancel();
|
||||||
|
}
|
||||||
|
DownloadsPanel.Children.Clear();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@ -1,6 +1,6 @@
|
|||||||
<Application xmlns="https://github.com/avaloniaui"
|
<Application xmlns="https://github.com/avaloniaui"
|
||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
x:Class="Млаумчерб.Клиент.видимое.Приложение"
|
x:Class="Млаумчерб.Клиент.зримое.Приложение"
|
||||||
RequestedThemeVariant="Dark">
|
RequestedThemeVariant="Dark">
|
||||||
<Application.Styles>
|
<Application.Styles>
|
||||||
<SimpleTheme />
|
<SimpleTheme />
|
||||||
@ -2,7 +2,7 @@ using Avalonia;
|
|||||||
using Avalonia.Controls.ApplicationLifetimes;
|
using Avalonia.Controls.ApplicationLifetimes;
|
||||||
using Avalonia.Markup.Xaml;
|
using Avalonia.Markup.Xaml;
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент.видимое;
|
namespace Млаумчерб.Клиент.зримое;
|
||||||
|
|
||||||
public class Приложение : Application
|
public class Приложение : Application
|
||||||
{
|
{
|
||||||
@ -11,10 +11,10 @@ public class GameVersionDescriptor
|
|||||||
[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 Downloads downloads { get; set; } = null!;
|
||||||
[JsonRequired] public JavaVersion javaVersion { get; set; } = null!;
|
|
||||||
[JsonRequired] public List<Library> libraries { get; set; } = null!;
|
[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 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; }
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
namespace Млаумчерб.Клиент.классы;
|
namespace Млаумчерб.Клиент.классы;
|
||||||
|
|
||||||
public class GameVersionProps
|
public class GameVersionProps : IComparable<GameVersionProps>, IEquatable<GameVersionProps>
|
||||||
{
|
{
|
||||||
public string Name { get; }
|
public string Name { get; }
|
||||||
public IOPath LocalDescriptorPath { get; }
|
public IOPath LocalDescriptorPath { get; }
|
||||||
@ -31,4 +31,33 @@ public class GameVersionProps
|
|||||||
this(name, url, Пути.GetVersionDescriptorPath(name)) { }
|
this(name, url, Пути.GetVersionDescriptorPath(name)) { }
|
||||||
|
|
||||||
public override string ToString() => 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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,23 +1,77 @@
|
|||||||
namespace Млаумчерб.Клиент.классы;
|
using System.Runtime.InteropServices;
|
||||||
|
|
||||||
|
namespace Млаумчерб.Клиент.классы;
|
||||||
|
|
||||||
public class JavaVersionCatalog
|
public class JavaVersionCatalog
|
||||||
{
|
{
|
||||||
|
[JsonProperty("linux")]
|
||||||
|
public Dictionary<string, JavaVersionProps[]>? linux_x86 { get; set; }
|
||||||
|
[JsonProperty("linux-i386")]
|
||||||
|
public Dictionary<string, JavaVersionProps[]>? linux_x64 { get; set; }
|
||||||
|
[JsonProperty("mac-os")]
|
||||||
|
public Dictionary<string, JavaVersionProps[]>? osx_x64 { get; set; }
|
||||||
|
[JsonProperty("mac-os-arm64")]
|
||||||
|
public Dictionary<string, JavaVersionProps[]>? osx_arm64 { get; set; }
|
||||||
|
[JsonProperty("windows-arm64")]
|
||||||
|
public Dictionary<string, JavaVersionProps[]>? windows_arm64 { get; set; }
|
||||||
|
[JsonProperty("windows-x64")]
|
||||||
|
public Dictionary<string, JavaVersionProps[]>? windows_x64 { get; set; }
|
||||||
|
[JsonProperty("windows-x86")]
|
||||||
|
public Dictionary<string, JavaVersionProps[]>? windows_x86 { get; set; }
|
||||||
|
|
||||||
|
public JavaVersionProps GetVersionProps(JavaVersion version)
|
||||||
|
{
|
||||||
|
var arch = RuntimeInformation.OSArchitecture;
|
||||||
|
Dictionary<string, JavaVersionProps[]>? propsDict = null;
|
||||||
|
switch (arch)
|
||||||
|
{
|
||||||
|
case Architecture.X86:
|
||||||
|
if (OperatingSystem.IsWindows())
|
||||||
|
propsDict = windows_x86;
|
||||||
|
else if (OperatingSystem.IsLinux())
|
||||||
|
propsDict = linux_x86;
|
||||||
|
break;
|
||||||
|
case Architecture.X64:
|
||||||
|
if (OperatingSystem.IsWindows())
|
||||||
|
propsDict = windows_x64;
|
||||||
|
else if (OperatingSystem.IsLinux())
|
||||||
|
propsDict = linux_x64;
|
||||||
|
else if (OperatingSystem.IsMacOS())
|
||||||
|
propsDict = osx_x64;
|
||||||
|
break;
|
||||||
|
case Architecture.Arm64:
|
||||||
|
if (OperatingSystem.IsWindows())
|
||||||
|
propsDict = windows_arm64;
|
||||||
|
else if (OperatingSystem.IsMacOS())
|
||||||
|
propsDict = osx_arm64;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (propsDict != null && propsDict.TryGetValue(version.component, out var props_array))
|
||||||
|
{
|
||||||
|
if (props_array.Length != 0)
|
||||||
|
return props_array[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new PlatformNotSupportedException($"Can't download java {version.majorVersion} for your operating system. " +
|
||||||
|
$"Download it manually to directory {Пути.GetJavaRuntimeDir(version.component)}");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public class JavaVersionProps
|
public class JavaVersionProps
|
||||||
{
|
{
|
||||||
[JsonRequired] public Artifact manifest { get; set; }
|
/// url of JavaDistributiveManifest
|
||||||
|
[JsonRequired] public Artifact manifest { get; set; } = null!;
|
||||||
}
|
}
|
||||||
|
|
||||||
public class JavaVersionManifest
|
public class JavaDistributiveManifest
|
||||||
{
|
{
|
||||||
[JsonRequired] public Dictionary<string, JavaDistributiveElementProps> manifest { get; set; }
|
[JsonRequired] public Dictionary<string, JavaDistributiveElementProps> files { get; set; } = null!;
|
||||||
}
|
}
|
||||||
|
|
||||||
public class JavaDistributiveElementProps
|
public class JavaDistributiveElementProps
|
||||||
{
|
{
|
||||||
// "directory" / "file"
|
/// "directory" / "file"
|
||||||
[JsonRequired] public string type { get; set; } = "";
|
[JsonRequired] public string type { get; set; } = "";
|
||||||
public bool? executable { get; set; }
|
public bool? executable { get; set; }
|
||||||
public JavaCompressedArtifact? downloads { get; set; }
|
public JavaCompressedArtifact? downloads { get; set; }
|
||||||
@ -26,5 +80,5 @@ public class JavaDistributiveElementProps
|
|||||||
public class JavaCompressedArtifact
|
public class JavaCompressedArtifact
|
||||||
{
|
{
|
||||||
public Artifact? lzma { get; set; }
|
public Artifact? lzma { get; set; }
|
||||||
public Artifact raw { get; set; } = null!;
|
[JsonRequired] public Artifact raw { get; set; } = null!;
|
||||||
}
|
}
|
||||||
@ -1,4 +1,5 @@
|
|||||||
using DTLib.Extensions;
|
using System.Runtime.InteropServices;
|
||||||
|
using DTLib.Extensions;
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент.классы;
|
namespace Млаумчерб.Клиент.классы;
|
||||||
|
|
||||||
@ -35,6 +36,23 @@ public class Libraries
|
|||||||
if(nativesKey is null)
|
if(nativesKey is null)
|
||||||
throw new Exception($"nativesKey for '{l.name}' is null");
|
throw new Exception($"nativesKey for '{l.name}' is null");
|
||||||
|
|
||||||
|
// example: "natives-windows-${arch}"
|
||||||
|
if (nativesKey.Contains('$'))
|
||||||
|
{
|
||||||
|
var span = nativesKey.AsSpan();
|
||||||
|
nativesKey = span.After("${").Before('}') switch
|
||||||
|
{
|
||||||
|
"arch" => RuntimeInformation.OSArchitecture switch
|
||||||
|
{
|
||||||
|
Architecture.X64 => span.Before("${").ToString() + "64",
|
||||||
|
Architecture.X86 => span.Before("${").ToString() + "32",
|
||||||
|
_ => throw new PlatformNotSupportedException(
|
||||||
|
$"Unsupported architecture: {RuntimeInformation.OSArchitecture}")
|
||||||
|
},
|
||||||
|
_ => throw new Exception($"unknown placeholder in {nativesKey}")
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
Artifact artifact = null!;
|
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}'");
|
throw new Exception($"can't find artifact for '{l.name}' with nativesKey '{nativesKey}'");
|
||||||
|
|||||||
@ -17,7 +17,7 @@ public static class Буржуазия
|
|||||||
&& os.arch switch
|
&& os.arch switch
|
||||||
{
|
{
|
||||||
null => true,
|
null => true,
|
||||||
"x86" => RuntimeInformation.OSArchitecture == Architecture.X86,
|
"i386" or "x86" => RuntimeInformation.OSArchitecture == Architecture.X86,
|
||||||
"x64" => RuntimeInformation.OSArchitecture == Architecture.X64,
|
"x64" => RuntimeInformation.OSArchitecture == Architecture.X64,
|
||||||
"arm64" => RuntimeInformation.OSArchitecture == Architecture.Arm64,
|
"arm64" => RuntimeInformation.OSArchitecture == Architecture.Arm64,
|
||||||
_ => false
|
_ => false
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
using Млаумчерб.Клиент.видимое;
|
using Млаумчерб.Клиент.зримое;
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент.классы;
|
namespace Млаумчерб.Клиент.классы;
|
||||||
|
|
||||||
@ -7,14 +7,14 @@ public static class Пути
|
|||||||
public static IOPath GetAssetIndexFilePath(string id) =>
|
public static IOPath GetAssetIndexFilePath(string id) =>
|
||||||
Path.Concat(Приложение.Настройки.путь_к_кубачу, $"assets/indexes/{id}.json");
|
Path.Concat(Приложение.Настройки.путь_к_кубачу, $"assets/indexes/{id}.json");
|
||||||
|
|
||||||
public static IOPath GetVersionDescriptorDir() =>
|
public static IOPath GetVersionDescriptorsDir() =>
|
||||||
Path.Concat(Приложение.Настройки.путь_к_кубачу, "version_descriptors");
|
Path.Concat(Приложение.Настройки.путь_к_кубачу, "versions");
|
||||||
|
|
||||||
public static string GetVersionDescriptorName(IOPath path) =>
|
public static string GetVersionDescriptorName(IOPath path) =>
|
||||||
path.LastName().RemoveExtension().ToString();
|
path.LastName().RemoveExtension().ToString();
|
||||||
|
|
||||||
public static IOPath GetVersionDescriptorPath(string name) =>
|
public static IOPath GetVersionDescriptorPath(string name) =>
|
||||||
Path.Concat(GetVersionDescriptorDir(), Path.ReplaceRestrictedChars(name) + ".json");
|
Path.Concat(GetVersionDescriptorsDir(), Path.ReplaceRestrictedChars(name) + ".json");
|
||||||
|
|
||||||
public static IOPath GetVersionDir(string id) =>
|
public static IOPath GetVersionDir(string id) =>
|
||||||
Path.Concat(Приложение.Настройки.путь_к_кубачу, "versions", id);
|
Path.Concat(Приложение.Настройки.путь_к_кубачу, "versions", id);
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
using Млаумчерб.Клиент.видимое;
|
using Млаумчерб.Клиент.зримое;
|
||||||
using Timer = DTLib.Timer;
|
using Timer = DTLib.Timer;
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент.сеть;
|
namespace Млаумчерб.Клиент.сеть;
|
||||||
@ -28,10 +28,9 @@ public class NetworkProgressReporter : IDisposable
|
|||||||
}
|
}
|
||||||
|
|
||||||
// atomic add
|
// atomic add
|
||||||
public void AddBytesCount(ArraySegment<byte> chunk)
|
public void AddBytesCount(byte[] buffer, int offset, int count)
|
||||||
{
|
{
|
||||||
long chunkSize = chunk.Count;
|
Interlocked.Add(ref _curSize, count);
|
||||||
Interlocked.Add(ref _curSize, chunkSize);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Start()
|
public void Start()
|
||||||
|
|||||||
@ -7,7 +7,7 @@ public class NetworkTask : IDisposable
|
|||||||
public enum Status
|
public enum Status
|
||||||
{
|
{
|
||||||
Initialized,
|
Initialized,
|
||||||
Running,
|
Started,
|
||||||
Completed,
|
Completed,
|
||||||
Cancelled,
|
Cancelled,
|
||||||
Failed
|
Failed
|
||||||
@ -15,6 +15,7 @@ public class NetworkTask : IDisposable
|
|||||||
|
|
||||||
public Status DownloadStatus { get; private set; } = Status.Initialized;
|
public Status DownloadStatus { get; private set; } = Status.Initialized;
|
||||||
|
|
||||||
|
public event Action? OnStart;
|
||||||
public event Action<DownloadProgress>? OnProgress;
|
public event Action<DownloadProgress>? OnProgress;
|
||||||
public event Action<Status>? OnStop;
|
public event Action<Status>? OnStop;
|
||||||
|
|
||||||
@ -35,15 +36,20 @@ public class NetworkTask : IDisposable
|
|||||||
|
|
||||||
public async Task StartAsync()
|
public async Task StartAsync()
|
||||||
{
|
{
|
||||||
if(DownloadStatus == Status.Running || DownloadStatus == Status.Completed)
|
if(DownloadStatus == Status.Started || DownloadStatus == Status.Completed)
|
||||||
return;
|
return;
|
||||||
DownloadStatus = Status.Running;
|
DownloadStatus = Status.Started;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
_progressReporter.Start();
|
_progressReporter.Start();
|
||||||
|
OnStart?.Invoke();
|
||||||
await _downloadAction(_progressReporter, _cts.Token);
|
await _downloadAction(_progressReporter, _cts.Token);
|
||||||
DownloadStatus = Status.Completed;
|
DownloadStatus = Status.Completed;
|
||||||
}
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
DownloadStatus = Status.Cancelled;
|
||||||
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
DownloadStatus = Status.Failed;
|
DownloadStatus = Status.Failed;
|
||||||
|
|||||||
@ -1,6 +1,8 @@
|
|||||||
using System.Security.Cryptography;
|
using System.Net;
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Security.Cryptography;
|
||||||
using DTLib.Extensions;
|
using DTLib.Extensions;
|
||||||
using Млаумчерб.Клиент.видимое;
|
using Млаумчерб.Клиент.зримое;
|
||||||
using Млаумчерб.Клиент.классы;
|
using Млаумчерб.Клиент.классы;
|
||||||
using static Млаумчерб.Клиент.сеть.Сеть;
|
using static Млаумчерб.Клиент.сеть.Сеть;
|
||||||
|
|
||||||
@ -37,7 +39,7 @@ public class AssetsDownloadTaskFactory : INetworkTaskFactory
|
|||||||
if(!File.Exists(_indexFilePath))
|
if(!File.Exists(_indexFilePath))
|
||||||
{
|
{
|
||||||
Приложение.Логгер.LogInfo(nameof(Сеть), $"started downloading asset index to '{_indexFilePath}'");
|
Приложение.Логгер.LogInfo(nameof(Сеть), $"started downloading asset index to '{_indexFilePath}'");
|
||||||
await DownloadFileHTTP(_descriptor.assetIndex.url, _indexFilePath);
|
await DownloadFile(_descriptor.assetIndex.url, _indexFilePath);
|
||||||
Приложение.Логгер.LogInfo(nameof(Сеть), "finished downloading asset index");
|
Приложение.Логгер.LogInfo(nameof(Сеть), "finished downloading asset index");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -86,7 +88,7 @@ public class AssetsDownloadTaskFactory : INetworkTaskFactory
|
|||||||
public string url;
|
public string url;
|
||||||
public IOPath filePath;
|
public IOPath filePath;
|
||||||
|
|
||||||
public AssetDownloadProperties(string key, GameAssetProperties p)
|
public AssetDownloadProperties(string key, AssetProperties p)
|
||||||
{
|
{
|
||||||
name = key;
|
name = key;
|
||||||
hash = p.hash;
|
hash = p.hash;
|
||||||
@ -100,12 +102,34 @@ public class AssetsDownloadTaskFactory : INetworkTaskFactory
|
|||||||
private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
|
private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
|
||||||
{
|
{
|
||||||
Приложение.Логгер.LogInfo(nameof(Сеть), $"started downloading assets '{_descriptor.assetIndex.id}'");
|
Приложение.Логгер.LogInfo(nameof(Сеть), $"started downloading assets '{_descriptor.assetIndex.id}'");
|
||||||
ParallelOptions opt = new() { MaxDegreeOfParallelism = ParallelDownloadsN, CancellationToken = ct };
|
ParallelOptions opt = new()
|
||||||
|
{
|
||||||
|
MaxDegreeOfParallelism = Приложение.Настройки.максимум_параллельных_загрузок,
|
||||||
|
CancellationToken = ct
|
||||||
|
};
|
||||||
await Parallel.ForEachAsync(_assetsToDownload, opt,
|
await Parallel.ForEachAsync(_assetsToDownload, opt,
|
||||||
async (a, _ct) =>
|
async (a, _ct) =>
|
||||||
|
{
|
||||||
|
bool completed = false;
|
||||||
|
while(!completed)
|
||||||
{
|
{
|
||||||
Приложение.Логгер.LogDebug(nameof(Сеть), $"downloading asset '{a.name}' {a.hash}");
|
Приложение.Логгер.LogDebug(nameof(Сеть), $"downloading asset '{a.name}' {a.hash}");
|
||||||
await DownloadFileHTTP(a.url, a.filePath, _ct, pr.AddBytesCount);
|
try
|
||||||
|
{
|
||||||
|
await DownloadFile(a.url, a.filePath, _ct, pr.AddBytesCount);
|
||||||
|
completed = true;
|
||||||
|
}
|
||||||
|
catch (HttpRequestException httpException)
|
||||||
|
{
|
||||||
|
// wait on rate limit
|
||||||
|
if(httpException.StatusCode == HttpStatusCode.TooManyRequests)
|
||||||
|
{
|
||||||
|
Приложение.Логгер.LogDebug(nameof(Сеть), "rate limit hit");
|
||||||
|
await Task.Delay(1000, _ct);
|
||||||
|
}
|
||||||
|
else throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
Приложение.Логгер.LogInfo(nameof(Сеть), $"finished downloading assets '{_descriptor.assetIndex.id}'");
|
Приложение.Логгер.LogInfo(nameof(Сеть), $"finished downloading assets '{_descriptor.assetIndex.id}'");
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,5 +1,6 @@
|
|||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using EasyCompressor;
|
using DTLib.Extensions;
|
||||||
|
using Млаумчерб.Клиент.зримое;
|
||||||
using Млаумчерб.Клиент.классы;
|
using Млаумчерб.Клиент.классы;
|
||||||
using static Млаумчерб.Клиент.сеть.Сеть;
|
using static Млаумчерб.Клиент.сеть.Сеть;
|
||||||
|
|
||||||
@ -7,23 +8,27 @@ namespace Млаумчерб.Клиент.сеть.NetworkTaskFactories;
|
|||||||
|
|
||||||
public class JavaDownloadTaskFactory : INetworkTaskFactory
|
public class JavaDownloadTaskFactory : INetworkTaskFactory
|
||||||
{
|
{
|
||||||
private const string INDEX_URL =
|
private const string CATALOG_URL =
|
||||||
"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 SHA1 _hasher;
|
||||||
private LZMACompressor _lzma;
|
private JavaDistributiveManifest? _distributiveManifest;
|
||||||
|
private List<(IOPath path, JavaDistributiveElementProps props)> _filesToDownload = new();
|
||||||
|
|
||||||
public JavaDownloadTaskFactory(GameVersionDescriptor descriptor)
|
public JavaDownloadTaskFactory(GameVersionDescriptor descriptor)
|
||||||
{
|
{
|
||||||
_descriptor = descriptor;
|
_descriptor = descriptor;
|
||||||
_javaVersionDir = Пути.GetJavaRuntimeDir(_descriptor.javaVersion.component);
|
_javaVersionDir = Пути.GetJavaRuntimeDir(_descriptor.javaVersion.component);
|
||||||
_hasher = SHA1.Create();
|
_hasher = SHA1.Create();
|
||||||
_lzma = new LZMACompressor();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task<NetworkTask?> CreateAsync(bool checkHashes)
|
public async Task<NetworkTask?> CreateAsync(bool checkHashes)
|
||||||
{
|
{
|
||||||
|
var catalog = await DownloadStringAndDeserialize<JavaVersionCatalog>(CATALOG_URL);
|
||||||
|
var versionProps = catalog.GetVersionProps(_descriptor.javaVersion);
|
||||||
|
_distributiveManifest = await DownloadStringAndDeserialize<JavaDistributiveManifest>(versionProps.manifest.url);
|
||||||
|
|
||||||
NetworkTask? networkTask = null;
|
NetworkTask? networkTask = null;
|
||||||
if (!CheckFiles(checkHashes))
|
if (!CheckFiles(checkHashes))
|
||||||
networkTask = new(
|
networkTask = new(
|
||||||
@ -31,26 +36,87 @@ public class JavaDownloadTaskFactory : INetworkTaskFactory
|
|||||||
GetTotalSize(),
|
GetTotalSize(),
|
||||||
Download
|
Download
|
||||||
);
|
);
|
||||||
return Task.FromResult(networkTask);
|
return networkTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
private bool CheckFiles(bool checkHashes)
|
private bool CheckFiles(bool checkHashes)
|
||||||
{
|
{
|
||||||
//TODO: download catalog
|
_filesToDownload.Clear();
|
||||||
//TODO: download manifest for required runtime
|
foreach (var pair in _distributiveManifest!.files)
|
||||||
//TODO: check whether files from manifest exist and match hashes
|
{
|
||||||
throw new NotImplementedException();
|
if (pair.Value.type != "file")
|
||||||
|
continue;
|
||||||
|
|
||||||
|
if (pair.Value.downloads != null)
|
||||||
|
{
|
||||||
|
var artifact = pair.Value.downloads;
|
||||||
|
IOPath file_path = Path.Concat(_javaVersionDir, pair.Key);
|
||||||
|
if (!File.Exists(file_path))
|
||||||
|
{
|
||||||
|
_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));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return _filesToDownload.Count == 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
private long GetTotalSize()
|
private long GetTotalSize()
|
||||||
{
|
{
|
||||||
//TODO: sum up size of all files invalidated by CheckFiles
|
long totalSize = 0;
|
||||||
throw new NotImplementedException();
|
foreach (var file in _filesToDownload)
|
||||||
|
{
|
||||||
|
if(file.props.downloads == null)
|
||||||
|
continue;
|
||||||
|
totalSize += file.props.downloads.lzma?.size ?? file.props.downloads.raw.size;
|
||||||
|
}
|
||||||
|
return totalSize;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Task Download(NetworkProgressReporter pr, CancellationToken ct)
|
private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
|
||||||
{
|
{
|
||||||
//TODO: download files using lzma decompression
|
Приложение.Логгер.LogInfo(nameof(Сеть), "started downloading java runtime " +
|
||||||
throw new NotImplementedException();
|
$"{_descriptor.javaVersion.majorVersion} '{_descriptor.javaVersion.component}'");
|
||||||
|
|
||||||
|
ParallelOptions opt = new()
|
||||||
|
{
|
||||||
|
MaxDegreeOfParallelism = Приложение.Настройки.максимум_параллельных_загрузок,
|
||||||
|
CancellationToken = ct
|
||||||
|
};
|
||||||
|
await Parallel.ForEachAsync(_filesToDownload, opt, async (f, _ct) =>
|
||||||
|
{
|
||||||
|
if (f.props.downloads!.lzma != null)
|
||||||
|
{
|
||||||
|
Приложение.Логгер.LogDebug(nameof(Сеть), $"downloading lzma-compressed file '{f.path}'");
|
||||||
|
await using var pipe = new TransformStream(await GetStream(f.props.downloads.lzma.url, _ct));
|
||||||
|
pipe.AddTransform(pr.AddBytesCount);
|
||||||
|
await using var fs = File.OpenWrite(f.path);
|
||||||
|
LZMACompressor.Decompress(pipe, fs);
|
||||||
}
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Приложение.Логгер.LogDebug(nameof(Сеть), $"downloading raw file '{f.path}'");
|
||||||
|
await DownloadFile(f.props.downloads.raw.url, f.path, _ct, pr.AddBytesCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
if(!OperatingSystem.IsWindows() && f.props.executable is true)
|
||||||
|
{
|
||||||
|
Приложение.Логгер.LogDebug(nameof(Сеть), $"adding execute rights to file '{f.path}'");
|
||||||
|
System.IO.File.SetUnixFileMode(f.path.ToString(), UnixFileMode.UserExecute);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Приложение.Логгер.LogInfo(nameof(Сеть), "finished downloading java runtime " +
|
||||||
|
$"{_descriptor.javaVersion.majorVersion} '{_descriptor.javaVersion.component}'");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@ -1,7 +1,7 @@
|
|||||||
using System.IO.Compression;
|
using System.IO.Compression;
|
||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using DTLib.Extensions;
|
using DTLib.Extensions;
|
||||||
using Млаумчерб.Клиент.видимое;
|
using Млаумчерб.Клиент.зримое;
|
||||||
using Млаумчерб.Клиент.классы;
|
using Млаумчерб.Клиент.классы;
|
||||||
using static Млаумчерб.Клиент.сеть.Сеть;
|
using static Млаумчерб.Клиент.сеть.Сеть;
|
||||||
|
|
||||||
@ -73,12 +73,16 @@ public class LibrariesDownloadTaskFactory : INetworkTaskFactory
|
|||||||
private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
|
private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
|
||||||
{
|
{
|
||||||
Приложение.Логгер.LogInfo(nameof(Сеть), $"started downloading libraries '{_descriptor.id}'");
|
Приложение.Логгер.LogInfo(nameof(Сеть), $"started downloading libraries '{_descriptor.id}'");
|
||||||
ParallelOptions opt = new() { MaxDegreeOfParallelism = ParallelDownloadsN, CancellationToken = ct };
|
|
||||||
|
ParallelOptions opt = new()
|
||||||
|
{
|
||||||
|
MaxDegreeOfParallelism = Приложение.Настройки.максимум_параллельных_загрузок,
|
||||||
|
CancellationToken = ct
|
||||||
|
};
|
||||||
await Parallel.ForEachAsync(_libsToDownload, opt, async (l, _ct) =>
|
await Parallel.ForEachAsync(_libsToDownload, opt, async (l, _ct) =>
|
||||||
{
|
{
|
||||||
Приложение.Логгер.LogDebug(nameof(Сеть),
|
Приложение.Логгер.LogDebug(nameof(Сеть), $"downloading library '{l.name}' to '{l.jarFilePath}'");
|
||||||
$"downloading library '{l.name}' to '{l.jarFilePath}'");
|
await DownloadFile(l.artifact.url, l.jarFilePath, _ct, pr.AddBytesCount);
|
||||||
await DownloadFileHTTP(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);
|
var zipf = File.OpenRead(n.jarFilePath);
|
||||||
@ -96,6 +100,7 @@ public class LibrariesDownloadTaskFactory : INetworkTaskFactory
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
Приложение.Логгер.LogInfo(nameof(Сеть), $"finished downloading libraries '{_descriptor.id}'");
|
Приложение.Логгер.LogInfo(nameof(Сеть), $"finished downloading libraries '{_descriptor.id}'");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1,6 +1,6 @@
|
|||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using DTLib.Extensions;
|
using DTLib.Extensions;
|
||||||
using Млаумчерб.Клиент.видимое;
|
using Млаумчерб.Клиент.зримое;
|
||||||
using Млаумчерб.Клиент.классы;
|
using Млаумчерб.Клиент.классы;
|
||||||
using static Млаумчерб.Клиент.сеть.Сеть;
|
using static Млаумчерб.Клиент.сеть.Сеть;
|
||||||
|
|
||||||
@ -50,7 +50,7 @@ public class VersionFileDownloadTaskFactory : INetworkTaskFactory
|
|||||||
private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
|
private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
|
||||||
{
|
{
|
||||||
Приложение.Логгер.LogInfo(nameof(Сеть), $"started downloading version file '{_descriptor.id}'");
|
Приложение.Логгер.LogInfo(nameof(Сеть), $"started downloading version file '{_descriptor.id}'");
|
||||||
await DownloadFileHTTP(_descriptor.downloads.client.url, _filePath, ct, pr.AddBytesCount);
|
await DownloadFile(_descriptor.downloads.client.url, _filePath, ct, pr.AddBytesCount);
|
||||||
Приложение.Логгер.LogInfo(nameof(Сеть), $"finished downloading version file '{_descriptor.id}'");
|
Приложение.Логгер.LogInfo(nameof(Сеть), $"finished downloading version file '{_descriptor.id}'");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1,53 +1,46 @@
|
|||||||
using System.Buffers;
|
using System.Net.Http;
|
||||||
using System.Net.Http;
|
using System.Net.Http.Headers;
|
||||||
using Млаумчерб.Клиент.видимое;
|
using Млаумчерб.Клиент.зримое;
|
||||||
using Млаумчерб.Клиент.классы;
|
using Млаумчерб.Клиент.классы;
|
||||||
|
|
||||||
namespace Млаумчерб.Клиент.сеть;
|
namespace Млаумчерб.Клиент.сеть;
|
||||||
|
|
||||||
public static class Сеть
|
public static class Сеть
|
||||||
{
|
{
|
||||||
public static int ParallelDownloadsN = 32;
|
private static HttpClient _http = new();
|
||||||
public static HttpClient http = new();
|
|
||||||
|
|
||||||
public static async Task DownloadFileHTTP(string url, IOPath outPath, CancellationToken ct = default,
|
static Сеть()
|
||||||
Action<ArraySegment<byte>>? transformFunc = null)
|
|
||||||
{
|
{
|
||||||
await using var src = await http.GetStreamAsync(url, ct);
|
// thanks for Sashok :3
|
||||||
await using var dst = File.OpenWrite(outPath);
|
// 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)");
|
||||||
await src.CopyTransformAsync(dst, transformFunc, ct).ConfigureAwait(false);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task CopyTransformAsync(this Stream src, Stream dst,
|
public static Task<string> GetString(string url, CancellationToken ct = default) => _http.GetStringAsync(url, ct);
|
||||||
Action<ArraySegment<byte>>? transformFunc = null, CancellationToken ct = default)
|
public static Task<Stream> GetStream(string url, CancellationToken ct = default) => _http.GetStreamAsync(url, ct);
|
||||||
|
|
||||||
|
public static async Task DownloadFile(string url, Stream outStream, CancellationToken ct = default,
|
||||||
|
params TransformStream.TransformFuncDelegate[] transforms)
|
||||||
{
|
{
|
||||||
// default dotnet runtime buffer size
|
await using var pipe = new TransformStream(await GetStream(url, ct));
|
||||||
int bufferSize = 81920;
|
if (transforms.Length > 0)
|
||||||
byte[] readBuffer = ArrayPool<byte>.Shared.Rent(bufferSize);
|
pipe.AddTransforms(transforms);
|
||||||
byte[] writeBuffer = ArrayPool<byte>.Shared.Rent(bufferSize);
|
await pipe.CopyToAsync(outStream, ct);
|
||||||
try
|
|
||||||
{
|
|
||||||
var readTask = src.ReadAsync(readBuffer, 0, bufferSize, ct).ConfigureAwait(false);
|
|
||||||
while (true)
|
|
||||||
{
|
|
||||||
int readCount = await readTask;
|
|
||||||
if (readCount == 0)
|
|
||||||
break;
|
|
||||||
(readBuffer, writeBuffer) = (writeBuffer, readBuffer);
|
|
||||||
readTask = src.ReadAsync(readBuffer, 0, bufferSize, ct).ConfigureAwait(false);
|
|
||||||
transformFunc?.Invoke(new ArraySegment<byte>(writeBuffer, 0, readCount));
|
|
||||||
dst.Write(writeBuffer, 0, readCount);
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
catch (OperationCanceledException)
|
public static async Task DownloadFile(string url, IOPath outPath, CancellationToken ct = default,
|
||||||
|
params TransformStream.TransformFuncDelegate[] transforms)
|
||||||
{
|
{
|
||||||
|
await using var file = File.OpenWrite(outPath);
|
||||||
|
await DownloadFile(url, file, ct, transforms);
|
||||||
}
|
}
|
||||||
finally
|
|
||||||
|
public static async Task<T> DownloadStringAndDeserialize<T>(string url)
|
||||||
{
|
{
|
||||||
ArrayPool<byte>.Shared.Return(readBuffer);
|
var text = await _http.GetStringAsync(url);
|
||||||
ArrayPool<byte>.Shared.Return(writeBuffer);
|
var result = JsonConvert.DeserializeObject<T>(text)
|
||||||
}
|
?? throw new Exception($"can't deserialize {typeof(T).Name}");
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static readonly string[] VERSION_MANIFEST_URLS =
|
private static readonly string[] VERSION_MANIFEST_URLS =
|
||||||
@ -62,9 +55,7 @@ public static class Сеть
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var manifestText = await http.GetStringAsync(url);
|
var catalog = await DownloadStringAndDeserialize<GameVersionCatalog>(url);
|
||||||
var catalog = JsonConvert.DeserializeObject<GameVersionCatalog>(manifestText);
|
|
||||||
if (catalog != null)
|
|
||||||
descriptors.AddRange(catalog.versions);
|
descriptors.AddRange(catalog.versions);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
|
|||||||
@ -4,7 +4,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Млаумчерб.Клие
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SolutionFolder", "SolutionFolder", "{A3217C18-CC0D-4CE8-9C48-1BDEC1E1B333}"
|
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SolutionFolder", "SolutionFolder", "{A3217C18-CC0D-4CE8-9C48-1BDEC1E1B333}"
|
||||||
ProjectSection(SolutionItems) = preProject
|
ProjectSection(SolutionItems) = preProject
|
||||||
nuget.config = nuget.config
|
.gitignore = .gitignore
|
||||||
EndProjectSection
|
EndProjectSection
|
||||||
EndProject
|
EndProject
|
||||||
Global
|
Global
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user