todo: wenn neuer mod aufgerufen wird, soll die zurückfunktion deaktviert sein oder so das sie den mod mit aktualisiert zu dem der davor ausgewählt war (:
667 lines
28 KiB
C#
667 lines
28 KiB
C#
using Avalonia.Media.Imaging; // <— für Bitmap
|
|
using Avalonia.Threading; // UI Thread
|
|
using Markdig;
|
|
using Markdig.Extensions.AutoIdentifiers;
|
|
using ReactiveUI;
|
|
using Splat.ModeDetection;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Collections.ObjectModel;
|
|
using System.Diagnostics;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Net;
|
|
using System.Net.Http;
|
|
using System.Net.Sockets;
|
|
using System.Reactive;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
using System.Text.RegularExpressions;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Valheim_Dashboard.Models;
|
|
|
|
namespace Valheim_Dashboard.ViewModels
|
|
{
|
|
public class ThunderstoreViewModel : ViewModelBase
|
|
{
|
|
private int _currentPage = 1;
|
|
private bool _hasMore = true;
|
|
private bool _isLoading;
|
|
private bool _inFlight;
|
|
private readonly ListFooterItem _footer = new();
|
|
// Index aller Mods, um Duplicates zu vermeiden
|
|
private static string MakeKey(string ns, string name) => $"{ns}/{name}";
|
|
private readonly Dictionary<string, StoreModInfo> _modIndex = new(StringComparer.OrdinalIgnoreCase);
|
|
|
|
|
|
// -------- HTTP Performance & Robustheit --------
|
|
private static readonly SocketsHttpHandler _httpHandler = new()
|
|
{
|
|
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.Brotli,
|
|
ConnectTimeout = TimeSpan.FromSeconds(5),
|
|
PooledConnectionLifetime = TimeSpan.FromMinutes(2),
|
|
MaxConnectionsPerServer = 8,
|
|
UseProxy = false,
|
|
ConnectCallback = async (ctx, ct) =>
|
|
{
|
|
var host = ctx.DnsEndPoint!.Host;
|
|
var port = ctx.DnsEndPoint!.Port;
|
|
IPAddress[] addrs = await Dns.GetHostAddressesAsync(host, ct).ConfigureAwait(false);
|
|
var addr = addrs.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork);
|
|
if (addr.Equals(default(IPAddress))) addr = addrs.First();
|
|
var socket = new Socket(addr.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
|
|
await socket.ConnectAsync(new IPEndPoint(addr, port), ct).ConfigureAwait(false);
|
|
return new NetworkStream(socket, ownsSocket: true);
|
|
}
|
|
};
|
|
|
|
// HTTP/1.1 erzwingen
|
|
private readonly HttpClient _http = new(_httpHandler)
|
|
{
|
|
Timeout = TimeSpan.FromSeconds(15),
|
|
DefaultRequestVersion = HttpVersion.Version11,
|
|
DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact
|
|
};
|
|
|
|
private readonly ThunderstoreApiClient _api;
|
|
public ModDetailsViewModel ModDetails { get; }
|
|
|
|
// Icon-Download Throttling
|
|
private static readonly SemaphoreSlim _iconGate = new(6);
|
|
|
|
private string? _searchText;
|
|
public string? SearchText
|
|
{
|
|
get => _searchText;
|
|
set => this.RaiseAndSetIfChanged(ref _searchText, value);
|
|
}
|
|
|
|
public ReactiveCommand<Unit, Unit> RunSearchCommand { get; }
|
|
public ReactiveCommand<Unit, Unit> ClearSearchCommand { get; }
|
|
|
|
public ThunderstoreViewModel()
|
|
{
|
|
_http.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
|
_http.DefaultRequestHeaders.UserAgent.ParseAdd("ValheimDashboard/1.0");
|
|
|
|
_api = new ThunderstoreApiClient(_http);
|
|
ModDetails = new ModDetailsViewModel(_api);
|
|
|
|
Mods.CollectionChanged += (_, __) => this.RaisePropertyChanged(nameof(ModsWithFooter));
|
|
|
|
LoadNextPageCommand = ReactiveCommand.CreateFromTask(() => LoadNextPageAsync(prefetchNext: false));
|
|
InstallModCommand = ReactiveCommand.CreateFromTask<StoreModInfo>(InstallModAsync);
|
|
OpenPageCommand = ReactiveUI.ReactiveCommand.Create<string>(OpenPage);
|
|
OpenModCommand = ReactiveUI.ReactiveCommand.Create<StoreModInfo>(m => SelectedMod = m);
|
|
|
|
RunSearchCommand = ReactiveCommand.CreateFromTask(RunSearchAsync);
|
|
ClearSearchCommand = ReactiveCommand.CreateFromTask(async () =>
|
|
{
|
|
if (!string.IsNullOrWhiteSpace(SearchText))
|
|
{
|
|
SearchText = "";
|
|
await RunSearchAsync();
|
|
}
|
|
});
|
|
|
|
_ = LoadNextPageAsync(prefetchNext: true);
|
|
}
|
|
|
|
private async Task RunSearchAsync()
|
|
{
|
|
_currentPage = 1;
|
|
HasMore = true;
|
|
|
|
await Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(() =>
|
|
{
|
|
Mods.Clear();
|
|
_modIndex.Clear(); // <— NEU
|
|
});
|
|
|
|
this.RaisePropertyChanged(nameof(ModsWithFooter));
|
|
await LoadNextPageAsync(prefetchNext: true);
|
|
}
|
|
|
|
private string BuildListingUrl()
|
|
{
|
|
var baseUrl = $"https://thunderstore.io/api/cyberstorm/listing/valheim/?deprecated=False&nsfw=False&ordering=top-rated&included_categories=17&page={_currentPage}";
|
|
if (!string.IsNullOrWhiteSpace(SearchText))
|
|
baseUrl += $"&q={Uri.EscapeDataString(SearchText)}";
|
|
return baseUrl;
|
|
}
|
|
|
|
public ObservableCollection<StoreModInfo> Mods { get; } = new();
|
|
public System.Collections.Generic.IEnumerable<object> ModsWithFooter
|
|
=> Mods.Cast<object>().Concat(new object[] { _footer });
|
|
|
|
private StoreModInfo? _selectedMod;
|
|
public StoreModInfo? SelectedMod
|
|
{
|
|
get => _selectedMod;
|
|
set
|
|
{
|
|
this.RaiseAndSetIfChanged(ref _selectedMod, value);
|
|
this.RaisePropertyChanged(nameof(HasSelection));
|
|
_ = LoadDetailsForSelectionAsync(value);
|
|
}
|
|
}
|
|
public bool HasSelection => _selectedMod != null;
|
|
|
|
private async Task LoadDetailsForSelectionAsync(StoreModInfo? mod)
|
|
{
|
|
if (mod == null) return;
|
|
await ModDetails.LoadAsync(mod.Namespace, mod.PackageName);
|
|
}
|
|
|
|
public bool IsLoading
|
|
{
|
|
get => _isLoading;
|
|
set
|
|
{
|
|
this.RaiseAndSetIfChanged(ref _isLoading, value);
|
|
this.RaisePropertyChanged(nameof(IsFooterVisible));
|
|
this.RaisePropertyChanged(nameof(IsListEndVisible));
|
|
}
|
|
}
|
|
|
|
public bool HasMore
|
|
{
|
|
get => _hasMore;
|
|
set
|
|
{
|
|
this.RaiseAndSetIfChanged(ref _hasMore, value);
|
|
this.RaisePropertyChanged(nameof(IsFooterVisible));
|
|
this.RaisePropertyChanged(nameof(IsListEndVisible));
|
|
}
|
|
}
|
|
|
|
public bool IsFooterVisible => IsLoading || !HasMore;
|
|
public bool IsListEndVisible => !IsLoading && !HasMore;
|
|
|
|
public ReactiveCommand<Unit, Unit> LoadNextPageCommand { get; }
|
|
public ReactiveCommand<StoreModInfo, Unit> InstallModCommand { get; }
|
|
public ReactiveCommand<string, Unit> OpenPageCommand { get; }
|
|
public ReactiveCommand<StoreModInfo, Unit> OpenModCommand { get; }
|
|
|
|
public async Task LoadNextPageAsync(bool prefetchNext = false)
|
|
{
|
|
if (_inFlight || !HasMore) return;
|
|
|
|
_inFlight = true;
|
|
IsLoading = true;
|
|
|
|
try
|
|
{
|
|
var req = new HttpRequestMessage(HttpMethod.Get, BuildListingUrl())
|
|
{
|
|
Version = HttpVersion.Version11,
|
|
VersionPolicy = HttpVersionPolicy.RequestVersionExact
|
|
};
|
|
|
|
using var res = await _http.SendAsync(req, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
|
|
res.EnsureSuccessStatusCode();
|
|
var json = await res.Content.ReadAsStringAsync().ConfigureAwait(false);
|
|
|
|
using var doc = JsonDocument.Parse(json);
|
|
var root = doc.RootElement;
|
|
|
|
if (root.TryGetProperty("results", out var results))
|
|
{
|
|
var buffer = new System.Collections.Generic.List<(string ns, string name, string? desc, string? iconUrl)>();
|
|
|
|
foreach (var el in results.EnumerateArray())
|
|
{
|
|
var name = el.GetProperty("name").GetString() ?? "";
|
|
var ns = el.GetProperty("namespace").GetString() ?? "";
|
|
var desc = el.TryGetProperty("description", out var d) ? d.GetString() : null;
|
|
var iconUrl = el.TryGetProperty("icon_url", out var i) ? i.GetString() : null;
|
|
buffer.Add((ns, name, desc, iconUrl));
|
|
}
|
|
|
|
// Auf dem UI-Thread Mods einfügen/aktualisieren und Index pflegen
|
|
var newForIcons = new System.Collections.Generic.List<(StoreModInfo mod, string iconUrl)>();
|
|
|
|
await Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(() =>
|
|
{
|
|
foreach (var (ns, name, desc, iconUrl) in buffer)
|
|
{
|
|
var key = MakeKey(ns, name);
|
|
if (_modIndex.TryGetValue(key, out var existing))
|
|
{
|
|
// Bereits vorhanden (ggf. temporär) -> nur anreichern
|
|
if (!string.IsNullOrWhiteSpace(desc) && string.IsNullOrWhiteSpace(existing.Description))
|
|
existing.Description = desc!;
|
|
existing.IsTemporary = false;
|
|
|
|
if (!string.IsNullOrWhiteSpace(iconUrl) && existing.Icon is null)
|
|
newForIcons.Add((existing, iconUrl!));
|
|
}
|
|
else
|
|
{
|
|
// Neu hinzufügen
|
|
var mod = new StoreModInfo
|
|
{
|
|
Namespace = ns,
|
|
PackageName = name,
|
|
Name = $"{ns}-{name}",
|
|
Description = desc ?? "",
|
|
Url = $"https://thunderstore.io/c/valheim/p/{ns}/{name}/"
|
|
};
|
|
Mods.Add(mod);
|
|
_modIndex[key] = mod;
|
|
|
|
if (!string.IsNullOrWhiteSpace(iconUrl))
|
|
newForIcons.Add((mod, iconUrl!));
|
|
}
|
|
}
|
|
});
|
|
|
|
// Icons asynchron (throttled) laden
|
|
foreach (var (mod, iconUrl) in newForIcons)
|
|
_ = LoadIconThrottledAsync(mod, iconUrl);
|
|
|
|
_currentPage++;
|
|
HasMore = root.TryGetProperty("next", out var next) && !string.IsNullOrWhiteSpace(next.GetString());
|
|
}
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
Debug.WriteLine("[Thunderstore] Ladefehler: The operation was canceled.");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Debug.WriteLine($"[Thunderstore] Ladefehler: {ex.Message}");
|
|
}
|
|
finally
|
|
{
|
|
IsLoading = false;
|
|
_inFlight = false;
|
|
this.RaisePropertyChanged(nameof(ModsWithFooter));
|
|
}
|
|
|
|
if (prefetchNext && HasMore)
|
|
_ = LoadNextPageAsync();
|
|
}
|
|
|
|
// Throttled Icon-Loader: lädt Bytes via API (IPv4/HTTP1.1) und setzt das Bitmap direkt.
|
|
public async Task LoadIconThrottledAsync(StoreModInfo mod, string iconUrl)
|
|
{
|
|
await _iconGate.WaitAsync().ConfigureAwait(false);
|
|
try
|
|
{
|
|
var bytes = await _api.GetBytesAsync(iconUrl).ConfigureAwait(false);
|
|
using var ms = new MemoryStream(bytes);
|
|
var bmp = new Bitmap(ms);
|
|
await Dispatcher.UIThread.InvokeAsync(() => { mod.Icon = bmp; }); // <— setzt direkt die gebundene Property
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Debug.WriteLine("[Icon] load failed: " + ex.Message);
|
|
}
|
|
finally
|
|
{
|
|
_iconGate.Release();
|
|
}
|
|
}
|
|
|
|
public StoreModInfo GetOrCreateTempMod(string ns, string name, string? url = null)
|
|
{
|
|
var key = MakeKey(ns, name);
|
|
if (_modIndex.TryGetValue(key, out var existing))
|
|
return existing;
|
|
|
|
var temp = new StoreModInfo
|
|
{
|
|
Namespace = ns,
|
|
PackageName = name,
|
|
Name = $"{ns}-{name}",
|
|
Url = url ?? $"https://thunderstore.io/c/valheim/p/{ns}/{name}/",
|
|
IsTemporary = true
|
|
};
|
|
|
|
Avalonia.Threading.Dispatcher.UIThread.Post(() =>
|
|
{
|
|
Mods.Add(temp);
|
|
_modIndex[key] = temp; // <— Index pflegen
|
|
this.RaisePropertyChanged(nameof(ModsWithFooter));
|
|
});
|
|
|
|
return temp;
|
|
}
|
|
|
|
|
|
public async Task OpenPackageAsync(string ns, string name, string? url = null)
|
|
{
|
|
var hit = GetOrCreateTempMod(ns, name, url); // <— statt eigener Logik
|
|
SelectedMod = hit;
|
|
|
|
await ModDetails.LoadAsync(ns, name);
|
|
|
|
var iconUrl = ModDetails?.Package?.Latest?.Icon;
|
|
if (!string.IsNullOrWhiteSpace(iconUrl))
|
|
_ = LoadIconThrottledAsync(hit, iconUrl!);
|
|
|
|
var desc = ModDetails?.Package?.Latest?.Description;
|
|
if (!string.IsNullOrWhiteSpace(desc))
|
|
await Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(() =>
|
|
{
|
|
hit.Description = desc!;
|
|
hit.IsTemporary = false;
|
|
});
|
|
}
|
|
|
|
|
|
private async Task InstallModAsync(StoreModInfo mod)
|
|
{
|
|
Debug.WriteLine($"Installiere: {mod.Name}");
|
|
await Task.CompletedTask;
|
|
}
|
|
|
|
private void OpenPage(string? url)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(url)) return;
|
|
try
|
|
{
|
|
var psi = new ProcessStartInfo { FileName = url, UseShellExecute = true };
|
|
Process.Start(psi);
|
|
}
|
|
catch { }
|
|
}
|
|
}
|
|
|
|
// -------------------- Details-VM (unverändert zur letzten Version) --------------------
|
|
public sealed class ModDetailsViewModel : ViewModelBase
|
|
{
|
|
private readonly ThunderstoreApiClient _api;
|
|
private CancellationTokenSource? _cts;
|
|
public event Action<string>? AnchorRequested;
|
|
public event Action<string, string, string?>? OpenPackageRequested; // ns,name,url
|
|
|
|
private string _readmeHtml = "<p>Loading…</p>";
|
|
public string ReadmeHtml
|
|
{
|
|
get => _readmeHtml;
|
|
private set => this.RaiseAndSetIfChanged(ref _readmeHtml, value);
|
|
}
|
|
|
|
public ModDetailsViewModel(ThunderstoreApiClient api)
|
|
{
|
|
_api = api;
|
|
OpenUrlCommand = ReactiveCommand.Create<string?>(OpenUrl);
|
|
}
|
|
|
|
private bool _isLoading;
|
|
public bool IsLoading { get => _isLoading; set => this.RaiseAndSetIfChanged(ref _isLoading, value); }
|
|
|
|
private string _error = "";
|
|
public string Error { get => _error; set { this.RaiseAndSetIfChanged(ref _error, value); this.RaisePropertyChanged(nameof(HasError)); } }
|
|
public bool HasError => !string.IsNullOrWhiteSpace(Error);
|
|
|
|
private ThunderstorePackageExperimental? _pkg;
|
|
public ThunderstorePackageExperimental? Package { get => _pkg; set => this.RaiseAndSetIfChanged(ref _pkg, value); }
|
|
|
|
private Avalonia.Media.Imaging.Bitmap? _iconBitmap;
|
|
public Avalonia.Media.Imaging.Bitmap? IconBitmap
|
|
{
|
|
get => _iconBitmap;
|
|
set => this.RaiseAndSetIfChanged(ref _iconBitmap, value);
|
|
}
|
|
|
|
public string CategoriesJoined =>
|
|
Package?.CommunityListings is { Count: > 0 }
|
|
? string.Join(", ", Package.CommunityListings
|
|
.Where(c => c.Categories != null)
|
|
.SelectMany(c => c.Categories!)
|
|
.Distinct()
|
|
.OrderBy(s => s))
|
|
: "";
|
|
|
|
public string DependenciesJoined =>
|
|
Package?.Latest?.Dependencies is { Count: > 0 }
|
|
? string.Join(", ", Package.Latest.Dependencies!)
|
|
: "—";
|
|
|
|
public string DisplayTotalDownloads =>
|
|
Package is { TotalDownloads: > 0 } ? $"{Package!.TotalDownloads:N0} dl" : "—";
|
|
|
|
public string DisplayRating =>
|
|
Package is not null ? $"★ {Math.Max(0, Package!.RatingScore):0.0}" : "★ —";
|
|
|
|
public ReactiveCommand<string?, Unit> OpenUrlCommand { get; }
|
|
public ReactiveCommand<string?, Unit> LinkCommand { get; }
|
|
|
|
public string Readme { get; private set; }
|
|
|
|
public async Task LoadAsync(string ns, string name)
|
|
{
|
|
_cts?.Cancel();
|
|
_cts?.Dispose();
|
|
_cts = new CancellationTokenSource();
|
|
var ct = _cts.Token;
|
|
|
|
try
|
|
{
|
|
IsLoading = true;
|
|
Error = "";
|
|
Readme = "";
|
|
IconBitmap = null;
|
|
|
|
Package = await _api.GetPackageAsync(ns, name, ct);
|
|
|
|
var iconUrl = Package?.Latest?.Icon;
|
|
if (!string.IsNullOrWhiteSpace(iconUrl))
|
|
{
|
|
try
|
|
{
|
|
var bytes = await _api.GetBytesAsync(iconUrl!, ct);
|
|
using var ms = new MemoryStream(bytes);
|
|
IconBitmap = new Avalonia.Media.Imaging.Bitmap(ms);
|
|
}
|
|
catch { }
|
|
}
|
|
|
|
var ver = Package?.Latest?.VersionNumber;
|
|
if (!string.IsNullOrWhiteSpace(ver))
|
|
{
|
|
var md = await _api.GetReadmeMarkdownAsync(ns, name, ver!, ct);
|
|
ReadmeHtml = BuildHtml(md ?? "");
|
|
}
|
|
|
|
this.RaisePropertyChanged(nameof(ReadmeHtml));
|
|
this.RaisePropertyChanged(nameof(CategoriesJoined));
|
|
this.RaisePropertyChanged(nameof(DependenciesJoined));
|
|
this.RaisePropertyChanged(nameof(DisplayTotalDownloads));
|
|
this.RaisePropertyChanged(nameof(DisplayRating));
|
|
}
|
|
catch (OperationCanceledException) { }
|
|
catch (Exception ex) { Error = ex.Message; }
|
|
finally { IsLoading = false; }
|
|
}
|
|
|
|
private static string BuildHtml(string md)
|
|
{
|
|
var pipeline = new MarkdownPipelineBuilder()
|
|
.UseAdvancedExtensions()
|
|
.UseAutoIdentifiers()
|
|
.Build();
|
|
|
|
var body = Markdig.Markdown.ToHtml(md, pipeline);
|
|
|
|
var css = @"html,body{margin:0;padding:0;background:#111;color:#eaeaea;font-family:system-ui,Segoe UI,Roboto;line-height:1.6;overflow-wrap:anywhere}
|
|
a{color:#6aafe6}
|
|
img,video{max-width:100%;height:auto;display:block}
|
|
table{border-collapse:collapse;width:100%;table-layout:fixed}
|
|
th,td{border:1px solid #333;padding:.5rem;vertical-align:top;word-break:break-word}
|
|
pre,code{background:#1b1b1b}
|
|
pre{white-space:pre-wrap;word-break:break-word}
|
|
blockquote{border-left:3px solid #444;padding-left:1rem;color:#cfcfcf}";
|
|
|
|
var js = @"(function(){
|
|
window.__VD_QUEUE = window.__VD_QUEUE || [];
|
|
function post(o){ try{ __VD_QUEUE.push(JSON.stringify(o)); }catch(e){} }
|
|
function log(m){ post({type:'log', msg: (typeof m==='string'? m : JSON.stringify(m))}); }
|
|
|
|
function scrollToId(id){
|
|
try{
|
|
var el = document.getElementById(id);
|
|
if(!el){ log('anchor not found: '+id); return; }
|
|
el.scrollIntoView({block:'start'});
|
|
window.scrollBy(0,-12);
|
|
}catch(e){ log('scroll err '+e); }
|
|
}
|
|
|
|
document.addEventListener('DOMContentLoaded', function(){
|
|
log('dom-ready');
|
|
}, {once:true});
|
|
|
|
document.addEventListener('click', function(e){
|
|
var a = e.target && e.target.closest ? e.target.closest('a[href]') : null;
|
|
if(!a) return;
|
|
if(e.defaultPrevented || e.button!==0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
|
|
|
|
var href = a.getAttribute('href'); if(!href) return;
|
|
|
|
// interne Anker
|
|
if(href[0]==='#'){ e.preventDefault(); scrollToId(decodeURIComponent(href.slice(1))); return; }
|
|
|
|
var u; try{ u = new URL(href, location.href); }catch(err){ return; }
|
|
|
|
var host=(u.hostname||'').toLowerCase(), path=u.pathname||'';
|
|
var isTs = /(^|\.)thunderstore\.io$/.test(host);
|
|
// Thunderstore-Package-Links
|
|
var m = path.match(/^\/c\/valheim\/p\/([^\/]+)\/([^\/]+)(?:\/.*)?$/i) || path.match(/^\/package\/([^\/]+)\/([^\/]+)(?:\/.*)?$/i);
|
|
|
|
if(isTs && m){
|
|
e.preventDefault();
|
|
post({type:'open-package', ns:m[1], name:m[2]});
|
|
return;
|
|
}
|
|
|
|
// Externe Navigation: WebView soll navigieren, aber Host informieren
|
|
try { post({type:'external-nav', url: u.href}); } catch(_){}
|
|
// kein preventDefault -> WebView navigiert selbst
|
|
}, true);
|
|
})();";
|
|
|
|
var sb = new StringBuilder();
|
|
sb.Append("<!doctype html><html><head><meta charset='utf-8'>");
|
|
sb.Append("<meta name='viewport' content='width=device-width,initial-scale=1'/>");
|
|
sb.Append("<style>").Append(css).Append("</style></head><body>");
|
|
sb.Append(body);
|
|
sb.Append("<script>").Append(js).Append("</script></body></html>");
|
|
return sb.ToString();
|
|
}
|
|
|
|
|
|
private void OpenUrl(string? url)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(url)) return;
|
|
try { System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo { FileName = url, UseShellExecute = true }); } catch { }
|
|
}
|
|
}
|
|
|
|
// -------------------- API-Client --------------------
|
|
public sealed class ThunderstoreApiClient
|
|
{
|
|
private readonly HttpClient _http;
|
|
private readonly JsonSerializerOptions _json = new()
|
|
{
|
|
PropertyNameCaseInsensitive = true,
|
|
NumberHandling = JsonNumberHandling.AllowReadingFromString
|
|
};
|
|
|
|
public ThunderstoreApiClient(HttpClient http) => _http = http;
|
|
|
|
public async Task<byte[]> GetBytesAsync(string url, CancellationToken ct = default)
|
|
{
|
|
using var req = new HttpRequestMessage(HttpMethod.Get, url)
|
|
{
|
|
Version = HttpVersion.Version11,
|
|
VersionPolicy = HttpVersionPolicy.RequestVersionExact
|
|
};
|
|
using var res = await _http.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false);
|
|
res.EnsureSuccessStatusCode();
|
|
return await res.Content.ReadAsByteArrayAsync(ct).ConfigureAwait(false);
|
|
}
|
|
|
|
public async Task<ThunderstorePackageExperimental?> GetPackageAsync(string ns, string name, CancellationToken ct = default)
|
|
{
|
|
var url = $"https://thunderstore.io/api/experimental/package/{Uri.EscapeDataString(ns)}/{Uri.EscapeDataString(name)}/";
|
|
using var req = new HttpRequestMessage(HttpMethod.Get, url)
|
|
{
|
|
Version = HttpVersion.Version11,
|
|
VersionPolicy = HttpVersionPolicy.RequestVersionExact
|
|
};
|
|
using var res = await _http.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false);
|
|
res.EnsureSuccessStatusCode();
|
|
await using var s = await res.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);
|
|
return await JsonSerializer.DeserializeAsync<ThunderstorePackageExperimental>(s, _json, ct).ConfigureAwait(false);
|
|
}
|
|
|
|
public async Task<string> GetReadmeMarkdownAsync(string ns, string name, string version, CancellationToken ct = default)
|
|
{
|
|
var url = $"https://thunderstore.io/api/experimental/package/{Uri.EscapeDataString(ns)}/{Uri.EscapeDataString(name)}/{Uri.EscapeDataString(version)}/readme/";
|
|
using var req = new HttpRequestMessage(HttpMethod.Get, url)
|
|
{
|
|
Version = HttpVersion.Version11,
|
|
VersionPolicy = HttpVersionPolicy.RequestVersionExact
|
|
};
|
|
using var res = await _http.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false);
|
|
res.EnsureSuccessStatusCode();
|
|
await using var s = await res.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);
|
|
var data = await JsonSerializer.DeserializeAsync<ThunderstoreReadmeResponse>(s, _json, ct).ConfigureAwait(false);
|
|
return data?.Markdown ?? "";
|
|
}
|
|
}
|
|
|
|
// -------------------- Experimental-Models --------------------
|
|
public sealed class ThunderstorePackageExperimental
|
|
{
|
|
[JsonPropertyName("namespace")] public string Namespace { get; set; } = "";
|
|
[JsonPropertyName("name")] public string Name { get; set; } = "";
|
|
[JsonPropertyName("full_name")] public string FullName { get; set; } = "";
|
|
[JsonPropertyName("owner")] public string Owner { get; set; } = "";
|
|
[JsonPropertyName("package_url")] public string PackageUrl { get; set; } = "";
|
|
[JsonPropertyName("date_created")] public DateTime? DateCreated { get; set; }
|
|
[JsonPropertyName("date_updated")] public DateTime? DateUpdated { get; set; }
|
|
[JsonPropertyName("rating_score")] public double RatingScore { get; set; }
|
|
[JsonPropertyName("is_pinned")] public bool IsPinned { get; set; }
|
|
[JsonPropertyName("is_deprecated")] public bool IsDeprecated { get; set; }
|
|
[JsonPropertyName("total_downloads")] public int TotalDownloads { get; set; }
|
|
[JsonPropertyName("latest")] public PackageVersionExperimental Latest { get; set; } = new();
|
|
[JsonPropertyName("community_listings")]
|
|
public System.Collections.Generic.List<PackageListingExperimental> CommunityListings { get; set; } = new();
|
|
}
|
|
|
|
public sealed class PackageVersionExperimental
|
|
{
|
|
[JsonPropertyName("namespace")] public string Namespace { get; set; } = "";
|
|
[JsonPropertyName("name")] public string Name { get; set; } = "";
|
|
[JsonPropertyName("version_number")] public string VersionNumber { get; set; } = "";
|
|
[JsonPropertyName("full_name")] public string FullName { get; set; } = "";
|
|
[JsonPropertyName("description")] public string Description { get; set; } = "";
|
|
[JsonPropertyName("icon")] public string Icon { get; set; } = "";
|
|
[JsonPropertyName("dependencies")] public System.Collections.Generic.List<string>? Dependencies { get; set; }
|
|
[JsonPropertyName("download_url")] public string DownloadUrl { get; set; } = "";
|
|
[JsonPropertyName("downloads")] public int Downloads { get; set; }
|
|
[JsonPropertyName("date_created")] public DateTime? DateCreated { get; set; }
|
|
[JsonPropertyName("website_url")] public string WebsiteUrl { get; set; } = "";
|
|
[JsonPropertyName("is_active")] public bool IsActive { get; set; }
|
|
}
|
|
|
|
public sealed class PackageListingExperimental
|
|
{
|
|
[JsonPropertyName("has_nsfw_content")] public bool HasNsfwContent { get; set; }
|
|
[JsonPropertyName("categories")] public System.Collections.Generic.List<string>? Categories { get; set; }
|
|
[JsonPropertyName("community")] public string Community { get; set; } = "";
|
|
[JsonPropertyName("review_status")] public string ReviewStatus { get; set; } = "";
|
|
}
|
|
|
|
public sealed class ThunderstoreReadmeResponse
|
|
{
|
|
[JsonPropertyName("markdown")] public string Markdown { get; set; } = "";
|
|
}
|
|
}
|