Skip to content

Usenet streaming with a WebDAV server and a SABnzbd-compatible API

C#

Improve speed deleting webdav directories.

nzbdav-dev12c5cecae76b
diff --git a/backend/Database/DavDatabaseContext.cs b/backend/Database/DavDatabaseContext.cs
index b93dfb2c..345c213c 100644
--- a/backend/Database/DavDatabaseContext.cs
+++ b/backend/Database/DavDatabaseContext.cs
@@ -1,7 +1,9 @@
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using NzbWebDAV.Database.Interceptors;
+using NzbWebDAV.Database.MigrationHelpers;
using NzbWebDAV.Database.Models;
using NzbWebDAV.Utils;
@@ -16,6 +18,7 @@ public sealed class DavDatabaseContext() : DbContext(Options.Value)
new DbContextOptionsBuilder<DavDatabaseContext>()
.UseSqlite($"Data Source={DatabaseFilePath}")
.AddInterceptors(new SqliteForeignKeyEnabler())
+ .ReplaceService<IMigrationsSqlGenerator, SqliteMigrationsSqlGenerator<SqliteMigrationsSqlGenerator>>()
.Options
);
@@ -33,6 +36,7 @@ public sealed class DavDatabaseContext() : DbContext(Options.Value)
public DbSet<ConfigItem> ConfigItems => Set<ConfigItem>();
public DbSet<BlobCleanupItem> BlobCleanupItems => Set<BlobCleanupItem>();
public DbSet<HistoryCleanupItem> HistoryCleanupItems => Set<HistoryCleanupItem>();
+ public DbSet<DavCleanupItem> DavCleanupItems => Set<DavCleanupItem>();
// blob items
public List<DavNzbFile> BlobNzbFiles = [];
@@ -123,11 +127,6 @@ public sealed class DavDatabaseContext() : DbContext(Options.Value)
.ValueGeneratedNever()
.IsRequired(false);
- e.HasOne(i => i.Parent)
- .WithMany(p => p.Children)
- .HasForeignKey(i => i.ParentId)
- .OnDelete(DeleteBehavior.Cascade);
-
e.HasIndex(i => new { i.ParentId, i.Name })
.IsUnique();
@@ -449,6 +448,16 @@ public sealed class DavDatabaseContext() : DbContext(Options.Value)
e.Property(i => i.Id)
.ValueGeneratedNever();
});
+
+ // DavCleanupItem
+ b.Entity<DavCleanupItem>(e =>
+ {
+ e.ToTable("DavCleanupItems");
+ e.HasKey(i => i.Id);
+
+ e.Property(i => i.Id)
+ .ValueGeneratedNever();
+ });
}
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
diff --git a/backend/Database/MigrationHelpers/Attributes/ExecuteAfterAttribute.cs b/backend/Database/MigrationHelpers/Attributes/ExecuteAfterAttribute.cs
new file mode 100644
index 00000000..7453b82b
--- /dev/null
+++ b/backend/Database/MigrationHelpers/Attributes/ExecuteAfterAttribute.cs
@@ -0,0 +1,6 @@
+namespace NzbWebDAV.Database.MigrationHelpers.Attributes;
+
+[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
+public class ExecuteAfterAttribute : Attribute
+{
+}
diff --git a/backend/Database/MigrationHelpers/Attributes/ExecuteBeforeAttribute.cs b/backend/Database/MigrationHelpers/Attributes/ExecuteBeforeAttribute.cs
new file mode 100644
index 00000000..4d40aaa4
--- /dev/null
+++ b/backend/Database/MigrationHelpers/Attributes/ExecuteBeforeAttribute.cs
@@ -0,0 +1,6 @@
+namespace NzbWebDAV.Database.MigrationHelpers.Attributes;
+
+[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
+public class ExecuteBeforeAttribute : Attribute
+{
+}
diff --git a/backend/Database/MigrationHelpers/BaseMigrationOperation.cs b/backend/Database/MigrationHelpers/BaseMigrationOperation.cs
new file mode 100644
index 00000000..9214c7e9
--- /dev/null
+++ b/backend/Database/MigrationHelpers/BaseMigrationOperation.cs
@@ -0,0 +1,13 @@
+using Microsoft.EntityFrameworkCore.Metadata;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Migrations.Operations;
+
+namespace NzbWebDAV.Database.MigrationHelpers;
+
+public abstract class BaseMigrationOperation : MigrationOperation
+{
+ public abstract void Generate(
+ MigrationsSqlGeneratorDependencies dependencies,
+ IModel? model,
+ MigrationCommandListBuilder builder);
+}
\ No newline at end of file
diff --git a/backend/Database/MigrationHelpers/MigrationBuilderExtensions.cs b/backend/Database/MigrationHelpers/MigrationBuilderExtensions.cs
new file mode 100644
index 00000000..63009372
--- /dev/null
+++ b/backend/Database/MigrationHelpers/MigrationBuilderExtensions.cs
@@ -0,0 +1,32 @@
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Migrations.Operations;
+using Microsoft.EntityFrameworkCore.Migrations.Operations.Builders;
+using NzbWebDAV.Database.MigrationHelpers.Operations;
+
+namespace NzbWebDAV.Database.MigrationHelpers;
+
+public static class MigrationBuilderExtensions
+{
+ extension(MigrationBuilder migrationBuilder)
+ {
+ private OperationBuilder<TOperation> AddOperation<TOperation>(TOperation operation)
+ where TOperation : MigrationOperation
+ {
+ migrationBuilder.Operations.Add(operation);
+ return new OperationBuilder<TOperation>(operation);
+ }
+
+ /// <summary>
+ /// Execute arbitrary SQL before EF Core's standard migration operations (including table rebuilds).
+ /// </summary>
+ public OperationBuilder<ArbitrarySqlBefore> SqlBefore(string sql)
+ => migrationBuilder.AddOperation(new ArbitrarySqlBefore(sql));
+
+ /// <summary>
+ /// Execute arbitrary SQL after EF Core's standard migration operations (including table rebuilds).
+ /// Use this for trigger creation when the migration includes DropForeignKey or other table-rebuilding operations.
+ /// </summary>
+ public OperationBuilder<ArbitrarySqlAfter> SqlAfter(string sql)
+ => migrationBuilder.AddOperation(new ArbitrarySqlAfter(sql));
+ }
+}
\ No newline at end of file
diff --git a/backend/Database/MigrationHelpers/Operations/ArbitrarySqlAfter.cs b/backend/Database/MigrationHelpers/Operations/ArbitrarySqlAfter.cs
new file mode 100644
index 00000000..9b8e2160
--- /dev/null
+++ b/backend/Database/MigrationHelpers/Operations/ArbitrarySqlAfter.cs
@@ -0,0 +1,17 @@
+using Microsoft.EntityFrameworkCore.Metadata;
+using Microsoft.EntityFrameworkCore.Migrations;
+using NzbWebDAV.Database.MigrationHelpers.Attributes;
+
+namespace NzbWebDAV.Database.MigrationHelpers.Operations;
+
+[ExecuteAfter]
+public class ArbitrarySqlAfter(string sql) : BaseMigrationOperation
+{
+ public string Sql { get; } = sql;
+
+ public override void Generate(MigrationsSqlGeneratorDependencies dependencies, IModel? model, MigrationCommandListBuilder builder)
+ {
+ builder.Append(Sql);
+ builder.EndCommand();
+ }
+}
diff --git a/backend/Database/MigrationHelpers/Operations/ArbitrarySqlBefore.cs b/backend/Database/MigrationHelpers/Operations/ArbitrarySqlBefore.cs
new file mode 100644
index 00000000..9808d9a3
--- /dev/null
+++ b/backend/Database/MigrationHelpers/Operations/ArbitrarySqlBefore.cs
@@ -0,0 +1,17 @@
+using Microsoft.EntityFrameworkCore.Metadata;
+using Microsoft.EntityFrameworkCore.Migrations;
+using NzbWebDAV.Database.MigrationHelpers.Attributes;
+
+namespace NzbWebDAV.Database.MigrationHelpers.Operations;
+
+[ExecuteBefore]
+public class ArbitrarySqlBefore(string sql) : BaseMigrationOperation
+{
+ public string Sql { get; } = sql;
+
+ public override void Generate(MigrationsSqlGeneratorDependencies dependencies, IModel? model, MigrationCommandListBuilder builder)
+ {
+ builder.Append(Sql);
+ builder.EndCommand();
+ }
+}
diff --git a/backend/Database/MigrationHelpers/SqliteMigrationsSqlGenerator.cs b/backend/Database/MigrationHelpers/SqliteMigrationsSqlGenerator.cs
new file mode 100644
index 00000000..a762f133
--- /dev/null
+++ b/backend/Database/MigrationHelpers/SqliteMigrationsSqlGenerator.cs
@@ -0,0 +1,76 @@
+using Microsoft.EntityFrameworkCore.Metadata;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Migrations.Operations;
+using NzbWebDAV.Database.MigrationHelpers.Attributes;
+
+namespace NzbWebDAV.Database.MigrationHelpers;
+
+/// <summary>
+/// Custom migrations SQL generator that reorders operations marked with ExecuteBefore/ExecuteAfter attributes.
+/// This ensures that custom SQL operations run at the correct time relative to EF Core's table rebuilds.
+/// </summary>
+public class SqliteMigrationsSqlGenerator<TGenerator> : IMigrationsSqlGenerator
+ where TGenerator : IMigrationsSqlGenerator
+{
+ public TGenerator BaseGenerator { get; }
+ protected MigrationsSqlGeneratorDependencies Dependencies { get; }
+
+ public SqliteMigrationsSqlGenerator(MigrationsSqlGeneratorDependencies dependencies,
+ IRelationalAnnotationProvider migrationsAnnotations)
+ {
+ if (Activator.CreateInstance(typeof(TGenerator), [dependencies, migrationsAnnotations]) is TGenerator generator)
+ {
+ BaseGenerator = generator;
+ Dependencies = dependencies;
+ }
+ else
+ {
+ throw new MissingMethodException(
+ $"{typeof(TGenerator)} is missing a constructor ({typeof(MigrationsSqlGeneratorDependencies)}, {typeof(IRelationalAnnotationProvider)})");
+ }
+ }
+
+ protected IReadOnlyList<MigrationCommand> Generate(List<MigrationOperation> operations, IModel? model)
+ {
+ var builder = new MigrationCommandListBuilder(Dependencies);
+ foreach (var operation in operations.OfType<BaseMigrationOperation>())
+ {
+ operation.Generate(Dependencies, model, builder);
+ }
+
+ return builder.GetCommandList();
+ }
+
+ public IReadOnlyList<MigrationCommand> Generate(
+ IReadOnlyList<MigrationOperation> operations,
+ IModel? model = null,
+ MigrationsSqlGenerationOptions options = MigrationsSqlGenerationOptions.Default)
+ {
+ var middleOperations = operations.ToList();
+
+ // Extract operations marked with ExecuteBefore
+ var operationsToExecuteBefore = middleOperations
+ .Where(o => o.GetType().CustomAttributes.Any(a => a.AttributeType == typeof(ExecuteBeforeAttribute)))
+ .ToList();
+ operationsToExecuteBefore.ForEach(o => middleOperations.Remove(o));
+
+ // Extract operations marked with ExecuteAfter
+ var operationsToExecuteAfter = middleOperations
+ .Where(o => o.GetType().CustomAttributes.Any(a => a.AttributeType == typeof(ExecuteAfterAttribute)))
+ .ToList();
+ operationsToExecuteAfter.ForEach(o => middleOperations.Remove(o));
+
+ // Generate SQL in order: before -> middle (EF Core) -> after
+ var before = Generate(operationsToExecuteBefore, model);
+ var middle = BaseGenerator.Generate(middleOperations, model, options);
+ var after = Generate(operationsToExecuteAfter, model);
+
+ // Combine and return
+ var combined = new List<MigrationCommand>();
+ combined.AddRange(before);
+ combined.AddRange(middle);
+ combined.AddRange(after);
+
+ return combined;
+ }
+}
\ No newline at end of file
diff --git a/backend/Database/Migrations/20260203071130_Add-DavCleanupItems-Table.Designer.cs b/backend/Database/Migrations/20260203071130_Add-DavCleanupItems-Table.Designer.cs
new file mode 100644
index 00000000..0927b6a0
--- /dev/null
+++ b/backend/Database/Migrations/20260203071130_Add-DavCleanupItems-Table.Designer.cs
@@ -0,0 +1,414 @@
+// <auto-generated />
+using System;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+using NzbWebDAV.Database;
+
+#nullable disable
+
+namespace NzbWebDAV.Database.Migrations
+{
+ [DbContext(typeof(DavDatabaseContext))]
+ [Migration("20260203071130_Add-DavCleanupItems-Table")]
+ partial class AddDavCleanupItemsTable
+ {
+ /// <inheritdoc />
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder.HasAnnotation("ProductVersion", "10.0.1");
+
+ modelBuilder.Entity("NzbWebDAV.Database.Models.Account", b =>
+ {
+ b.Property<int>("Type")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Username")
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("PasswordHash")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("RandomSalt")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.HasKey("Type", "Username");
+
+ b.ToTable("Accounts", (string)null);
+ });
+
+ modelBuilder.Entity("NzbWebDAV.Database.Models.BlobCleanupItem", b =>
+ {
+ b.Property<Guid>("Id")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("BlobCleanupItems", (string)null);
+ });
+
+ modelBuilder.Entity("NzbWebDAV.Database.Models.ConfigItem", b =>
+ {
+ b.Property<string>("ConfigName")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ConfigValue")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.HasKey("ConfigName");
+
+ b.ToTable("ConfigItems", (string)null);
+ });
+
+ modelBuilder.Entity("NzbWebDAV.Database.Models.DavCleanupItem", b =>
+ {
+ b.Property<Guid>("Id")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("DavCleanupItems", (string)null);
+ });
+
+ modelBuilder.Entity("NzbWebDAV.Database.Models.DavItem", b =>
+ {
+ b.Property<Guid>("Id")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("TEXT");
+
+ b.Property<Guid?>("FileBlobId")
+ .HasColumnType("TEXT");
+
+ b.Property<long?>("FileSize")
+ .HasColumnType("INTEGER");
+
+ b.Property<Guid?>("HistoryItemId")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("IdPrefix")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<long?>("LastHealthCheck")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Name")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.Property<long?>("NextHealthCheck")
+ .HasColumnType("INTEGER");
+
+ b.Property<Guid?>("ParentId")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Path")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<long?>("ReleaseDate")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SubType")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Type")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("IdPrefix", "Type");
+
+ b.HasIndex("ParentId", "Name")
+ .IsUnique();
+
+ b.HasIndex("HistoryItemId", "SubType", "CreatedAt");
+
+ b.HasIndex("HistoryItemId", "Type", "CreatedAt");
+
+ b.HasIndex("Type", "HistoryItemId", "NextHealthCheck", "ReleaseDate", "Id");
+
+ b.ToTable("DavItems", (string)null);
+ });
+
+ modelBuilder.Entity("NzbWebDAV.Database.Models.DavMultipartFile", b =>
+ {
+ b.Property<Guid>("Id")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Metadata")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("DavMultipartFiles", (string)null);
+ });
+
+ modelBuilder.Entity("NzbWebDAV.Database.Models.DavNzbFile", b =>
+ {
+ b.Property<Guid>("Id")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("SegmentIds")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("DavNzbFiles", (string)null);
+ });
+
+ modelBuilder.Entity("NzbWebDAV.Database.Models.DavRarFile", b =>
+ {
+ b.Property<Guid>("Id")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("RarParts")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("DavRarFiles", (string)null);
+ });
+
+ modelBuilder.Entity("NzbWebDAV.Database.Models.HealthCheckResult", b =>
+ {
+ b.Property<Guid>("Id")
+ .HasColumnType("TEXT");
+
+ b.Property<long>("CreatedAt")
+ .HasColumnType("INTEGER");
+
+ b.Property<Guid>("DavItemId")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Message")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Path")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<int>("RepairStatus")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Result")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("CreatedAt");
+
+ b.HasIndex("DavItemId")
+ .HasFilter("\"RepairStatus\" = 3");
+
+ b.HasIndex("Result", "RepairStatus", "CreatedAt");
+
+ b.ToTable("HealthCheckResults", (string)null);
+ });
+
+ modelBuilder.Entity("NzbWebDAV.Database.Models.HealthCheckStat", b =>
+ {
+ b.Property<long>("DateStartInclusive")
+ .HasColumnType("INTEGER");
+
+ b.Property<long>("DateEndExclusive")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Result")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("RepairStatus")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Count")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("DateStartInclusive", "DateEndExclusive", "Result", "RepairStatus");
+
+ b.ToTable("HealthCheckStats", (string)null);
+ });
+
+ modelBuilder.Entity("NzbWebDAV.Database.Models.HistoryCleanupItem", b =>
+ {
+ b.Property<Guid>("Id")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("HistoryCleanupItems", (string)null);
+ });
+
+ modelBuilder.Entity("NzbWebDAV.Database.Models.HistoryItem", b =>
+ {
+ b.Property<Guid>("Id")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Category")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("TEXT");
+
+ b.Property<Guid?>("DownloadDirId")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("DownloadStatus")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("DownloadTimeSeconds")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("FailMessage")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("FileName")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("JobName")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<long>("TotalSegmentBytes")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Category");
+
+ b.HasIndex("CreatedAt");
+
+ b.HasIndex("Category", "CreatedAt");
+
+ b.HasIndex("Category", "DownloadDirId");
+
+ b.ToTable("HistoryItems", (string)null);
+ });
+
+ modelBuilder.Entity("NzbWebDAV.Database.Models.QueueItem", b =>
+ {
+ b.Property<Guid>("Id")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Category")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("FileName")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("JobName")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<long>("NzbFileSize")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime?>("PauseUntil")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("PostProcessing")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Priority")
+ .HasColumnType("INTEGER");
+
+ b.Property<long>("TotalSegmentBytes")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Category");
+
+ b.HasIndex("CreatedAt");
+
+ b.HasIndex("FileName")
+ .IsUnique();
+
+ b.HasIndex("Priority");
+
+ b.HasIndex("Priority", "CreatedAt");
+
+ b.HasIndex("Category", "Priority", "CreatedAt");
+
+ b.ToTable("QueueItems", (string)null);
+ });
+
+ modelBuilder.Entity("NzbWebDAV.Database.Models.QueueNzbContents", b =>
+ {
+ b.Property<Guid>("Id")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NzbContents")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("QueueNzbContents", (string)null);
+ });
+
+ modelBuilder.Entity("NzbWebDAV.Database.Models.DavMultipartFile", b =>
+ {
+ b.HasOne("NzbWebDAV.Database.Models.DavItem", "DavItem")
+ .WithOne()
+ .HasForeignKey("NzbWebDAV.Database.Models.DavMultipartFile", "Id")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("DavItem");
+ });
+
+ modelBuilder.Entity("NzbWebDAV.Database.Models.DavNzbFile", b =>
+ {
+ b.HasOne("NzbWebDAV.Database.Models.DavItem", "DavItem")
+ .WithOne()
+ .HasForeignKey("NzbWebDAV.Database.Models.DavNzbFile", "Id")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("DavItem");
+ });
+
+ modelBuilder.Entity("NzbWebDAV.Database.Models.DavRarFile", b =>
+ {
+ b.HasOne("NzbWebDAV.Database.Models.DavItem", "DavItem")
+ .WithOne()
+ .HasForeignKey("NzbWebDAV.Database.Models.DavRarFile", "Id")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("DavItem");
+ });
+
+ modelBuilder.Entity("NzbWebDAV.Database.Models.QueueNzbContents", b =>
+ {
+ b.HasOne("NzbWebDAV.Database.Models.QueueItem", "QueueItem")
+ .WithOne()
+ .HasForeignKey("NzbWebDAV.Database.Models.QueueNzbContents", "Id")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("QueueItem");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/backend/Database/Migrations/20260203071130_Add-DavCleanupItems-Table.cs b/backend/Database/Migrations/20260203071130_Add-DavCleanupItems-Table.cs
new file mode 100644
index 00000000..12f79be4
--- /dev/null
+++ b/backend/Database/Migrations/20260203071130_Add-DavCleanupItems-Table.cs
@@ -0,0 +1,97 @@
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+using NzbWebDAV.Database.MigrationHelpers;
+
+#nullable disable
+
+namespace NzbWebDAV.Database.Migrations
+{
+ /// <inheritdoc />
+ public partial class AddDavCleanupItemsTable : Migration
+ {
+ /// <inheritdoc />
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropForeignKey(
+ name: "FK_DavItems_DavItems_ParentId",
+ table: "DavItems");
+
+ migrationBuilder.CreateTable(
+ name: "DavCleanupItems",
+ columns: table => new
+ {
+ Id = table.Column<Guid>(type: "TEXT", nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_DavCleanupItems", x => x.Id);
+ });
+
+ // Recreate triggers destroyed by DropForeignKey's table rebuild (runs AFTER EF Core operations)
+ // And add new `TR_DavItems_DeleteDirectory` trigger.
+ migrationBuilder.SqlAfter(
+ """
+ CREATE TRIGGER TR_DavItems_Delete_AddBlobCleanup
+ AFTER DELETE ON DavItems
+ WHEN OLD.FileBlobId IS NOT NULL
+ BEGIN
+ INSERT INTO BlobCleanupItems (Id)
+ VALUES (OLD.FileBlobId);
+ END;
+
+ CREATE TRIGGER TR_DavItems_Update_AddBlobCleanup
+ AFTER UPDATE OF FileBlobId ON DavItems
+ WHEN OLD.FileBlobId IS NOT NULL AND OLD.FileBlobId != NEW.FileBlobId
+ BEGIN
+ INSERT INTO BlobCleanupItems (Id)
+ VALUES (OLD.FileBlobId);
+ END;
+
+ CREATE TRIGGER TR_DavItems_DeleteDirectory
+ AFTER DELETE ON DavItems
+ WHEN OLD.SubType = 101
+ BEGIN
+ INSERT INTO DavCleanupItems (Id)
+ VALUES (OLD.Id);
+ END;
+ """);
+ }
+
+ /// <inheritdoc />
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.Sql("DROP TRIGGER IF EXISTS TR_DavItems_DeleteDirectory;");
+
+ migrationBuilder.DropTable(
+ name: "DavCleanupItems");
+
+ migrationBuilder.AddForeignKey(
+ name: "FK_DavItems_DavItems_ParentId",
+ table: "DavItems",
+ column: "ParentId",
+ principalTable: "DavItems",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Cascade);
+
+ // Recreate triggers destroyed by AddForeignKey's table rebuild (runs AFTER EF Core operations)
+ migrationBuilder.SqlAfter(
+ """
+ CREATE TRIGGER TR_DavItems_Delete_AddBlobCleanup
+ AFTER DELETE ON DavItems
+ WHEN OLD.FileBlobId IS NOT NULL
+ BEGIN
+ INSERT INTO BlobCleanupItems (Id)
+ VALUES (OLD.FileBlobId);
+ END;
+
+ CREATE TRIGGER TR_DavItems_Update_AddBlobCleanup
+ AFTER UPDATE OF FileBlobId ON DavItems
+ WHEN OLD.FileBlobId IS NOT NULL AND OLD.FileBlobId != NEW.FileBlobId
+ BEGIN
+ INSERT INTO BlobCleanupItems (Id)
+ VALUES (OLD.FileBlobId);
+ END;
+ """);
+ }
+ }
+}
diff --git a/backend/Database/Migrations/DavDatabaseContextModelSnapshot.cs b/backend/Database/Migrations/DavDatabaseContextModelSnapshot.cs
index 3b3ba936..516ff24a 100644
--- a/backend/Database/Migrations/DavDatabaseContextModelSnapshot.cs
+++ b/backend/Database/Migrations/DavDatabaseContextModelSnapshot.cs
@@ -63,6 +63,16 @@ namespace NzbWebDAV.Database.Migrations
b.ToTable("ConfigItems", (string)null);
});
+ modelBuilder.Entity("NzbWebDAV.Database.Models.DavCleanupItem", b =>
+ {
+ b.Property<Guid>("Id")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("DavCleanupItems", (string)null);
+ });
+
modelBuilder.Entity("NzbWebDAV.Database.Models.DavItem", b =>
{
b.Property<Guid>("Id")
@@ -352,16 +362,6 @@ namespace NzbWebDAV.Database.Migrations
b.ToTable("QueueNzbContents", (string)null);
});
- modelBuilder.Entity("NzbWebDAV.Database.Models.DavItem", b =>
- {
- b.HasOne("NzbWebDAV.Database.Models.DavItem", "Parent")
- .WithMany("Children")
- .HasForeignKey("ParentId")
- .OnDelete(DeleteBehavior.Cascade);
-
- b.Navigation("Parent");
- });
-
modelBuilder.Entity("NzbWebDAV.Database.Models.DavMultipartFile", b =>
{
b.HasOne("NzbWebDAV.Database.Models.DavItem", "DavItem")
@@ -405,11 +405,6 @@ namespace NzbWebDAV.Database.Migrations
b.Navigation("QueueItem");
});
-
- modelBuilder.Entity("NzbWebDAV.Database.Models.DavItem", b =>
- {
- b.Navigation("Children");
- });
#pragma warning restore 612, 618
}
}
diff --git a/backend/Database/Models/DavCleanupItem.cs b/backend/Database/Models/DavCleanupItem.cs
new file mode 100644
index 00000000..5be02850
--- /dev/null
+++ b/backend/Database/Models/DavCleanupItem.cs
@@ -0,0 +1,9 @@
+using System.Text.Json.Serialization;
+using NzbWebDAV.Extensions;
+
+namespace NzbWebDAV.Database.Models;
+
+public class DavCleanupItem
+{
+ public Guid Id { get; set; }
+}
\ No newline at end of file
diff --git a/backend/Database/Models/DavItem.cs b/backend/Database/Models/DavItem.cs
index 59259a83..f559defc 100644
--- a/backend/Database/Models/DavItem.cs
+++ b/backend/Database/Models/DavItem.cs
@@ -81,13 +81,6 @@ public class DavItem
MultipartFile = 203,
}
- // navigation helpers
- [JsonIgnore]
- public DavItem? Parent { get; set; }
-
- [JsonIgnore]
- public ICollection<DavItem> Children { get; set; } = new List<DavItem>();
-
// static instances
// Important: assigned values cannot be
// changed without a database migration.
diff --git a/backend/Program.cs b/backend/Program.cs
index 262ca22d..9a5944b2 100644
--- a/backend/Program.cs
+++ b/backend/Program.cs
@@ -87,6 +87,7 @@ class Program
.AddHostedService<ArrMonitoringService>()
.AddHostedService<BlobCleanupService>()
.AddHostedService<HistoryCleanupService>()
+ .AddHostedService<DavCleanupService>()
.AddHostedService<UsenetFileToBlobstoreMigrationService>()
.AddScoped<DavDatabaseContext>()
.AddScoped<DavDatabaseClient>()
diff --git a/backend/Services/DavCleanupService.cs b/backend/Services/DavCleanupService.cs
new file mode 100644
index 00000000..6a244b30
--- /dev/null
+++ b/backend/Services/DavCleanupService.cs
@@ -0,0 +1,50 @@
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Hosting;
+using NzbWebDAV.Database;
+using Serilog;
+
+namespace NzbWebDAV.Services;
+
+public class DavCleanupService : BackgroundService
+{
+ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
+ {
+ while (!stoppingToken.IsCancellationRequested)
+ {
+ try
+ {
+ await using var dbContext = new DavDatabaseContext();
+
+ // Get the first item from the queue
+ var cleanupItem = await dbContext.DavCleanupItems
+ .FirstOrDefaultAsync(stoppingToken)
+ .ConfigureAwait(false);
+
+ // If no items in queue, wait 10 seconds before checking again
+ if (cleanupItem == null)
+ {
+ await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken).ConfigureAwait(false);
+ continue;
+ }
+
+ // Delete any children
+ await dbContext.Items
+ .Where(x => x.ParentId == cleanupItem.Id)
+ .ExecuteDeleteAsync(stoppingToken);
+
+ // Remove the queue item from database
+ dbContext.DavCleanupItems.Remove(cleanupItem);
+ await dbContext.SaveChangesAsync(stoppingToken).ConfigureAwait(false);
+
+ // Continue immediately to next iteration to process more items
+ }
+ catch (Exception e)
+ {
+ Log.Error(e, $"Error processing dav cleanup queue: {e.Message}");
+
+ // Wait 10 seconds before continuing on exception
+ await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken).ConfigureAwait(false);
+ }
+ }
+ }
+}