Add missing extensions

This commit is contained in:
Kieran 2024-01-13 19:20:50 +00:00
parent bb6fba1087
commit 494f6b1e00
No known key found for this signature in database
GPG Key ID: DE71CEB3925BE941

View File

@ -1,5 +1,7 @@
using System.Net.WebSockets;
using Newtonsoft.Json;
using Nostr.Client.Identifiers;
using Nostr.Client.Json;
using Nostr.Client.Messages;
using Nostr.Client.Utils;
using NostrRelay;
@ -59,31 +61,49 @@ public static class Extensions
return new NostrProfileIdentifier(px.PubKey.ToHex(), []);
}
public static void MapNostrRelay<THandler>(this IEndpointRouteBuilder app, string path) where THandler : INostrRelay
public static async Task<NostrIdentifier?> TryParseIdentifier(string id)
{
app.MapGet(path, async ctx =>
NostrIdentifier? nout;
if ((NostrIdentifierParser.TryParse(id, out nout) && nout != default) ||
(nout = NostrBareIdentifier.Parse(id)) != default ||
(nout = await TryParseNip05(id, default)) != default)
{
if (ctx.WebSockets.IsWebSocketRequest)
return nout;
}
return default;
}
private static async Task<NostrIdentifier?> TryParseNip05(string id, CancellationToken cts)
{
try
{
using var client = new HttpClient();
if (id.Contains("@"))
{
var logger = app.ServiceProvider.GetRequiredService<ILogger<NostrRelay<THandler>>>();
var handler = app.ServiceProvider.GetRequiredService<THandler>();
try
var idSplit = id.Split("@");
var url = new Uri($"https://{idSplit[1]}/.well-known/nostr.json?name={Uri.EscapeDataString(idSplit[0])}");
var json = await client.GetStringAsync(url, cts);
var parsed = JsonConvert.DeserializeObject<NostrJson>(json);
var match = parsed?.Names?.FirstOrDefault(a => a.Key.Equals(idSplit[0], StringComparison.CurrentCultureIgnoreCase));
if (match.HasValue && !string.IsNullOrEmpty(match.Value.Value))
{
var ws = await ctx.WebSockets.AcceptWebSocketAsync();
var wsCtx = new NostrClientContext(ws, ctx.Connection.RemoteIpAddress!,
ctx.Request.Headers.UserAgent.FirstOrDefault() ?? string.Empty);
var nostrRelay = new NostrRelay<THandler>(handler, wsCtx, ctx.RequestAborted, logger);
await nostrRelay.Read();
await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, null, ctx.RequestAborted);
}
catch (Exception ex)
{
logger.LogDebug(ex.Message);
return new NostrProfileIdentifier(match.Value.Value.ToLower(), null);
}
}
});
}
catch (Exception ex)
{
//_logger.LogWarning("Failed to parse nostr address {id} {msg}", id, ex.Message);
}
return default;
}
class NostrJson
{
[JsonProperty("names")]
public Dictionary<string, string>? Names { get; init; } = new();
}
}