-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWatcherService.cs
More file actions
96 lines (80 loc) · 2.95 KB
/
Copy pathWatcherService.cs
File metadata and controls
96 lines (80 loc) · 2.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace GameSnapPlugin
{
public class WatcherService : IDisposable
{
private readonly GameSnapSettings _settings;
private readonly OrganizerService _organizer;
private readonly GameSnapLogger _logger;
private FileSystemWatcher? _watcher;
private Timer? _pollingTimer;
private bool _disposed;
public WatcherService(GameSnapSettings settings, OrganizerService organizer, GameSnapLogger logger)
{
_settings = settings;
_organizer = organizer;
_logger = logger;
}
public void Start()
{
if (string.IsNullOrEmpty(_settings.SourceFolder) || !Directory.Exists(_settings.SourceFolder))
{
_logger.Error($"Source folder not found: {_settings.SourceFolder}");
return;
}
// FileSystemWatcher — reage imediatamente a novos arquivos
_watcher = new FileSystemWatcher(_settings.SourceFolder)
{
NotifyFilter = NotifyFilters.FileName | NotifyFilters.CreationTime,
IncludeSubdirectories = false,
EnableRaisingEvents = true
};
_watcher.Created += OnFileCreated;
_watcher.Error += OnWatcherError;
// Loop de polling — captura arquivos que o watcher possa ter perdido
var interval = TimeSpan.FromSeconds(_settings.PollingIntervalSeconds);
_pollingTimer = new Timer(_ => SafeOrganize(), null, interval, interval);
_logger.Info($"Watcher started on: {_settings.SourceFolder}");
}
public void Stop()
{
_pollingTimer?.Dispose();
_pollingTimer = null;
if (_watcher != null)
{
_watcher.EnableRaisingEvents = false;
_watcher.Dispose();
_watcher = null;
}
_logger.Info("Watcher stopped.");
}
private void OnFileCreated(object sender, FileSystemEventArgs e)
{
// Delay then organize fully off the watcher thread — never blocks Playnite
Task.Delay(2000).ContinueWith(_ =>
Task.Run(() => SafeOrganize()));
}
private void OnWatcherError(object sender, ErrorEventArgs e)
{
_logger.Error($"Watcher error: {e.GetException().Message}");
// Tenta reiniciar o watcher
Stop();
Thread.Sleep(5000);
Start();
}
private void SafeOrganize()
{
try { _organizer.Organize(); }
catch (Exception ex) { _logger.Error($"Organize error: {ex.Message}"); }
}
public void Dispose()
{
if (_disposed) return;
Stop();
_disposed = true;
}
}
}