|
| 1 | +using Microsoft.Extensions.Logging; |
| 2 | +using OrchardCore.ContentManagement; |
| 3 | +using OrchardCore.Modules; |
| 4 | +using OrchardCoreContrib.Infrastructure; |
| 5 | +using OrchardCoreContrib.ViewCount.Handlers; |
| 6 | +using OrchardCoreContrib.ViewCount.Models; |
| 7 | + |
| 8 | +namespace OrchardCoreContrib.ViewCount.Services; |
| 9 | + |
| 10 | +public class ViewCountService( |
| 11 | + IContentManager contentManager, |
| 12 | + IEnumerable<IViewCountContentHandler> handlers, |
| 13 | + ILogger<ViewCountService> logger) : IViewCountService |
| 14 | +{ |
| 15 | + public int GetViewsCount(ContentItem contentItem) |
| 16 | + { |
| 17 | + Guard.ArgumentNotNull(contentItem, nameof(contentItem)); |
| 18 | + |
| 19 | + var viewCountPart = contentItem.As<ViewCountPart>(); |
| 20 | + |
| 21 | + return viewCountPart?.Count ?? 0; |
| 22 | + } |
| 23 | + |
| 24 | + public async Task ViewAsync(ContentItem contentItem) |
| 25 | + { |
| 26 | + Guard.ArgumentNotNull(contentItem, nameof(contentItem)); |
| 27 | + |
| 28 | + var viewCountPart = contentItem.As<ViewCountPart>() |
| 29 | + ?? throw new InvalidOperationException($"The content item doesn't have a `{nameof(ViewCountPart)}`."); |
| 30 | + var count = viewCountPart.Count; |
| 31 | + var context = new ViewCountContentContext(contentItem, count); |
| 32 | + |
| 33 | + await handlers.InvokeAsync((handler, context) => handler.ViewingAsync(context), context, logger); |
| 34 | + |
| 35 | + contentItem.Content.ViewCountPart.Count = ++count; |
| 36 | + |
| 37 | + await contentManager.UpdateAsync(contentItem); |
| 38 | + |
| 39 | + context = new ViewCountContentContext(contentItem, count); |
| 40 | + |
| 41 | + await handlers.InvokeAsync((handler, context) => handler.ViewedAsync(context), context, logger); |
| 42 | + } |
| 43 | +} |
0 commit comments