| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.IO; |
| | | 4 | | using System.Linq; |
| | | 5 | | using System.Text.Json; |
| | | 6 | | using System.Threading; |
| | | 7 | | using System.Threading.Tasks; |
| | | 8 | | using Jellyfin.Database.Implementations; |
| | | 9 | | using Jellyfin.Database.Implementations.Entities; |
| | | 10 | | using Jellyfin.Extensions; |
| | | 11 | | using MediaBrowser.Controller; |
| | | 12 | | using MediaBrowser.Controller.Entities; |
| | | 13 | | using MediaBrowser.Controller.Library; |
| | | 14 | | using MediaBrowser.Model.Entities; |
| | | 15 | | using Microsoft.EntityFrameworkCore; |
| | | 16 | | using Microsoft.Extensions.Logging; |
| | | 17 | | using LinkedChildType = Jellyfin.Database.Implementations.Entities.LinkedChildType; |
| | | 18 | | |
| | | 19 | | namespace Jellyfin.Server.Migrations.Routines; |
| | | 20 | | |
| | | 21 | | /// <summary> |
| | | 22 | | /// Migrates LinkedChildren data from JSON Data column to the LinkedChildren table. |
| | | 23 | | /// </summary> |
| | | 24 | | [JellyfinMigration("2026-01-13T12:00:00", nameof(MigrateLinkedChildren))] |
| | | 25 | | [JellyfinMigrationBackup(JellyfinDb = true)] |
| | | 26 | | internal class MigrateLinkedChildren : IDatabaseMigrationRoutine |
| | | 27 | | { |
| | | 28 | | private const int ParseProgressLogStep = 25_000; |
| | | 29 | | private const int FileCheckProgressLogStep = 10_000; |
| | | 30 | | private const int ResolveProgressLogStep = 10_000; |
| | | 31 | | private const int DeleteProgressLogStep = 25; |
| | | 32 | | private const string CollectionFolderTypeName = "MediaBrowser.Controller.Entities.CollectionFolder"; |
| | | 33 | | |
| | | 34 | | private readonly ILogger<MigrateLinkedChildren> _logger; |
| | | 35 | | private readonly IDbContextFactory<JellyfinDbContext> _dbProvider; |
| | | 36 | | private readonly ILibraryManager _libraryManager; |
| | | 37 | | private readonly IServerApplicationHost _appHost; |
| | | 38 | | private readonly IServerApplicationPaths _appPaths; |
| | | 39 | | |
| | | 40 | | public MigrateLinkedChildren( |
| | | 41 | | ILoggerFactory loggerFactory, |
| | | 42 | | IDbContextFactory<JellyfinDbContext> dbProvider, |
| | | 43 | | ILibraryManager libraryManager, |
| | | 44 | | IServerApplicationHost appHost, |
| | | 45 | | IServerApplicationPaths appPaths) |
| | | 46 | | { |
| | 6 | 47 | | _logger = loggerFactory.CreateLogger<MigrateLinkedChildren>(); |
| | 6 | 48 | | _dbProvider = dbProvider; |
| | 6 | 49 | | _libraryManager = libraryManager; |
| | 6 | 50 | | _appHost = appHost; |
| | 6 | 51 | | _appPaths = appPaths; |
| | 6 | 52 | | } |
| | | 53 | | |
| | | 54 | | /// <inheritdoc /> |
| | | 55 | | public Task PerformAsync(CancellationToken cancellationToken) |
| | | 56 | | { |
| | | 57 | | // This routine predates the async interface and has not been ported to async database access yet. |
| | 6 | 58 | | PerformCore(); |
| | 6 | 59 | | return Task.CompletedTask; |
| | | 60 | | } |
| | | 61 | | |
| | | 62 | | private void PerformCore() |
| | | 63 | | { |
| | 6 | 64 | | using var context = _dbProvider.CreateDbContext(); |
| | | 65 | | |
| | 6 | 66 | | var containerTypes = new[] |
| | 6 | 67 | | { |
| | 6 | 68 | | "MediaBrowser.Controller.Entities.Movies.BoxSet", |
| | 6 | 69 | | "MediaBrowser.Controller.Playlists.Playlist", |
| | 6 | 70 | | "MediaBrowser.Controller.Entities.CollectionFolder" |
| | 6 | 71 | | }; |
| | | 72 | | |
| | 6 | 73 | | var videoTypes = new[] |
| | 6 | 74 | | { |
| | 6 | 75 | | "MediaBrowser.Controller.Entities.Video", |
| | 6 | 76 | | "MediaBrowser.Controller.Entities.Movies.Movie", |
| | 6 | 77 | | "MediaBrowser.Controller.Entities.TV.Episode" |
| | 6 | 78 | | }; |
| | | 79 | | |
| | 6 | 80 | | var itemsWithData = context.BaseItems |
| | 6 | 81 | | .Where(b => b.Data != null && (containerTypes.Contains(b.Type) || videoTypes.Contains(b.Type))) |
| | 6 | 82 | | .Select(b => new { b.Id, b.Data, b.Type, b.Path, b.IsFolder }) |
| | 6 | 83 | | .ToList(); |
| | | 84 | | |
| | 6 | 85 | | _logger.LogInformation("Found {Count} potential items with LinkedChildren data to process.", itemsWithData.Count |
| | | 86 | | |
| | 6 | 87 | | var pathToIdMap = context.BaseItems |
| | 6 | 88 | | .Where(b => b.Path != null) |
| | 6 | 89 | | .Select(b => new { b.Id, b.Path }) |
| | 6 | 90 | | .GroupBy(b => b.Path!) |
| | 6 | 91 | | .ToDictionary(g => g.Key, g => g.First().Id); |
| | | 92 | | |
| | | 93 | | // Needed to tell a stale cached ItemId apart from one that still points at a real item. |
| | 6 | 94 | | var allItemIds = context.BaseItems.Select(b => b.Id).ToHashSet(); |
| | | 95 | | |
| | 6 | 96 | | var playlistParentIds = itemsWithData |
| | 6 | 97 | | .Where(b => b.Type == "MediaBrowser.Controller.Playlists.Playlist") |
| | 6 | 98 | | .Select(b => b.Id) |
| | 6 | 99 | | .ToHashSet(); |
| | | 100 | | |
| | 6 | 101 | | var droppedChildren = 0; |
| | 6 | 102 | | var linkedChildrenToAdd = new List<LinkedChildEntity>(); |
| | 6 | 103 | | var processedCount = 0; |
| | 6 | 104 | | var totalItems = itemsWithData.Count; |
| | | 105 | | |
| | 12 | 106 | | foreach (var item in itemsWithData) |
| | | 107 | | { |
| | 0 | 108 | | if (string.IsNullOrEmpty(item.Data)) |
| | | 109 | | { |
| | | 110 | | continue; |
| | | 111 | | } |
| | | 112 | | |
| | 0 | 113 | | if (processedCount > 0 && processedCount % ParseProgressLogStep == 0) |
| | | 114 | | { |
| | 0 | 115 | | _logger.LogInformation("Processing LinkedChildren: {Processed}/{Total} items", processedCount, totalItem |
| | | 116 | | } |
| | | 117 | | |
| | | 118 | | try |
| | | 119 | | { |
| | 0 | 120 | | using var doc = JsonDocument.Parse(item.Data); |
| | | 121 | | |
| | 0 | 122 | | var isVideo = videoTypes.Contains(item.Type); |
| | | 123 | | |
| | | 124 | | // Handle Video alternate versions |
| | 0 | 125 | | if (isVideo) |
| | | 126 | | { |
| | 0 | 127 | | ProcessVideoAlternateVersions(doc.RootElement, item.Id, pathToIdMap, allItemIds, linkedChildrenToAdd |
| | | 128 | | } |
| | | 129 | | |
| | | 130 | | // Handle LinkedChildren (for containers and other items) |
| | 0 | 131 | | if (!doc.RootElement.TryGetProperty("LinkedChildren", out var linkedChildrenElement) || linkedChildrenEl |
| | | 132 | | { |
| | 0 | 133 | | processedCount++; |
| | 0 | 134 | | continue; |
| | | 135 | | } |
| | | 136 | | |
| | | 137 | | // Legacy entries may hold a path relative to the container that holds them, so the |
| | | 138 | | // container's own location has to be a real path, not a virtual one. |
| | 0 | 139 | | var itemPath = item.Path is null ? null : _appHost.ExpandVirtualPath(item.Path); |
| | 0 | 140 | | var containingFolderPath = item.IsFolder ? itemPath : Path.GetDirectoryName(itemPath); |
| | 0 | 141 | | var sortOrder = 0; |
| | 0 | 142 | | foreach (var childElement in linkedChildrenElement.EnumerateArray()) |
| | | 143 | | { |
| | 0 | 144 | | var childId = ResolveChildId(childElement, containingFolderPath, pathToIdMap, allItemIds); |
| | 0 | 145 | | if (!childId.HasValue) |
| | | 146 | | { |
| | 0 | 147 | | droppedChildren++; |
| | 0 | 148 | | _logger.LogWarning( |
| | 0 | 149 | | "Dropping unresolvable LinkedChild of {ParentId}: ItemId {ItemId}, path {ChildPath}", |
| | 0 | 150 | | item.Id, |
| | 0 | 151 | | GetStringProperty(childElement, "ItemId") ?? "none", |
| | 0 | 152 | | GetStringProperty(childElement, "Path") ?? "none"); |
| | 0 | 153 | | continue; |
| | | 154 | | } |
| | | 155 | | |
| | 0 | 156 | | var childType = LinkedChildType.Manual; |
| | 0 | 157 | | if (childElement.TryGetProperty("Type", out var typeProp)) |
| | | 158 | | { |
| | 0 | 159 | | if (typeProp.ValueKind == JsonValueKind.Number) |
| | | 160 | | { |
| | 0 | 161 | | childType = (LinkedChildType)typeProp.GetInt32(); |
| | | 162 | | } |
| | 0 | 163 | | else if (typeProp.ValueKind == JsonValueKind.String) |
| | | 164 | | { |
| | 0 | 165 | | var typeStr = typeProp.GetString(); |
| | 0 | 166 | | if (Enum.TryParse<LinkedChildType>(typeStr, out var parsedType)) |
| | | 167 | | { |
| | 0 | 168 | | childType = parsedType; |
| | | 169 | | } |
| | | 170 | | } |
| | | 171 | | } |
| | | 172 | | |
| | 0 | 173 | | linkedChildrenToAdd.Add(new LinkedChildEntity |
| | 0 | 174 | | { |
| | 0 | 175 | | ParentId = item.Id, |
| | 0 | 176 | | ChildId = childId.Value, |
| | 0 | 177 | | ChildType = childType, |
| | 0 | 178 | | SortOrder = sortOrder |
| | 0 | 179 | | }); |
| | | 180 | | |
| | 0 | 181 | | sortOrder++; |
| | | 182 | | } |
| | | 183 | | |
| | 0 | 184 | | processedCount++; |
| | 0 | 185 | | } |
| | 0 | 186 | | catch (JsonException ex) |
| | | 187 | | { |
| | 0 | 188 | | _logger.LogWarning(ex, "Failed to parse JSON for item {ItemId}", item.Id); |
| | 0 | 189 | | } |
| | | 190 | | } |
| | | 191 | | |
| | 6 | 192 | | if (linkedChildrenToAdd.Count > 0) |
| | | 193 | | { |
| | 0 | 194 | | _logger.LogInformation("Inserting {Count} LinkedChildren records.", linkedChildrenToAdd.Count); |
| | | 195 | | |
| | 0 | 196 | | var existingKeys = context.LinkedChildren |
| | 0 | 197 | | .Select(lc => new { lc.ParentId, lc.ChildId }) |
| | 0 | 198 | | .ToHashSet(); |
| | | 199 | | |
| | | 200 | | // A playlist may list the same child more than once, so it cannot be keyed by |
| | | 201 | | // (ParentId, ChildId): skip a playlist wholesale if it already has rows instead, which |
| | | 202 | | // keeps the routine re-runnable without collapsing repeated entries. |
| | 0 | 203 | | var populatedParentIds = context.LinkedChildren |
| | 0 | 204 | | .Select(lc => lc.ParentId) |
| | 0 | 205 | | .Distinct() |
| | 0 | 206 | | .ToHashSet(); |
| | | 207 | | |
| | 0 | 208 | | var toInsert = linkedChildrenToAdd |
| | 0 | 209 | | .Where(lc => playlistParentIds.Contains(lc.ParentId) |
| | 0 | 210 | | ? !populatedParentIds.Contains(lc.ParentId) |
| | 0 | 211 | | : !existingKeys.Contains(new { lc.ParentId, lc.ChildId })) |
| | 0 | 212 | | .ToList(); |
| | | 213 | | |
| | 0 | 214 | | if (toInsert.Count > 0) |
| | | 215 | | { |
| | | 216 | | // Every container type other than a playlist keeps a single entry per child. |
| | | 217 | | // Priority: LocalAlternateVersion > LinkedAlternateVersion > Other |
| | 0 | 218 | | toInsert = |
| | 0 | 219 | | [ |
| | 0 | 220 | | .. toInsert.Where(lc => playlistParentIds.Contains(lc.ParentId)), |
| | 0 | 221 | | .. toInsert |
| | 0 | 222 | | .Where(lc => !playlistParentIds.Contains(lc.ParentId)) |
| | 0 | 223 | | .OrderBy(lc => lc.ChildType switch |
| | 0 | 224 | | { |
| | 0 | 225 | | LinkedChildType.LocalAlternateVersion => 0, |
| | 0 | 226 | | LinkedChildType.LinkedAlternateVersion => 1, |
| | 0 | 227 | | _ => 2 |
| | 0 | 228 | | }) |
| | 0 | 229 | | .DistinctBy(lc => new { lc.ParentId, lc.ChildId }) |
| | 0 | 230 | | ]; |
| | | 231 | | |
| | 0 | 232 | | var childIds = toInsert.Select(lc => lc.ChildId).Distinct().ToList(); |
| | 0 | 233 | | var existingChildIds = context.BaseItems |
| | 0 | 234 | | .WhereOneOrMany(childIds, b => b.Id) |
| | 0 | 235 | | .Select(b => b.Id) |
| | 0 | 236 | | .ToHashSet(); |
| | | 237 | | |
| | 0 | 238 | | toInsert = toInsert.Where(lc => existingChildIds.Contains(lc.ChildId)).ToList(); |
| | | 239 | | |
| | | 240 | | // Drop linked (user-merged) entries that point at items the parent owns (local |
| | | 241 | | // file-based alternates or extras). These stem from legacy data that merged an |
| | | 242 | | // owned item onto its own primary and would wrongly mark server-merged groups |
| | | 243 | | // as user-merged (splittable). |
| | 0 | 244 | | var linkedChildIds = toInsert |
| | 0 | 245 | | .Where(lc => lc.ChildType == LinkedChildType.LinkedAlternateVersion) |
| | 0 | 246 | | .Select(lc => lc.ChildId) |
| | 0 | 247 | | .Distinct() |
| | 0 | 248 | | .ToList(); |
| | | 249 | | |
| | 0 | 250 | | if (linkedChildIds.Count > 0) |
| | | 251 | | { |
| | 0 | 252 | | var ownerIdByChildId = context.BaseItems |
| | 0 | 253 | | .WhereOneOrMany(linkedChildIds, b => b.Id) |
| | 0 | 254 | | .Where(b => b.OwnerId.HasValue) |
| | 0 | 255 | | .Select(b => new { b.Id, b.OwnerId }) |
| | 0 | 256 | | .ToDictionary(b => b.Id, b => b.OwnerId!.Value); |
| | | 257 | | |
| | 0 | 258 | | var removedCount = toInsert.RemoveAll(lc => |
| | 0 | 259 | | lc.ChildType == LinkedChildType.LinkedAlternateVersion |
| | 0 | 260 | | && ownerIdByChildId.TryGetValue(lc.ChildId, out var ownerId) |
| | 0 | 261 | | && ownerId.Equals(lc.ParentId)); |
| | | 262 | | |
| | 0 | 263 | | if (removedCount > 0) |
| | | 264 | | { |
| | 0 | 265 | | _logger.LogInformation("Skipped {Count} LinkedAlternateVersion records pointing at items owned b |
| | | 266 | | } |
| | | 267 | | } |
| | | 268 | | |
| | 0 | 269 | | context.LinkedChildren.AddRange(toInsert); |
| | 0 | 270 | | context.SaveChanges(); |
| | | 271 | | |
| | 0 | 272 | | _logger.LogInformation("Successfully inserted {Count} LinkedChildren records.", toInsert.Count); |
| | | 273 | | } |
| | | 274 | | else |
| | | 275 | | { |
| | 0 | 276 | | _logger.LogInformation("All LinkedChildren records already exist, nothing to insert."); |
| | | 277 | | } |
| | | 278 | | } |
| | | 279 | | else |
| | | 280 | | { |
| | 6 | 281 | | _logger.LogInformation("No LinkedChildren data found to migrate."); |
| | | 282 | | } |
| | | 283 | | |
| | 6 | 284 | | _logger.LogInformation( |
| | 6 | 285 | | "LinkedChildren migration completed. Processed {Count} items, dropped {DroppedCount} unresolvable children." |
| | 6 | 286 | | processedCount, |
| | 6 | 287 | | droppedChildren); |
| | | 288 | | |
| | 6 | 289 | | CleanupWrongTypeAlternateVersions(context); |
| | 6 | 290 | | CleanupOrphanedAlternateVersionBaseItems(context); |
| | 6 | 291 | | CleanupItemsFromDeletedLibraries(context); |
| | 6 | 292 | | CleanupStaleFileEntries(context); |
| | 6 | 293 | | CleanupOrphanedLinkedChildren(context); |
| | 12 | 294 | | } |
| | | 295 | | |
| | | 296 | | private void CleanupWrongTypeAlternateVersions(JellyfinDbContext context) |
| | | 297 | | { |
| | 6 | 298 | | _logger.LogInformation("Cleaning up alternate version items with wrong type..."); |
| | | 299 | | |
| | | 300 | | // Find all LocalAlternateVersion relationships where the child is a generic Video |
| | | 301 | | // but the parent is a more specific type (like Movie). |
| | | 302 | | // Since IDs are computed from type + path, just updating the Type column would break ID lookups. |
| | | 303 | | // Instead, delete them and let the runtime recreate them with the correct type during the next library scan. |
| | 6 | 304 | | var wrongTypeChildIds = context.LinkedChildren |
| | 6 | 305 | | .Where(lc => lc.ChildType == LinkedChildType.LocalAlternateVersion) |
| | 6 | 306 | | .Join( |
| | 6 | 307 | | context.BaseItems, |
| | 6 | 308 | | lc => lc.ParentId, |
| | 6 | 309 | | parent => parent.Id, |
| | 6 | 310 | | (lc, parent) => new { lc.ChildId, ParentType = parent.Type }) |
| | 6 | 311 | | .Join( |
| | 6 | 312 | | context.BaseItems, |
| | 6 | 313 | | x => x.ChildId, |
| | 6 | 314 | | child => child.Id, |
| | 6 | 315 | | (x, child) => new { x.ChildId, x.ParentType, ChildType = child.Type }) |
| | 6 | 316 | | .Where(x => x.ChildType != x.ParentType) |
| | 6 | 317 | | .Select(x => x.ChildId) |
| | 6 | 318 | | .Distinct() |
| | 6 | 319 | | .ToList(); |
| | | 320 | | |
| | 6 | 321 | | if (wrongTypeChildIds.Count == 0) |
| | | 322 | | { |
| | 6 | 323 | | _logger.LogInformation("No wrong-type alternate version items found."); |
| | 6 | 324 | | return; |
| | | 325 | | } |
| | | 326 | | |
| | 0 | 327 | | _logger.LogInformation("Found {Count} wrong-type alternate version items to remove.", wrongTypeChildIds.Count); |
| | | 328 | | |
| | 0 | 329 | | var deleted = ResolveAndDeleteItems(wrongTypeChildIds, "wrong-type alternate version items"); |
| | | 330 | | |
| | 0 | 331 | | _logger.LogInformation("Removed {Count} wrong-type alternate version items. They will be recreated with the corr |
| | 0 | 332 | | } |
| | | 333 | | |
| | | 334 | | private void CleanupOrphanedAlternateVersionBaseItems(JellyfinDbContext context) |
| | | 335 | | { |
| | 6 | 336 | | _logger.LogInformation("Starting cleanup of orphaned alternate version BaseItems..."); |
| | | 337 | | |
| | | 338 | | // Find BaseItems that have OwnerId set (they belonged to another item) and are not extras, |
| | | 339 | | // but no LinkedChild entry references them — meaning they're orphaned alternate versions. |
| | | 340 | | // This happens when a version file is renamed: the old BaseItem remains in the DB |
| | | 341 | | // with a stale OwnerId but nothing links to it anymore. |
| | 6 | 342 | | var orphanedVersionIds = context.BaseItems |
| | 6 | 343 | | .Where(b => b.OwnerId.HasValue && b.ExtraType == null) |
| | 6 | 344 | | .Where(b => !context.LinkedChildren.Any(lc => lc.ChildId.Equals(b.Id))) |
| | 6 | 345 | | .Select(b => b.Id) |
| | 6 | 346 | | .ToList(); |
| | | 347 | | |
| | 6 | 348 | | if (orphanedVersionIds.Count == 0) |
| | | 349 | | { |
| | 6 | 350 | | _logger.LogInformation("No orphaned alternate version BaseItems found."); |
| | 6 | 351 | | return; |
| | | 352 | | } |
| | | 353 | | |
| | 0 | 354 | | _logger.LogInformation("Found {Count} orphaned alternate version BaseItems to remove.", orphanedVersionIds.Count |
| | | 355 | | |
| | 0 | 356 | | var deleted = ResolveAndDeleteItems(orphanedVersionIds, "orphaned alternate version BaseItems"); |
| | | 357 | | |
| | 0 | 358 | | _logger.LogInformation("Removed {Count} orphaned alternate version BaseItems.", deleted); |
| | 0 | 359 | | } |
| | | 360 | | |
| | | 361 | | private void CleanupItemsFromDeletedLibraries(JellyfinDbContext context) |
| | | 362 | | { |
| | 6 | 363 | | _logger.LogInformation("Starting cleanup of items from deleted libraries..."); |
| | | 364 | | |
| | | 365 | | // Find BaseItems whose TopParentId points to a library (collection folder) that no longer exists. |
| | | 366 | | // This happens when a library is removed but the scan didn't fully clean up all items under it. |
| | 6 | 367 | | var orphanedIds = context.BaseItems |
| | 6 | 368 | | .Where(b => b.TopParentId.HasValue) |
| | 6 | 369 | | .Where(b => !context.BaseItems.Any(lib => lib.Id.Equals(b.TopParentId!.Value))) |
| | 6 | 370 | | .Select(b => b.Id) |
| | 6 | 371 | | .ToList(); |
| | | 372 | | |
| | 6 | 373 | | if (orphanedIds.Count == 0) |
| | | 374 | | { |
| | 6 | 375 | | _logger.LogInformation("No items from deleted libraries found."); |
| | 6 | 376 | | return; |
| | | 377 | | } |
| | | 378 | | |
| | 0 | 379 | | _logger.LogInformation("Found {Count} items from deleted libraries to remove.", orphanedIds.Count); |
| | | 380 | | |
| | 0 | 381 | | var deleted = ResolveAndDeleteItems(orphanedIds, "items from deleted libraries"); |
| | | 382 | | |
| | 0 | 383 | | _logger.LogInformation("Removed {Count} items from deleted libraries.", deleted); |
| | 0 | 384 | | } |
| | | 385 | | |
| | | 386 | | private void CleanupStaleFileEntries(JellyfinDbContext context) |
| | | 387 | | { |
| | 6 | 388 | | _logger.LogInformation("Starting cleanup of items with missing files..."); |
| | | 389 | | |
| | | 390 | | // Get all library media locations and partition into accessible vs inaccessible. |
| | | 391 | | // This mirrors the scanner's safeguard: if a library root is inaccessible |
| | | 392 | | // (e.g. NAS offline), we skip items under it to avoid false deletions. |
| | 6 | 393 | | var virtualFolders = _libraryManager.GetVirtualFolders(); |
| | 6 | 394 | | var accessiblePaths = new List<string>(); |
| | 6 | 395 | | var inaccessiblePaths = new List<string>(); |
| | | 396 | | |
| | 22 | 397 | | foreach (var folder in virtualFolders) |
| | | 398 | | { |
| | 20 | 399 | | foreach (var location in folder.Locations) |
| | | 400 | | { |
| | 5 | 401 | | if (Directory.Exists(location) && Directory.EnumerateFileSystemEntries(location).Any()) |
| | | 402 | | { |
| | 5 | 403 | | accessiblePaths.Add(location); |
| | | 404 | | } |
| | | 405 | | else |
| | | 406 | | { |
| | 0 | 407 | | inaccessiblePaths.Add(location); |
| | 0 | 408 | | _logger.LogWarning( |
| | 0 | 409 | | "Library location {Path} is inaccessible or empty, skipping file existence checks for items unde |
| | 0 | 410 | | location); |
| | | 411 | | } |
| | | 412 | | } |
| | | 413 | | } |
| | | 414 | | |
| | 6 | 415 | | var allLibraryPaths = accessiblePaths.Concat(inaccessiblePaths).ToList(); |
| | | 416 | | |
| | | 417 | | // Get all non-folder, non-virtual items with paths from the DB |
| | 6 | 418 | | var itemsWithPaths = context.BaseItems |
| | 6 | 419 | | .Where(b => b.Path != null && b.Path != string.Empty) |
| | 6 | 420 | | .Where(b => !b.IsFolder && !b.IsVirtualItem) |
| | 6 | 421 | | .Select(b => new { b.Id, b.Path }) |
| | 6 | 422 | | .ToList(); |
| | | 423 | | |
| | 6 | 424 | | var internalMetadataPath = _appPaths.InternalMetadataPath; |
| | | 425 | | |
| | | 426 | | // An item outside every library location is normally left over from a removed media path, but |
| | | 427 | | // it looks exactly the same as one whose storage failed to mount (a wrong bind mount on the |
| | | 428 | | // first container start, for example). Only act on it while every location is readable. |
| | | 429 | | // Resolving no locations at all is the same hazard with none of the evidence: it cannot be |
| | | 430 | | // told apart from an install that has libraries the server has not read yet, and acting on it |
| | | 431 | | // means every file-backed item in the database is outside every location. |
| | 6 | 432 | | var canRemoveUnrootedItems = inaccessiblePaths.Count == 0 && allLibraryPaths.Count > 0; |
| | 6 | 433 | | var skippedUnrootedItems = 0; |
| | 6 | 434 | | var removedUnrootedItems = 0; |
| | | 435 | | |
| | | 436 | | // One library losing its definition folder is the same accident confined to that library: it |
| | | 437 | | // contributes no locations, so everything it held reads as unrooted while the other libraries |
| | | 438 | | // still look healthy enough to act on. |
| | 6 | 439 | | var itemsInMissingLibraries = GetItemsInMissingLibraries(context, virtualFolders); |
| | 6 | 440 | | var skippedMissingLibraryItems = 0; |
| | | 441 | | |
| | 6 | 442 | | var staleIds = new List<Guid>(); |
| | 6 | 443 | | var checkedCount = 0; |
| | 6 | 444 | | _logger.LogInformation("Checking {Total} items for missing files.", itemsWithPaths.Count); |
| | | 445 | | |
| | 24 | 446 | | foreach (var item in itemsWithPaths) |
| | | 447 | | { |
| | | 448 | | // A miss on offline storage can block for the mount timeout, so report while scanning. |
| | 6 | 449 | | if (checkedCount > 0 && checkedCount % FileCheckProgressLogStep == 0) |
| | | 450 | | { |
| | 0 | 451 | | _logger.LogInformation( |
| | 0 | 452 | | "Checking for missing files: {Checked}/{Total} items, {Stale} stale so far.", |
| | 0 | 453 | | checkedCount, |
| | 0 | 454 | | itemsWithPaths.Count, |
| | 0 | 455 | | staleIds.Count); |
| | | 456 | | } |
| | | 457 | | |
| | 6 | 458 | | checkedCount++; |
| | | 459 | | |
| | | 460 | | // Expand virtual path placeholders (%AppDataPath%, %MetadataPath%) to real paths |
| | 6 | 461 | | var path = _appHost.ExpandVirtualPath(item.Path!); |
| | | 462 | | |
| | | 463 | | // Skip items stored under internal metadata (images, subtitles, trickplay, etc.) |
| | 6 | 464 | | if (path.StartsWith(internalMetadataPath, StringComparison.OrdinalIgnoreCase)) |
| | | 465 | | { |
| | | 466 | | continue; |
| | | 467 | | } |
| | | 468 | | |
| | 6 | 469 | | if (accessiblePaths.Any(p => path.StartsWith(p, StringComparison.OrdinalIgnoreCase))) |
| | | 470 | | { |
| | | 471 | | // Item is under an accessible library location — check if it still exists |
| | | 472 | | // Directory check covers BDMV/DVD items whose Path points to a folder |
| | 2 | 473 | | if (!File.Exists(path) && !Directory.Exists(path)) |
| | | 474 | | { |
| | 1 | 475 | | _logger.LogDebug("Removing item {ItemId}: file {Path} no longer exists.", item.Id, path); |
| | 1 | 476 | | staleIds.Add(item.Id); |
| | | 477 | | } |
| | | 478 | | } |
| | 4 | 479 | | else if (!allLibraryPaths.Any(p => path.StartsWith(p, StringComparison.OrdinalIgnoreCase))) |
| | | 480 | | { |
| | | 481 | | // Item is not under ANY library location (accessible or not) — |
| | | 482 | | // it's orphaned from all libraries (e.g. media path was removed from config) |
| | 4 | 483 | | if (itemsInMissingLibraries.Contains(item.Id)) |
| | | 484 | | { |
| | | 485 | | // Its library is the thing that went missing, not its media path. |
| | 1 | 486 | | skippedMissingLibraryItems++; |
| | | 487 | | } |
| | 3 | 488 | | else if (canRemoveUnrootedItems) |
| | | 489 | | { |
| | 2 | 490 | | _logger.LogDebug("Removing item {ItemId}: path {Path} is outside every library location.", item.Id, |
| | 2 | 491 | | staleIds.Add(item.Id); |
| | 2 | 492 | | removedUnrootedItems++; |
| | | 493 | | } |
| | | 494 | | else |
| | | 495 | | { |
| | 1 | 496 | | skippedUnrootedItems++; |
| | | 497 | | } |
| | | 498 | | } |
| | | 499 | | |
| | | 500 | | // Otherwise: item is under an inaccessible location — skip (storage may be offline) |
| | | 501 | | } |
| | | 502 | | |
| | 6 | 503 | | if (skippedMissingLibraryItems > 0) |
| | | 504 | | { |
| | 1 | 505 | | _logger.LogWarning( |
| | 1 | 506 | | "Keeping {Count} items whose library definition is missing from {Path}. Restore the definition or recrea |
| | 1 | 507 | | skippedMissingLibraryItems, |
| | 1 | 508 | | _appPaths.DefaultUserViewsPath); |
| | | 509 | | } |
| | | 510 | | |
| | 6 | 511 | | if (skippedUnrootedItems > 0) |
| | | 512 | | { |
| | 1 | 513 | | if (allLibraryPaths.Count == 0) |
| | | 514 | | { |
| | 1 | 515 | | _logger.LogWarning( |
| | 1 | 516 | | "Keeping {Count} items that are outside every library location because this server resolved no libra |
| | 1 | 517 | | skippedUnrootedItems); |
| | | 518 | | } |
| | | 519 | | else |
| | | 520 | | { |
| | 0 | 521 | | _logger.LogWarning( |
| | 0 | 522 | | "Keeping {Count} items that are outside every library location because {LocationCount} library locat |
| | 0 | 523 | | skippedUnrootedItems, |
| | 0 | 524 | | inaccessiblePaths.Count); |
| | | 525 | | } |
| | | 526 | | } |
| | | 527 | | |
| | 6 | 528 | | if (staleIds.Count == 0) |
| | | 529 | | { |
| | 3 | 530 | | _logger.LogInformation("No stale items found."); |
| | 3 | 531 | | return; |
| | | 532 | | } |
| | | 533 | | |
| | | 534 | | // Whether an item went because its own file is gone or because nothing claims its path is the |
| | | 535 | | // difference between a handful of deletions and a whole library, so report the split. |
| | 3 | 536 | | _logger.LogInformation( |
| | 3 | 537 | | "Found {Count} stale items to remove, {UnrootedCount} of them because their path is outside every library lo |
| | 3 | 538 | | staleIds.Count, |
| | 3 | 539 | | removedUnrootedItems); |
| | | 540 | | |
| | 3 | 541 | | var deleted = ResolveAndDeleteItems(staleIds, "items with missing files"); |
| | | 542 | | |
| | 3 | 543 | | _logger.LogInformation("Removed {Count} stale items.", deleted); |
| | 3 | 544 | | } |
| | | 545 | | |
| | | 546 | | // Items under a library whose definition folder is gone. Their locations cannot be resolved, so |
| | | 547 | | // they read as unrooted, but the library is what went missing and the media path is still theirs. |
| | | 548 | | private HashSet<Guid> GetItemsInMissingLibraries(JellyfinDbContext context, IReadOnlyList<VirtualFolderInfo> virtual |
| | | 549 | | { |
| | 6 | 550 | | var liveLibraryPaths = virtualFolders |
| | 6 | 551 | | .Select(folder => Path.Combine(_appPaths.DefaultUserViewsPath, folder.Name)) |
| | 6 | 552 | | .ToHashSet(StringComparer.OrdinalIgnoreCase); |
| | | 553 | | |
| | 6 | 554 | | var missingLibraryIds = context.BaseItems |
| | 6 | 555 | | .Where(b => b.Type == CollectionFolderTypeName && b.Path != null) |
| | 6 | 556 | | .Select(b => new { b.Id, b.Path }) |
| | 6 | 557 | | .ToList() |
| | 6 | 558 | | .Where(b => !liveLibraryPaths.Contains(_appHost.ExpandVirtualPath(b.Path!))) |
| | 6 | 559 | | .Select(b => b.Id) |
| | 6 | 560 | | .ToList(); |
| | | 561 | | |
| | 6 | 562 | | if (missingLibraryIds.Count == 0) |
| | | 563 | | { |
| | 5 | 564 | | return []; |
| | | 565 | | } |
| | | 566 | | |
| | 1 | 567 | | _logger.LogWarning( |
| | 1 | 568 | | "{Count} library definition(s) known to the database are not in {Path}.", |
| | 1 | 569 | | missingLibraryIds.Count, |
| | 1 | 570 | | _appPaths.DefaultUserViewsPath); |
| | | 571 | | |
| | 1 | 572 | | return context.AncestorIds |
| | 1 | 573 | | .WhereOneOrMany(missingLibraryIds, a => a.ParentItemId) |
| | 1 | 574 | | .Select(a => a.ItemId) |
| | 1 | 575 | | .ToHashSet(); |
| | | 576 | | } |
| | | 577 | | |
| | | 578 | | private int ResolveAndDeleteItems(IReadOnlyCollection<Guid> ids, string description) |
| | | 579 | | { |
| | 3 | 580 | | if (ids.Count == 0) |
| | | 581 | | { |
| | 0 | 582 | | return 0; |
| | | 583 | | } |
| | | 584 | | |
| | 3 | 585 | | return DeleteItems(ResolveItems(ids, description), description); |
| | | 586 | | } |
| | | 587 | | |
| | | 588 | | private List<BaseItem> ResolveItems(IReadOnlyCollection<Guid> ids, string description) |
| | | 589 | | { |
| | | 590 | | // Each lookup is a separate repository read; cached ones are fast, so this only reports |
| | | 591 | | // once a set is large enough for the reads to add up to a noticeable stretch. |
| | 3 | 592 | | var items = new List<BaseItem>(ids.Count); |
| | 3 | 593 | | var processed = 0; |
| | 12 | 594 | | foreach (var id in ids) |
| | | 595 | | { |
| | 3 | 596 | | if (processed > 0 && processed % ResolveProgressLogStep == 0) |
| | | 597 | | { |
| | 0 | 598 | | _logger.LogInformation("Loading {Description}: {Processed}/{Total} items", description, processed, ids.C |
| | | 599 | | } |
| | | 600 | | |
| | 3 | 601 | | processed++; |
| | | 602 | | |
| | 3 | 603 | | var item = _libraryManager.GetItemById(id); |
| | 3 | 604 | | if (item is not null) |
| | | 605 | | { |
| | 3 | 606 | | items.Add(item); |
| | | 607 | | } |
| | | 608 | | } |
| | | 609 | | |
| | 3 | 610 | | return items; |
| | | 611 | | } |
| | | 612 | | |
| | | 613 | | private int DeleteItems(IReadOnlyCollection<BaseItem> items, string description) |
| | | 614 | | { |
| | 3 | 615 | | if (items.Count == 0) |
| | | 616 | | { |
| | 0 | 617 | | return 0; |
| | | 618 | | } |
| | | 619 | | |
| | 3 | 620 | | var options = new DeleteOptions { DeleteFileLocation = false, DeleteFromExternalProvider = false }; |
| | 3 | 621 | | var deleted = 0; |
| | 3 | 622 | | var processed = 0; |
| | 12 | 623 | | foreach (var item in items) |
| | | 624 | | { |
| | 3 | 625 | | if (processed > 0 && processed % DeleteProgressLogStep == 0) |
| | | 626 | | { |
| | 0 | 627 | | _logger.LogInformation("Removing {Description}: {Processed}/{Total} items", description, processed, item |
| | | 628 | | } |
| | | 629 | | |
| | 3 | 630 | | processed++; |
| | | 631 | | |
| | | 632 | | try |
| | | 633 | | { |
| | 3 | 634 | | _libraryManager.DeleteItem(item, options); |
| | 3 | 635 | | deleted++; |
| | 3 | 636 | | } |
| | 0 | 637 | | catch (Exception ex) |
| | | 638 | | { |
| | 0 | 639 | | _logger.LogWarning(ex, "Skipping item {ItemId} ({ItemName}): delete failed.", item.Id, item.Name ?? "Unk |
| | 0 | 640 | | } |
| | | 641 | | } |
| | | 642 | | |
| | 3 | 643 | | return deleted; |
| | | 644 | | } |
| | | 645 | | |
| | | 646 | | private void CleanupOrphanedLinkedChildren(JellyfinDbContext context) |
| | | 647 | | { |
| | 6 | 648 | | _logger.LogInformation("Starting cleanup of orphaned LinkedChildren records..."); |
| | | 649 | | |
| | | 650 | | // Find all LinkedChildren where the ChildId doesn't exist in BaseItems |
| | 6 | 651 | | var orphanedLinkedChildren = context.LinkedChildren |
| | 6 | 652 | | .Where(lc => !context.BaseItems.Any(b => b.Id.Equals(lc.ChildId))) |
| | 6 | 653 | | .ToList(); |
| | | 654 | | |
| | 6 | 655 | | if (orphanedLinkedChildren.Count == 0) |
| | | 656 | | { |
| | 6 | 657 | | _logger.LogInformation("No orphaned LinkedChildren found."); |
| | 6 | 658 | | return; |
| | | 659 | | } |
| | | 660 | | |
| | 0 | 661 | | _logger.LogInformation("Found {Count} orphaned LinkedChildren records to remove.", orphanedLinkedChildren.Count) |
| | | 662 | | |
| | 0 | 663 | | var orphanedByParent = context.LinkedChildren |
| | 0 | 664 | | .Where(lc => !context.BaseItems.Any(b => b.Id.Equals(lc.ParentId))) |
| | 0 | 665 | | .ToList(); |
| | | 666 | | |
| | 0 | 667 | | if (orphanedByParent.Count > 0) |
| | | 668 | | { |
| | 0 | 669 | | _logger.LogInformation("Found {Count} LinkedChildren with non-existent parent.", orphanedByParent.Count); |
| | 0 | 670 | | orphanedLinkedChildren.AddRange(orphanedByParent); |
| | | 671 | | } |
| | | 672 | | |
| | | 673 | | // Remove all orphaned records. Both queries can return the same row, and a playlist may hold |
| | | 674 | | // several rows for one child, so the position is what identifies an entry here. |
| | 0 | 675 | | var distinctOrphaned = orphanedLinkedChildren.DistinctBy(lc => new { lc.ParentId, lc.SortOrder }).ToList(); |
| | 0 | 676 | | context.LinkedChildren.RemoveRange(distinctOrphaned); |
| | 0 | 677 | | context.SaveChanges(); |
| | | 678 | | |
| | 0 | 679 | | _logger.LogInformation("Successfully removed {Count} orphaned LinkedChildren records.", distinctOrphaned.Count); |
| | 0 | 680 | | } |
| | | 681 | | |
| | | 682 | | /// <summary> |
| | | 683 | | /// Resolves the item a legacy LinkedChild entry points at. |
| | | 684 | | /// </summary> |
| | | 685 | | private static Guid? ResolveChildId( |
| | | 686 | | JsonElement childElement, |
| | | 687 | | string? containingFolderPath, |
| | | 688 | | Dictionary<string, Guid> pathToIdMap, |
| | | 689 | | HashSet<Guid> allItemIds) |
| | | 690 | | { |
| | | 691 | | // Pre-12 data only cached ItemId and re-resolved it from the path whenever the cached value |
| | | 692 | | // went stale (BaseItem.GetLinkedChild in 10.x). An id that no longer exists must therefore |
| | | 693 | | // fall through to the path, or the entry is lost even though its file is still in the library. |
| | 0 | 694 | | if (TryGetGuidProperty(childElement, "ItemId", out var itemId) && allItemIds.Contains(itemId)) |
| | | 695 | | { |
| | 0 | 696 | | return itemId; |
| | | 697 | | } |
| | | 698 | | |
| | 0 | 699 | | var path = GetStringProperty(childElement, "Path"); |
| | 0 | 700 | | if (!string.IsNullOrEmpty(path)) |
| | | 701 | | { |
| | 0 | 702 | | if (pathToIdMap.TryGetValue(path, out var idByPath)) |
| | | 703 | | { |
| | 0 | 704 | | return idByPath; |
| | | 705 | | } |
| | | 706 | | |
| | | 707 | | // 10.x resolved entries relative to the container that holds them. |
| | 0 | 708 | | if (!Path.IsPathRooted(path) && !string.IsNullOrEmpty(containingFolderPath)) |
| | | 709 | | { |
| | 0 | 710 | | string? absolutePath = null; |
| | | 711 | | try |
| | | 712 | | { |
| | 0 | 713 | | absolutePath = Path.GetFullPath(Path.Combine(containingFolderPath, path)); |
| | 0 | 714 | | } |
| | 0 | 715 | | catch (ArgumentException) |
| | | 716 | | { |
| | | 717 | | // Malformed path, nothing to resolve. |
| | 0 | 718 | | } |
| | | 719 | | |
| | 0 | 720 | | if (absolutePath is not null && pathToIdMap.TryGetValue(absolutePath, out var idByAbsolutePath)) |
| | | 721 | | { |
| | 0 | 722 | | return idByAbsolutePath; |
| | | 723 | | } |
| | | 724 | | } |
| | | 725 | | } |
| | | 726 | | |
| | 0 | 727 | | if (TryGetGuidProperty(childElement, "LibraryItemId", out var libraryItemId) && allItemIds.Contains(libraryItemI |
| | | 728 | | { |
| | 0 | 729 | | return libraryItemId; |
| | | 730 | | } |
| | | 731 | | |
| | 0 | 732 | | return null; |
| | | 733 | | } |
| | | 734 | | |
| | | 735 | | private static string? GetStringProperty(JsonElement element, string propertyName) |
| | 0 | 736 | | => element.TryGetProperty(propertyName, out var property) && property.ValueKind == JsonValueKind.String |
| | 0 | 737 | | ? property.GetString() |
| | 0 | 738 | | : null; |
| | | 739 | | |
| | | 740 | | private static bool TryGetGuidProperty(JsonElement element, string propertyName, out Guid value) |
| | | 741 | | { |
| | 0 | 742 | | value = Guid.Empty; |
| | 0 | 743 | | var raw = GetStringProperty(element, propertyName); |
| | | 744 | | |
| | 0 | 745 | | return !string.IsNullOrEmpty(raw) && Guid.TryParse(raw, out value) && !value.IsEmpty(); |
| | | 746 | | } |
| | | 747 | | |
| | | 748 | | private void ProcessVideoAlternateVersions( |
| | | 749 | | JsonElement root, |
| | | 750 | | Guid parentId, |
| | | 751 | | Dictionary<string, Guid> pathToIdMap, |
| | | 752 | | HashSet<Guid> allItemIds, |
| | | 753 | | List<LinkedChildEntity> linkedChildrenToAdd) |
| | | 754 | | { |
| | 0 | 755 | | int sortOrder = 0; |
| | | 756 | | |
| | 0 | 757 | | if (root.TryGetProperty("LocalAlternateVersions", out var localAlternateVersionsElement) |
| | 0 | 758 | | && localAlternateVersionsElement.ValueKind == JsonValueKind.Array) |
| | | 759 | | { |
| | 0 | 760 | | foreach (var pathElement in localAlternateVersionsElement.EnumerateArray()) |
| | | 761 | | { |
| | 0 | 762 | | if (pathElement.ValueKind != JsonValueKind.String) |
| | | 763 | | { |
| | | 764 | | continue; |
| | | 765 | | } |
| | | 766 | | |
| | 0 | 767 | | var path = pathElement.GetString(); |
| | 0 | 768 | | if (string.IsNullOrEmpty(path)) |
| | | 769 | | { |
| | | 770 | | continue; |
| | | 771 | | } |
| | | 772 | | |
| | | 773 | | // Try to resolve the path to an ItemId |
| | 0 | 774 | | if (pathToIdMap.TryGetValue(path, out var childId)) |
| | | 775 | | { |
| | 0 | 776 | | linkedChildrenToAdd.Add(new LinkedChildEntity |
| | 0 | 777 | | { |
| | 0 | 778 | | ParentId = parentId, |
| | 0 | 779 | | ChildId = childId, |
| | 0 | 780 | | ChildType = LinkedChildType.LocalAlternateVersion, |
| | 0 | 781 | | SortOrder = sortOrder++ |
| | 0 | 782 | | }); |
| | | 783 | | |
| | 0 | 784 | | _logger.LogDebug( |
| | 0 | 785 | | "Migrating LocalAlternateVersion: Parent={ParentId}, Child={ChildId}, Path={Path}", |
| | 0 | 786 | | parentId, |
| | 0 | 787 | | childId, |
| | 0 | 788 | | path); |
| | | 789 | | } |
| | | 790 | | else |
| | | 791 | | { |
| | 0 | 792 | | _logger.LogWarning( |
| | 0 | 793 | | "Could not resolve LocalAlternateVersion path to ItemId: {Path} for parent {ParentId}", |
| | 0 | 794 | | path, |
| | 0 | 795 | | parentId); |
| | | 796 | | } |
| | | 797 | | } |
| | | 798 | | } |
| | | 799 | | |
| | 0 | 800 | | if (root.TryGetProperty("LinkedAlternateVersions", out var linkedAlternateVersionsElement) |
| | 0 | 801 | | && linkedAlternateVersionsElement.ValueKind == JsonValueKind.Array) |
| | | 802 | | { |
| | 0 | 803 | | foreach (var linkedChildElement in linkedAlternateVersionsElement.EnumerateArray()) |
| | | 804 | | { |
| | 0 | 805 | | var childId = ResolveChildId(linkedChildElement, null, pathToIdMap, allItemIds); |
| | 0 | 806 | | if (!childId.HasValue) |
| | | 807 | | { |
| | 0 | 808 | | _logger.LogWarning("Could not resolve LinkedAlternateVersion child ID for parent {ParentId}", parent |
| | 0 | 809 | | continue; |
| | | 810 | | } |
| | | 811 | | |
| | 0 | 812 | | linkedChildrenToAdd.Add(new LinkedChildEntity |
| | 0 | 813 | | { |
| | 0 | 814 | | ParentId = parentId, |
| | 0 | 815 | | ChildId = childId.Value, |
| | 0 | 816 | | ChildType = LinkedChildType.LinkedAlternateVersion, |
| | 0 | 817 | | SortOrder = sortOrder++ |
| | 0 | 818 | | }); |
| | | 819 | | |
| | 0 | 820 | | _logger.LogDebug( |
| | 0 | 821 | | "Migrating LinkedAlternateVersion: Parent={ParentId}, Child={ChildId}", |
| | 0 | 822 | | parentId, |
| | 0 | 823 | | childId.Value); |
| | | 824 | | } |
| | | 825 | | } |
| | 0 | 826 | | } |
| | | 827 | | } |