//
// 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/.
//
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Serilog;
namespace slskd.Events;
///
/// 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();
///
/// 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;
}
}
///
/// Removes event records older than the specified .
///
/// The age after which event records are eligible for pruning, in days.
/// The number of pruned event records.
public virtual int Prune(int ageInDays)
{
try
{
using var context = ContextFactory.CreateDbContext();
var cutoffDateTime = DateTime.UtcNow.AddDays(-ageInDays);
var pruned = context.Events.Where(e => e.Timestamp < cutoffDateTime).ExecuteDelete();
if (pruned > 0)
{
Log.Debug("Pruned {Count} expired events", pruned);
}
return pruned;
}
catch (Exception ex)
{
Log.Error(ex, "Failed to prune events: {Message}", ex.Message);
throw;
}
}
}