Skip to content
Merged
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
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project>
<PropertyGroup>
<Version>1.3.2</Version>
<Version>1.4.0</Version>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
Expand Down
4 changes: 3 additions & 1 deletion src/NoteBookmark.AIServices/ResearchService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,9 @@ private async Task SaveToFile(string prefix, string responseContent)
{
string datetime = DateTime.Now.ToString("yyyy-MM-dd_HH-mm");
string fileName = $"{prefix}_{datetime}.json";
string folderPath = "Data";
// Use the app's sandboxed data directory so this works on Android/iOS as well as desktop
string folderPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Data");
Directory.CreateDirectory(folderPath);
string filePath = Path.Combine(folderPath, fileName);
await File.WriteAllTextAsync(filePath, responseContent);
Expand Down
163 changes: 163 additions & 0 deletions src/NoteBookmark.Api.Tests/Services/PostParserClientTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging.Abstractions;
using Moq.Protected;

namespace NoteBookmark.Api.Tests.Services;

public class PostParserClientTests
{
private readonly Mock<IConfiguration> _mockConfig;
private readonly Mock<HttpMessageHandler> _mockHandler;

public PostParserClientTests()
{
_mockConfig = new Mock<IConfiguration>();
_mockHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);

// Default config setups
_mockConfig.Setup(c => c["Parser:BaseUrl"]).Returns((string?)null);
_mockConfig.Setup(c => c["Parser:ApiKey"]).Returns((string?)null);
}

private PostParserClient CreateSut(HttpClient httpClient) =>
new(httpClient, _mockConfig.Object, NullLogger<PostParserClient>.Instance);

[Fact]
public async Task ExtractContentAsync_WithDefaults_CallsDefaultUrlWithoutApiKey()
{
// Arrange
var expectedUrl = "https://azpostlight-parser.azurewebsites.net/api/parser";
var sourceUrl = "https://example.com/blog-post";

_mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(req =>
req.Method == HttpMethod.Post &&
req.RequestUri != null &&
req.RequestUri.ToString() == expectedUrl &&
!req.Headers.Contains("x-functions-key")),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("{\"content\":\"extracted blog content\"}", Encoding.UTF8, "application/json")
});

var httpClient = new HttpClient(_mockHandler.Object);
var sut = CreateSut(httpClient);

// Act
var result = await sut.ExtractContentAsync(sourceUrl);

// Assert
result.Should().Be("extracted blog content");
_mockHandler.Protected().Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(req => req.RequestUri != null && req.RequestUri.ToString() == expectedUrl),
ItExpr.IsAny<CancellationToken>());
}

[Fact]
public async Task ExtractContentAsync_WithApiKey_SendsXFunctionsKeyHeader()
{
// Arrange
var expectedUrl = "https://azpostlight-parser.azurewebsites.net/api/parser";
var sourceUrl = "https://example.com/blog-post";
var apiKey = "test-api-key-123";

_mockConfig.Setup(c => c["Parser:ApiKey"]).Returns(apiKey);

_mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(req =>
req.Method == HttpMethod.Post &&
req.RequestUri != null &&
req.RequestUri.ToString() == expectedUrl &&
req.Headers.Contains("x-functions-key") &&
string.Join("", req.Headers.GetValues("x-functions-key")) == apiKey),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("{\"content\":\"content with auth\"}", Encoding.UTF8, "application/json")
});

var httpClient = new HttpClient(_mockHandler.Object);
var sut = CreateSut(httpClient);

// Act
var result = await sut.ExtractContentAsync(sourceUrl);

// Assert
result.Should().Be("content with auth");
}

[Fact]
public async Task ExtractContentAsync_WithCustomUrl_CallsCustomUrl()
{
// Arrange
var customUrl = "https://my-custom-parser.com/api/parser";
var sourceUrl = "https://example.com/blog-post";

_mockConfig.Setup(c => c["Parser:BaseUrl"]).Returns(customUrl);

_mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(req =>
req.Method == HttpMethod.Post &&
req.RequestUri != null &&
req.RequestUri.ToString() == customUrl),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("{\"content\":\"custom url content\"}", Encoding.UTF8, "application/json")
});

var httpClient = new HttpClient(_mockHandler.Object);
var sut = CreateSut(httpClient);

// Act
var result = await sut.ExtractContentAsync(sourceUrl);

// Assert
result.Should().Be("custom url content");
}

[Fact]
public async Task ExtractContentAsync_ParserReturnsErrorCode_ReturnsNull()
{
// Arrange
var sourceUrl = "https://example.com/blog-post";

_mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.InternalServerError
});

var httpClient = new HttpClient(_mockHandler.Object);
var sut = CreateSut(httpClient);

// Act
var result = await sut.ExtractContentAsync(sourceUrl);

// Assert
result.Should().BeNull();
}
}
24 changes: 17 additions & 7 deletions src/NoteBookmark.Api/PostParserClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,22 @@
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace NoteBookmark.Api;

public class PostParserClient : IPostParserClient
{
private readonly HttpClient _httpClient;
private readonly IConfiguration _config;
private readonly ILogger<PostParserClient> _logger;

public PostParserClient(HttpClient httpClient, ILogger<PostParserClient> logger)
public PostParserClient(HttpClient httpClient, IConfiguration config, ILogger<PostParserClient> logger)
{
_httpClient = httpClient;
_config = config;
_logger = logger;
// Configure base address or default headers if needed, but since URL is fully specified we can just configure it or call it directly.
if (_httpClient.BaseAddress == null)
{
_httpClient.BaseAddress = new Uri("https://azpostlight-parser.azurewebsites.net/");
}
}

public async Task<string?> ExtractContentAsync(string url, CancellationToken cancellationToken = default)
Expand All @@ -30,7 +28,19 @@ public PostParserClient(HttpClient httpClient, ILogger<PostParserClient> logger)
{
_logger.LogInformation("Calling parser API for URL: {Url}", url);
var requestBody = new { url = url };
var response = await _httpClient.PostAsJsonAsync("parser", requestBody, cancellationToken);

var endpoint = _config["Parser:BaseUrl"] ?? "https://azpostlight-parser.azurewebsites.net/api/parser";
var apiKey = _config["Parser:ApiKey"];

using var request = new HttpRequestMessage(HttpMethod.Post, endpoint);
request.Content = JsonContent.Create(requestBody);

if (!string.IsNullOrEmpty(apiKey))
{
request.Headers.Add("x-functions-key", apiKey);
}

var response = await _httpClient.SendAsync(request, cancellationToken);

if (!response.IsSuccessStatusCode)
{
Expand Down
28 changes: 24 additions & 4 deletions src/NoteBookmark.AppHost/AppHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@

var builder = DistributedApplication.CreateBuilder(args);

var parserUrl = builder.Configuration["Parser:BaseUrl"]
?? Environment.GetEnvironmentVariable("PARSER_BASE_URL")
?? "https://azpostlight-parser.azurewebsites.net/api/parser";
var parserKey = builder.Configuration["Parser:ApiKey"]
?? Environment.GetEnvironmentVariable("PARSER_API_KEY");

// Load docker-compose environment
var compose = builder.AddDockerComposeEnvironment("docker-env");

Expand All @@ -24,12 +30,19 @@
var tables = noteStorage.AddTables("nb-tables");
var blobs = noteStorage.AddBlobs("nb-blobs");

var api = builder.AddProject<NoteBookmark_Api>("api")
var apiBuilder = builder.AddProject<NoteBookmark_Api>("api")
.WithReference(tables)
.WithReference(blobs)
.WaitFor(tables)
.WaitFor(blobs)
.PublishAsDockerComposeService((resource, service) =>
.WithEnvironment("Parser__BaseUrl", parserUrl);

if (!string.IsNullOrEmpty(parserKey))
{
apiBuilder = apiBuilder.WithEnvironment("Parser__ApiKey", parserKey);
}

var api = apiBuilder.PublishAsDockerComposeService((resource, service) =>
{
service.ContainerName = "notebookmark-api";
});
Expand Down Expand Up @@ -58,12 +71,19 @@
var tables = noteStorage.AddTables("nb-tables");
var blobs = noteStorage.AddBlobs("nb-blobs");

var api = builder.AddProject<NoteBookmark_Api>("api")
var apiBuilder = builder.AddProject<NoteBookmark_Api>("api")
.WithReference(tables)
.WithReference(blobs)
.WaitFor(tables)
.WaitFor(blobs)
.PublishAsDockerComposeService((resource, service) =>
.WithEnvironment("Parser__BaseUrl", parserUrl);

if (!string.IsNullOrEmpty(parserKey))
{
apiBuilder = apiBuilder.WithEnvironment("Parser__ApiKey", parserKey);
}

var api = apiBuilder.PublishAsDockerComposeService((resource, service) =>
{
service.ContainerName = "notebookmark-api";
});
Expand Down
4 changes: 4 additions & 0 deletions src/NoteBookmark.AppHost/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
"AppSettings": {
"REKA_API_KEY": "KEY_HERE"
},
"Parser": {
"BaseUrl": "https://azpostlight-parser.azurewebsites.net/api/parser",
"ApiKey": "KEY_HERE"
},
"Keycloak": {
"Authority": "http://localhost:8080/realms/notebookmark",
"ClientId": "notebookmark",
Expand Down
6 changes: 6 additions & 0 deletions src/NoteBookmark.MauiApp/NoteBookmark.MauiApp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,14 @@
<ItemGroup>
<ProjectReference Include="..\NoteBookmark.SharedUI\NoteBookmark.SharedUI.csproj" />
<ProjectReference Include="..\NoteBookmark.Domain\NoteBookmark.Domain.csproj" />
<ProjectReference Include="..\NoteBookmark.AIServices\NoteBookmark.AIServices.csproj" />
</ItemGroup>

<!-- Disable the Android linker in Debug so compiler-generated closure types are never stripped -->
<PropertyGroup Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android' and '$(Configuration)' == 'Debug'">
<AndroidLinkMode>None</AndroidLinkMode>
</PropertyGroup>

<!--
SharedUI (and the MAUI Blazor WebView package) causes Microsoft.AspNetCore.App
to be added as a FrameworkReference via the UpdateAspNetToFrameworkReference target.
Expand Down
Loading