From 1a14beda3ac954cc0ea7bbed476c9fa316abe3d9 Mon Sep 17 00:00:00 2001 From: femsci Date: Mon, 6 May 2024 12:40:10 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=A5=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../{ => Access}/IResolver.cs | 5 ++- src/Nyanlabs.Pubresolv/DocumentResolver.cs | 41 +++++++++++++++++++ src/Nyanlabs.Pubresolv/Pubresolv.cs | 4 +- 3 files changed, 47 insertions(+), 3 deletions(-) rename src/Nyanlabs.Pubresolv/{ => Access}/IResolver.cs (55%) create mode 100644 src/Nyanlabs.Pubresolv/DocumentResolver.cs diff --git a/src/Nyanlabs.Pubresolv/IResolver.cs b/src/Nyanlabs.Pubresolv/Access/IResolver.cs similarity index 55% rename from src/Nyanlabs.Pubresolv/IResolver.cs rename to src/Nyanlabs.Pubresolv/Access/IResolver.cs index f91038b..a804d4e 100644 --- a/src/Nyanlabs.Pubresolv/IResolver.cs +++ b/src/Nyanlabs.Pubresolv/Access/IResolver.cs @@ -1,9 +1,10 @@ using System.Net; -namespace Nyanlabs.Pubresolv; +namespace Nyanlabs.Pubresolv.Access; -public interface IResolver +public interface IAccessor { public Task Resolve(Doi doi); + public string Host { get; } public Task Authenticate(ICredentials credentials); } diff --git a/src/Nyanlabs.Pubresolv/DocumentResolver.cs b/src/Nyanlabs.Pubresolv/DocumentResolver.cs new file mode 100644 index 0000000..8ccbd3f --- /dev/null +++ b/src/Nyanlabs.Pubresolv/DocumentResolver.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Reflection; +using System.Threading.Tasks; +using Nyanlabs.Pubresolv.Access; + +namespace Nyanlabs.Pubresolv; + +public class DocumentResolver : IDisposable +{ + private readonly HttpClient _cli = new(); + + public async Task Resolve(Doi doi) + { + var resp = await _cli.GetAsync(new Uri($"https://doi.org/{doi}")); + resp.EnsureSuccessStatusCode(); + Uri? redirect = resp.Headers.Location ?? throw new DataException("Cannot resolve DOI."); + return Resolve(redirect); + } + + public IAccessor Resolve(Uri uri) + { + string host = uri.Host; + var accessor = Pubresolv.GetResolvers().SingleOrDefault(s => s.Host.Equals(host, StringComparison.OrdinalIgnoreCase)); + + if (accessor is null) + { + throw new DataException("This URI does not have a bound accessor."); + } + + return accessor; + } + + public void Dispose() + { + GC.SuppressFinalize(this); + _cli.Dispose(); + } +} diff --git a/src/Nyanlabs.Pubresolv/Pubresolv.cs b/src/Nyanlabs.Pubresolv/Pubresolv.cs index ca7fd1c..52ad547 100644 --- a/src/Nyanlabs.Pubresolv/Pubresolv.cs +++ b/src/Nyanlabs.Pubresolv/Pubresolv.cs @@ -1,8 +1,10 @@ +using Nyanlabs.Pubresolv.Access; + namespace Nyanlabs.Pubresolv; public class Pubresolv { - public ICollection GetResolvers() + public static ICollection GetResolvers() { throw new NotImplementedException(); }