Skip to content

Commit

Permalink
Merge pull request #47 from CodeBunTes/Feature_PostCache
Browse files Browse the repository at this point in the history
Add caching for Mastodon posts - #22
  • Loading branch information
OwainWilliams authored Oct 23, 2023
2 parents d0f550c + 19eead3 commit 3db0864
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 7 deletions.
2 changes: 1 addition & 1 deletion Core/Services/IMastodonService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ namespace h5yr.Core.Services
{
public interface IMastodonService
{
Task<IReadOnlyList<MastodonStatus>> GetStatuses(int limit, string? maxId = null);
Task<List<MastodonStatus>> GetStatuses(int limit);
}
}
37 changes: 31 additions & 6 deletions Core/Services/MastodonService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,55 @@
using Skybrud.Social.Mastodon.Models.Statuses;
using Skybrud.Social.Mastodon.Options.Timeline;
using Skybrud.Social.Mastodon.Responses.Statuses;
using Umbraco.Cms.Core.Cache;

namespace h5yr.Core.Services {

public class MastodonService : IMastodonService
{

private readonly ILogger<MastodonService> _logger;
private readonly AppCaches _appCaches;

public MastodonService(ILogger<MastodonService> logger)
private const string FeedDomain = "umbracocommunity.social";
private const string FeedHashtag = "h5yr";
private const string FeedCacheKey = "mastodonposts";
private const int FeedCacheMinutes = 15;

public MastodonService(ILogger<MastodonService> logger, AppCaches appCaches)
{
_logger = logger;
_appCaches = appCaches;
}

public async Task<List<MastodonStatus>> GetStatuses(int limit)
{
var posts = _appCaches.RuntimeCache.GetCacheItem($"{FeedCacheKey}_{limit}",
() => LoadStatuses(limit),
TimeSpan.FromMinutes(FeedCacheMinutes));

if (posts != null)
{
return await posts;
}
else
{
return await Task.FromResult(new List<MastodonStatus>());
}
}

public async Task<IReadOnlyList<MastodonStatus>> GetStatuses(int limit, string? maxId = null)

private async Task<List<MastodonStatus>> LoadStatuses(int limit)
{

// Initialize a new HTTP service (basically the API wrapper)
MastodonHttpService mastodon = MastodonHttpService
.CreateFromDomain("umbracocommunity.social");
.CreateFromDomain(FeedDomain);

// Initialize the options for the request to the API
MastodonGetHashtagTimelineOptions options = new()
{
Hashtag = "h5yr",
Hashtag = FeedHashtag,
Limit = limit
};

Expand All @@ -38,7 +63,7 @@ public async Task<IReadOnlyList<MastodonStatus>> GetStatuses(int limit, string?
.GetHashtagTimelineAsync(options);

// Return the statuses
return response.Body;
return response.Body.ToList();

}
catch (Exception ex)
Expand All @@ -49,7 +74,7 @@ public async Task<IReadOnlyList<MastodonStatus>> GetStatuses(int limit, string?
}


return Array.Empty<MastodonStatus>();
return new List<MastodonStatus>();

}

Expand Down

0 comments on commit 3db0864

Please sign in to comment.