Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
50 changes: 48 additions & 2 deletions Decorators/ItemRepositoryDecorator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
Expand All @@ -27,10 +28,55 @@ public GelatoItemRepository(IItemRepository inner, IHttpContextAccessor http) {
_http = http ?? throw new ArgumentNullException(nameof(http));
}

public void DeleteItem(params IReadOnlyList<Guid> ids) => _inner.DeleteItem(ids);
// Gelato's own code (PurgeStreams, SaveItems stale cleanup) sets this
// to true so the DeleteItem guard lets the call through.
[ThreadStatic]
public static bool SuppressGuard;

public void SaveItems(IReadOnlyList<BaseItem> items, CancellationToken cancellationToken) =>
public void DeleteItem(params IReadOnlyList<Guid> ids) {
// When Gelato itself is the caller, skip protection.
if (SuppressGuard) {
_inner.DeleteItem(ids);
return;
}

// Protect gelato-stream items from being deleted by the library scanner.
var protected_ids = new HashSet<Guid>();
foreach (var id in ids) {
var item = _inner.RetrieveItem(id);
if (item is not null && GelatoManager.HasStreamTag(item)) {
protected_ids.Add(id);
}
}
if (protected_ids.Count > 0) {
var filtered = ids.Where(id => !protected_ids.Contains(id)).ToList();
if (filtered.Count > 0)
_inner.DeleteItem(filtered);
return;
}
_inner.DeleteItem(ids);
}

public void SaveItems(IReadOnlyList<BaseItem> items, CancellationToken cancellationToken) {
// Prevent the library scanner from overwriting Gelato stream items.
// When the scanner discovers .strm files on disk, it resolves them into
// new BaseItem objects WITHOUT the gelato-stream tag. If we let these
// through, they'd overwrite the tagged items and break Gelato's tracking.
var dominated = new HashSet<Guid>();
foreach (var item in items) {
if (GelatoManager.HasStreamTag(item)) continue; // Gelato's own saves pass through
var existing = _inner.RetrieveItem(item.Id);
if (existing is not null && GelatoManager.HasStreamTag(existing)) {
dominated.Add(item.Id);
}
}
if (dominated.Count > 0) {
var filtered = items.Where(i => !dominated.Contains(i.Id)).ToList();
_inner.SaveItems(filtered, cancellationToken);
return;
}
_inner.SaveItems(items, cancellationToken);
}

public void SaveImages(BaseItem item) => _inner.SaveImages(item);

Expand Down
49 changes: 45 additions & 4 deletions GelatoManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,8 @@ public async Task<int> SyncStreams(BaseItem item, Guid userId, CancellationToken
.GetItemList(query)
.OfType<Video>()
.Where(v => IsStream(v))
.ToDictionary(v => v.GelatoData<Guid>("guid"));
.GroupBy(v => v.GelatoData<Guid>("guid"))
.ToDictionary(g => g.Key, g => g.First());

var newVideos = new List<Video>();

Expand Down Expand Up @@ -531,7 +532,7 @@ public async Task<int> SyncStreams(BaseItem item, Guid userId, CancellationToken
newVideos.Add(target);
}

newVideos = SaveItems(newVideos, (Folder)primary.GetParent()).Cast<Video>().ToList();
newVideos = SaveItemsStrm(newVideos, (Folder)primary.GetParent()).Cast<Video>().ToList();

var newIds = new HashSet<Guid>(newVideos.Select(x => x.Id));
var stale = existing.Values
Expand Down Expand Up @@ -1160,7 +1161,7 @@ public IEnumerable<BaseItem> SaveItemsStrm(IEnumerable<BaseItem> items, Folder p
item.ShortcutPath = item.Path;
item.IsShortcut = true;
item.Path = BuildStrmPath(item, parent);
// Ensure parent directory exists for resolvers that hit System.IO directly
// Ensure parent directory exists
var dir = Path.GetDirectoryName(item.Path);
if (!string.IsNullOrEmpty(dir))
Directory.CreateDirectory(dir);
Expand All @@ -1175,10 +1176,50 @@ public IEnumerable<BaseItem> SaveItemsStrm(IEnumerable<BaseItem> items, Folder p
item.DateLastSaved = now;
}

var oldId = item.Id;
item.Id = _library.GetNewItemId(item.Path, item.GetType());
item.PresentationUniqueKey = item.CreatePresentationUniqueKey();

parent.AddChild(item);
// If the path changed, the ID changes too. Delete the stale record
// so we don't end up with two DB entries for the same logical stream.
if (oldId != Guid.Empty && oldId != item.Id) {
try {
Decorators.GelatoItemRepository.SuppressGuard = true;
_repo.DeleteItem(oldId);
} finally {
Decorators.GelatoItemRepository.SuppressGuard = false;
}
}

// Parent the item to the folder that actually contains its file on
// disk, so the scanner's currentChildren dict matches the resolved
// .strm files and items survive ValidateChildrenInternal2.
//
// For movies the .strm lives inside a subfolder (e.g.
// /movies/Star Trek (2009)/something.strm)
// so the parent must be the "Star Trek (2009)" Folder, not root.
var strmDir = item.IsFolder ? null : Path.GetDirectoryName(item.Path);
if (!string.IsNullOrEmpty(strmDir) && strmDir != parent.Path) {
var folderId = _library.GetNewItemId(strmDir, typeof(Folder));
var folder = _library.GetItemById(folderId) as Folder;
if (folder is null) {
folder = new Folder {
Id = folderId,
Path = strmDir,
Name = Path.GetFileName(strmDir),
};
parent.AddChild(folder);
var ts = DateTime.UtcNow;
folder.DateLastRefreshed = ts;
folder.DateLastSaved = ts;
_repo.SaveItems(new List<BaseItem> { folder }, CancellationToken.None);
_library.RegisterItem(folder);
}
folder.AddChild(item);
}
else {
parent.AddChild(item);
}

}
_repo.SaveItems(items.ToList(), CancellationToken.None);
Expand Down
36 changes: 21 additions & 15 deletions ScheduledTasks/PurgeStreams.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,22 +80,28 @@ CancellationToken cancellationToken

int done = 0;

foreach (var item in streams) {
cancellationToken.ThrowIfCancellationRequested();

try {
_library.DeleteItem(
item,
new DeleteOptions { DeleteFileLocation = true },
true);
try {
Gelato.Decorators.GelatoItemRepository.SuppressGuard = true;
foreach (var item in streams) {
cancellationToken.ThrowIfCancellationRequested();

try {
_library.DeleteItem(
item,
new DeleteOptions { DeleteFileLocation = true },
true);
}
catch (Exception ex) {
_log.LogWarning(ex, "Failed to delete item {ItemId}", item.Id);
}

done++;
var pct = Math.Min(100.0, ((double)done / total) * 100.0);
progress?.Report(pct);
}
catch (Exception ex) {
_log.LogWarning(ex, "Failed to delete item {ItemId}", item.Id);
}

done++;
var pct = Math.Min(100.0, ((double)done / total) * 100.0);
progress?.Report(pct);
}
finally {
Gelato.Decorators.GelatoItemRepository.SuppressGuard = false;
}

progress?.Report(100.0);
Expand Down