Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add notification for item deleted #282

Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Jellyfin.Plugin.Webhook/Configuration/Web/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export default function (view) {
template: document.querySelector("#template-notification-type"),
values: {
"ItemAdded": "Item Added",
"ItemDeleted": "Item Deleted",
"PlaybackStart": "Playback Start",
"PlaybackProgress": "Playback Progress",
"PlaybackStop": "Playback Stop",
Expand Down
7 changes: 6 additions & 1 deletion Jellyfin.Plugin.Webhook/Destinations/NotificationType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,5 +123,10 @@ public enum NotificationType
/// <summary>
/// User data saved.
/// </summary>
UserDataSaved = 23
UserDataSaved = 23,

/// <summary>
/// Item Deleted notification.
/// </summary>
ItemDeleted = 24
}
20 changes: 17 additions & 3 deletions Jellyfin.Plugin.Webhook/Models/QueuedItemContainer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,33 @@ public class QueuedItemContainer
/// Initializes a new instance of the <see cref="QueuedItemContainer"/> class.
/// </summary>
/// <param name="id">The item id.</param>
public QueuedItemContainer(Guid id)
/// <param name="name">The item name (nullable).</param>
/// <param name="itemType">The item type.</param>
public QueuedItemContainer(Guid id, string? name = null, string? itemType = null)
{
ItemId = id;
Name = name;
ItemType = itemType;
RetryCount = 0;
}

/// <summary>
/// Gets or sets the current retry count.
/// Gets or sets the item name.
/// </summary>
public int RetryCount { get; set; }
public string? Name { get; set; }

/// <summary>
/// Gets or sets the item type.
/// </summary>
public string? ItemType { get; set; }

/// <summary>
/// Gets or sets the current item id.
/// </summary>
public Guid ItemId { get; set; }

/// <summary>
/// Gets or sets the current retry count.
/// </summary>
public int RetryCount { get; set; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System.Threading.Tasks;
using MediaBrowser.Controller.Entities;

namespace Jellyfin.Plugin.Webhook.Notifiers.ItemDeletedNotifier;

/// <summary>
/// Item deleted manager interface.
/// </summary>
public interface IItemDeletedManager
{
/// <summary>
/// Process the current queue.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public Task ProcessItemsAsync();

/// <summary>
/// Add item to process queue.
/// </summary>
/// <param name="item">The deleted item.</param>
public void AddItem(BaseItem item);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using Jellyfin.Plugin.Webhook.Destinations;
using Jellyfin.Plugin.Webhook.Helpers;
using Jellyfin.Plugin.Webhook.Models;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace Jellyfin.Plugin.Webhook.Notifiers.ItemDeletedNotifier;

/// <inheritdoc />
public class ItemDeletedManager : IItemDeletedManager
{
private readonly ILogger<ItemDeletedManager> _logger;
private readonly ILibraryManager _libraryManager;
private readonly IServerApplicationHost _applicationHost;
private readonly ConcurrentDictionary<Guid, QueuedItemContainer> _itemProcessQueue;
private readonly ConcurrentDictionary<Guid, BaseItem> _deletedItems;

/// <summary>
/// Initializes a new instance of the <see cref="ItemDeletedManager"/> class.
/// </summary>
/// <param name="logger">Instance of the <see cref="ILogger{ItemDeletedManager}"/> interface.</param>
/// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
/// <param name="applicationHost">Instance of the <see cref="IServerApplicationHost"/> interface.</param>
public ItemDeletedManager(
ILogger<ItemDeletedManager> logger,
ILibraryManager libraryManager,
IServerApplicationHost applicationHost)
{
_logger = logger;
_libraryManager = libraryManager;
_applicationHost = applicationHost;
_itemProcessQueue = new ConcurrentDictionary<Guid, QueuedItemContainer>();
_deletedItems = new ConcurrentDictionary<Guid, BaseItem>();
}

/// <inheritdoc />
public async Task ProcessItemsAsync()
{
_logger.LogDebug("ProcessItemsAsync");
// Attempt to process all items in queue.
var currentItems = _itemProcessQueue.ToArray();
if (currentItems.Length != 0)
{
var scope = _applicationHost.ServiceProvider!.CreateAsyncScope();
await using (scope.ConfigureAwait(false))
{
var webhookSender = scope.ServiceProvider.GetRequiredService<IWebhookSender>();
foreach (var (key, container) in currentItems)
{
if (_deletedItems.TryGetValue(key, out var item))
{
if (item != null)
{
// Skip notification if item type is Studio
if (container.ItemType == "Studio")
{
_logger.LogDebug("Skipping notification for item type Studio");
_itemProcessQueue.TryRemove(key, out _);
_deletedItems.TryRemove(key, out _);
continue;
}

_logger.LogDebug("Notifying for {ItemName}", container.Name);

// Send notification to each configured destination.
var dataObject = DataObjectHelpers
.GetBaseDataObject(_applicationHost, NotificationType.ItemDeleted)
.AddBaseItemData(item);

var itemType = Type.GetType($"MediaBrowser.Controller.Entities.{container.ItemType}");
await webhookSender.SendNotification(NotificationType.ItemDeleted, dataObject, itemType)
.ConfigureAwait(false);

// Remove item from queue.
_itemProcessQueue.TryRemove(key, out _);
_deletedItems.TryRemove(key, out _);
}
}
Fixed Show fixed Hide fixed
}
}
}
}

/// <inheritdoc />
public void AddItem(BaseItem item)
{
var itemType = item.GetType().Name;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of stringifying the item type, why not just pass the type in?

_itemProcessQueue.TryAdd(item.Id, new QueuedItemContainer(item.Id, item.Name, itemType));
_deletedItems.TryAdd(item.Id, item);
_logger.LogDebug("Queued {ItemName} for notification", item.Name);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Library;
using Microsoft.Extensions.Hosting;

namespace Jellyfin.Plugin.Webhook.Notifiers.ItemDeletedNotifier;

/// <summary>
/// Notifier when a library item is deleted.
/// </summary>
public class ItemDeletedNotifierEntryPoint : IHostedService
{
private readonly IItemDeletedManager _itemDeletedManager;
private readonly ILibraryManager _libraryManager;

/// <summary>
/// Initializes a new instance of the <see cref="ItemDeletedNotifierEntryPoint"/> class.
/// </summary>
/// <param name="itemDeletedManager">Instance of the <see cref="IItemDeletedManager"/> interface.</param>
/// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
public ItemDeletedNotifierEntryPoint(
IItemDeletedManager itemDeletedManager,
ILibraryManager libraryManager)
{
_itemDeletedManager = itemDeletedManager;
_libraryManager = libraryManager;
}

private void ItemDeletedHandler(object? sender, ItemChangeEventArgs itemChangeEventArgs)
{
// Never notify on virtual items.
if (itemChangeEventArgs.Item.IsVirtualItem)
{
return;
}

_itemDeletedManager.AddItem(itemChangeEventArgs.Item);
}

/// <inheritdoc />
public Task StartAsync(CancellationToken cancellationToken)
{
_libraryManager.ItemRemoved += ItemDeletedHandler;
return Task.CompletedTask;
}

/// <inheritdoc />
public Task StopAsync(CancellationToken cancellationToken)
{
_libraryManager.ItemRemoved -= ItemDeletedHandler;
return Task.CompletedTask;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Tasks;

namespace Jellyfin.Plugin.Webhook.Notifiers.ItemDeletedNotifier;

/// <summary>
/// Scheduled task that processes item deleted events.
/// </summary>
public class ItemDeletedScheduledTask : IScheduledTask, IConfigurableScheduledTask
{
private const int RecheckIntervalSec = 30;
private readonly IItemDeletedManager _itemDeletedManager;
private readonly ILocalizationManager _localizationManager;

/// <summary>
/// Initializes a new instance of the <see cref="ItemDeletedScheduledTask"/> class.
/// </summary>
/// <param name="itemDeletedManager">Instance of the <see cref="IItemDeletedManager"/> interface.</param>
/// <param name="localizationManager">Instance of the <see cref="ILocalizationManager"/> interface.</param>
public ItemDeletedScheduledTask(
IItemDeletedManager itemDeletedManager,
ILocalizationManager localizationManager)
{
_itemDeletedManager = itemDeletedManager;
_localizationManager = localizationManager;
}

/// <inheritdoc />
public string Name => "Webhook Item Deleted Notifier";

/// <inheritdoc />
public string Key => "WebhookItemDeleted";

/// <inheritdoc />
public string Description => "Processes item deleted queue";

/// <inheritdoc />
public string Category => _localizationManager.GetLocalizedString("TasksLibraryCategory");

/// <inheritdoc />
public bool IsHidden => false;

/// <inheritdoc />
public bool IsEnabled => true;

/// <inheritdoc />
public bool IsLogged => false;

/// <inheritdoc />
public Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
{
return _itemDeletedManager.ProcessItemsAsync();
}

/// <inheritdoc />
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
{
return new[]
{
new TaskTriggerInfo
{
Type = TaskTriggerInfo.TriggerInterval,
IntervalTicks = TimeSpan.FromSeconds(RecheckIntervalSec).Ticks
}
};
}
}
3 changes: 3 additions & 0 deletions Jellyfin.Plugin.Webhook/PluginServiceRegistrator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
using Jellyfin.Plugin.Webhook.Helpers;
using Jellyfin.Plugin.Webhook.Notifiers;
using Jellyfin.Plugin.Webhook.Notifiers.ItemAddedNotifier;
using Jellyfin.Plugin.Webhook.Notifiers.ItemDeletedNotifier;
using Jellyfin.Plugin.Webhook.Notifiers.UserDataSavedNotifier;
using MediaBrowser.Common.Updates;
using MediaBrowser.Controller;
Expand Down Expand Up @@ -58,6 +59,7 @@ public void RegisterServices(IServiceCollection serviceCollection, IServerApplic
// Library consumers.
serviceCollection.AddScoped<IEventConsumer<SubtitleDownloadFailureEventArgs>, SubtitleDownloadFailureNotifier>();
serviceCollection.AddSingleton<IItemAddedManager, ItemAddedManager>();
serviceCollection.AddSingleton<IItemDeletedManager, ItemDeletedManager>();

// Security consumers.
serviceCollection.AddScoped<IEventConsumer<AuthenticationRequestEventArgs>, AuthenticationFailureNotifier>();
Expand Down Expand Up @@ -90,6 +92,7 @@ public void RegisterServices(IServiceCollection serviceCollection, IServerApplic

serviceCollection.AddHostedService<WebhookServerEntryPoint>();
serviceCollection.AddHostedService<ItemAddedNotifierEntryPoint>();
serviceCollection.AddHostedService<ItemDeletedNotifierEntryPoint>();
serviceCollection.AddHostedService<UserDataSavedNotifierEntryPoint>();
}
}