Compare commits

..

14 Commits
1.0.1 ... main

Author SHA1 Message Date
1c3b8963ac v1.1.2 2025-05-21 13:52:56 +05:00
e915892fa2 fixed some bugs, added ability to work without internet 2025-05-21 13:52:33 +05:00
ab1aefd619 native libraries check fix 2025-05-21 12:33:57 +05:00
459b3f09f9 check inheritFrom in parent descriptors 2025-05-21 12:29:35 +05:00
9bcdfd88e6 made dog image smaller 2025-04-20 05:20:55 +05:00
2dc472c85a README.md 2025-04-20 05:16:15 +05:00
2087c14285 Merge branch 'main' of https://timerix.ddns.net/git/Timerix/mlaumcherb 2025-04-20 04:55:42 +05:00
ef36fb5584 v1.1.1 2025-04-20 04:54:26 +05:00
d6bd7b9ef0 renamed build script 2025-04-20 04:54:18 +05:00
23195bd7c7 updated git repository url 2025-04-20 04:44:28 +05:00
5e439ee8d5 fixes for linux 2025-04-07 06:18:22 +05:00
cbfd5f8da8 Updater 2025-01-06 01:01:34 +05:00
da58c11e59 Modpack format v2 2025-01-05 22:19:56 +05:00
23ec6dd194 fabric loader descriptors support 2025-01-02 18:42:19 +05:00
26 changed files with 382 additions and 138 deletions

View File

@ -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;
@ -26,6 +27,13 @@ public record Config
new() { name = "Mojang", url = "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json" },
];
public UpdateHelper.GiteaConfig gitea { get; set; } = new()
{
serverUrl = "https://timerix.ddns.net/git/",
user = "Timerix",
repo = "mlaumcherb",
};
[JsonIgnore] private static IOPath _filePath = "млаумчерб.json";

View File

@ -34,10 +34,11 @@ public class GameVersion
_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 Download(bool update, Action<NetworkTask> networkTaskCreatedCallback)
public async Task Download(bool checkHashes, Action<NetworkTask> networkTaskCreatedCallback)
{
LauncherApp.Logger.LogInfo(Id, $"started updating version {Id}");
@ -46,7 +47,7 @@ public class GameVersion
new AssetsDownloadTaskFactory(_descriptor),
new LibrariesDownloadTaskFactory(_descriptor, _libraries),
];
if (LauncherApp.Config.download_java)
if (LauncherApp.Config.download_java && (!File.Exists(JavaExecutableFilePath) || checkHashes))
taskFactories.Add(new JavaDownloadTaskFactory(_descriptor));
if (_descriptor.modpack != null)
taskFactories.Add(new ModpackDownloadTaskFactory(_descriptor));
@ -56,7 +57,7 @@ public class GameVersion
var networkTasks = new List<NetworkTask>();
for (int i = 0; i < taskFactories.Count; i++)
{
var nt = await taskFactories[i].CreateAsync(update);
var nt = await taskFactories[i].CreateAsync(checkHashes);
if (nt != null)
{
networkTasks.Add(nt);
@ -108,6 +109,7 @@ 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() {
@ -127,14 +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", ";"},
{ "classpath_separator", classSeparator},
{ "path", GetLog4jConfigFilePath().ToString() },
{ "version_name", _descriptor.id },
{ "version_type", _descriptor.type },

View File

@ -5,7 +5,7 @@ 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()
{

View File

@ -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,20 +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.*" />

View File

@ -2,6 +2,8 @@ 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.зримое;
@ -18,13 +20,47 @@ 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();
InstalledVersionCatalog = InstalledVersionCatalog.Load();
// 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);
}
}
public override void OnFrameworkInitializationCompleted()

View File

@ -178,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"

View File

@ -1,3 +1,4 @@
using System.Reflection;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Data;
@ -70,6 +71,7 @@ public partial class MainWindow : Window
try
{
LauncherApp.Logger.OnLogMessage += GuiLogMessage;
LauncherVersionTextBox.Text = $"v{Assembly.GetExecutingAssembly().GetName().Version}";
PlayerName = LauncherApp.Config.player_name;
MemoryLimit = LauncherApp.Config.max_memory;
@ -90,6 +92,20 @@ public partial class MainWindow : Window
}
}
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();
@ -119,8 +135,15 @@ public partial class MainWindow : Window
private void RescanInstalledVersionsButton_OnClick(object? sender, RoutedEventArgs e)
{
var selectedVersionView = InstalledVersionCatalogComboBox.SelectedItem as InstalledGameVersionItemView;
UpdateInstalledVersionsCatalogView(selectedVersionView?.Props.Id);
try
{
var selectedVersionView = InstalledVersionCatalogComboBox.SelectedItem as InstalledGameVersionItemView;
UpdateInstalledVersionsCatalogView(selectedVersionView?.Props.Id);
}
catch (Exception ex)
{
ErrorHelper.ShowMessageBox(nameof(MainWindow), ex);
}
}
private void GuiLogMessage(LauncherLogger.LogMessage msg)
@ -145,22 +168,27 @@ public partial class MainWindow : Window
Dispatcher.UIThread.Invoke(() => LaunchButton.IsEnabled = false);
LauncherApp.Config.last_launched_version = selectedVersionView.Props.Id;
LauncherApp.Config.player_name = PlayerName;
LauncherApp.Config.max_memory = MemoryLimit;
LauncherApp.Config.download_java = EnableJavaDownload;
LauncherApp.Config.redirect_game_output = RedirectGameOutput;
LauncherApp.Config.SaveToFile();
SaveGuiPropertiesToConfig();
var v = await selectedVersionView.Props.LoadDescriptor(UpdateGameFiles);
await v.Download(UpdateGameFiles, nt =>
{
Dispatcher.UIThread.Invoke(() =>
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(() =>
{
UpdateGameFiles = false;
@ -181,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)
@ -194,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)
@ -207,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)

View File

@ -67,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

View File

@ -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; }

View File

@ -66,23 +66,26 @@ public class InstalledGameVersionProps : IComparable<InstalledGameVersionProps>,
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))
// 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");
?? throw new Exception("inheritsFrom is null");
LauncherApp.Logger.LogInfo(Id, $"merging descriptor '{parentDescriptorId}' with '{Id}'");
IOPath parentDescriptorPath = PathHelper.GetVersionDescriptorPath(parentDescriptorId);
if (!File.Exists(parentDescriptorPath))
throw new Exception($"Версия '{Id} требует установить версию '{parentDescriptorId}'");
string parentDescriptorText = File.ReadAllText(parentDescriptorPath);
JObject parentDescriptorRaw = JObject.Parse(parentDescriptorText);
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;
// removing dependency
descriptorRaw.Remove("inheritsFrom");
File.WriteAllText(DescriptorPath, descriptorRaw.ToString());
}
var descriptor = descriptorRaw.ToObject<GameVersionDescriptor>()

View File

@ -29,7 +29,6 @@ public class InstalledVersionCatalog
}
catalog.CheckInstalledVersions();
catalog.Save();
return catalog;
}
@ -44,6 +43,7 @@ public class InstalledVersionCatalog
/// <summary>
/// Check if any versions were installed or deleted manually.
/// Calls <see cref="Save"/>
/// </summary>
public void CheckInstalledVersions()
{
@ -53,17 +53,16 @@ public class InstalledVersionCatalog
{
string id = subdir.LastName().ToString();
if (!File.Exists(PathHelper.GetVersionDescriptorPath(id)))
throw new Exception(
$"Can't find version descriptor file in directory '{subdir}'. Rename it as directory name.");
{
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));
}
else versionsUpdated.Add(new InstalledGameVersionProps(id, null, null));
}
// reverse sort
@ -73,5 +72,7 @@ public class InstalledVersionCatalog
versionsUpdated.Select(props =>
new KeyValuePair<string, InstalledGameVersionProps>(props.Id, props)
));
Save();
}
}

View File

@ -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));
}
}
}

View File

@ -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!;
}

View File

@ -2,37 +2,30 @@
namespace Mlaumcherb.Client.Avalonia.классы;
public class MyModpackRemoteProps
public class MyModpackV2
{
[JsonRequired] public int format_version { get; set; }
[JsonRequired] public Artifact artifact { get; set; } = null!;
}
public class MyModpackV1
{
// 1
// 2
[JsonRequired] public int format_version { get; set; }
[JsonRequired] public string name { get; set; } = "";
// zip archive with all files
[JsonRequired] public Artifact zip { get; set; } = null!;
/// relative_path, hash
/// relative_path, props
// ReSharper disable once CollectionNeverUpdated.Global
[JsonRequired] public Dictionary<string, FileProps> files { get; set; } = new();
public class FileProps
{
[JsonRequired] public string sha1 { get; set; } = "";
[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; }
}
/// <param name="unmatchedFilesLocalPaths">relative, absolute</param>
public Dictionary<IOPath, IOPath> CheckFiles(IOPath basedir, bool checkHashes, bool downloadOptionalFiles)
public record FileCheckResult(FileProps props, IOPath relativePath, IOPath absolutePath);
public List<FileCheckResult> CheckFiles(IOPath basedir, bool checkHashes, bool downloadOptionalFiles)
{
Dictionary<IOPath, IOPath> unmatchedFiles = new();
List<FileCheckResult> unmatchedFiles = new();
IOPath launcherRoot = PathHelper.GetRootFullPath();
foreach (var p in files)
{
@ -40,11 +33,12 @@ public class MyModpackV1
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.sha1, checkHashes && !p.Value.allow_edit))
if (!HashHelper.CheckFileSHA1(absolutePath, p.Value.artifact.sha1, checkHashes && !p.Value.allow_edit))
{
unmatchedFiles.Add(relativePath, absolutePath);
unmatchedFiles.Add(new FileCheckResult(p.Value, relativePath, absolutePath));
}
}

View File

@ -12,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);

View File

@ -42,14 +42,20 @@ public class LibrariesDownloadTaskFactory : INetworkTaskFactory
foreach (var l in _libraries.Libs)
{
if (!HashHelper.CheckFileSHA1(l.jarFilePath, l.artifact.sha1, checkHashes))
if (l is Libraries.NativeLib native)
{
_libsToDownload.Add(l);
//TODO: replace with actual native libraries check
if(!nativeDirExists || checkHashes)
{
_libsToDownload.Add(l);
}
}
//TODO: replace with actual native libraries check
else if (!nativeDirExists && l is Libraries.NativeLib)
else
{
_libsToDownload.Add(l);
if (!HashHelper.CheckFileSHA1(l.jarFilePath, l.artifact?.sha1, checkHashes))
{
_libsToDownload.Add(l);
}
}
}
@ -60,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;
}
@ -76,7 +82,7 @@ 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)

View File

@ -5,17 +5,15 @@ namespace Mlaumcherb.Client.Avalonia.сеть.TaskFactories;
public class ModpackDownloadTaskFactory : INetworkTaskFactory
{
INetworkTaskFactory _implementationVersion;
private GameVersionDescriptor _descriptor;
public ModpackDownloadTaskFactory(GameVersionDescriptor descriptor)
{
if(descriptor.modpack is null)
throw new ArgumentNullException(nameof(descriptor.modpack));
_descriptor = descriptor;
_implementationVersion = descriptor.modpack.format_version switch
{
1 => new MyModpackV1DownloadTaskFactory(descriptor),
2 => new MyModpackV2DownloadTaskFactory(descriptor),
_ => throw new Exception($"Unknown Modpack format_version: {descriptor.modpack.format_version}")
};
}

View File

@ -1,20 +1,20 @@
using System.IO.Compression;
using System.Linq;
using Mlaumcherb.Client.Avalonia.зримое;
using Mlaumcherb.Client.Avalonia.классы;
using Mlaumcherb.Client.Avalonia.холопы;
namespace Mlaumcherb.Client.Avalonia.сеть.TaskFactories;
public class MyModpackV1DownloadTaskFactory : INetworkTaskFactory
public class MyModpackV2DownloadTaskFactory : INetworkTaskFactory
{
private readonly GameVersionDescriptor _descriptor;
private IOPath _modpackDescriptorPath;
private IOPath _versionDir;
private MyModpackV1? _modpack;
private MyModpackV2? _modpack;
// relative, absolute
private Dictionary<IOPath, IOPath> _filesToDosnload = new();
private List<MyModpackV2.FileCheckResult> _filesToDownload = new();
public MyModpackV1DownloadTaskFactory(GameVersionDescriptor descriptor)
public MyModpackV2DownloadTaskFactory(GameVersionDescriptor descriptor)
{
_descriptor = descriptor;
_modpackDescriptorPath = PathHelper.GetModpackDescriptorPath(_descriptor.id);
@ -26,7 +26,7 @@ public class MyModpackV1DownloadTaskFactory : INetworkTaskFactory
if(_descriptor.modpack is null)
throw new ArgumentNullException(nameof(_descriptor.modpack));
(_modpack, bool didDownloadModpackDescriptor) = await NetworkHelper.ReadOrDownloadAndDeserialize<MyModpackV1>(
(_modpack, bool didDownloadModpackDescriptor) = await NetworkHelper.ReadOrDownloadAndDeserialize<MyModpackV2>(
_modpackDescriptorPath,
_descriptor.modpack.artifact.url,
_descriptor.modpack.artifact.sha1,
@ -36,12 +36,12 @@ public class MyModpackV1DownloadTaskFactory : INetworkTaskFactory
$"{_modpack.format_version} != {_descriptor.modpack.format_version}");
NetworkTask? networkTask = null;
_filesToDosnload = _modpack.CheckFiles(_versionDir, checkHashes, didDownloadModpackDescriptor);
if(_filesToDosnload.Count > 0)
_filesToDownload = _modpack.CheckFiles(_versionDir, checkHashes, didDownloadModpackDescriptor);
if(_filesToDownload.Count > 0)
{
networkTask = new NetworkTask(
$"modpack '{_modpack.name}'",
_modpack.zip.size,
_filesToDownload.Sum(f => f.props.artifact.size),
Download
);
}
@ -52,23 +52,19 @@ public class MyModpackV1DownloadTaskFactory : INetworkTaskFactory
private async Task Download(NetworkProgressReporter pr, CancellationToken ct)
{
LauncherApp.Logger.LogInfo(nameof(NetworkHelper), $"started downloading modpack '{_modpack!.name}'");
if(string.IsNullOrEmpty(_modpack.zip.url))
throw new Exception($"modpack '{_modpack.name}' doesn't have a url to download");
var _archivePath = Path.Concat(PathHelper.GetCacheDir(), "modpacks", _modpack.name + ".zip");
await NetworkHelper.DownloadFile(_modpack.zip.url, _archivePath, ct, pr.AddBytesCount);
await using var zipf = File.OpenRead(_archivePath);
using var archive = new ZipArchive(zipf);
foreach (var entry in archive.Entries)
ParallelOptions opt = new()
{
IOPath relativePath = new(entry.FullName);
if(_filesToDosnload.TryGetValue(relativePath, out var absolutePath))
{
Directory.Create(absolutePath.ParentDir());
entry.ExtractToFile(absolutePath.ToString(), true);
}
}
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}'");
}

View 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);
}
}

View 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);
}
}

View File

@ -24,8 +24,8 @@ public static class HashHelper
if (!File.Exists(f))
return false;
if(checkHash)
return sha1 is not null && HashFileSHA1(f) == sha1;
if(checkHash && sha1 is not null)
return HashFileSHA1(f) == sha1;
return true;
}

View File

@ -40,14 +40,17 @@ 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";

14
README.md Normal file
View 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
```

View File

@ -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

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

View File

@ -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