interlace /source/samples/ObviousCode.Interlace.BitTunnel/Knock/KnockServer/MountedFileCache.cs

Language C# Lines 434
MD5 Hash 49df61f7b1a76aa449768723a23d0772 Estimated Cost $8,086 (why?)
Repository https://bitbucket.org/VahidN/interlace.git View Raw File View Project SPDX
  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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using KnockServer.Events;
using ObviousCode.Interlace.BitTunnelLibrary.File;
using TelexplorerServer.Mounting;
using ObviousCode.Interlace.BitTunnel.Connectivity;
using ObviousCode.Interlace.BitTunnelLibrary.Events;
using System.Threading;

namespace KnockServer
{
    public class MountedFileCache
    {

        public event EventHandler PromptRequested;

        public event EventHandler<MountDeletedEventArgs> FileMountDeleted;
        public event EventHandler<MountDeletedEventArgs> DirectoryMountDeleted;

        Dictionary<string, FileSystemWatcher> _watchers;

        Dictionary<string, List<string>> _relevantFiles;
        Dictionary<string, List<string>> _relevantDirectories;
        Dictionary<string, FileDescriptor> _cachedDescriptors;
        List<string> _cachedDirectories;

        string AllFilesTag = "all-files";
        private static MountedFileCache _cache;

        private MountedFileCache()
        {
            _watchers = new Dictionary<string, FileSystemWatcher>();

            _relevantDirectories = new Dictionary<string, List<string>>();
            _relevantFiles = new Dictionary<string, List<string>>();

            _cachedDescriptors = new Dictionary<string, FileDescriptor>();
            _cachedDirectories = new List<string>();
        }

        public static MountedFileCache Cache
        {
            get
            {
                if (_cache == null) _cache = new MountedFileCache();

                return _cache;
            }
        }

        public ClientInstance Client { private get; set; }
        public ServerInstance Server { private get; set; } 

        public bool AddFile(FileDescriptor file)
        {
            return AddFile(file, false);
        }

        private bool AddFile(FileDescriptor file, bool force)
        {
            bool hashed = false;
            Exception hashException = null;
            int loops = 0;

            if (!force && (ContainsFile(file)))
            {
                Console.WriteLine("{0} already mounted. Ignoring.", file.FileFullName);
                return false;
            }

            //Hashing operations

            Console.WriteLine("Preparing \"{0}\"", file.FileFullName);            

            file.HashGenerationCompleted += new EventHandler(delegate(object sender, EventArgs e)
            {
                hashed = true;
            });

            file.HashGenerationFailed += new EventHandler<ExceptionEventArgs>(delegate(object sender, ExceptionEventArgs e)
            {
                hashException = e.ThrownException;
            });

            file.GenerateHash();

            Console.Write("Hashing ..");

            while (!hashed && hashException == null)
            {
                if (loops++ % 10 == 0)
                {
                    Console.Write(".");
                }

                Thread.Sleep(100);
            }

            Console.WriteLine();

            if (hashException != null)
            {
                Console.WriteLine(hashException.Message);
                Console.WriteLine("Unable to hash {0}. Ignoring", file.FileName);

                return false;
            }

            if(_cachedDescriptors.Count(d => d.Value.Hash == file.Hash) > 0)
            {
                Console.WriteLine("Identically hashed file already mounted. Ignoring.");
                return false;
            }

            //Caching operations

            EnsureRequiredWatcherExists(file.DirectoryName);

            EnsureRelevantFileListExists(file.DirectoryName);

            if (!_relevantFiles[file.DirectoryName].Contains(file.FileFullName))
            {
                _relevantFiles[file.DirectoryName].Add(file.FileFullName);
            }            

            //mounting

            bool fileAvailable = false;

            EventHandler<FileListModificationEventArgs> handler = delegate(object sender, FileListModificationEventArgs e)
            {
                StringBuilder builder = new StringBuilder();

                foreach (FileModificationDescriptor item in e.Modifications)
                {
                    if (item.Mode == FileModificationMode.New)
                    {
                        builder.AppendFormat("Available File: \"{0}\"{1}", item.FileFullName, Environment.NewLine);
                    }
                }

                Console.Write(builder.ToString());
                
                _cachedDescriptors[e.Modifications[0].FileFullName] = e.Modifications[0].ToFileDescriptor();

                fileAvailable = true;
            };

            Client.FileListUpdateReceived += new EventHandler<FileListModificationEventArgs>(handler);

            Client.AddFiles(new FileDescriptor[] { file });

            DateTime then = DateTime.Now;

            while (!fileAvailable && ((TimeSpan)(DateTime.Now - then)).TotalSeconds < 30)
            {
                Thread.Sleep(100);
            }

            if (!fileAvailable)
            {
                ConsoleColor oldColour = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Red;

                Console.WriteLine("File Add Request not responded after 30 seconds. Check network and consider restarting.");
                Console.WriteLine("Terminating request ...");
                Console.ForegroundColor = oldColour;

                return false;
            }

            Client.FileListUpdateReceived -= new EventHandler<FileListModificationEventArgs>(handler);

            return true;
        }
        
        public bool AddDirectory(DirectoryInfo directory)
        {
            if (directory.Parent != null)
            {
                EnsureRequiredWatcherExists(directory.Parent.FullName);

                EnsureRelevantDirectoryListExists(directory.Parent.FullName);

                if (!_relevantDirectories[directory.Parent.FullName].Contains(directory.FullName))//it shouldn't
                {
                    _relevantDirectories[directory.Parent.FullName].Add(directory.FullName);                    
                }
                else throw new InvalidOperationException();

                _relevantDirectories[directory.Parent.FullName].Add(directory.FullName);
            }            

            EnsureRelevantFileListExists(directory.FullName);            

            foreach (FileInfo file in directory.GetFiles())
            {
                AddFile(FileDescriptor.Create(file, false));
            }

            _relevantFiles[directory.FullName].Insert(0, AllFilesTag);
            
            _cachedDirectories.Add(directory.FullName);

            return true;
        }        

        public FileDescriptor GetFileDescriptor(string path)
        {
            return (_cachedDescriptors.ContainsKey(path)) ? _cachedDescriptors[path] : (FileDescriptor)null;
        }

        private void RenameFile(string oldFileName, string newFileName)
        {
            FileDescriptor descriptor = GetFileDescriptor(oldFileName);
            
            descriptor.FileFullName = newFileName;

            if (descriptor == null) return;

            bool fileRenamed = false;

            EventHandler<FileListModificationEventArgs> handler = delegate(object sender, FileListModificationEventArgs e)
            {
                StringBuilder builder = new StringBuilder();

                if (e.Modifications[0].Mode == FileModificationMode.Renamed)
                {
                    Console.Write("Renamed File: \"{0}\"{1}", e.Modifications[0].FileFullName, Environment.NewLine);

                    _cachedDescriptors.Remove(oldFileName);
                    _cachedDescriptors[e.Modifications[0].FileFullName] = e.Modifications[0].ToFileDescriptor();                

                    fileRenamed = true;
                }                                
            };

            Client.FileListUpdateReceived += new EventHandler<FileListModificationEventArgs>(handler);

            Client.RenameFiles(new FileDescriptor[] { descriptor });

            DateTime then = DateTime.Now;

            while (!fileRenamed && ((TimeSpan)(DateTime.Now - then)).TotalSeconds < 30)
            {
                Thread.Sleep(100);
            }

            if (!fileRenamed)
            {
                ConsoleColor oldColour = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Red;

                Console.WriteLine("File Rename Request not responded after 30 seconds. Check network and consider restarting.");
                Console.WriteLine("Terminating request ...");
                Console.ForegroundColor = oldColour;

                return;
            }

            Client.FileListUpdateReceived -= new EventHandler<FileListModificationEventArgs>(handler);           
        }

        private void RemoveFile(string path)
        {
            FileDescriptor descriptor = GetFileDescriptor(path);

            if (descriptor == null) return;

            if (_relevantFiles[descriptor.DirectoryName].Contains(descriptor.FileFullName))//it should
            {
                _relevantFiles.Remove(path);
            }
            else throw new InvalidOperationException();

            if (_relevantFiles[descriptor.DirectoryName].Count == 0)
            {
                _relevantFiles.Remove(descriptor.DirectoryName);
            }

            FileDescriptor toRemove = GetFileDescriptor(path);

            _cachedDescriptors.Remove(path);

            bool fileRemoved = false;

            EventHandler<FileListModificationEventArgs> handler = delegate(object sender, FileListModificationEventArgs e)
            {
                StringBuilder builder = new StringBuilder();

                foreach (FileModificationDescriptor item in e.Modifications)
                {
                    if (item.Mode == FileModificationMode.Remove)
                    {
                        builder.AppendFormat("Removed File: \"{0}\"{1}", item.FileFullName, Environment.NewLine);
                    }
                }

                Console.Write(builder.ToString());

                _cachedDescriptors[e.Modifications[0].FileFullName] = e.Modifications[0].ToFileDescriptor();

                fileRemoved = true;
            };

            Client.FileListUpdateReceived += new EventHandler<FileListModificationEventArgs>(handler);

            Client.RemoveFiles(new FileDescriptor[] { toRemove });

            DateTime then = DateTime.Now;

            while (!fileRemoved && ((TimeSpan)(DateTime.Now - then)).TotalSeconds < 30)
            {
                Thread.Sleep(100);
            }

            if (!fileRemoved)
            {
                ConsoleColor oldColour = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Red;

                Console.WriteLine("File Remove Request not responded after 30 seconds. Check network and consider restarting.");
                Console.WriteLine("Terminating request ...");
                Console.ForegroundColor = oldColour;

                return;
            }

            Client.FileListUpdateReceived -= new EventHandler<FileListModificationEventArgs>(handler);           
        }

        private bool ContainsFile(FileDescriptor file)
        {
            if (_relevantFiles.ContainsKey(file.DirectoryName))
            {
                return (
                    _relevantFiles[file.DirectoryName].Contains(AllFilesTag)
                    || _relevantFiles[file.DirectoryName].Contains(file.FileFullName));
            }

            return false;

        }                 

        internal bool ContainsDirectory(string fullName)
        {
            return _cachedDirectories.Contains(fullName);
        }

        private void EnsureRelevantDirectoryListExists(string directoryName)
        {
            if (!_relevantDirectories.ContainsKey(directoryName))
            {
                _relevantDirectories[directoryName] = new List<string>();
            }
        }

        private void EnsureRelevantFileListExists(string directoryName)
        {
            if (!_relevantFiles.ContainsKey(directoryName))
            {
                _relevantFiles[directoryName] = new List<string>();
            }
        }

        private void EnsureRequiredWatcherExists(string watcherKey)
        {
            if (!_watchers.ContainsKey(watcherKey))
            {
                FileSystemWatcher watcher = new FileSystemWatcher(watcherKey);

                watcher.Created += new FileSystemEventHandler(FileSystemWatcher_ItemCreated);
                watcher.Deleted += new FileSystemEventHandler(FileSystemWatcher_ItemDeleted);
                watcher.Renamed += new RenamedEventHandler(FileSystemWatcher_ItemRenamed);

                watcher.EnableRaisingEvents = true;

                _watchers[watcherKey] = watcher;
            }
        }


        void FileSystemWatcher_ItemRenamed(object sender, RenamedEventArgs e)
        {
            RenameFile(e.OldFullPath, e.FullPath);

            if (PromptRequested != null)
            {
                PromptRequested(this, EventArgs.Empty);
            }
        }
        
        void FileSystemWatcher_ItemDeleted(object sender, FileSystemEventArgs e)
        {
            RemoveFile(e.FullPath);

            if (PromptRequested != null)
            {
                PromptRequested(this, EventArgs.Empty);
            }
        }

        void FileSystemWatcher_ItemCreated(object sender, FileSystemEventArgs e)
        {
            AddFile(FileDescriptor.Create(e.FullPath, false), true);
            
            if (PromptRequested != null)
            {
                PromptRequested(this, EventArgs.Empty);
            }
        }


        public int DirectoryCount
        {
            get
            {
                return _cachedDirectories.Count;
            }
        }

        public IEnumerable<string> DirectoryNames
        {
            get
            {
                return _cachedDirectories;
            }
        }
    }
}
Back to Top