diff --git a/src/Lumina.Domain/Common/Errors/Errors.MediaConsumption.cs b/src/Lumina.Domain/Common/Errors/Errors.MediaConsumption.cs new file mode 100644 index 00000000..e3545816 --- /dev/null +++ b/src/Lumina.Domain/Common/Errors/Errors.MediaConsumption.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +#endregion + +namespace Lumina.Domain.Common.Errors; + +/// +/// Media consumption error types. +/// +public static partial class Errors +{ + public static class MediaConsumption + { + public static Error UnsupportedMediaKind => Error.Validation(description: nameof(UnsupportedMediaKind)); + public static Error MediaKindCannotStartCompleted => Error.Forbidden(description: nameof(MediaKindCannotStartCompleted)); + public static Error InvalidMediaPosition => Error.Validation(description: nameof(InvalidMediaPosition)); + public static Error InvalidProgressFraction => Error.Validation(description: nameof(InvalidProgressFraction)); + public static Error ConsumedDurationMustBeNonNegative => Error.Validation(description: nameof(ConsumedDurationMustBeNonNegative)); + public static Error ConsumedDurationCannotDecrease => Error.Forbidden(description: nameof(ConsumedDurationCannotDecrease)); + public static Error ConsecutivePagesReadMustBeNonNegative => Error.Validation(description: nameof(ConsecutivePagesReadMustBeNonNegative)); + public static Error ConsecutivePagesReadIsOnlySupportedForPageBasedMedia => Error.Forbidden(description: nameof(ConsecutivePagesReadIsOnlySupportedForPageBasedMedia)); + public static Error ConsumptionIsNotInProgress => Error.Conflict(description: nameof(ConsumptionIsNotInProgress)); + public static Error ConsumptionIsAlreadyTerminal => Error.Conflict(description: nameof(ConsumptionIsAlreadyTerminal)); + public static Error InProgressConsumptionCannotHaveEndTime => Error.Validation(description: nameof(InProgressConsumptionCannotHaveEndTime)); + public static Error EndedConsumptionMustHaveEndTime => Error.Validation(description: nameof(EndedConsumptionMustHaveEndTime)); + public static Error LastActivityCannotPrecedeStart => Error.Forbidden(description: nameof(LastActivityCannotPrecedeStart)); + public static Error EndedConsumptionCannotPrecedeLastActivity => Error.Forbidden(description: nameof(EndedConsumptionCannotPrecedeLastActivity)); + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/Common/ValueObjects/MediaConsumptionRule.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/Common/ValueObjects/MediaConsumptionRule.cs index 3e7c950a..a9cfe826 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/Common/ValueObjects/MediaConsumptionRule.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/Common/ValueObjects/MediaConsumptionRule.cs @@ -40,6 +40,11 @@ public abstract class MediaConsumptionRule : ValueObject /// public bool CanResume => PositionKind.HasValue; + /// + /// Gets a value indicating whether a consumption session of this kind of media is a one-shot session, which completes at the moment it starts. + /// + public abstract bool IsOneShot { get; } + /// /// Determines whether a consumption session of this kind of media counts towards statistics. /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/Common/ValueObjects/MediaPosition.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/Common/ValueObjects/MediaPosition.cs new file mode 100644 index 00000000..23f0f3b0 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/Common/ValueObjects/MediaPosition.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; + +/// +/// Value Object for the position reached in a media item during a consumption session. +/// +public sealed class MediaPosition : ValueObject +{ + /// + /// Gets the kind of representation that the position uses. + /// + public MediaPositionKind Kind { get; private set; } + + /// + /// Gets the position within the media item, for positions that are expressed as a time offset. + /// + public Optional TimeOffset { get; private set; } + + /// + /// Gets the opaque locator within the media item, for positions that are not expressed as a time offset, such as a reading location of a book. + /// + public Optional Location { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The kind of representation that the position uses. + /// The position within the media item, for positions that are expressed as a time offset. + /// The opaque locator within the media item, for positions that are not expressed as a time offset. + private MediaPosition(MediaPositionKind kind, Optional timeOffset, Optional location) + { + Kind = kind; + TimeOffset = timeOffset; + Location = location; + } + + /// + /// Creates a position expressed as a time offset within the media item. + /// + /// The position within the media item. + /// The created instance. + public static MediaPosition CreateTimeOffset(TimeSpan timeOffset) + { + return new MediaPosition(MediaPositionKind.TimeOffset, Optional.Some(timeOffset), Optional.None()); + } + + /// + /// Creates a position expressed as an opaque locator within the media item. + /// + /// The opaque locator within the media item. + /// The created instance. + public static MediaPosition CreateLocation(string location) + { + return new MediaPosition(MediaPositionKind.Location, Optional.None(), Optional.Some(location)); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Kind; + yield return TimeOffset; + yield return Location; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/Events/MediaConsumptionCompletedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/Events/MediaConsumptionCompletedDomainEvent.cs new file mode 100644 index 00000000..9ae86c67 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/Events/MediaConsumptionCompletedDomainEvent.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.Events; + +/// +/// Domain event raised when a media consumption session completes. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the consumption record. +/// The unique identifier of the user that owns the consumption record. +/// The unique identifier of the media library that contains the consumed item. +/// The unique identifier of the consumed media item. +/// The kind of media that was consumed. +/// The last known position for the media item, if any. +/// The final progress fraction reported for the media item. +/// The active duration consumed by the session. +/// The number of consecutive pages read in the session. +/// The date and time when the domain event occurred. +[DebuggerDisplay("MediaConsumptionRecordId: {MediaConsumptionRecordId.Value}; MediaKind: {MediaKind}")] +public record MediaConsumptionCompletedDomainEvent( + Guid Id, + MediaConsumptionRecordId MediaConsumptionRecordId, + UserId UserId, + LibraryId LibraryId, + MediaItemId MediaItemId, + MediaKind MediaKind, + Optional LastPosition, + double LastProgressFraction, + TimeSpan ConsumedDuration, + int ConsecutivePagesRead, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/Events/MediaConsumptionProgressedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/Events/MediaConsumptionProgressedDomainEvent.cs new file mode 100644 index 00000000..d9fc0801 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/Events/MediaConsumptionProgressedDomainEvent.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.Events; + +/// +/// Domain event raised when a client reports the progress of a media consumption session. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the consumption record. +/// The unique identifier of the user that owns the consumption record. +/// The unique identifier of the media library that contains the consumed item. +/// The unique identifier of the consumed media item. +/// The kind of media that is being consumed. +/// The last known position for the media item, if any. +/// The last progress fraction reported by the client. +/// The active duration consumed so far. +/// The number of consecutive pages read so far. +/// The date and time when the domain event occurred. +[DebuggerDisplay("MediaConsumptionRecordId: {MediaConsumptionRecordId.Value}; LastProgressFraction: {LastProgressFraction}")] +public record MediaConsumptionProgressedDomainEvent( + Guid Id, + MediaConsumptionRecordId MediaConsumptionRecordId, + UserId UserId, + LibraryId LibraryId, + MediaItemId MediaItemId, + MediaKind MediaKind, + Optional LastPosition, + double LastProgressFraction, + TimeSpan ConsumedDuration, + int ConsecutivePagesRead, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/Events/MediaConsumptionStartedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/Events/MediaConsumptionStartedDomainEvent.cs new file mode 100644 index 00000000..270620bf --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/Events/MediaConsumptionStartedDomainEvent.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.Events; + +/// +/// Domain event raised when a media consumption session starts. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the consumption record. +/// The unique identifier of the user that started the session. +/// The unique identifier of the media library that contains the consumed item. +/// The unique identifier of the consumed media item. +/// The kind of media that is being consumed. +/// The date and time when the domain event occurred. +[DebuggerDisplay("MediaConsumptionRecordId: {MediaConsumptionRecordId.Value}; MediaKind: {MediaKind}")] +public record MediaConsumptionStartedDomainEvent( + Guid Id, + MediaConsumptionRecordId MediaConsumptionRecordId, + UserId UserId, + LibraryId LibraryId, + MediaItemId MediaItemId, + MediaKind MediaKind, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/Events/MediaConsumptionStoppedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/Events/MediaConsumptionStoppedDomainEvent.cs new file mode 100644 index 00000000..482122be --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/Events/MediaConsumptionStoppedDomainEvent.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.Events; + +/// +/// Domain event raised when a media consumption session stops before it completes. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the consumption record. +/// The unique identifier of the user that owns the consumption record. +/// The unique identifier of the media library that contains the consumed item. +/// The unique identifier of the consumed media item. +/// The kind of media that was consumed. +/// The last known position for the media item, if any. +/// The final progress fraction reported for the media item. +/// The active duration consumed by the session. +/// The number of consecutive pages read in the session. +/// The date and time when the domain event occurred. +[DebuggerDisplay("MediaConsumptionRecordId: {MediaConsumptionRecordId.Value}; MediaKind: {MediaKind}")] +public record MediaConsumptionStoppedDomainEvent( + Guid Id, + MediaConsumptionRecordId MediaConsumptionRecordId, + UserId UserId, + LibraryId LibraryId, + MediaItemId MediaItemId, + MediaKind MediaKind, + Optional LastPosition, + double LastProgressFraction, + TimeSpan ConsumedDuration, + int ConsecutivePagesRead, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/MediaConsumptionRecord.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/MediaConsumptionRecord.cs new file mode 100644 index 00000000..d61676a3 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/MediaConsumptionRecord.cs @@ -0,0 +1,511 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate; + +/// +/// Aggregate root for a media consumption session. +/// +[DebuggerDisplay("Id: {Id.Value}; MediaKind: {MediaKind}; Status: {Status}")] +public sealed class MediaConsumptionRecord : AggregateRoot +{ + /// + /// Gets the object representing the unique identifier of the user that started the consumption session. + /// + public UserId UserId { get; private set; } + + /// + /// Gets the Id of the media library that contains the consumed media item. + /// + public LibraryId LibraryId { get; private set; } + + /// + /// Gets the Id of the consumed media item. + /// + public MediaItemId MediaItemId { get; private set; } + + /// + /// Gets the kind of media that is consumed. + /// + public MediaKind MediaKind { get; private set; } + + /// + /// Gets the state of the consumption session. + /// + public ConsumptionStatus Status { get; private set; } + + /// + /// Gets the date and time when the consumption session started. + /// + public DateTime StartedOnUtc { get; private set; } + + /// + /// Gets the date and time when the consumption session last received activity. + /// + public DateTime LastActivityOnUtc { get; private set; } + + /// + /// Gets the date and time when the consumption session completed or stopped, if it has ended. + /// + public Optional EndedOnUtc { get; private set; } + + /// + /// Gets the active duration that the user has consumed in the session. It never decreases within one record. + /// + public TimeSpan ConsumedDuration { get; private set; } + + /// + /// Gets the last position reported for the media item, if the session has a known position. The position is the latest reported one, so it may + /// be earlier in the media item than a previously reported position. + /// + public Optional LastPosition { get; private set; } + + /// + /// Gets the latest reported progress fraction of the media item. It is the latest reported value, so it may be lower than a previously reported + /// fraction. + /// + public double LastProgressFraction { get; private set; } + + /// + /// Gets the number of consecutive pages reported read in the current session. It is zero for every kind of media except books. + /// + public int ConsecutivePagesRead { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The object representing the unique identifier of the consumption record. + /// The object representing the unique identifier of the user that started the consumption session. + /// The Id of the media library that contains the consumed media item. + /// The Id of the consumed media item. + /// The kind of media that is consumed. + /// The state of the consumption session. + /// The date and time when the consumption session started. + /// The date and time when the consumption session last received activity. + /// The date and time when the consumption session completed or stopped, if it has ended. + /// The active duration that the user has consumed in the session. + /// The last position reported for the media item, if the session has a known position. + /// The latest reported progress fraction of the media item. + /// The number of consecutive pages reported read in the current session. + private MediaConsumptionRecord( + MediaConsumptionRecordId id, + UserId userId, + LibraryId libraryId, + MediaItemId mediaItemId, + MediaKind mediaKind, + ConsumptionStatus status, + DateTime startedOnUtc, + DateTime lastActivityOnUtc, + Optional endedOnUtc, + TimeSpan consumedDuration, + Optional lastPosition, + double lastProgressFraction, + int consecutivePagesRead) : base(id) + { + Id = id; + UserId = userId; + LibraryId = libraryId; + MediaItemId = mediaItemId; + MediaKind = mediaKind; + Status = status; + StartedOnUtc = startedOnUtc; + LastActivityOnUtc = lastActivityOnUtc; + EndedOnUtc = endedOnUtc; + ConsumedDuration = consumedDuration; + LastPosition = lastPosition; + LastProgressFraction = lastProgressFraction; + ConsecutivePagesRead = consecutivePagesRead; + CreatedOnUtc = startedOnUtc; + UpdatedOnUtc = lastActivityOnUtc > startedOnUtc ? Optional.Some(lastActivityOnUtc) : Optional.None(); + } + + /// + /// Starts a new consumption session for a media item. + /// + /// The object representing the unique identifier of the user that starts the consumption session. + /// The Id of the media library that contains the consumed media item. + /// The Id of the consumed media item. + /// The kind of media that is consumed. + /// The position to initialize the session with, such as the position of an existing resume point, if any. + /// The progress fraction to initialize the session with, such as the fraction of an existing resume point. + /// + /// An containing either a successfully started , or an error message. + /// + public static Result Start(UserId userId, LibraryId libraryId, MediaItemId mediaItemId, MediaKind mediaKind, Optional lastPosition, double lastProgressFraction) + { + Optional ruleResult = MediaConsumptionRule.For(mediaKind); + if (!ruleResult.HasValue) + return Errors.MediaConsumption.UnsupportedMediaKind; + if (!IsProgressFractionValid(lastProgressFraction)) + return Errors.MediaConsumption.InvalidProgressFraction; + if (!DoesPositionMatchRule(ruleResult.Value, lastPosition)) + return Errors.MediaConsumption.InvalidMediaPosition; + + DateTime occurredOnUtc = DateTime.UtcNow; + MediaConsumptionRecord record = new( + MediaConsumptionRecordId.CreateUnique(), + userId, + libraryId, + mediaItemId, + mediaKind, + ConsumptionStatus.InProgress, + occurredOnUtc, + occurredOnUtc, + Optional.None(), + TimeSpan.Zero, + lastPosition, + lastProgressFraction, + 0); + + record._domainEvents.Add(new MediaConsumptionStartedDomainEvent( + Guid.NewGuid(), + record.Id, + userId, + libraryId, + mediaItemId, + mediaKind, + occurredOnUtc)); + return record; + } + + /// + /// Starts and completes a consumption session in the same call, for one-shot discrete kinds of media such as a photo view. + /// + /// The object representing the unique identifier of the user that consumed the media item. + /// The Id of the media library that contains the consumed media item. + /// The Id of the consumed media item. + /// The kind of media that is consumed. + /// + /// An containing either a successfully created completed , or an error message. + /// + public static Result StartCompleted(UserId userId, LibraryId libraryId, MediaItemId mediaItemId, MediaKind mediaKind) + { + Optional ruleResult = MediaConsumptionRule.For(mediaKind); + if (!ruleResult.HasValue) + return Errors.MediaConsumption.UnsupportedMediaKind; + if (!ruleResult.Value.IsOneShot) + return Errors.MediaConsumption.MediaKindCannotStartCompleted; + + DateTime occurredOnUtc = DateTime.UtcNow; + MediaConsumptionRecord record = new( + MediaConsumptionRecordId.CreateUnique(), + userId, + libraryId, + mediaItemId, + mediaKind, + ConsumptionStatus.Completed, + occurredOnUtc, + occurredOnUtc, + Optional.Some(occurredOnUtc), + TimeSpan.Zero, + Optional.None(), + 1, + 0); + + record._domainEvents.Add(new MediaConsumptionStartedDomainEvent( + Guid.NewGuid(), + record.Id, + userId, + libraryId, + mediaItemId, + mediaKind, + occurredOnUtc)); + record._domainEvents.Add(new MediaConsumptionCompletedDomainEvent( + Guid.NewGuid(), + record.Id, + userId, + libraryId, + mediaItemId, + mediaKind, + record.LastPosition, + record.LastProgressFraction, + record.ConsumedDuration, + record.ConsecutivePagesRead, + occurredOnUtc)); + return record; + } + + /// + /// Creates a new instance of the class, with pre-existing data. + /// + /// The object representing the unique identifier of the consumption record. + /// The object representing the unique identifier of the user that started the consumption session. + /// The Id of the media library that contains the consumed media item. + /// The Id of the consumed media item. + /// The kind of media that is consumed. + /// The state of the consumption session. + /// The date and time when the consumption session started. + /// The date and time when the consumption session last received activity. + /// The date and time when the consumption session completed or stopped, if it has ended. + /// The active duration that the user has consumed in the session. + /// The last position reported for the media item, if the session has a known position. + /// The latest reported progress fraction of the media item. + /// The number of consecutive pages reported read in the current session. + /// + /// An containing either a successfully reconstituted , or an error message. + /// + public static Result Reconstitute( + MediaConsumptionRecordId id, + UserId userId, + LibraryId libraryId, + MediaItemId mediaItemId, + MediaKind mediaKind, + ConsumptionStatus status, + DateTime startedOnUtc, + DateTime lastActivityOnUtc, + Optional endedOnUtc, + TimeSpan consumedDuration, + Optional lastPosition, + double lastProgressFraction, + int consecutivePagesRead) + { + Optional ruleResult = MediaConsumptionRule.For(mediaKind); + if (!ruleResult.HasValue) + return Errors.MediaConsumption.UnsupportedMediaKind; + if (consumedDuration < TimeSpan.Zero) + return Errors.MediaConsumption.ConsumedDurationMustBeNonNegative; + if (!IsProgressFractionValid(lastProgressFraction)) + return Errors.MediaConsumption.InvalidProgressFraction; + if (consecutivePagesRead < 0) + return Errors.MediaConsumption.ConsecutivePagesReadMustBeNonNegative; + if (consecutivePagesRead > 0 && !IsPageBased(ruleResult.Value)) + return Errors.MediaConsumption.ConsecutivePagesReadIsOnlySupportedForPageBasedMedia; + if (!DoesPositionMatchRule(ruleResult.Value, lastPosition)) + return Errors.MediaConsumption.InvalidMediaPosition; + if (status == ConsumptionStatus.InProgress && endedOnUtc.HasValue) + return Errors.MediaConsumption.InProgressConsumptionCannotHaveEndTime; + if (status != ConsumptionStatus.InProgress && !endedOnUtc.HasValue) + return Errors.MediaConsumption.EndedConsumptionMustHaveEndTime; + if (lastActivityOnUtc < startedOnUtc) + return Errors.MediaConsumption.LastActivityCannotPrecedeStart; + if (status != ConsumptionStatus.InProgress && endedOnUtc.Value < lastActivityOnUtc) + return Errors.MediaConsumption.EndedConsumptionCannotPrecedeLastActivity; + + return new MediaConsumptionRecord( + id, + userId, + libraryId, + mediaItemId, + mediaKind, + status, + startedOnUtc, + lastActivityOnUtc, + endedOnUtc, + consumedDuration, + lastPosition, + lastProgressFraction, + consecutivePagesRead); + } + + /// + /// Updates the measured progress of an in-progress consumption session. + /// + /// The last position reported by the client, if the report carries one. When it is absent, the last known position is kept. + /// The last progress fraction reported by the client. + /// The active duration consumed so far. + /// The number of consecutive pages read in the current session. + /// An representing either a successful update, or an error. + public Result ReportProgress(Optional lastPosition, double lastProgressFraction, TimeSpan consumedDuration, int consecutivePagesRead) + { + if (Status != ConsumptionStatus.InProgress) + return Errors.MediaConsumption.ConsumptionIsNotInProgress; + + Optional ruleResult = MediaConsumptionRule.For(MediaKind); + if (!ruleResult.HasValue) + return Errors.MediaConsumption.UnsupportedMediaKind; + if (!IsProgressFractionValid(lastProgressFraction)) + return Errors.MediaConsumption.InvalidProgressFraction; + if (consumedDuration < TimeSpan.Zero) + return Errors.MediaConsumption.ConsumedDurationMustBeNonNegative; + if (consumedDuration < ConsumedDuration) + return Errors.MediaConsumption.ConsumedDurationCannotDecrease; + if (consecutivePagesRead < 0) + return Errors.MediaConsumption.ConsecutivePagesReadMustBeNonNegative; + if (consecutivePagesRead > 0 && !IsPageBased(ruleResult.Value)) + return Errors.MediaConsumption.ConsecutivePagesReadIsOnlySupportedForPageBasedMedia; + if (!DoesPositionMatchRule(ruleResult.Value, lastPosition)) + return Errors.MediaConsumption.InvalidMediaPosition; + + if (lastPosition.HasValue) + LastPosition = lastPosition; + LastProgressFraction = lastProgressFraction; + ConsumedDuration = consumedDuration; + ConsecutivePagesRead = consecutivePagesRead; + + DateTime occurredOnUtc = GetNextActivityOnUtc(); + LastActivityOnUtc = occurredOnUtc; + UpdatedOnUtc = Optional.Some(occurredOnUtc); + _domainEvents.Add(new MediaConsumptionProgressedDomainEvent( + Guid.NewGuid(), + Id, + UserId, + LibraryId, + MediaItemId, + MediaKind, + LastPosition, + LastProgressFraction, + ConsumedDuration, + ConsecutivePagesRead, + occurredOnUtc)); + return Result.Updated; + } + + /// + /// Marks an in-progress consumption session as completed. + /// + /// The final position reported by the client, if the call carries one. When it is absent, the last known position is kept. + /// The final progress fraction reported by the client. + /// The active duration consumed by the session. + /// An representing either a successful completion, or an error. + public Result Complete(Optional lastPosition, double lastProgressFraction, TimeSpan consumedDuration) + { + if (Status != ConsumptionStatus.InProgress) + return Errors.MediaConsumption.ConsumptionIsAlreadyTerminal; + + Optional ruleResult = MediaConsumptionRule.For(MediaKind); + if (!ruleResult.HasValue) + return Errors.MediaConsumption.UnsupportedMediaKind; + if (!IsProgressFractionValid(lastProgressFraction)) + return Errors.MediaConsumption.InvalidProgressFraction; + if (consumedDuration < TimeSpan.Zero) + return Errors.MediaConsumption.ConsumedDurationMustBeNonNegative; + if (consumedDuration < ConsumedDuration) + return Errors.MediaConsumption.ConsumedDurationCannotDecrease; + if (!DoesPositionMatchRule(ruleResult.Value, lastPosition)) + return Errors.MediaConsumption.InvalidMediaPosition; + + if (lastPosition.HasValue) + LastPosition = lastPosition; + LastProgressFraction = lastProgressFraction; + ConsumedDuration = consumedDuration; + Status = ConsumptionStatus.Completed; + + DateTime occurredOnUtc = GetNextActivityOnUtc(); + EndedOnUtc = Optional.Some(occurredOnUtc); + LastActivityOnUtc = occurredOnUtc; + UpdatedOnUtc = Optional.Some(occurredOnUtc); + _domainEvents.Add(new MediaConsumptionCompletedDomainEvent( + Guid.NewGuid(), + Id, + UserId, + LibraryId, + MediaItemId, + MediaKind, + LastPosition, + LastProgressFraction, + ConsumedDuration, + ConsecutivePagesRead, + occurredOnUtc)); + return Result.Updated; + } + + /// + /// Marks an in-progress consumption session as stopped before it completed. + /// + /// The final position reported by the client, if the call carries one. When it is absent, the last known position is kept. + /// The final progress fraction reported by the client. + /// The active duration consumed by the session. + /// An representing either a successful stop, or an error. + public Result Stop(Optional lastPosition, double lastProgressFraction, TimeSpan consumedDuration) + { + if (Status != ConsumptionStatus.InProgress) + return Errors.MediaConsumption.ConsumptionIsAlreadyTerminal; + + Optional ruleResult = MediaConsumptionRule.For(MediaKind); + if (!ruleResult.HasValue) + return Errors.MediaConsumption.UnsupportedMediaKind; + if (!IsProgressFractionValid(lastProgressFraction)) + return Errors.MediaConsumption.InvalidProgressFraction; + if (consumedDuration < TimeSpan.Zero) + return Errors.MediaConsumption.ConsumedDurationMustBeNonNegative; + if (consumedDuration < ConsumedDuration) + return Errors.MediaConsumption.ConsumedDurationCannotDecrease; + if (!DoesPositionMatchRule(ruleResult.Value, lastPosition)) + return Errors.MediaConsumption.InvalidMediaPosition; + + if (lastPosition.HasValue) + LastPosition = lastPosition; + LastProgressFraction = lastProgressFraction; + ConsumedDuration = consumedDuration; + Status = ConsumptionStatus.Stopped; + + DateTime occurredOnUtc = GetNextActivityOnUtc(); + EndedOnUtc = Optional.Some(occurredOnUtc); + LastActivityOnUtc = occurredOnUtc; + UpdatedOnUtc = Optional.Some(occurredOnUtc); + _domainEvents.Add(new MediaConsumptionStoppedDomainEvent( + Guid.NewGuid(), + Id, + UserId, + LibraryId, + MediaItemId, + MediaKind, + LastPosition, + LastProgressFraction, + ConsumedDuration, + ConsecutivePagesRead, + occurredOnUtc)); + return Result.Updated; + } + + /// + /// Determines whether the progress fraction is a finite value between zero and one. + /// + /// The progress fraction to check. + /// if the progress fraction is valid, otherwise. + private static bool IsProgressFractionValid(double progressFraction) + { + return double.IsFinite(progressFraction) && progressFraction >= 0 && progressFraction <= 1; + } + + /// + /// Determines whether the rule of the media kind counts its sessions by the number of consecutive pages read. + /// + /// The consumption rule of the media kind. + /// if the rule is page based, otherwise. + private static bool IsPageBased(MediaConsumptionRule rule) + { + return rule is PageThresholdConsumptionRule; + } + + /// + /// Determines whether a reported position uses the position representation of the consumption rule of the media kind. + /// + /// The consumption rule of the media kind. + /// The reported position, if the report carries one. + /// if the position is valid for the media kind, otherwise. + private static bool DoesPositionMatchRule(MediaConsumptionRule rule, Optional lastPosition) + { + if (!lastPosition.HasValue) + return true; + return rule.PositionKind.HasValue && lastPosition.Value.Kind == rule.PositionKind.Value; + } + + /// + /// Gets the current UTC date and time, advanced past the last recorded activity so that activity timestamps never go backwards. When the last + /// recorded activity is already the maximum representable timestamp, that timestamp is returned instead of advancing it. + /// + /// The date and time of the new activity. + private DateTime GetNextActivityOnUtc() + { + DateTime utcNow = DateTime.UtcNow; + if (utcNow > LastActivityOnUtc) + return utcNow; + if (LastActivityOnUtc == DateTime.MaxValue) + return DateTime.MaxValue; + return LastActivityOnUtc.AddTicks(1); + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/AudiobookConsumptionRule.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/AudiobookConsumptionRule.cs index c43bd5ff..6eb589be 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/AudiobookConsumptionRule.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/AudiobookConsumptionRule.cs @@ -28,6 +28,11 @@ public sealed class AudiobookConsumptionRule : DurationThresholdConsumptionRule /// public override Optional PositionKind { get; } = MediaPositionKind.TimeOffset; + /// + /// Gets a value indicating whether a consumption session of this kind of media is a one-shot session, which completes at the moment it starts. + /// + public override bool IsOneShot { get; } = false; + /// /// Gets the minimum consumed duration that a session of this kind of media must reach to be counted, when it is not completed. /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/BookConsumptionRule.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/BookConsumptionRule.cs index 648831f9..6a903d1e 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/BookConsumptionRule.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/BookConsumptionRule.cs @@ -27,6 +27,11 @@ public sealed class BookConsumptionRule : PageThresholdConsumptionRule /// public override Optional PositionKind { get; } = MediaPositionKind.Location; + /// + /// Gets a value indicating whether a consumption session of this kind of media is a one-shot session, which completes at the moment it starts. + /// + public override bool IsOneShot { get; } = false; + /// /// Gets the minimum number of consecutive pages that a session of this kind of media must read to be counted, when it is not completed. /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/MediaConsumptionRecordId.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/MediaConsumptionRecordId.cs new file mode 100644 index 00000000..8b219eb2 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/MediaConsumptionRecordId.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects; + +/// +/// Value Object for the Id of a media consumption record. +/// +[DebuggerDisplay("{Value}")] +public sealed class MediaConsumptionRecordId : EntityId +{ + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private MediaConsumptionRecordId(Guid value) : base(value) + { + } + + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static MediaConsumptionRecordId CreateUnique() + { + return new MediaConsumptionRecordId(Guid.NewGuid()); + } + + /// + /// Creates a new instance of the class, from a pre-existing . + /// + /// The value used to create the instance. + /// The created instance. + public static MediaConsumptionRecordId Create(Guid value) + { + return new MediaConsumptionRecordId(value); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/MovieConsumptionRule.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/MovieConsumptionRule.cs index eb6a1ee8..e86cf9d5 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/MovieConsumptionRule.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/MovieConsumptionRule.cs @@ -28,6 +28,11 @@ public sealed class MovieConsumptionRule : DurationThresholdConsumptionRule /// public override Optional PositionKind { get; } = MediaPositionKind.TimeOffset; + /// + /// Gets a value indicating whether a consumption session of this kind of media is a one-shot session, which completes at the moment it starts. + /// + public override bool IsOneShot { get; } = false; + /// /// Gets the minimum consumed duration that a session of this kind of media must reach to be counted, when it is not completed. /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/MusicTrackConsumptionRule.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/MusicTrackConsumptionRule.cs index ec319036..1b3033bd 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/MusicTrackConsumptionRule.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/MusicTrackConsumptionRule.cs @@ -28,6 +28,11 @@ public sealed class MusicTrackConsumptionRule : DurationThresholdConsumptionRule /// public override Optional PositionKind { get; } = MediaPositionKind.TimeOffset; + /// + /// Gets a value indicating whether a consumption session of this kind of media is a one-shot session, which completes at the moment it starts. + /// + public override bool IsOneShot { get; } = false; + /// /// Gets the minimum consumed duration that a session of this kind of media must reach to be counted, when it is not completed. /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/PhotoConsumptionRule.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/PhotoConsumptionRule.cs index 3eee03d3..212e4454 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/PhotoConsumptionRule.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/PhotoConsumptionRule.cs @@ -26,4 +26,9 @@ public sealed class PhotoConsumptionRule : EverySessionConsumptionRule /// Gets the kind of position used to resume this kind of media. A photo cannot be resumed, so it has no position kind. /// public override Optional PositionKind { get; } = Optional.None(); + + /// + /// Gets a value indicating whether a consumption session of this kind of media is a one-shot session, which completes at the moment it starts. + /// + public override bool IsOneShot { get; } = true; } diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/PodcastEpisodeConsumptionRule.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/PodcastEpisodeConsumptionRule.cs index 257f480a..a3b27752 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/PodcastEpisodeConsumptionRule.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/PodcastEpisodeConsumptionRule.cs @@ -28,6 +28,11 @@ public sealed class PodcastEpisodeConsumptionRule : DurationThresholdConsumption /// public override Optional PositionKind { get; } = MediaPositionKind.TimeOffset; + /// + /// Gets a value indicating whether a consumption session of this kind of media is a one-shot session, which completes at the moment it starts. + /// + public override bool IsOneShot { get; } = false; + /// /// Gets the minimum consumed duration that a session of this kind of media must reach to be counted, when it is not completed. /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/TvEpisodeConsumptionRule.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/TvEpisodeConsumptionRule.cs index e3193902..61e5478c 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/TvEpisodeConsumptionRule.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/TvEpisodeConsumptionRule.cs @@ -28,6 +28,11 @@ public sealed class TvEpisodeConsumptionRule : DurationThresholdConsumptionRule /// public override Optional PositionKind { get; } = MediaPositionKind.TimeOffset; + /// + /// Gets a value indicating whether a consumption session of this kind of media is a one-shot session, which completes at the moment it starts. + /// + public override bool IsOneShot { get; } = false; + /// /// Gets the minimum consumed duration that a session of this kind of media must reach to be counted, when it is not completed. /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/VideoConsumptionRule.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/VideoConsumptionRule.cs index 62b1cdc3..c9801bde 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/VideoConsumptionRule.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/ValueObjects/VideoConsumptionRule.cs @@ -28,6 +28,11 @@ public sealed class VideoConsumptionRule : DurationThresholdConsumptionRule /// public override Optional PositionKind { get; } = MediaPositionKind.TimeOffset; + /// + /// Gets a value indicating whether a consumption session of this kind of media is a one-shot session, which completes at the moment it starts. + /// + public override bool IsOneShot { get; } = false; + /// /// Gets the minimum consumed duration that a session of this kind of media must reach to be counted, when it is not completed. ///