Skip to content

Commit

Permalink
switch to .net7, waiting for .net8 to fix dotnet/runtime#68895
Browse files Browse the repository at this point in the history
  • Loading branch information
softlion committed Nov 26, 2022
1 parent 7e8e839 commit 0c8e4cf
Show file tree
Hide file tree
Showing 43 changed files with 754 additions and 614 deletions.
8 changes: 4 additions & 4 deletions Demos/DemoNotionBlog/DemoNotionBlog.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<UserSecretsId>d3ee1fbc-fd2c-4ce9-9756-e439a73af1b6</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<DockerfileContext>..\..</DockerfileContext>
Expand All @@ -10,13 +10,13 @@
<DebugType>portable</DebugType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.14.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.17.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="2.2.0" />
<!-- <PackageReference Include="Softlion.NotionSharp" Version="1.0.11" />-->
<ProjectReference Include="..\..\NotionSharp\NotionSharp.csproj" />
<PackageReference Include="System.Reactive" Version="5.0.0" />
<PackageReference Include="Toolbelt.Blazor.HeadElement" Version="6.0.0" />
<PackageReference Include="Hangfire" Version="1.7.23" />
<PackageReference Include="Toolbelt.Blazor.HeadElement" Version="7.3.0" />
<PackageReference Include="Hangfire" Version="1.7.32" />
<PackageReference Include="Hangfire.MemoryStorage" Version="1.7.0" />
</ItemGroup>

Expand Down
11 changes: 6 additions & 5 deletions Demos/DemoNotionBlog/Libs/Services/NotionCmsService.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System.Reactive.Subjects;
using System.ServiceModel.Syndication;
using Flurl.Http;
using FluentRest.Http;
using Hangfire;
using Microsoft.Extensions.Options;
using NotionSharp;
Expand Down Expand Up @@ -89,18 +89,19 @@ public async Task RefreshNotionData()

try
{
var notionSession = new NotionSession(new NotionSessionInfo { TokenV2 = option.Key, NotionBrowserId = option.BrowserId, NotionUserId = option.UserId });
var notionSession = new NotionSession(new() { TokenV2 = option.Key, NotionBrowserId = option.BrowserId, NotionUserId = option.UserId, NotionUserAgent = option.UserAgent });
var userContent = await notionSession.LoadUserContent().ConfigureAwait(false);
var spacePages = userContent.RecordMap.Space.First().Value.Pages;
var space = userContent.RecordMap.Space.First().Value;
var spacePages = space.Pages;

//Refresh CMS
var cmsPageId = spacePages.First(pageId => userContent.RecordMap.Block.TryGetValue(pageId, out var page) && page.Title == option.CmsPageTitle);
var cmsPages = userContent.RecordMap.Block[cmsPageId].Content;
var cmsItems = await notionSession.GetSyndicationFeed(cmsPages, maxBlocks: 100, stopBeforeFirstSubHeader: false).ConfigureAwait(false);
var cmsItems = await notionSession.GetSyndicationFeed(space.Id, cmsPages, maxBlocks: 100, stopBeforeFirstSubHeader: false).ConfigureAwait(false);
CmsTitle = userContent.RecordMap.Block[cmsPageId].Title;
CmsArticles.OnNext(cmsItems.Items.ToList());
}
catch (FlurlHttpException e) when(e.StatusCode == 401)
catch (FluentRestHttpException e) when(e.StatusCode == 401)
{
logger.LogError(e, $"Invalid notion credentials for page {option?.CmsPageTitle}");
}
Expand Down
1 change: 1 addition & 0 deletions Demos/DemoNotionBlog/Libs/Services/NotionOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ public class NotionOptions
public string? Key { get; set; }
public Guid BrowserId { get; set; }
public Guid UserId { get; set; }
public string UserAgent { get; set; }
public string? CmsPageTitle { get; set; }
}
}
2 changes: 1 addition & 1 deletion Demos/PackTemplateProjects.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
</PropertyGroup>

<PropertyGroup>
Expand Down
12 changes: 6 additions & 6 deletions NotionSharp.ApiClient.Tests/NotionSharp.ApiClient.Tests.csproj
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>

<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
<PackageReference Include="MSTest.TestAdapter" Version="2.2.8" />
<PackageReference Include="MSTest.TestFramework" Version="2.2.8" />
<PackageReference Include="coverlet.collector" Version="3.1.0">
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.0" />
<PackageReference Include="MSTest.TestAdapter" Version="2.2.10" />
<PackageReference Include="MSTest.TestFramework" Version="2.2.10" />
<PackageReference Include="coverlet.collector" Version="3.2.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="System.Linq.Async" Version="5.0.0" />
<PackageReference Include="System.Linq.Async" Version="6.0.1" />
</ItemGroup>

<ItemGroup>
Expand Down
4 changes: 2 additions & 2 deletions NotionSharp.ApiClient/Lib/Helpers/JsonExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Flurl.Http;
using FluentRest.Http;

namespace NotionSharp.ApiClient.Lib
{
Expand All @@ -23,7 +23,7 @@ public static T ToObject<T>(this JsonElement element, JsonSerializerOptions? opt
return JsonSerializer.Deserialize(bufferWriter.WrittenSpan, targetType, options);
}

public static async Task<T> GetJson<T>(this IFlurlRequest request, CancellationToken cancel = default) where T: BaseObject, new()
public static async Task<T> GetJson<T>(this IFluentRestRequest request, CancellationToken cancel = default) where T: BaseObject, new()
{
var response = await request.SendAsync(HttpMethod.Get, cancellationToken: cancel, completionOption: HttpCompletionOption.ResponseContentRead).ConfigureAwait(false);
var json = await response.GetStringAsync().ConfigureAwait(false);
Expand Down
143 changes: 61 additions & 82 deletions NotionSharp.ApiClient/Lib/HttpNotionSession.cs
Original file line number Diff line number Diff line change
@@ -1,107 +1,86 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Flurl.Http;
using Flurl.Http.Configuration;
using FluentRest.Http;
using FluentRest.Http.Configuration;
using Polly;
using Polly.Retry;

namespace NotionSharp.ApiClient.Lib
{
/// <summary>
/// Flurl depends on newtonsoft json. Use System.Text.Json instead.
/// </summary>
internal class TextJsonSerializer : ISerializer
{
private readonly JsonSerializerOptions? options;

public TextJsonSerializer(JsonSerializerOptions? options = null) => this.options = options;
public T Deserialize<T>(string s) => JsonSerializer.Deserialize<T>(s, options)!;
public string Serialize(object obj) => JsonSerializer.Serialize(obj, options);
namespace NotionSharp.ApiClient.Lib;

public T Deserialize<T>(Stream stream)
{
using var reader = new StreamReader(stream);
return Deserialize<T>(reader.ReadToEnd());
}
}

internal class JsonLowerCaseNamingPolicy : JsonNamingPolicy
{
public override string ConvertName(string name) => name.ToLowerInvariant();
}
internal class JsonLowerCaseNamingPolicy : JsonNamingPolicy
{
public override string ConvertName(string name) => name.ToLowerInvariant();
}

public class HttpNotionSession
{
private readonly FlurlClient flurlClient;
public class HttpNotionSession
{
private readonly FluentRestClient flurlClient;

public static readonly JsonSerializerOptions NotionJsonSerializationOptions = new JsonSerializerOptions()
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault,
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = new JsonLowerCaseNamingPolicy()
};
public static JsonSerializerOptions NotionJsonSerializationOptions { get; } = new (JsonSerializerDefaults.Web)
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = new JsonLowerCaseNamingPolicy()
};

public HttpNotionSession(Action<FlurlClient> configure)
public HttpNotionSession(Action<FluentRestClient> configure)
{
flurlClient = new (new HttpClient(new PolicyHandler()))
{
flurlClient = new FlurlClient(new HttpClient(new PolicyHandler()))
{
Settings = new ClientFlurlHttpSettings {
JsonSerializer = new TextJsonSerializer(NotionJsonSerializationOptions),
Settings = new () {
JsonSerializer = new SystemTextJsonSerializer(NotionJsonSerializationOptions),
#if DEBUG
BeforeCall = call =>
{
var request = call.Request;
var requestBody = call.RequestBody;
var i = 0;
},
OnError = call =>
{
var exception = call.Exception;
var response = call.Response;
var i = 0;
},
AfterCall = call =>
{
var exception = call.Exception;
var response = call.Response;
//var tt = response.ResponseMessage.Content.ReadAsStringAsync();
var i = 0;
}
BeforeCall = call =>
{
var request = call.Request;
var requestBody = call.RequestBody;
var i = 0;
},
OnError = call =>
{
var exception = call.Exception;
var response = call.Response;
var i = 0;
},
AfterCall = call =>
{
var exception = call.Exception;
var response = call.Response;
//var tt = response.ResponseMessage.Content.ReadAsStringAsync();
var i = 0;
}
#endif
},
};
configure(flurlClient);
}

public IFlurlRequest CreateRequest(Uri uri)
=> new FlurlRequest(uri) { Client = flurlClient };
},
};
configure(flurlClient);
}

public IFlurlRequest CreateRequest(string uri)
=> new FlurlRequest(uri) { Client = flurlClient };
public IFluentRestRequest CreateRequest(Uri uri)
=> new FluentRestRequest(uri) { Client = flurlClient };

class PolicyHandler : DelegatingHandler
{
private readonly AsyncRetryPolicy<HttpResponseMessage> retryPolicy;
public IFluentRestRequest CreateRequest(string uri)
=> new FluentRestRequest(uri) { Client = flurlClient };

public PolicyHandler()
{
InnerHandler = new HttpClientHandler();
class PolicyHandler : DelegatingHandler
{
private readonly AsyncRetryPolicy<HttpResponseMessage> retryPolicy;

//retry on 502
retryPolicy = Policy
.HandleResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.BadGateway)
.WaitAndRetryAsync(5, retry => TimeSpan.FromSeconds(0.3));
}
public PolicyHandler()
{
InnerHandler = new HttpClientHandler();

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
=> retryPolicy.ExecuteAsync(ct => base.SendAsync(request, ct), cancellationToken);
//retry on 502
retryPolicy = Policy
.HandleResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.BadGateway)
.WaitAndRetryAsync(5, retry => TimeSpan.FromSeconds(0.3));
}

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
=> retryPolicy.ExecuteAsync(ct => base.SendAsync(request, ct), cancellationToken);
}
}
18 changes: 12 additions & 6 deletions NotionSharp.ApiClient/Lib/PublicApi/Model/Page.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using NotionSharp.ApiClient.Lib;

Expand Down Expand Up @@ -66,13 +67,18 @@ public class PageParentJsonConverter : JsonConverter<PageParent>

public override bool CanConvert(Type typeToConvert) => typeof(PageParent).IsAssignableFrom(typeToConvert);

public override PageParent Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
public override PageParent? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var element = JsonSerializer.Deserialize<JsonElement>(ref reader);
var type = element.EnumerateObject().FirstOrDefault(p => p.Name == "type").Value.GetString();
if(type == null || !PolymorphismTypes.TryGetValue(type, out var parentType))
throw new JsonException($"Error deserializing PageParent: unknown type '{type ?? "null"}'");
return (PageParent)element.ToObject(parentType, options);
var node = JsonNode.Parse(ref reader) as JsonObject;
if (node?.TryGetPropertyValue("type", out var oType) == true)
{
var type = oType?.GetValue<string>();
if (type == null || !PolymorphismTypes.TryGetValue(type, out var parentType))
throw new JsonException($"Error deserializing PageParent: unknown type '{type ?? "null"}'");
return (PageParent?)node.Deserialize(parentType, options);
}

return null;
}

public override void Write(Utf8JsonWriter writer, PageParent value, JsonSerializerOptions options)
Expand Down
37 changes: 18 additions & 19 deletions NotionSharp.ApiClient/NotionSession.cs
Original file line number Diff line number Diff line change
@@ -1,31 +1,30 @@
using System.Collections.Generic;
using Flurl.Http;
using FluentRest.Http;
using NotionSharp.ApiClient.Lib;
using NotionSharp.ApiClient.Lib.Model;

namespace NotionSharp.ApiClient
namespace NotionSharp.ApiClient;

/// <summary>
/// Official integration
/// </summary>
public class NotionSession
{
/// <summary>
/// Official integration
/// </summary>
public class NotionSession
public NotionSessionInfo SessionInfo { get; }
public HttpNotionSession HttpSession { get; }

public NotionSession(NotionSessionInfo sessionInfo)
{
public NotionSessionInfo SessionInfo { get; }
public HttpNotionSession HttpSession { get; }
SessionInfo = sessionInfo;

public NotionSession(NotionSessionInfo sessionInfo)
HttpSession = new (client =>
{
SessionInfo = sessionInfo;

HttpSession = new HttpNotionSession(client =>
client.WithHeaders(new Dictionary<string, string>
{
client.WithHeaders(new Dictionary<string, string>
{
{"Authorization", $"Bearer {sessionInfo.Token}"},
{"Notion-Version", Constants.NotionApiVersion}, //Required
//{"User-Agent", Constants.UserAgent },
});
{"Authorization", $"Bearer {sessionInfo.Token}"},
{"Notion-Version", Constants.NotionApiVersion}, //Required
//{"User-Agent", Constants.UserAgent },
});
}
});
}
}
2 changes: 1 addition & 1 deletion NotionSharp.ApiClient/NotionSessionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
using System.ServiceModel.Syndication;
using System.Threading;
using System.Threading.Tasks;
using Flurl.Http;
using FluentRest.Http;
using NotionSharp.ApiClient.Lib;
using NotionSharp.ApiClient.Lib.HtmlRendering;

Expand Down
Loading

0 comments on commit 0c8e4cf

Please sign in to comment.