using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Plugin.RecentlyAddedGuard.Core;
using MediaBrowser.Controller.Library;
namespace Jellyfin.Plugin.RecentlyAddedGuard.Services;
///
/// Writes "date added" through the library manager and remembers which items it is currently saving,
/// so the resulting ItemUpdated events can be ignored.
///
public sealed class LibraryItemDateWriter : IItemDateWriter
{
private readonly ILibraryManager _libraryManager;
private readonly ConcurrentDictionary _inFlight = new();
///
/// Initializes a new instance of the class.
///
/// The library manager.
public LibraryItemDateWriter(ILibraryManager libraryManager)
{
_libraryManager = libraryManager;
}
///
/// Checks whether the item is being saved by this writer right now.
///
/// The item.
/// true while a correction of the item is in progress.
public bool IsWriting(Guid itemId) => _inFlight.ContainsKey(itemId);
///
public async Task TrySetDateCreatedAsync(Guid itemId, DateTime dateCreated, CancellationToken cancellationToken)
{
var item = _libraryManager.GetItemById(itemId);
if (item is null)
{
return false;
}
_inFlight.TryAdd(itemId, 0);
try
{
item.DateCreated = dateCreated;
// MetadataEdit also lets the NFO saver (if enabled) write the restored .
await _libraryManager.UpdateItemAsync(item, item.GetParent(), ItemUpdateType.MetadataEdit, cancellationToken)
.ConfigureAwait(false);
return true;
}
finally
{
_inFlight.TryRemove(itemId, out _);
}
}
}