Skip to content

Commit

Permalink
🚨 Fixed some sonarcloud code smells (#83)
Browse files Browse the repository at this point in the history
  • Loading branch information
eduwardpost authored Feb 15, 2024
1 parent 4606137 commit 49749ad
Show file tree
Hide file tree
Showing 8 changed files with 34 additions and 35 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace uActivityPub.Tests.ServiceTests;
public class UActivitySettingsServiceTests
{

private readonly IUActivitySettingsService _unitUnderTest;
private readonly UActivitySettingsService _unitUnderTest;

// Mock
private readonly Mock<IUmbracoDatabase> _dataBaseMock;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
function dashboardController($controller, $scope, $http, $timeout, navigationService, eventsService, notificationsService) {
$scope.loaded = false;

var vm = this;
let vm = this;

vm.settings = {
singleUserMode: false,
singleUserModeUserName: '',
Expand All @@ -15,7 +15,7 @@
};

function loadSettings () {
var url = Umbraco.Sys.ServerVariables.uActivityPub.uActivityPubService;
let url = Umbraco.Sys.ServerVariables.uActivityPub.uActivityPubService;

$http({
method: 'get',
Expand Down
17 changes: 7 additions & 10 deletions src/uActivityPub/Controllers/ActivityPubController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public async Task<ActionResult<Collection>> GetFollowersCollection(string userNa
scope.Database.FetchAsync<ReceivedActivitiesSchema>(
"SELECT * FROM receivedActivityPubActivities WHERE Type = @0", "Follow");

if (!followers.Any())
if (followers.Count == 0)
return Ok(new Collection());

var collection = new Collection<string>();
Expand Down Expand Up @@ -91,19 +91,16 @@ public async Task<ActionResult<Activity>> PostInbox(string userName, [FromBody]
activityPubUserName = uActivitySettingsService.GetSettings(uActivitySettingKeys.SingleUserModeUserName)!.Value;
}

var signature = Request.Headers["Signature"];
var signature = Request.Headers["Signature"].FirstOrDefault() ?? string.Empty;

try
{
switch (activity.Type)
return activity.Type switch
{
case "Follow":
return Ok(await inboxService.HandleFollow(activity, signature, activityPubUserName, userId));
case "Undo":
return Ok(await inboxService.HandleUndo(activity, signature));
default:
return BadRequest($"{activity.Type} is not supported on this server");
}
"Follow" => Ok(await inboxService.HandleFollow(activity, signature, activityPubUserName, userId)),
"Undo" => Ok(await inboxService.HandleUndo(activity, signature)),
_ => BadRequest($"{activity.Type} is not supported on this server")
};
}
catch
{
Expand Down
2 changes: 1 addition & 1 deletion src/uActivityPub/Expansions/SettingsTreeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ protected override ActionResult<MenuItemCollection> GetMenuForNode(string id, Fo
return rootResult;
}

var root = rootResult.Value ?? throw new NullReferenceException(nameof(rootResult));
var root = rootResult.Value ?? throw new InvalidOperationException($"The value of {nameof(rootResult)} is unexpectedly null");

//set the route
root.RoutePath = $"{SectionAlias}/{uActivityPubConstants.Package.TreeName}/dashboard";
Expand Down
2 changes: 1 addition & 1 deletion src/uActivityPub/Models/Actor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class Actor : ActivityPubBase
public string? Outbox { get; set; }
public string? Followers { get; set; }
public Icon? Icon { get; set; }
public DateTime? Published { get; set; } = new DateTime(2023, 07, 17, 12, 00, 00);
public DateTime? Published { get; set; } = DateTime.Now.AddDays(-1);
public DateTime? Updated { get; set; } = DateTime.Now;
public bool ManuallyApprovesFollowers { get; set; } = false;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ public class uActivityPubServerVariablesHandler : INotificationHandler<ServerVa
/// <inheritdoc cref="INotificationHandler{TNotification}" />
public uActivityPubServerVariablesHandler(LinkGenerator linkGenerator)
{
_linkGenerator = linkGenerator;
_linkGenerator = linkGenerator ?? throw new ArgumentNullException(nameof(linkGenerator));
}

public void Handle(ServerVariablesParsingNotification notification)
{
notification.ServerVariables.Add("uActivityPub", new Dictionary<string, object>
notification.ServerVariables.Add("uActivityPub", new Dictionary<string, object?>
{
{ "uActivityPubService", _linkGenerator.GetUmbracoApiServiceBaseUrl<UActivityPubDashboardApiController>(controller => controller.GetApi()) }
});
Expand Down
20 changes: 11 additions & 9 deletions src/uActivityPub/Services/ContentPublishPostHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ namespace uActivityPub.Services;
// ReSharper disable once ClassNeverInstantiated.Global
public class ContentPublishPostHandler : INotificationHandler<ContentPublishedNotification>
{
private static readonly JsonSerializerOptions JsonSerializerOptions = new()
{
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};

private readonly IUmbracoDatabaseFactory _databaseFactory;
private readonly IOptions<WebRoutingSettings> _webRoutingSettings;
private readonly IUserService _userService;
Expand All @@ -37,9 +43,9 @@ public ContentPublishPostHandler(IUmbracoDatabaseFactory databaseFactory,

public void Handle(ContentPublishedNotification notification)
{
var settings = _uActivitySettingsService.GetAllSettings();
var contentAlias = settings?.FirstOrDefault(s => s.Key == uActivitySettingKeys.ContentTypeAlias);
var userPropertyAlias = settings?.FirstOrDefault(s => s.Key == uActivitySettingKeys.UserNameContentAlias);
var settings = _uActivitySettingsService.GetAllSettings()?.ToList();
var contentAlias = settings?.Find(s => s.Key == uActivitySettingKeys.ContentTypeAlias);
var userPropertyAlias = settings?.Find(s => s.Key == uActivitySettingKeys.UserNameContentAlias);

if (contentAlias == null)
throw new InvalidOperationException("Could not find configured key for the content type");
Expand Down Expand Up @@ -67,7 +73,7 @@ public void Handle(ContentPublishedNotification notification)

if (_uActivitySettingsService.GetSettings(uActivitySettingKeys.SingleUserMode)!.Value == "false")
{
userId = post.GetValue<int>(userPropertyAlias!.Value);
userId = post.GetValue<int>(userPropertyAlias.Value);
var user = _userService.GetUserById(userId);
if (user == null)
{
Expand All @@ -87,11 +93,7 @@ public void Handle(ContentPublishedNotification notification)
var activity = _activityHelper.GetActivityFromContent(post, actor);

var keyInfo = _signatureService.GetPrimaryKeyForUser(userName, userId).Result;
var serializedActivity = JsonSerializer.Serialize(activity, new JsonSerializerOptions
{
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
var serializedActivity = JsonSerializer.Serialize(activity, JsonSerializerOptions);

var followers =
database.Query<ReceivedActivitiesSchema>(
Expand Down
16 changes: 8 additions & 8 deletions src/uActivityPub/Services/InboxService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,8 @@
using Newtonsoft.Json.Linq;
using Serilog;
using uActivityPub.Data;
using uActivityPub.Helpers;
using uActivityPub.Models;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Models.Membership;
using Umbraco.Cms.Infrastructure.Persistence;

namespace uActivityPub.Services;
Expand All @@ -18,6 +16,12 @@ public class InboxService(
ISingedRequestHandler singedRequestHandler)
: IInboxService
{
private static readonly JsonSerializerOptions JsonSerializerOptions = new()
{
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};

public async Task<Activity?> HandleFollow(Activity activity, string signature, string userName, int userId)
{
Log.Information("Handling follow request for {Actor}. with activity {@Activity}", activity.Actor, activity);
Expand All @@ -30,7 +34,7 @@ public class InboxService(
var publicPem = actor.PublicKey?.PublicKeyPem;
var signatureParts = signature.Split(',');

if (!string.IsNullOrEmpty(publicPem) && signatureParts.Any())
if (!string.IsNullOrEmpty(publicPem) && signatureParts.Length != 0)
{
//we have a pem file and signature header parts
// var rsa = publicPem.GetRSAFromPem();

Check warning on line 40 in src/uActivityPub/Services/InboxService.cs

View workflow job for this annotation

GitHub Actions / run_build_and_test

Remove this commented out code. (https://rules.sonarsource.com/csharp/RSPEC-125)

Check warning on line 40 in src/uActivityPub/Services/InboxService.cs

View workflow job for this annotation

GitHub Actions / run_build_and_test

Remove this commented out code. (https://rules.sonarsource.com/csharp/RSPEC-125)
Expand Down Expand Up @@ -64,11 +68,7 @@ public class InboxService(

var keyInfo = await signatureService.GetPrimaryKeyForUser(userName, userId);

var response = await singedRequestHandler.SendSingedPost(new Uri(actor.Inbox), keyInfo.Rsa, JsonSerializer.Serialize(responseActivity, new JsonSerializerOptions
{
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
}), keyInfo.KeyId);
var response = await singedRequestHandler.SendSingedPost(new Uri(actor.Inbox), keyInfo.Rsa, JsonSerializer.Serialize(responseActivity, JsonSerializerOptions), keyInfo.KeyId);

Log.Information("Send {@ResponseActivity} to {@Actor} response is {@Response} with content {Content}", responseActivity, actor, response, await response.Content.ReadAsStringAsync());

Expand Down

0 comments on commit 49749ad

Please sign in to comment.