forked from RoliSoft/RS-TV-Show-Tracker
/
FileSearch.cs
290 lines (256 loc) · 9.68 KB
/
FileSearch.cs
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
namespace RoliSoft.TVShowTracker
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security;
using System.Text.RegularExpressions;
using System.Threading;
using Dependencies.USNJournal;
using Parsers.Guides;
/// <summary>
/// Provides file search for finding the episodes on the disk.
/// </summary>
public class FileSearch
{
/// <summary>
/// Occurs when a file search is done.
/// </summary>
public event EventHandler<EventArgs<List<string>>> FileSearchDone;
/// <summary>
/// Occurs when a multiple file search is done.
/// </summary>
public event EventHandler<EventArgs<List<string>[]>> MultiFileSearchDone;
/// <summary>
/// Occurs when the progress of the file search has changed.
/// </summary>
public event EventHandler<EventArgs<string>> FileSearchProgressChanged;
/// <summary>
/// Gets the search thread.
/// </summary>
/// <value>The search thread.</value>
public Thread SearchThread { get; internal set; }
private Dictionary<string, List<string>> _paths;
private List<string>[] _files;
private Episode[] _episodes;
private Regex[] _titleRegex, _episodeRegex;
/// <summary>
/// Initializes a new instance of the <see cref="FileSearch"/> class.
/// </summary>
/// <param name="paths">The paths where to start the search.</param>
/// <param name="episode">The episode to search for.</param>
public FileSearch(IEnumerable<string> paths, Episode episode)
{
_episodes = new[] { episode };
_titleRegex = new[] { episode.Show.GenerateRegex() };
_episodeRegex = new[] { episode.GenerateRegex() };
InitStartPaths(paths);
}
/// <summary>
/// Initializes a new instance of the <see cref="FileSearch"/> class.
/// </summary>
/// <param name="paths">The paths where to start the search.</param>
/// <param name="episodes">The episodes to search for.</param>
public FileSearch(IEnumerable<string> paths, IEnumerable<Episode> episodes)
{
_episodes = episodes.ToArray();
_titleRegex = new Regex[_episodes.Length];
_episodeRegex = new Regex[_episodes.Length];
for (var i = 0; i < _episodes.Length; i++)
{
_titleRegex[i] = _episodes[i].Show.GenerateRegex();
_episodeRegex[i] = _episodes[i].GenerateRegex();
}
InitStartPaths(paths);
}
/// <summary>
/// Groups the start paths into <see cref="_paths"/>.
/// </summary>
/// <param name="paths">The paths where to start the search.</param>
private void InitStartPaths(IEnumerable<string> paths)
{
_paths = new Dictionary<string, List<string>>();
foreach (var path in paths)
{
var match = Regex.Match(path, @"^([A-Za-z]{1,2}):\\");
var drive = match.Success ? match.Groups[1].Value : string.Empty;
if (!_paths.ContainsKey(drive))
{
_paths[drive] = new List<string>();
}
_paths[drive].Add(path);
}
}
/// <summary>
/// Begins the search asynchronously.
/// </summary>
public void BeginSearch()
{
SearchThread = new Thread(Search);
SearchThread.Start();
}
/// <summary>
/// Cancels the asynchronous search.
/// </summary>
public void CancelSearch()
{
try { SearchThread.Abort(); } catch { }
}
/// <summary>
/// Starts the search.
/// </summary>
private void Search()
{
_files = new List<string>[_episodes.Length];
for (var i = 0; i < _files.Length; i++)
{
_files[i] = new List<string>();
}
foreach (var paths in _paths)
{
DriveInfo drive = null;
if (paths.Key != string.Empty)
{
try
{
drive = new DriveInfo(paths.Key);
}
catch (Exception ex)
{
MainWindow.HandleUnexpectedException(ex);
}
}
if (drive != null && drive.DriveFormat == "NTFS" && Settings.Get<bool>("Search NTFS MFT records") && Utils.IsAdmin)
{
try
{
ScanNtfsMftForFile(drive, paths.Value.Count == 1 && paths.Value[0].Length == 3 ? null : paths.Value);
}
catch (Exception ex)
{
MainWindow.HandleUnexpectedException(ex);
}
}
else
{
foreach (var path in paths.Value)
{
FileSearchProgressChanged.Fire(this, "Searching recursively for matching files in " + path + "...");
ScanDirectoryForFile(path);
}
}
}
if (_files.Length == 1)
{
FileSearchDone.Fire(this, _files[0]);
}
else
{
MultiFileSearchDone.Fire(this, _files);
}
}
/// <summary>
/// Scans the directory recursively for a matching file.
/// </summary>
/// <param name="path">The path to start the search from.</param>
private void ScanDirectoryForFile(string path)
{
// search for matching files
try
{
foreach (var file in Directory.EnumerateFiles(path))
{
try
{
CheckFile(file);
}
catch (PathTooLongException) { }
catch (SecurityException) { }
catch (UnauthorizedAccessException) { }
catch (DirectoryNotFoundException) { }
catch (Exception ex)
{
MainWindow.HandleUnexpectedException(ex);
}
}
}
catch (PathTooLongException) { }
catch (SecurityException) { }
catch (UnauthorizedAccessException) { }
catch (DirectoryNotFoundException) { }
catch (Exception ex)
{
MainWindow.HandleUnexpectedException(ex);
}
// WE MUST GO DEEPER!
try
{
foreach (var dir in Directory.EnumerateDirectories(path))
{
if (string.IsNullOrWhiteSpace(dir))
{
continue;
}
ScanDirectoryForFile(dir);
}
}
catch (PathTooLongException) { }
catch (SecurityException) { }
catch (UnauthorizedAccessException) { }
catch (DirectoryNotFoundException) { }
catch (Exception ex)
{
MainWindow.HandleUnexpectedException(ex);
}
}
/// <summary>
/// Scans the NTFS Master File Table entries for a matching file.
/// </summary>
/// <param name="drive">The partition to scan.</param>
/// <param name="paths">The paths to which the search should be limited.</param>
private void ScanNtfsMftForFile(DriveInfo drive, IEnumerable<string> paths = null)
{
FileSearchProgressChanged.Fire(this, "Reading the MFT records of the " + drive.Name[0] + " partition...");
var usn = new NtfsUsnJournal(drive);
var list = usn.GetParsedPaths(ShowNames.Regexes.KnownVideo, paths);
FileSearchProgressChanged.Fire(this, "Searching for matching files in the " + drive.Name[0] + " partition...");
foreach (var file in list)
{
try
{
CheckFile(file);
}
catch (PathTooLongException) { }
catch (SecurityException) { }
catch (UnauthorizedAccessException) { }
catch (DirectoryNotFoundException) { }
catch (Exception ex)
{
MainWindow.HandleUnexpectedException(ex);
}
}
}
/// <summary>
/// Determines whether the specified file is a match and inserts it into <see cref="_files"/> if it is.
/// </summary>
/// <param name="file">The file.</param>
private void CheckFile(string file)
{
var name = Path.GetFileName(file);
var dirs = Path.GetDirectoryName(file) ?? string.Empty;
for (var i = 0; i < _files.Length; i++)
{
if (ShowNames.Parser.IsMatch(dirs + @"\" + name, _titleRegex[i], _episodeRegex[i]))
{
var pf = FileNames.Parser.ParseFile(name, dirs.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries), false);
if (pf.Success)
{
_files[i].Add(file);
break;
}
}
}
}
}
}