Skip to content

Commit

Permalink
Merge pull request #112 from eduardobragaxz/v3
Browse files Browse the repository at this point in the history
Add Json source generators and mark the library as trimmable
  • Loading branch information
glacasa authored Dec 15, 2023
2 parents e136eff + 1d3dd83 commit 7195f01
Show file tree
Hide file tree
Showing 13 changed files with 189 additions and 30 deletions.
21 changes: 15 additions & 6 deletions Mastonet.Entities/Enums/FilterContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using Mastonet.Entities;

namespace Mastonet;

Expand All @@ -21,8 +22,13 @@ public class FilterContextConverter : JsonConverter<FilterContext>
public override FilterContext Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
FilterContext context = 0;
var contextStrings = JsonSerializer.Deserialize<IEnumerable<string>>(ref reader, options);
if (contextStrings != null) {
#if NET6_0_OR_GREATER
var contextStrings = JsonSerializer.Deserialize(ref reader, EntitiesContext.Default.IEnumerableString);
#else
var contextStrings = JsonSerializer.Deserialize<IEnumerable<string>>(ref reader, options);
#endif
if (contextStrings != null)
{
foreach (var contextString in contextStrings)
{
switch (contextString)
Expand All @@ -45,15 +51,18 @@ public override FilterContext Read(ref Utf8JsonReader reader, Type typeToConvert

return context;
}

public override void Write(Utf8JsonWriter writer, FilterContext value, JsonSerializerOptions options)
{
var contextStrings = new List<string>();
if ((value & FilterContext.Home) == FilterContext.Home) contextStrings.Add("home");
if ((value & FilterContext.Notifications) == FilterContext.Notifications) contextStrings.Add("notifications");
if ((value & FilterContext.Public) == FilterContext.Public) contextStrings.Add("public");
if ((value & FilterContext.Thread) == FilterContext.Thread) contextStrings.Add("thread");
JsonSerializer.Serialize(writer, contextStrings, options);
#if NET6_0_OR_GREATER
JsonSerializer.Serialize(writer, contextStrings, EntitiesContext.Default.ListString);
#else
JsonSerializer.Serialize(writer, contextStrings, options);
#endif
}

}
}
16 changes: 13 additions & 3 deletions Mastonet.Entities/Enums/NotificationType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System;
using System.Collections.Generic;
using System.Text.Json;
using Mastonet.Entities;

namespace Mastonet;

Expand All @@ -22,7 +23,11 @@ public class NotificationTypeConverter : JsonConverter<NotificationType>
public override NotificationType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
NotificationType context = 0;
var contextStrings = JsonSerializer.Deserialize<IEnumerable<string>>(ref reader, options);
#if NET6_0_OR_GREATER
var contextStrings = JsonSerializer.Deserialize(ref reader, EntitiesContext.Default.IEnumerableString);
#else
var contextStrings = JsonSerializer.Deserialize<IEnumerable<string>>(ref reader, options);
#endif
if (contextStrings != null)
{
foreach (var contextString in contextStrings)
Expand Down Expand Up @@ -59,6 +64,11 @@ public override void Write(Utf8JsonWriter writer, NotificationType value, JsonSe
if ((value & NotificationType.Reblog) == NotificationType.Reblog) contextStrings.Add("reblog");
if ((value & NotificationType.Mention) == NotificationType.Mention) contextStrings.Add("mention");
if ((value & NotificationType.Poll) == NotificationType.Poll) contextStrings.Add("poll");
JsonSerializer.Serialize(writer, contextStrings, options);
#if NET6_0_OR_GREATER
JsonSerializer.Serialize(writer, contextStrings, EntitiesContext.Default.ListString);
#else
JsonSerializer.Serialize(writer, contextStrings, options);
#endif
}
}
}

1 change: 1 addition & 0 deletions Mastonet.Entities/Enums/Scope.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ public enum GranularScope
Write__Reports,
Write__Statuses,

Follow,
Push,

Admin__Read,
Expand Down
10 changes: 10 additions & 0 deletions Mastonet.Entities/JsonSourceGenerators.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using System.Collections.Generic;
using System.Text.Json.Serialization;

namespace Mastonet.Entities;

[JsonSerializable(typeof(IEnumerable<string>))]
[JsonSerializable(typeof(List<string>))]
internal partial class EntitiesContext : JsonSerializerContext
{
}
10 changes: 6 additions & 4 deletions Mastonet.Entities/Mastonet.Entities.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>netstandard2.0;net6.0;net7.0</TargetFrameworks>
<TargetFrameworks>netstandard2.0;net6.0;net7.0;net8.0</TargetFrameworks>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<Title>Mastonet.Entities</Title>
Expand All @@ -19,14 +19,16 @@
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageTags>Mastodon</PackageTags>
<IsTrimmable>true</IsTrimmable>
<EnableTrimAnalyzer>true</EnableTrimAnalyzer>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="System.Text.Json" Version="7.0.2" />
<PackageReference Include="System.Text.Json" Version="8.0.0" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0" PrivateAssets="All" />
</ItemGroup>

<ItemGroup>
Expand Down
6 changes: 3 additions & 3 deletions Mastonet.Tests/Mastonet.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.0" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.7.2" />
<PackageReference Include="xunit" Version="2.6.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
Expand Down
19 changes: 18 additions & 1 deletion Mastonet/BaseHttpClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -304,17 +304,34 @@ protected async Task<string> PatchMedia(string route, IEnumerable<KeyValuePair<s

private static T TryDeserialize<T>(string json)
{
#if NET6_0_OR_GREATER

if (json[0] == '{')
{

var error = JsonSerializer.Deserialize(json, ErrorContext.Default.Error);

if (error != null && !string.IsNullOrEmpty(error.Description))
{
throw new ServerErrorException(error);
}
}

return (T?)JsonSerializer.Deserialize(json, typeof(T), TryDeserializeContext.Default)!;
#else

if (json[0] == '{')
{
var error = JsonSerializer.Deserialize<Error>(json);

if (error != null && !string.IsNullOrEmpty(error.Description))
{
throw new ServerErrorException(error);
}
}

return JsonSerializer.Deserialize<T>(json)!;

#endif
}

protected static string AddQueryStringParam(string queryParams, string queryStringParam, string? value)
Expand Down
4 changes: 2 additions & 2 deletions Mastonet/MastodonClient.Status.cs
Original file line number Diff line number Diff line change
Expand Up @@ -147,12 +147,12 @@ public Task<Status> PublishStatus(string status, Visibility? visibility = null,
data.Add(new KeyValuePair<string, string>("poll[expires_in]", poll.ExpiresIn.TotalSeconds.ToString()));
if (poll.Multiple.HasValue)
{
data.Add(new KeyValuePair<string, string>("poll[multiple]", poll.Multiple.Value.ToString()));
data.Add(new KeyValuePair<string, string>("poll[multiple]", poll.Multiple.Value.ToString().ToLowerInvariant()));
}

if (poll.HideTotals.HasValue)
{
data.Add(new KeyValuePair<string, string>("poll[hide_totals]", poll.HideTotals.Value.ToString()));
data.Add(new KeyValuePair<string, string>("poll[hide_totals]", poll.HideTotals.Value.ToString().ToLowerInvariant()));
}
}

Expand Down
28 changes: 25 additions & 3 deletions Mastonet/MastodonClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,29 @@ public Task<IEnumerable<Activity>> GetInstanceActivity()
/// <returns></returns>
public Task<IEnumerable<Tag>> GetTrendingTags()
{
return Get<IEnumerable<Tag>>("/api/v1/trends");
return Get<IEnumerable<Tag>>("/api/v1/trends/tags");
}

/// <summary>
/// Statuses that have been interacted with more than others.
/// </summary>
/// <param name="offset"></param>
/// <param name="limit"></param>
/// <returns></returns>
public Task<MastodonList<Status>> GetTrendingStatuses(int? offset = null, int? limit = null)
{
var queryParams = "";

if(offset.HasValue)
{
queryParams = "?offset=" + offset.Value;
}
if(limit.HasValue)
{
queryParams += (queryParams != "" ? "&" : "?") + "limit=" + limit.Value;
}

return GetMastodonList<Status>("/api/v1/trends/statuses" + queryParams);
}

/// <summary>
Expand Down Expand Up @@ -348,7 +370,7 @@ public Task<Attachment> UploadMedia(MediaDefinition media, string? description =
data.Add("focus", $"{focus.X},{focus.Y}");
}

return this.Post<Attachment>("/api/v1/media", data, list);
return this.Post<Attachment>("/api/v2/media", data, list);
}

/// <summary>
Expand Down Expand Up @@ -502,7 +524,7 @@ public Task<Report> Report(string accountId, IEnumerable<string>? statusIds = nu
{
var data = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("account_id", accountId.ToString()),
new KeyValuePair<string, string>("account_id", accountId),
};
if (statusIds != null)
{
Expand Down
8 changes: 5 additions & 3 deletions Mastonet/Mastonet.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>netstandard2.0;net6.0;net7.0</TargetFrameworks>
<TargetFrameworks>netstandard2.0;net6.0;net7.0;net8.0</TargetFrameworks>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<Title>Mastonet</Title>
Expand All @@ -19,14 +19,16 @@
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageTags>Mastodon</PackageTags>
<IsTrimmable>true</IsTrimmable>
<EnableTrimAnalyzer>true</EnableTrimAnalyzer>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="System.Text.Json" Version="7.0.2" />
<PackageReference Include="System.Text.Json" Version="8.0.0" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0" PrivateAssets="All" />
</ItemGroup>

<ItemGroup>
Expand Down
18 changes: 15 additions & 3 deletions Mastonet/TimelineStreaming.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,22 @@ protected void SendEvent(string eventName, string data)
switch (eventName)
{
case "update":
var status = JsonSerializer.Deserialize<Status>(data);
#if NET6_0_OR_GREATER
var status = JsonSerializer.Deserialize(data, TryDeserializeContext.Default.Status);
#else
var status = JsonSerializer.Deserialize<Status>(data);
#endif
if (status != null)
{
OnUpdate?.Invoke(this, new StreamUpdateEventArgs(status));
}
break;
case "notification":
var notification = JsonSerializer.Deserialize<Notification>(data);
#if NET6_0_OR_GREATER
var notification = JsonSerializer.Deserialize(data, TryDeserializeContext.Default.Notification);
#else
var notification = JsonSerializer.Deserialize<Notification>(data);
#endif
if (notification != null)
{
OnNotification?.Invoke(this, new StreamNotificationEventArgs(notification));
Expand All @@ -55,7 +63,11 @@ protected void SendEvent(string eventName, string data)
OnFiltersChanged?.Invoke(this, new StreamFiltersChangedEventArgs());
break;
case "conversation":
var conversation = JsonSerializer.Deserialize<Conversation>(data);
#if NET6_0_OR_GREATER
var conversation = JsonSerializer.Deserialize(data, TryDeserializeContext.Default.Conversation);
#else
var conversation = JsonSerializer.Deserialize<Conversation>(data);
#endif
if (conversation != null)
{
OnConversation?.Invoke(this, new StreamConversationEvenTargs(conversation));
Expand Down
15 changes: 13 additions & 2 deletions Mastonet/TimelineWebSocketStreaming.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using static Mastonet.TimelineWebSocketStreaming;

namespace Mastonet;

Expand Down Expand Up @@ -81,7 +83,11 @@ public override async Task Start()
{
var messageStr = Encoding.UTF8.GetString(ms.ToArray());

var message = JsonSerializer.Deserialize<TimelineMessage>(messageStr);
#if NET6_0_OR_GREATER
var message = JsonSerializer.Deserialize(messageStr, TimelineMessageContext.Default.TimelineMessage);
#else
var message = JsonSerializer.Deserialize<TimelineMessage>(messageStr);
#endif
if (message != null)
{
SendEvent(message.Event, message.Payload);
Expand All @@ -96,7 +102,7 @@ public override async Task Start()
this.Stop();
}

private class TimelineMessage
internal class TimelineMessage
{
public string Event { get; set; } = default!;

Expand All @@ -115,3 +121,8 @@ public override void Stop()
base.Stop();
}
}

[JsonSerializable(typeof(TimelineMessage), GenerationMode = JsonSourceGenerationMode.Metadata)]
internal partial class TimelineMessageContext : JsonSerializerContext
{
}
Loading

0 comments on commit 7195f01

Please sign in to comment.