Browse Source

added autoconnect in server list

Veloe 1 year ago
parent
commit
88f2dbc114

+ 32 - 5
VeloeMinecraftLauncher/Models/ServerPanelModel.cs

@@ -8,13 +8,17 @@ public class ServerPanelModel : ReactiveValidationObject
     private string _status;
     private string _tip;
     private string _players;
+    private string _clientName;
+    private string? _userClientName;
 
-    public ServerPanelModel(string name, string status, string tip, string players)
+    public ServerPanelModel(string name, string status, string tip, string players, string address, string clientName)
     {
-        _name= name;
-        _status= status;
-        _tip= tip;
-        _players= players;
+        _name = name;
+        _status = status;
+        _tip = tip;
+        _players = players;
+        Address = address;
+        _clientName = clientName;
     }
 
     public string Name
@@ -40,5 +44,28 @@ public class ServerPanelModel : ReactiveValidationObject
         get => _players;
         set => this.RaiseAndSetIfChanged(ref _players, value);
     }
+
+    public string Address { get; set; }
+
+    public string ClientName 
+    { 
+        get => _clientName;
+        set => this.RaiseAndSetIfChanged(ref _clientName, value);
+    }
+
+    public string? UserClientName 
+    { 
+        get => _userClientName;
+        set 
+        {
+            this.RaiseAndSetIfChanged(ref _userClientName, value);
+            this.RaisePropertyChanged(nameof(IsOverriden));
+            this.RaisePropertyChanged(nameof(IsResetable));
+        }
+    }
+
+    public bool IsOverriden => !string.IsNullOrEmpty(UserClientName);
+
+    public bool IsResetable => IsOverriden && !string.IsNullOrEmpty(ClientName);
 }
 

+ 5 - 0
VeloeMinecraftLauncher/Utils/Settings.cs

@@ -40,6 +40,11 @@ internal static class SettingsService
                 logger?.Error(ex.Message);
             }
         }
+        else
+        {
+            Instance = new SettingsSerializable();
+            logger?.Warning("Empty settings.json");
+        }
     }
 
     public static void SaveSettings()

+ 4 - 1
VeloeMinecraftLauncher/Utils/SettingsSerializable.cs

@@ -1,12 +1,13 @@
 using Serilog.Events;
 using System;
+using System.Collections.Generic;
 using System.IO;
 
 namespace VeloeMinecraftLauncher.Utils;
 
 public class SettingsSerializable : ICloneable
 {
-    public string JavaPath {get; set;} = string.Empty;
+    public string JavaPath { get; set; } = string.Empty;
     public string MinecraftForlderPath { get; set; } = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar;
     public UInt32 MaxRam { get; set; } = 2048;
     public bool UseCustomJava { get; set; } = false;
@@ -33,6 +34,8 @@ public class SettingsSerializable : ICloneable
     public LogEventLevel ConsoleLogEventLevel { get; set; } = LogEventLevel.Debug;
     public LogEventLevel FileLogEventLevel { get; set; } = LogEventLevel.Debug;
 
+    public Dictionary<string, string> ServerAutoConnectLinks { get; set; } = new();
+
     public object Clone()
     {
         return MemberwiseClone();

+ 6 - 2
VeloeMinecraftLauncher/VeloeMinecraftLauncher.csproj

@@ -10,9 +10,13 @@
 		<DebugType>embedded</DebugType>
 		<StartupObject>VeloeMinecraftLauncher.Program</StartupObject>
 		<PlatformTarget>x64</PlatformTarget>
-		<AssemblyVersion>1.6.0.70</AssemblyVersion>
-		<FileVersion>1.6.0.70</FileVersion>
+		<AssemblyVersion>1.6.0.153</AssemblyVersion>
+		<FileVersion>1.6.0.153</FileVersion>
 		<Configurations>Debug;Release</Configurations>
+		<Copyright>MIT</Copyright>
+		<RepositoryType>git</RepositoryType>
+		<RepositoryUrl>https://gogs.veloe.link/Veloe/VeloeMinecraftLauncher.git</RepositoryUrl>
+		<PackageProjectUrl>https://gogs.veloe.link/Veloe/VeloeMinecraftLauncher/wiki</PackageProjectUrl>
 	</PropertyGroup>
 	<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
 		<NoWarn>NU1605</NoWarn>

+ 86 - 17
VeloeMinecraftLauncher/ViewModels/MainWindowViewModel.cs

@@ -116,9 +116,9 @@ public class MainWindowViewModel : ViewModelBase
                 _logger.Debug("Connecting to WebSoket");
                 //conection to my servers 
 
-                var serverNames = await Downloader.DownloadAndDeserializeJsonData<List<string>>("https://files.veloe.link/launcher/servers.json");
+                var serverInfo = await Downloader.DownloadAndDeserializeJsonData<Dictionary<string, string[]>>("https://files.veloe.link/launcher/serversInfo.json");
 
-                if (serverNames is not null)
+                if (serverInfo is not null)
                 {
                     _connection = new HubConnectionBuilder()
                     .WithUrl("https://monitor.veloe.link/hubs/data")
@@ -132,23 +132,26 @@ public class MainWindowViewModel : ViewModelBase
                     Func<string, Task> reconnected = str => Task.Run(() =>
                     {
                         _logger.Warning("Reconnected to WebCoket.");
-                        foreach (var server in serverNames)
+                        foreach (var server in serverInfo)
                         {
-                            _connection.InvokeAsync("ConnectToGroup", server);
+                            _connection.InvokeAsync("ConnectToGroup", server.Key);
                         }
                     });
 
                     _connection.Reconnecting += reconnecting;
                     _connection.Reconnected += reconnected;
-                        
-                    foreach (var server in serverNames)
-                        ServerPanels.Add(CreateServerPanel(server));
+                    
+                    await Dispatcher.UIThread.InvokeAsync(()=>
+                    {
+                        foreach (var server in serverInfo)
+                            ServerPanels.Add(CreateServerPanel(server.Key, server.Value[0], server.Value[1]));
+                    });
 
                     await _connection.StartAsync();
 
-                    foreach (var server in serverNames)
+                    foreach (var server in serverInfo)
                     {
-                        await _connection.InvokeAsync("ConnectToGroup", server);
+                        await _connection.InvokeAsync("ConnectToGroup", server.Key);
                     }
                     _logger.Debug("Connected to WebSoket");
                 }
@@ -267,6 +270,8 @@ public class MainWindowViewModel : ViewModelBase
         set => this.RaiseAndSetIfChanged(ref _downloadedVersion, value);
     }
 
+    public bool DownloadedVersionNotNull => DownloadedVersion is not null;
+
     public int DownloadedIndex
     {
         get => _downloadedIndex;
@@ -378,8 +383,15 @@ public class MainWindowViewModel : ViewModelBase
         }
     }
 
-    public async void StartMinecraft()
+    public void StartMinecraft()
     {
+        StartMinecraft(string.Empty);
+    }
+
+    public async void StartMinecraft(string additionalArgs)
+    {
+        if (!IsNoGameRunning) return;
+
         await Task.Run(async() =>
         {
             try
@@ -391,6 +403,8 @@ public class MainWindowViewModel : ViewModelBase
                     return;
                 }
 
+                IsNoGameRunning = false;
+
                 int version = 0;
                 var arguments = string.Empty;
 
@@ -409,7 +423,7 @@ public class MainWindowViewModel : ViewModelBase
 
                         var parameters = new DownloaderParameters();
                         parameters.Action.DownloadingFileName = value => StartButtonOutput = value;
-                        parameters.Action.IsControlsEnabled = value => IsNoGameRunning = value;
+                        parameters.Action.IsControlsEnabled = value => IsNoGameRunning = false;
 
                         if (string.IsNullOrEmpty(versionJson.InheritsFrom))
                         {
@@ -502,14 +516,14 @@ public class MainWindowViewModel : ViewModelBase
                 ProcessStartInfo proc;
                 proc = new ProcessStartInfo
                 {
-                    UseShellExecute = false,                    
+                    UseShellExecute = false,
                     RedirectStandardOutput = true,
                     RedirectStandardError = true,
                     CreateNoWindow = true,
                     FileName = Path.GetFullPath(Path.Combine(SettingsService.Instance.MinecraftForlderPath, javaPath)),
                     StandardErrorEncoding = Encoding.UTF8,
                     WorkingDirectory = Path.GetDirectoryName(Path.Combine(SettingsService.Instance.MinecraftForlderPath, javaPath)),
-                    Arguments = arguments
+                    Arguments = arguments + additionalArgs
                 };
 
                 Process minecraft = new()
@@ -571,7 +585,8 @@ public class MainWindowViewModel : ViewModelBase
 
             }
             catch (Exception ex)
-            {              
+            {
+                IsNoGameRunning = true;
                 OpenErrorWindow(ex);
             }
         });
@@ -840,16 +855,20 @@ public class MainWindowViewModel : ViewModelBase
 
     }
 
-    private ServerPanelModel CreateServerPanel(string name)
+    private ServerPanelModel CreateServerPanel(string name, string address, string clientName)
     {
-        ServerPanelModel serverPanelModel = new(name, "Wait for update...", "No players.","-/-");
+        ServerPanelModel serverPanelModel = new(name, "Wait for update...", "No players.","-/-", address, clientName);
+
+        if (SettingsService.Instance.ServerAutoConnectLinks.ContainsKey(name))
+            serverPanelModel.UserClientName = SettingsService.Instance.ServerAutoConnectLinks[name];
 
         System.Timers.Timer timeoutTimer = new System.Timers.Timer(30000);
 
         timeoutTimer.Elapsed += (object? source, ElapsedEventArgs e) => 
         { 
             serverPanelModel.Status = $"{serverPanelModel.Name}: Offline"; 
-            serverPanelModel.Players = "-/-"; 
+            serverPanelModel.Players = "-/-";
+            serverPanelModel.Tip = "Server timeout.";
         };
         timeoutTimer.Start();
 
@@ -874,6 +893,56 @@ public class MainWindowViewModel : ViewModelBase
         return serverPanelModel;
     }
 
+    public void OnServerPanelClick(ServerPanelModel server)
+    {
+        if (string.IsNullOrWhiteSpace(server?.Name))
+            return;
+
+        if (SettingsService.Instance.ServerAutoConnectLinks.ContainsKey(server.Name))
+        {
+            var downloadedVersion = DownloadedVersions.FirstOrDefault(x => string.Equals(x.Version, SettingsService.Instance.ServerAutoConnectLinks[server.Name], StringComparison.Ordinal));
+
+            if (downloadedVersion != null)
+            {
+                DownloadedIndex = DownloadedVersions.IndexOf(downloadedVersion);
+                StartMinecraft($" -server {server.Address}");
+                return;
+            }
+        }
+
+        if (!string.IsNullOrWhiteSpace(server.ClientName))
+        {
+            var downloadedVersion = DownloadedVersions.FirstOrDefault(x => string.Equals(x.Version, server.ClientName, StringComparison.Ordinal));
+
+            if (downloadedVersion != null)
+            {
+                DownloadedIndex = DownloadedVersions.IndexOf(downloadedVersion);
+                StartMinecraft($" -server {server.Address}");
+                return;
+            }
+        }
+
+        //version not found
+        Debug.WriteLine("Version not found, or not set on server!");
+    }
+
+    public void SetNewPreferredVersion(ServerPanelModel server)
+    {
+        SettingsService.Instance.ServerAutoConnectLinks.Add(server.Name, DownloadedVersion?.Version);
+        server.UserClientName = DownloadedVersion?.Version;
+        SettingsService.SaveSettings();
+    }
+
+    public void ResetPreferredVersion(ServerPanelModel server)
+    {
+        if (SettingsService.Instance.ServerAutoConnectLinks.ContainsKey(server.Name))
+        {
+            SettingsService.Instance.ServerAutoConnectLinks.Remove(server.Name);
+            server.UserClientName = string.Empty;
+            SettingsService.SaveSettings();
+        }
+    }
+
     public void OnClosing(object sender, CancelEventArgs args)
     {
         _tokenSource.Cancel();

+ 3 - 3
VeloeMinecraftLauncher/ViewModels/SettingsWindowViewModel.cs

@@ -65,14 +65,14 @@ public class SettingsWindowViewModel : ViewModelBase
         this.RaisePropertyChanged(nameof(SetMinecraftFolder));
     }
 
-    public void SaveSettingsAndClose(Window window)
+    public void SaveSettingsAndClose(object window)
     {
         SettingsService.Instance = (SettingsSerializable)Settings.Clone();
         SettingsService.SaveSettings();
         ((Window)window).Close();
     }
 
-    public void OpenMinecraftPathDialog(Window window)
+    public void OpenMinecraftPathDialog(object window)
     {
         Task.Run(async() =>
         {
@@ -97,7 +97,7 @@ public class SettingsWindowViewModel : ViewModelBase
         });
     }
 
-    public void OpenJavaPathDialog(Window window)
+    public void OpenJavaPathDialog(object window)
     {
         Task.Run(async() =>
         {

+ 71 - 25
VeloeMinecraftLauncher/Views/MainWindow.axaml

@@ -77,7 +77,8 @@
 					<TabItem
 						Header="Servers"
 						VerticalContentAlignment="Center">
-						<ItemsControl 
+						<ItemsControl
+							Name="ServerPanelsControls"
 							ItemsSource="{Binding ServerPanels}">
 							<ItemsControl.ItemsPanel>
 								<ItemsPanelTemplate>
@@ -85,38 +86,83 @@
 								</ItemsPanelTemplate>
 							</ItemsControl.ItemsPanel>
 							<ItemsControl.ItemTemplate>
-								<DataTemplate DataType="m:ServerPanelModel">
-									<Panel
+								<DataTemplate 
+									x:CompileBindings="True" 
+									DataType="m:ServerPanelModel">
+									<Button
 										VerticalAlignment="Top"
 										HorizontalAlignment="Stretch"
 										Height="75"
 										Width="150"
-										Margin="0 0 10 10">
-										<Border
-											Background="Black"
-											Opacity="0.2"
-											CornerRadius="15"/>
+										Margin="0 0 10 10"
+										CornerRadius="15"
+										Command="{Binding $parent[ItemsControl].((vm:MainWindowViewModel)DataContext).OnServerPanelClick}" 
+										CommandParameter="{Binding }"
+										IsEnabled="{Binding $parent[ItemsControl].((vm:MainWindowViewModel)DataContext).IsStartButtonEnabled}">
+										<Button.ContextMenu>
+											<ContextMenu>
+												<MenuItem 
+													Header="Override with current"
+													Command="{Binding #ServerPanelsControls((vm:MainWindowViewModel)DataContext).SetNewPreferredVersion}"
+													CommandParameter="{Binding }"/>
+												<MenuItem
+													Header="Reset to default"
+													IsEnabled="{Binding IsResetable}"
+													Command="{Binding #ServerPanelsControls((vm:MainWindowViewModel)DataContext).ResetPreferredVersion}"
+													CommandParameter="{Binding }"/>
+											</ContextMenu>
+										</Button.ContextMenu>
+										<Button.Background>
+											<SolidColorBrush Color="Black" Opacity="0.275"/>
+										</Button.Background>
 										<ToolTip.Tip>
-											<TextBlock 
+											<TextBlock
 												Text="{Binding Tip}"
 												TextWrapping="Wrap"/>
 										</ToolTip.Tip>
-										<UniformGrid
-											Columns="1"
-											Rows="2"
-											VerticalAlignment="Center"
-											HorizontalAlignment="Center">
-											<TextBlock
-												VerticalAlignment="Center"
-												HorizontalAlignment="Center"
-												Text="{Binding Status}"/>
-											<TextBlock
+										<Button.Content>
+											<UniformGrid
+												Opacity="1"
+												Columns="1"
+												Rows="2"
 												VerticalAlignment="Center"
-												HorizontalAlignment="Center"
-												FontSize="20"
-												Text="{Binding Players}"/>
-										</UniformGrid>
-									</Panel>
+												HorizontalAlignment="Center">
+												<TextBlock
+													VerticalAlignment="Center"
+													HorizontalAlignment="Center"
+													Text="{Binding Status}"
+													Opacity="1"/>
+												<TextBlock
+													VerticalAlignment="Center"
+													HorizontalAlignment="Center"
+													FontSize="20"
+													Opacity="1"
+													Text="{Binding Players}"/>
+											</UniformGrid>
+										</Button.Content>
+										<Button.Styles>
+											<Style Selector="Button:pointerover /template/ ContentPresenter">
+												<Setter	Property="Background">
+													<SolidColorBrush Color="Black" Opacity="0.375"/>
+												</Setter>
+											</Style>
+											<Style Selector="Button:pressed /template/ ContentPresenter">
+												<Setter	Property="Background">
+													<SolidColorBrush Color="Black" Opacity="0.325"/>
+												</Setter>
+											</Style>
+											<Style Selector="Button:disabled /template/ ContentPresenter">
+												<Setter	Property="Background">
+													<SolidColorBrush Color="Black" Opacity="0.175"/>
+												</Setter>
+											</Style>
+											<Style Selector="Button:disabled TextBlock">
+												<Setter Property="Foreground">
+													<SolidColorBrush Color="White" Opacity="2"/>
+												</Setter>
+											</Style>
+										</Button.Styles>
+									</Button>
 								</DataTemplate>
 							</ItemsControl.ItemTemplate>			
 						</ItemsControl>
@@ -269,7 +315,7 @@
 					</TextBlock>
 					<Button
 						Content="{Binding StartButton}"
-						Command="{Binding StartMinecraft}"
+						Command="{Binding StartMinecraft}" 
 						IsEnabled="{Binding IsStartButtonEnabled}">
 					</Button>
 				</StackPanel>