-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMonitor.cs
More file actions
225 lines (199 loc) · 6.99 KB
/
Monitor.cs
File metadata and controls
225 lines (199 loc) · 6.99 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
using Serilog;
namespace DirectoryGuardian;
public class Monitor
{
private FileSystemWatcher? _watcher;
private readonly ILogger _Logger;
private readonly DirGuard Guard;
public bool IsActive { get; private set; }
// private field for logic in the delegates for the watcher
private JobType _Monitor_Job;
public Monitor(ILogger logger, JobType jobType, DirGuard Guard)
{
_watcher = new FileSystemWatcher();
_Logger = logger;
_Monitor_Job = jobType;
this.Guard = Guard;
}
public void MonitorDirectory(string dir, JobType jobType)
{
_watcher?.Dispose();
_Monitor_Job = jobType;
_watcher = new FileSystemWatcher(dir)
{
NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Size,
Filter = "*",
EnableRaisingEvents = true
};
_watcher.Created += OnChanged;
_watcher.Changed += OnChanged;
_watcher.Deleted += OnChanged;
_watcher.Renamed += OnRenamed;
//unregister the watcher
_watcher.Disposed += (sender, e) =>
{
_watcher.Created -= OnChanged;
_watcher.Changed -= OnChanged;
_watcher.Deleted -= OnChanged;
_watcher.Renamed -= OnRenamed;
};
// Do the initial sorting
if (jobType is JobType.MonitorByType)
{
Guard.Sort_By_Type();
}
if (jobType is JobType.MonitorByExtension)
{
Guard.Sort_By_Extension();
}
IsActive = true;
}
private void OnChanged(object sender, FileSystemEventArgs e)
{
_Logger.Information($"File: {e.FullPath} {e.ChangeType}");
if (_Monitor_Job is JobType.MonitorByExtension)
{
if (!Guard.Setup.ExtensionsToSort.Contains(Path.GetExtension(e.FullPath), StringComparer.OrdinalIgnoreCase))
{
_Logger.Information($"File: {e.FullPath} is not a type to watch, ignoring.");
return;
}
if (e.ChangeType == WatcherChangeTypes.Created)
{
HandleNewFile(e.FullPath);
}
}
if (_Monitor_Job == JobType.MonitorByType)
{
bool matched = false;
foreach (var type in Guard.Setup.TypesToSort)
{
// Fetch the extensions related to the type
if (TypeLists.ExtensionsMap.TryGetValue(type, out var extensions))
continue;
// Check if the file extension matches any in the list
if (extensions.Any(extension => extension.Equals(Path.GetExtension(e.FullPath), StringComparison.OrdinalIgnoreCase)))
{
if (e.ChangeType == WatcherChangeTypes.Created)
{
HandleNewFile(e.FullPath);
}
matched = true; // Mark as matched
}
}
// If no match was found, log a message
if (!matched)
{
_Logger.Information($"File: {e.FullPath} is not a type to watch, ignoring.");
}
}
}
private void OnRenamed(object sender, RenamedEventArgs e)
{
_Logger.Information($"File: {e.OldFullPath} renamed to {e.FullPath}");
if (_Monitor_Job is JobType.MonitorByExtension)
{
if (!Guard.Setup.ExtensionsToSort.Contains(Path.GetExtension(e.FullPath), StringComparer.OrdinalIgnoreCase))
{
_Logger.Information($"File: {e.FullPath} is not a type to watch, ignoring.");
return;
}
if (!IsFileLocked(e.FullPath, _Logger))
{
_Logger.Information($"File: {e.FullPath} is not in use, can be moved.");
Thread.Sleep(3000);
Guard.Sort_By_Extension();
}
else
{
_Logger.Information($"File: {e.FullPath} is in use, cannot move.");
}
}
if (_Monitor_Job == JobType.MonitorByType)
{
bool matched = false;
if (Guard.Setup.TypesToSort is not null)
{
foreach (var type in Guard.Setup.TypesToSort)
{
// Fetch the extensions related to the type
if (!TypeLists.ExtensionsMap.TryGetValue(type, out var extensions))
continue;
// Check if the file extension matches any in the list
if (extensions.Any(extension => extension.Equals(Path.GetExtension(e.FullPath), StringComparison.OrdinalIgnoreCase)))
{
if (e.ChangeType == WatcherChangeTypes.Created && !IsFileLocked(e.FullPath, _Logger))
{
_Logger.Information($"File: {e.FullPath} is not in use, can be moved.");
Thread.Sleep(3000);
Guard.Sort_By_Type();
}
matched = true; // Mark as matched
}
}
}
// If no match was found, log a message
if (!matched)
{
_Logger.Information($"File: {e.FullPath} is not a type to watch, ignoring.");
}
}
}
public void StopMonitoring()
{
if (_watcher != null)
{
_watcher.EnableRaisingEvents = false;
_watcher.Dispose();
_watcher = null;
}
IsActive = false;
}
private void HandleNewFile(string filePath)
{
// wait a little bit
Thread.Sleep(1000);
if (!IsFileLocked(filePath, _Logger))
{
// moving logic here
_Logger.Information($"File: {filePath} is not in use, can be moved.");
// sort the files
if (_Monitor_Job is JobType.MonitorByExtension)
{
Guard.Sort_By_Extension();
}
if (_Monitor_Job is JobType.MonitorByType)
{
Guard.Sort_By_Type();
}
}
else
{
_Logger.Information($"File: {filePath} is in use, cannot move.");
}
}
internal static bool IsFileLocked(string filePath, ILogger logger)
{
FileStream? stream = null;
try
{
stream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
logger.Information($"File: {filePath} is not in use, can be moved");
return false;
}
catch (IOException)
{
logger.Warning($"File: {filePath} is locked, cannot move.");
return true;
}
catch (UnauthorizedAccessException)
{
logger.Warning($"File: {filePath} Not authorized, cannot move.");
return true;
}
finally
{
stream?.Close();
}
}
}