Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": []
}
2 changes: 2 additions & 0 deletions SS14.Launcher/Assets/Locale/en-US/text.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,8 @@ region-short-south-america-west = SA West
## Strings for the "servers" tab

tab-servers-title = Servers
tab-servers-classic-title = Classic Servers
tab-servers-classic-desc = All servers listed here connect via the BYOND client.
tab-servers-refresh = Refresh
filters = Filters ({ $filteredServers } / { $totalServers })
tab-servers-search-watermark = Search For Servers…
Expand Down
227 changes: 227 additions & 0 deletions SS14.Launcher/Models/ServerStatus/ClassicServerListCache.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Serilog;
using Splat;
using SS14.Launcher.Utility;

namespace SS14.Launcher.Models.ServerStatus;

public sealed class ClassicServerListCache
{
private readonly HttpClient _http;
private readonly ObservableCollection<ClassicServerStatusData> _allServers = new();

public ReadOnlyObservableCollection<ClassicServerStatusData> AllServers { get; }

public ClassicServerListCache()
{
_http = Locator.Current.GetRequiredService<HttpClient>();
AllServers = new ReadOnlyObservableCollection<ClassicServerStatusData>(_allServers);
}

public async Task Refresh()
{
try
{
var response = await _http.GetStringAsync("http://www.byond.com/games/exadv1/spacestation13?format=text");
// Log.Information("BYOND Response: {Response}", response);
await File.WriteAllTextAsync("byond_dump.txt", response);
var servers = ParseByondResponse(response);

Avalonia.Threading.Dispatcher.UIThread.Post(() =>
{
_allServers.Clear();
foreach (var server in servers)
{
_allServers.Add(server);
}
});
}
catch (Exception e)
{
Log.Error(e, "Failed to fetch Classic SS13 server list.");
}
}

private List<ClassicServerStatusData> ParseByondResponse(string response)
{
var list = new List<ClassicServerStatusData>();
using var reader = new StringReader(response);

string? line;
string? currentName = null;
string? currentUrl = null;
string? currentStatus = null;
int currentPlayers = 0;

// Simple state machine to parse the text format
// The format uses 'world/ID' blocks for servers.

bool inServerBlock = false;

while ((line = reader.ReadLine()) != null)
{
var trimmed = line.Trim();
if (string.IsNullOrWhiteSpace(trimmed)) continue;

if (trimmed.StartsWith("world/"))
{
// If we were parsing a server, save it
if (inServerBlock && currentUrl != null)
{
// Name might be missing, try to extract from status or use URL
var name = currentName ?? ExtractNameFromStatus(currentStatus) ?? "Unknown Server";
var roundTime = ExtractRoundTimeFromStatus(currentStatus);
list.Add(new ClassicServerStatusData(name, currentUrl, currentPlayers, CleanStatus(currentStatus, name) ?? "", roundTime ?? "In-Lobby"));
}

// Reset for new server
inServerBlock = true;
currentName = null;
currentUrl = null;
currentStatus = null;
currentPlayers = 0;
}
else if (inServerBlock)
{
if (trimmed.StartsWith("name ="))
{
currentName = ParseStringValue(trimmed);
}
else if (trimmed.StartsWith("url ="))
{
currentUrl = ParseStringValue(trimmed);
}
else if (trimmed.StartsWith("status ="))
{
currentStatus = ParseStringValue(trimmed);
}
else if (trimmed.StartsWith("players = list("))
{
// "players = list("Bob","Alice")"
// Just count the commas + 1, correcting for empty list "list()"
var content = trimmed.Substring("players = list(".Length);
if (content.EndsWith(")"))
{
content = content.Substring(0, content.Length - 1);
if (string.IsNullOrWhiteSpace(content))
{
currentPlayers = 0;
}
else
{
// A simple Count(',') + 1 is risky if names contain commas, but usually they are quoted.
// However, parsing full CSV is safer but 'Splitting by ",' might be enough?
// Let's iterate and count quoted segments.
// Or simpler: Splitting by ',' is mostly fine for SS13 ckeys.
currentPlayers = content.Split(',').Length;
}
}
}
else if (trimmed.StartsWith("players ="))
{
// Fallback for simple number if ever used
var parts = trimmed.Split('=');
if (parts.Length > 1 && int.TryParse(parts[1].Trim(), out var p))
{
currentPlayers = p;
}
}
}
}

// Add the last one if exists
if (inServerBlock && currentUrl != null)
{
var name = currentName ?? ExtractNameFromStatus(currentStatus) ?? "Unknown Server";
var roundTime = ExtractRoundTimeFromStatus(currentStatus);
list.Add(new ClassicServerStatusData(name, currentUrl, currentPlayers, CleanStatus(currentStatus, name) ?? "", roundTime ?? "In-Lobby"));
}

return list;
}

private string? ExtractRoundTimeFromStatus(string? status)
{
if (string.IsNullOrEmpty(status)) return null;

// Try to match "Round time: <b>00:07</b>" or similar
var match = System.Text.RegularExpressions.Regex.Match(status, @"Round\s+time:\s+(?:<b>)?(\d{1,2}:\d{2})(?:</b>)?", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
if (match.Success)
{
return match.Groups[1].Value;
}
return null;
}

private string? ExtractNameFromStatus(string? status)
{
if (string.IsNullOrEmpty(status)) return null;
// Usually starts with <b>Name</b>
var match = System.Text.RegularExpressions.Regex.Match(status, @"<b>(.*?)</b>");
if (match.Success)
{
var raw = match.Groups[1].Value;
// Remove nested tags if any
var clean = System.Text.RegularExpressions.Regex.Replace(raw, "<.*?>", String.Empty);
return System.Net.WebUtility.HtmlDecode(clean);
}
return null;
}

private string? CleanStatus(string? status, string? nameToRemove)
{
if (string.IsNullOrEmpty(status)) return null;

var s = status.Replace("<br>", "\n").Replace("<br/>", "\n").Replace("<br />", "\n");
// Remove tags
s = System.Text.RegularExpressions.Regex.Replace(s, "<.*?>", String.Empty);

// Decode HTML
s = System.Net.WebUtility.HtmlDecode(s);

if (nameToRemove != null && s.StartsWith(nameToRemove))
{
s = s.Substring(nameToRemove.Length);
}

// Clean artifacts
char[] trims = { ' ', '\t', '\n', '\r', ']', ')', '-', '—', ':' };
s = s.TrimStart(trims).Trim();

// Reduce multiple newlines
s = System.Text.RegularExpressions.Regex.Replace(s, @"\n\s+", "\n");
s = System.Text.RegularExpressions.Regex.Replace(s, @"\n{3,}", "\n\n");

return s;
}

private string ParseStringValue(string line)
{
// format: key = "value"
var idx = line.IndexOf('"');
if (idx == -1) return string.Empty;
var lastIdx = line.LastIndexOf('"');
if (lastIdx <= idx) return string.Empty;

// Extract content inside quotes
var inner = line.Substring(idx + 1, lastIdx - idx - 1);

// Unescape BYOND/C string escapes
// \" -> "
// \n -> newline
// \\ -> \
// The most critical one is \n showing up as literal \n in UI.

// Simple manual unescape for common sequences
return inner.Replace("\\\"", "\"")
.Replace("\\n", "\n")
.Replace("\\\\", "\\")
.Replace("\\t", "\t");
}
}
21 changes: 21 additions & 0 deletions SS14.Launcher/Models/ServerStatus/ClassicServerStatusData.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System.Collections.Generic;

namespace SS14.Launcher.Models.ServerStatus;

public class ClassicServerStatusData
{
public string Name { get; set; } = string.Empty;
public string Address { get; set; } = string.Empty;
public int PlayerCount { get; set; }
public string Status { get; set; } = string.Empty;
public string RoundTime { get; set; } = string.Empty;

public ClassicServerStatusData(string name, string address, int playerCount, string status, string roundTime)
{
Name = name;
Address = address;
PlayerCount = playerCount;
Status = status;
RoundTime = roundTime;
}
}
1 change: 1 addition & 0 deletions SS14.Launcher/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ private static AppBuilder BuildAvaloniaApp(DataManager cfg)
locator.RegisterConstant(authApi);
locator.RegisterConstant(hubApi);
locator.RegisterConstant(new ServerListCache());
locator.RegisterConstant(new ClassicServerListCache());
locator.RegisterConstant(loginManager);
locator.RegisterConstant(overrideAssets);
locator.RegisterConstant(launcherInfo);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
using System;
using System.Diagnostics;
using Microsoft.Win32;
using ReactiveUI;
using SS14.Launcher;
using SS14.Launcher.Localization;
using SS14.Launcher.Models.ServerStatus;
using SS14.Launcher.ViewModels;

namespace SS14.Launcher.ViewModels.MainWindowTabs;

public class ClassicServerEntryViewModel : ViewModelBase
{
private readonly ClassicServerStatusData _server;

public string Name => _server.Name;
public string Address => _server.Address;
public string PlayerCount => _server.PlayerCount.ToString();
public string Status => _server.Status;
public string RoundTime => _server.RoundTime;

private bool _isExpanded;
public bool IsExpanded
{
get => _isExpanded;
set => this.RaiseAndSetIfChanged(ref _isExpanded, value);
}

public ReactiveCommand<System.Reactive.Unit, System.Reactive.Unit> ConnectCommand { get; }

public ClassicServerEntryViewModel(ClassicServerStatusData server)
{
_server = server;

ConnectCommand = ReactiveCommand.Create(Connect);
}

private void Connect()
{
if (IsByondInstalled())
{
Helpers.OpenUri(new Uri(_server.Address));
}
else
{
// Prompt to download
// We can use the native MessageBox helper from Helpers if available or just open the link.
// Following the prompt instructions mostly literally: "prompted to install it first by going to this link"

// On Windows we can use the MessageBox to be nicer.
// NOTE: Helper MessageBox returns int, 1 is usually OK.
if (OperatingSystem.IsWindows())
{
var res = Helpers.MessageBoxHelper(
"BYOND not detected. You need the BYOND client to play Space Station 13. Go to download page?",
"BYOND Missing",
0x00000004 | 0x00000030); // MB_YESNO | MB_ICONWARNING

if (res == 6) // IDYES
{
Helpers.OpenUri(new Uri("https://www.byond.com/download/"));
}
}
else
{
// Non-windows, just open the link? Or maybe they have it via Wine?
// For now, let's open the link if we can't be sure, or maybe just try launching it?
// The prompt was "Check if they have BYOND... If not... prompt".
// Since I can't check on Linux easily, I'll assume they might not have it if I can't check.
// But actually, opening the URI is the best 'try'.
// Let's just try to open it on non-windows.
Helpers.OpenUri(new Uri(_server.Address));
}
}
}

private bool IsByondInstalled()
{
if (!OperatingSystem.IsWindows())
{
// On Linux/Mac, we can't easily check for BYOND (usually running under Wine).
// We'll return true to let the OS/Wine try to handle the protocol.
return true;
}

try
{
// Check for BYOND in Registry
// HKCU\Software\Dantom\BYOND is the standard key.
using var key = Registry.CurrentUser.OpenSubKey(@"Software\Dantom\BYOND");
return key != null;
}
catch
{
return false;
}
}
}
Loading
Loading