//
// Copyright (c) slskd Team. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see https://www.gnu.org/licenses/.
//
namespace slskd.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Serilog;
///
/// Manages events.
///
public class EventService
{
///
/// Initializes a new instance of the class.
///
///
public EventService(IDbContextFactory contextFactory)
{
ContextFactory = contextFactory;
}
private IDbContextFactory ContextFactory { get; }
private ILogger Log { get; } = Serilog.Log.ForContext();
///
/// Gets list of events, optionally applying the specified and .
///
/// The beginning offset for the page.
/// The page size limit.
/// The retrieved list.
/// Thrown when the specified is less than zero.
/// Thrown when the specified is zero.
public virtual IReadOnlyCollection Get(int offset = 0, int limit = int.MaxValue)
{
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), "Offset must be greater than or equal to zero");
}
if (limit <= 0)
{
throw new ArgumentOutOfRangeException(nameof(limit), "Limit must be greater than zero");
}
try
{
using var context = ContextFactory.CreateDbContext();
var events = context.Events
.OrderByDescending(e => e.Timestamp)
.Skip(offset)
.Take(limit)
.ToList();
return events;
}
catch (Exception ex)
{
Log.Error(ex, "Failed to get event records with options {Options}: {Message}", new { offset, limit }, ex.Message);
throw;
}
}
///
/// Gets the total number of events.
///
/// The total number of events.
public virtual int Count()
{
try
{
using var context = ContextFactory.CreateDbContext();
var count = context.Events.Count();
return count;
}
catch (Exception ex)
{
Log.Error(ex, "Failed to count event records: {Message}", ex.Message);
throw;
}
}
///
/// Adds the specified event .
///
///
/// To ensure proper construction of the record, use .
///
/// The record to add.
/// Thrown when the specified record is null.
public virtual void Add(EventRecord eventRecord)
{
if (eventRecord is null)
{
throw new ArgumentNullException(nameof(eventRecord));
}
try
{
using var context = ContextFactory.CreateDbContext();
context.Add(eventRecord);
context.SaveChanges();
}
catch (Exception ex)
{
Log.Error(ex, "Failed to add event record: {Message}", ex.Message);
throw;
}
}
}