Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 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
15 changes: 5 additions & 10 deletions src/Files.App.Server/AppService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,15 @@ public sealed partial class AppService : IDisposable
internal bool IsDisposed => disposed != 0;

public bool CanRestorePreviousSession { get; }
public int ProcessId => Environment.ProcessId;
public PinnedFoldersService PinnedFolders { get; }
public RecycleBinService RecycleBin { get; }

public AppService(int processId)
{
(ClientId, CanRestorePreviousSession) = ServerHost.AddClient(processId);
PinnedFolders = new(this);
RecycleBin = new(this);
}

~AppService() => Dispose();
Expand All @@ -31,16 +36,6 @@ public event EventHandler<string> Changed

public static IAsyncAction InitializeAsync() => ServerAsync.Run(token => StartupServices.InitializeAsync().WaitAsync(token));

public static IAsyncOperation<IReadOnlyList<LibraryInfo>> GetLibrariesAsync() => ServerAsync.Run(token => InitializationCache.Libraries.GetAsync().WaitAsync(token));

public static IAsyncOperation<IReadOnlyList<PinnedFolderInfo>> GetPinnedFoldersAsync() => ServerAsync.Run(token => InitializationCache.PinnedFolders.GetAsync().WaitAsync(token));

public static void InvalidatePinnedFolders()
{
InitializationCache.PinnedFolders.Invalidate();
ServerEvents.Notify(ServerChangeNames.PinnedFolders);
}

public void Dispose()
{
if (Interlocked.Exchange(ref disposed, 1) == 0)
Expand Down
191 changes: 191 additions & 0 deletions src/Files.App.Server/Caching/DirectoryChangeMonitor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
// Copyright (c) Files Community
// Licensed under the MIT License.

using Microsoft.Extensions.Logging;
using System.IO.Enumeration;

namespace Files.App.Server;

internal sealed partial class DirectoryChangeMonitor : IDisposable
{
private readonly Lock gate = new();
private readonly Lock configureGate = new();
private readonly string directory;
private readonly string filter;
private readonly bool recursive;
private readonly Action<FileSystemEventArgs> changed;
private FileSystemWatcher? watcher;
private FileSystemWatcher? parentWatcher;
private bool watchingTarget;
private bool disposed;
private long configurationVersion;

internal DirectoryChangeMonitor(string directory, string filter, bool recursive, Action<FileSystemEventArgs> changed)
{
this.directory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(directory));
this.filter = filter;
this.recursive = recursive;
this.changed = changed;
Configure();
}

private void Configure()
{
long version;
lock (gate)
{
if (disposed)
return;
version = ++configurationVersion;
}
var existing = directory;
var next = directory;
while (!Directory.Exists(existing))
{
next = existing;
existing = Path.GetDirectoryName(existing);
if (string.IsNullOrEmpty(existing))
return;
}

var targetExists = string.Equals(existing, directory, StringComparison.OrdinalIgnoreCase);
var replacement = CreateWatcher(existing, targetExists ? filter : Path.GetFileName(next), targetExists && recursive,
NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite);
FileSystemWatcher? replacementParent = null;
try
{
if (targetExists && Path.GetDirectoryName(directory) is { } parent)
replacementParent = CreateWatcher(parent, Path.GetFileName(directory), false, NotifyFilters.DirectoryName);
}
catch
{
replacement.Dispose();
throw;
}
FileSystemWatcher? previous;
FileSystemWatcher? previousParent;
lock (gate)
{
if (disposed || version != configurationVersion)
{
previous = replacement;
previousParent = replacementParent;
}
else
{
previous = watcher;
previousParent = parentWatcher;
watcher = replacement;
parentWatcher = replacementParent;
watchingTarget = targetExists;
}
}
previous?.Dispose();
previousParent?.Dispose();
// The missing component may have appeared before its parent watch was enabled.
if (!targetExists && Directory.Exists(next))
Configure();
}

private FileSystemWatcher CreateWatcher(string path, string pattern, bool includeSubdirectories, NotifyFilters notifyFilter)
{
var replacement = new FileSystemWatcher(path, pattern)
{
IncludeSubdirectories = includeSubdirectories,
NotifyFilter = notifyFilter,
};
try
{
replacement.Created += OnChanged;
replacement.Deleted += OnChanged;
replacement.Changed += OnChanged;
replacement.Renamed += OnChanged;
replacement.Error += OnError;
replacement.EnableRaisingEvents = true;
}
catch
{
replacement.Dispose();
throw;
}
return replacement;
}

private bool Relevant(string path)
=> (recursive
? path.StartsWith(directory + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)
: string.Equals(Path.GetDirectoryName(path), directory, StringComparison.OrdinalIgnoreCase))
&& FileSystemName.MatchesSimpleExpression(filter, Path.GetFileName(path), ignoreCase: true);

private void OnChanged(object sender, FileSystemEventArgs args)
{
bool reconfigure;
lock (gate)
{
if (disposed || (!ReferenceEquals(sender, watcher) && !ReferenceEquals(sender, parentWatcher)))
return;
reconfigure = ReferenceEquals(sender, parentWatcher) || !watchingTarget;
}
if (reconfigure || !Directory.Exists(directory))
{
if (!Reconfigure(sender))
return;
args = new FileSystemEventArgs(WatcherChangeTypes.All, directory, string.Empty);
}
else if (!Relevant(args.FullPath) && !(args is RenamedEventArgs renamed && Relevant(renamed.OldFullPath)))
return;
if (!Volatile.Read(ref disposed))
changed(args);
}

private void OnError(object sender, ErrorEventArgs args)
{
lock (gate)
{
if (disposed || (!ReferenceEquals(sender, watcher) && !ReferenceEquals(sender, parentWatcher)))
return;
}
if (args.GetException() is not InternalBufferOverflowException && !Reconfigure(sender))
return;
if (!Volatile.Read(ref disposed))
changed(new FileSystemEventArgs(WatcherChangeTypes.All, directory, string.Empty));
}

private bool Reconfigure(object sender)
{
lock (configureGate)
{
lock (gate)
{
if (disposed || (!ReferenceEquals(sender, watcher) && !ReferenceEquals(sender, parentWatcher)))
return false;
}
try
{
Configure();
}
catch (Exception ex)
{
Program.Logger.LogWarning(ex, "Could not update a directory watch.");
}
return !Volatile.Read(ref disposed);
}
}

public void Dispose()
{
FileSystemWatcher? previous;
FileSystemWatcher? previousParent;
lock (gate)
{
disposed = true;
configurationVersion++;
previous = watcher;
previousParent = parentWatcher;
watcher = null;
parentWatcher = null;
}
previous?.Dispose();
previousParent?.Dispose();
}
}
154 changes: 154 additions & 0 deletions src/Files.App.Server/Catalogs/CatalogWatchers.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
// Copyright (c) Files Community
// Licensed under the MIT License.

using Files.Storage;
using Microsoft.Extensions.Logging;
using System.Security.Principal;

namespace Files.App.Server;

internal static class CatalogWatchers
{
private static List<DirectoryChangeMonitor> watchers = [];
private static readonly Lazy<bool> initialized = new(Start);
private static readonly Lock recycleBinGate = new();
private static List<DirectoryChangeMonitor> recycleBins = [];
private static long recycleBinVersion;
private static bool stopped;

internal static void Initialize() => _ = initialized.Value;

private static bool Start()
{
var recent = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Recent), "AutomaticDestinations");
Watch(recent, "f01b4d95cf55d32a.automaticDestinations-ms", () =>
{
InitializationCache.PinnedFolders.Invalidate();
JumpListCatalog.Invalidate();
ServerEvents.Notify(ServerChangeNames.PinnedFolders);
});
Watch(recent, "5f7b5f1e01b83767.automaticDestinations-ms", () =>
{
LocationCatalog.RecentFiles.Invalidate();
LocationCatalog.RecentFolders.Invalidate();
ServerEvents.Notify(ServerChangeNames.RecentItems);
});
Watch(ShellLibraryItem.LibrariesPath, "*.library-ms", () =>
{
InitializationCache.Libraries.Invalidate();
ServerEvents.Notify(ServerChangeNames.Libraries);
});
Watch(Environment.GetFolderPath(Environment.SpecialFolder.NetworkShortcuts), "*", () =>
{
LocationCatalog.NetworkShortcuts.Invalidate();
ServerEvents.Notify(ServerChangeNames.Network);
});
RefreshRecycleBinWatcher();
return true;
}

internal static void RefreshRecycleBinWatcher()
{
long version;
lock (recycleBinGate)
{
if (stopped)
return;
version = ++recycleBinVersion;
}
var replacements = new List<DirectoryChangeMonitor>();
try
{
using var identity = WindowsIdentity.GetCurrent();
var sid = identity.User?.Value;
if (!string.IsNullOrEmpty(sid))
{
foreach (var drive in System.IO.DriveInfo.GetDrives())
{
if (drive.DriveType == System.IO.DriveType.Network)
continue;
var watcher = SafetyExtensions.IgnoreExceptions(() => new DirectoryChangeMonitor(
Path.Combine(drive.Name, "$RECYCLE.BIN", sid), "*", false, OnRecycleBinChanged), Program.Logger);
if (watcher is not null)
replacements.Add(watcher);
}
}
}
catch
{
foreach (var watcher in replacements)
watcher.Dispose();
throw;
}
List<DirectoryChangeMonitor> previous;
bool installed;
lock (recycleBinGate)
{
installed = !stopped && version == recycleBinVersion;
previous = installed ? recycleBins : replacements;
if (installed)
recycleBins = replacements;
}
foreach (var watcher in previous)
watcher.Dispose();
if (installed)
RecycleBinCatalog.RecordChange(new FileSystemEventArgs(WatcherChangeTypes.All, string.Empty, string.Empty), refresh: true);
}

private static void OnRecycleBinChanged(FileSystemEventArgs e)
{
if (e.ChangeType == WatcherChangeTypes.All)
RecycleBinCatalog.RecordChange(e, refresh: true);
else if (e.ChangeType is WatcherChangeTypes.Created or WatcherChangeTypes.Deleted && !string.IsNullOrEmpty(e.Name))
{
if (e.Name.StartsWith("$I", StringComparison.Ordinal))
{
// Availability depends on metadata files, but they aren't items to display in the view.
RecycleBinCatalog.Invalidate();
ServerEvents.Notify(ServerChangeNames.RecycleBin);
}
else
RecycleBinCatalog.RecordChange(e, refresh: false);
}
}

private static void Watch(string directory, string filter, Action changed)
{
if (string.IsNullOrEmpty(directory))
return;
try
{
var watcher = new DirectoryChangeMonitor(directory, filter, true, _ => changed());
lock (recycleBinGate)
{
if (!stopped)
{
watchers.Add(watcher);
return;
}
}
watcher.Dispose();
}
catch (Exception ex)
{
Program.Logger.LogWarning(ex, "Could not watch a startup catalog.");
}
}

internal static void Dispose()
{
List<DirectoryChangeMonitor> previous;
List<DirectoryChangeMonitor> previousBins;
lock (recycleBinGate)
{
stopped = true;
recycleBinVersion++;
previous = watchers;
previousBins = recycleBins;
watchers = [];
recycleBins = [];
}
foreach (var watcher in previous.Concat(previousBins))
watcher.Dispose();
}
}
1 change: 1 addition & 0 deletions src/Files.App.Server/Catalogs/DriveCatalog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ private static void Start()
private static void OnDriveChanged(object? sender, DeviceEventArgs e)
{
Changed(e.DeviceId.TrimEnd('\\') + "\\");
_ = Task.Run(() => SafetyExtensions.IgnoreExceptions(CatalogWatchers.RefreshRecycleBinWatcher, Program.Logger));
}

private static void Changed(string id)
Expand Down
Loading
Loading