Ejemplo n.º 1
0
        public async Task <bool> Delete(CustomFileHash customFileHash)
        {
            // Prepare and send the DELETE command
            var deleteCommandBytes = Encoding.UTF8.GetBytes("DELETE:" + customFileHash.RelativePath + ":");

            _tcpCommunication.SendCommand(deleteCommandBytes, 0, deleteCommandBytes.Length);

            Thread.Sleep(250);

            await _tcpCommunication.CommandResponseBuffer.OutputAvailableAsync();

            var readMessage  = _tcpCommunication.CommandResponseBuffer.Receive();
            var messageParts = Encoding.UTF8.GetString(readMessage).Split(':');

            if (messageParts[0].Equals("ACKNOWLEDGE"))
            {
                return(true);
            }

            if (!Context.InAutoMode)
            {
                throw new Exception(messageParts[1]);
            }
            Logger.WriteLine("Error message in DELETE Command: " + messageParts[1]);
            return(false);
        }
Ejemplo n.º 2
0
        public static void WriteFileHash(CustomFileHash customFileHash)
        {
            var str = string.Format(
                "{0}. File Change Enqueued:\n\tRelativePath: {1}\n\tChangeType: {2}\n\tHashCode: {3}\n\tReadOnly: {4}\n",
                _enqueuedFilesCounter++,
                customFileHash.RelativePath,
                customFileHash.ChangeType,
                customFileHash.HashCode,
                customFileHash.WasReadOnly);

            WriteLine(str);
        }
Ejemplo n.º 3
0
        public static void WriteFileHash(CustomFileHash customFileHash)
        {
            var str = string.Format(
                "{0}. Schimbare a fișierului pusă in coadă: CaleRelativă: {1} - TipSchimbare: {2}\n\tCodHash: {3}\n\tReadOnly: {4}\n",
                _enqueuedFilesCounter++,
                customFileHash.RelativePath,
                customFileHash.ChangeType,
                customFileHash.HashCode,
                customFileHash.WasReadOnly);

            WriteLine(str);
        }
Ejemplo n.º 4
0
        private void EnqueuingManager(FileChangeTypes fileChangeType, string fullPath, string oldFullPath = "")
        {
            var relativePath = Helper.GetRelativePath(fullPath);

            if (fileChangeType == FileChangeTypes.DeletedOnClient
                ||
                (!Helper.IsFileLocked(fullPath) && !_syncProcessor.InProcessingList(relativePath) && Helper.ExtensionIsNotExcluded(Path.GetExtension(fullPath).ToLower())))
            {
                var fileHash = new CustomFileHash(fileChangeType, fullPath, oldFullPath);
                _syncProcessor.AddChangedFile(fileHash);
                Logger.WriteFileHash(fileHash);
            }
        }
Ejemplo n.º 5
0
        public async Task <bool> Rename(CustomFileHash customFileHash)
        {
            // Prepare and send the RENAME command
            var renameCommandBytes = Encoding.UTF8.GetBytes("RENAME:" + customFileHash.OldRelativePath + ":" + customFileHash.RelativePath + ":");

            _tcpCommunication.SendCommand(renameCommandBytes, 0, renameCommandBytes.Length);

            // Processing the response for the requested rename
            string message;
            await _tcpCommunication.CommandResponseBuffer.OutputAvailableAsync();

            var readMessage  = _tcpCommunication.CommandResponseBuffer.Receive();
            var messageParts = Encoding.UTF8.GetString(readMessage).Split(':');

            if (messageParts[0].Equals("ACKNOWLEDGE"))
            {
                await _tcpCommunication.CommandResponseBuffer.OutputAvailableAsync();

                readMessage  = _tcpCommunication.CommandResponseBuffer.Receive();
                messageParts = Encoding.UTF8.GetString(readMessage).Split(':');
                if (messageParts[0].Equals("ACKNOWLEDGE"))
                {
                    // when a folder is renamed
                    if (customFileHash.FileStream != null)
                    {
                        customFileHash.FileStream.Dispose();
                    }
                    return(true);
                }
                else
                {
                    message = messageParts[1];
                }
            }
            else
            {
                message = messageParts[1];
            }

            if (customFileHash.FileStream != null)
            {
                customFileHash.FileStream.Dispose();
            }

            if (!Context.InAutoMode)
            {
                throw new Exception(message);
            }
            Logger.WriteLine("Error message in RENAME Command: " + message);
            return(false);
        }
Ejemplo n.º 6
0
        private Action AppendNewCustomFileHash(string command, string fileName, string newFileName)
        {
            return(() =>
            {
                CustomFileHash customFileHash = null;
                string message;
                string fullLocalPath;
                switch (command)
                {
                case "CHANGED":
                    message = string.Format("PushNotification: Schimbat - {0}", fileName);
                    fullLocalPath = Helper.GetLocalPath(fileName);
                    customFileHash = new CustomFileHash(FileChangeTypes.ChangedOnServer, fullLocalPath);
                    break;

                case "MKDIR":
                    message = string.Format("PushNotification: CreatDirectorNou - {0}", fileName);
                    fullLocalPath = Helper.GetLocalPath(fileName);
                    customFileHash = new CustomFileHash(FileChangeTypes.CreatedOnServer, fullLocalPath);
                    break;

                case "RENAMED":
                    // oldName to newName
                    message = string.Format("PushNotification: Redenumit - {0} to {1}", fileName, newFileName);
                    fullLocalPath = Helper.GetLocalPath(newFileName);
                    var oldFullLocalPath = Helper.GetLocalPath(fileName);
                    customFileHash = new CustomFileHash(FileChangeTypes.RenamedOnServer, fullLocalPath, oldFullLocalPath);
                    break;

                case "DELETED":
                    message = string.Format("PushNotification: Șters - {0}", fileName);
                    fullLocalPath = Helper.GetLocalPath(fileName);
                    customFileHash = new CustomFileHash(FileChangeTypes.DeletedOnServer, fullLocalPath);
                    break;

                default:
                    message = string.Format("Problemă la PushNotification recepționat: \n\tComandă: {0}\n\tNumeFișier: {1}\n\tNumeNouFișier: {2}",
                                            command, fileName, newFileName);
                    break;
                }
                if (customFileHash != null)
                {
                    ChangedFilesList.Add(customFileHash);
                }

                Logger.WriteLine(message);

                return;
            });
        }
        private Action AppendNewCustomFileHash(string command, string fileName, string newFileName)
        {
            return(() =>
            {
                CustomFileHash customFileHash = null;
                string message;
                string fullLocalPath;
                switch (command)
                {
                case "CHANGED":
                    message = string.Format("PushNotification: ChangedOnServer - {0}", fileName);
                    fullLocalPath = Helper.GetLocalPath(fileName);
                    customFileHash = new CustomFileHash(FileChangeTypes.ChangedOnServer, fullLocalPath);
                    break;

                case "MKDIR":
                    message = string.Format("PushNotification: MakedNewDirectory - {0}", fileName);
                    fullLocalPath = Helper.GetLocalPath(fileName);
                    customFileHash = new CustomFileHash(FileChangeTypes.CreatedOnServer, fullLocalPath);
                    break;

                case "RENAMED":
                    // oldName to newName
                    message = string.Format("PushNotification: RenamedOnServer - {0} to {1}", fileName, newFileName);
                    fullLocalPath = Helper.GetLocalPath(newFileName);
                    var oldFullLocalPath = Helper.GetLocalPath(fileName);
                    customFileHash = new CustomFileHash(FileChangeTypes.RenamedOnServer, fullLocalPath, oldFullLocalPath);
                    break;

                case "DELETED":
                    message = string.Format("PushNotification: DeletedOnServer - {0}", fileName);
                    fullLocalPath = Helper.GetLocalPath(fileName);
                    customFileHash = new CustomFileHash(FileChangeTypes.DeletedOnServer, fullLocalPath);
                    break;

                default:
                    message = string.Format("Received push notification ISSUE:\n\tCommand: {0}\n\tFileName: {1}\n\tNewFileName: {2}", command, fileName, newFileName);
                    break;
                }
                if (customFileHash != null)
                {
                    ChangedFilesList.Add(customFileHash);
                }

                Logger.WriteLine(message);

                return;
            });
        }
Ejemplo n.º 8
0
        public static bool ChangeFileAttributes(CustomFileHash customFileHash, string creationTimeTicks, string lastWriteTimeTicks, string isReadOnlyString)
        {
            var fullPath = GetLocalPath(customFileHash.RelativePath);

            var numberOfRetries = 5;
            var delayOnRetry    = 100;

            for (int i = 1; i <= numberOfRetries; ++i)
            {
                try
                {
                    if (customFileHash.FileInfo == null)
                    {
                        customFileHash.FileInfo = new FileInfo(fullPath);
                    }

                    customFileHash.FileInfo.CreationTimeUtc  = new DateTime(long.Parse(creationTimeTicks));
                    customFileHash.FileInfo.LastWriteTimeUtc = new DateTime(long.Parse(lastWriteTimeTicks));

                    var isReadOnly     = bool.Parse(isReadOnlyString);
                    var fileAttributes = File.GetAttributes(fullPath);
                    if (isReadOnly)
                    {
                        fileAttributes |= FileAttributes.ReadOnly;
                    }

                    customFileHash.FileInfo.Attributes = fileAttributes;

                    return(true);
                }
                catch (IOException ex)
                {
                    var msg = string.Format("Ajutor: SchimbăAtributeleFișierului - {0}: \n\tNumărul reîncercării: {1} of {2}\n\tMesaj: {3}\n\tStackTrace: {4}",
                                            fullPath, i, numberOfRetries, ex.Message, ex.StackTrace);
                    Logger.WriteLine(msg);

                    if (i == numberOfRetries)
                    {
                        return(false);
                    }

                    Thread.Sleep(delayOnRetry);
                }
            }

            Logger.WriteLine("Ajutor: SchimbăAtributeleFișierului - comportament neașteptat");
            return(false);
        }
Ejemplo n.º 9
0
        public static bool ChangeFileAttributes(CustomFileHash customFileHash, string creationTimeTicks, string lastWriteTimeTicks, string isReadOnlyString)
        {
            var fullPath = GetLocalPath(customFileHash.RelativePath);

            var numberOfRetries = 5;
            var delayOnRetry    = 100;

            for (int i = 1; i <= numberOfRetries; ++i)
            {
                try
                {
                    if (customFileHash.FileInfo == null)
                    {
                        customFileHash.FileInfo = new FileInfo(fullPath);
                    }

                    customFileHash.FileInfo.CreationTimeUtc  = new DateTime(long.Parse(creationTimeTicks));
                    customFileHash.FileInfo.LastWriteTimeUtc = new DateTime(long.Parse(lastWriteTimeTicks));

                    var isReadOnly     = bool.Parse(isReadOnlyString);
                    var fileAttributes = File.GetAttributes(fullPath);
                    if (isReadOnly)
                    {
                        fileAttributes |= FileAttributes.ReadOnly;
                    }

                    customFileHash.FileInfo.Attributes = fileAttributes;

                    return(true);
                }
                catch (IOException ex)
                {
                    var msg = string.Format("Helper (ChangeFileAttributes - {0}): \n\tRetry number: {1} of {2}\n\tMessage: {3}\n\tStackTrace: {4}",
                                            fullPath, i, numberOfRetries, ex.Message, ex.StackTrace);
                    Logger.WriteLine(msg);

                    if (i == numberOfRetries)
                    {
                        return(false);
                    }

                    Thread.Sleep(delayOnRetry);
                }
            }

            Logger.WriteLine("Helper - ChangeFileAttributes - WHY DID IT GOT HERE ?!");
            return(false);
        }
Ejemplo n.º 10
0
        public async Task <bool> Mkdir(CustomFileHash fileHash)
        {
            // Prepare and send the MKDIR command
            var newFolderCommandBytes = Encoding.UTF8.GetBytes("MKDIR:" + fileHash.RelativePath + ":");

            _tcpCommunication.SendCommand(newFolderCommandBytes, 0, newFolderCommandBytes.Length);

            await _tcpCommunication.CommandResponseBuffer.OutputAvailableAsync();

            var readMessage  = _tcpCommunication.CommandResponseBuffer.Receive();
            var messageParts = Encoding.UTF8.GetString(readMessage).Split(':');

            if (messageParts[0].Equals("ACKNOWLEDGE"))
            {
                return(true);
            }

            Logger.WriteLine("Mesaj din comanda CrDirector: " + messageParts[1]);
            return(false);
        }
Ejemplo n.º 11
0
        public async Task ChangedFileManager()
        {
            On = true;
            while (true)
            {
                CustomFileHash fileHash = null;
                try
                {
                    if (_changedFilesList.Count != 0)
                    {
                        fileHash = _changedFilesList.First();
                        var processed = false;
                        switch (fileHash.ChangeType)
                        {
                        // Changes on CLIENT
                        case FileChangeTypes.CreatedOnClient:
                            if (Helper.IsDirectory(fileHash.FullLocalPath))
                            {
                                await _commandHandler.Mkdir(fileHash);
                            }
                            else
                            {
                                await _commandHandler.Put(fileHash);
                            }
                            Logger.WriteLine(string.Format("{0}. Succes on dequeue: {1} ==> {2}",
                                                           _dequeuedFilesCounter++, fileHash.RelativePath, fileHash.ChangeType));
                            break;

                        case FileChangeTypes.ChangedOnClient:
                            await _commandHandler.Put(fileHash);

                            Logger.WriteLine(string.Format("{0}. Succes on dequeue: {1} ==> {2}",
                                                           _dequeuedFilesCounter++, fileHash.RelativePath, fileHash.ChangeType));
                            break;

                        case FileChangeTypes.RenamedOnClient:
                            await _commandHandler.Rename(fileHash);

                            Logger.WriteLine(string.Format("{0}. Succes on dequeue: {1} renamed to {2}",
                                                           _dequeuedFilesCounter++, fileHash.OldRelativePath, fileHash.RelativePath));
                            break;

                        case FileChangeTypes.DeletedOnClient:
                            await _commandHandler.Delete(fileHash);

                            Logger.WriteLine(string.Format("{0}. Succes on dequeue: {1} ==> {2}",
                                                           _dequeuedFilesCounter++, fileHash.RelativePath, fileHash.ChangeType));
                            break;


                        // Changes on SERVER
                        case FileChangeTypes.CreatedOnServer:
                            //if (Helper.IsDirectory(fileHash.FullLocalPath))
                            //{
                            Directory.CreateDirectory(fileHash.FullLocalPath);
                            Logger.WriteLine(string.Format("{0}. Succes on dequeue: {1} ==> {2}",
                                                           _dequeuedFilesCounter++, fileHash.RelativePath, fileHash.ChangeType));
                            //}
                            //else
                            //{
                            //    Logger.WriteLine(string.Format("{0}. Fail on dequeue: {1} ==> {2} - It should've been a folder here.",
                            //        _dequeuedFilesCounter++, fileHash.RelativePath, fileHash.ChangeType));
                            //}
                            break;

                        case FileChangeTypes.ChangedOnServer:
                            var fileCreated = _commandHandler.Get(fileHash);
                            if (await fileCreated)
                            {
                                Logger.WriteLine(string.Format("{0}. Succes on dequeue: {1} ==> {2}",
                                                               _dequeuedFilesCounter++, fileHash.RelativePath, fileHash.ChangeType));
                            }
                            else
                            {
                                Logger.WriteLine(string.Format("{0}. Fail on dequeue: {1} ==> {2}",
                                                               _dequeuedFilesCounter++, fileHash.RelativePath, fileHash.ChangeType));
                            }
                            break;

                        case FileChangeTypes.RenamedOnServer:
                            if (Helper.IsDirectory(fileHash.OldFullLocalPath))
                            {
                                Directory.Move(fileHash.OldFullLocalPath, fileHash.FullLocalPath);

                                //var tempName = Helper.SyncLocation + "~RenamingFolder~";
                                //var dir = new DirectoryInfo(fileHash.OldFullLocalPath);
                                //dir.MoveTo(tempName);
                                //Thread.Sleep(2000);
                                //dir.MoveTo(fileHash.FullLocalPath);
                            }
                            else
                            {
                                //fileHash.FileStream.Close();
                                File.Move(fileHash.OldFullLocalPath, fileHash.FullLocalPath);
                            }

                            Logger.WriteLine(string.Format("{0}. Succes on dequeue: {1} ==> {2}",
                                                           _dequeuedFilesCounter++, fileHash.RelativePath, fileHash.ChangeType));
                            break;

                        case FileChangeTypes.DeletedOnServer:
                            if (Helper.IsDirectory(fileHash.FullLocalPath))
                            {
                                if (Directory.Exists(fileHash.FullLocalPath))
                                {
                                    Directory.Delete(fileHash.FullLocalPath, true);
                                    Logger.WriteLine(string.Format("{0}. Succes on dequeue: {1} ==> {2}",
                                                                   _dequeuedFilesCounter++, fileHash.RelativePath, fileHash.ChangeType));
                                }
                                else
                                {
                                    Logger.WriteLine(string.Format("{0}. Fail on dequeue: {1} ==> {2}\n(Directory " + fileHash.FullLocalPath + "doesn't exist)",
                                                                   _dequeuedFilesCounter++, fileHash.RelativePath, fileHash.ChangeType));
                                }
                            }
                            else if (File.Exists(fileHash.FullLocalPath))
                            {
                                fileHash.FileStream.Close();
                                File.Delete(fileHash.FullLocalPath);
                                Logger.WriteLine(string.Format("{0}. Succes on dequeue: {1} ==> {2}",
                                                               _dequeuedFilesCounter++, fileHash.RelativePath, fileHash.ChangeType));
                            }
                            else
                            {
                                Logger.WriteLine(string.Format("{0}. Fail on dequeue: {1} ==> {2}\n(File " + fileHash.FullLocalPath + "doesn't exist)",
                                                               _dequeuedFilesCounter++, fileHash.RelativePath, fileHash.ChangeType));
                            }
                            break;
                        }
                        processed = true;

                        _changedFilesList.Remove(fileHash);
                        if (!processed)
                        {
                            _changedFilesList.Add(fileHash);
                        }

                        Thread.Sleep(500);
                    }
                    else
                    {
                        On = false;
                        return;
                    }
                }
                catch (Exception ex)
                {
                    string exMessage;
                    if (fileHash != null)
                    {
                        exMessage = string.Format("\n!!! EXCEPTION on SyncProcessor:\n\tFileHash:\n{0}\n\tMessage: {1}\n\n\tType: {2}\n\n\tSource: {3}\n\n\tStackTrace:\n {4}\n",
                                                  fileHash,
                                                  ex.Message,
                                                  ex.GetType(),
                                                  ex.Source,
                                                  ex.StackTrace);

                        if (fileHash.FileStream != null)
                        {
                            fileHash.FileStream.Dispose();
                        }

                        if (_changedFilesList != null)
                        {
                            _changedFilesList.Remove(fileHash);
                        }
                        else
                        {
                            exMessage += "\n!!! _changedFilesList was null !!! Why ?";
                        }
                    }
                    else
                    {
                        exMessage = "!!! EXCEPTION on SyncProcessor: fileHash was null. HOW ?!?!?!";
                    }

                    Logger.WriteLine(exMessage);
                }
            }
        }
Ejemplo n.º 12
0
 public void AddChangedFile(CustomFileHash customFileHash)
 {
     _changedFilesList.Add(customFileHash);
 }
Ejemplo n.º 13
0
        public async Task <bool> Get(CustomFileHash customFileHash)
        {
            // Prepare and send the GET command
            var getCommandBytes = Encoding.UTF8.GetBytes("GET:" + customFileHash.RelativePath + ":");

            _tcpCommunication.SendCommand(getCommandBytes, 0, getCommandBytes.Count());

            await _tcpCommunication.CommandResponseBuffer.OutputAvailableAsync();

            var readMessage  = _tcpCommunication.CommandResponseBuffer.Receive();
            var fullMessage  = Encoding.UTF8.GetString(readMessage);
            var messageParts = fullMessage.Split(':');

            // If we get Acknowledge => the file exists. Beside this, we get the file details.
            if (messageParts[0].Equals("ACKNOWLEDGE"))
            {
                int fileLen;
                var lenParsed = int.TryParse(messageParts[1], out fileLen);
                if (fileLen > 0)
                {
                    var offsetSize = (messageParts[0].Length                // Acknowledge
                                      + messageParts[1].Length              // MessageLength
                                      + messageParts[2].Length              // CreationTime
                                      + messageParts[3].Length              // LastWriteTime
                                      + messageParts[4].Length              // IsReadOnly
                                      + 5);                                 // Plus 1 for each ':' contained in readMessage

                    var fullLength = offsetSize + messageParts[5].Length - 1;

                    // If we have some DataContent in the Acknowledge message we write that in the file.
                    var remainedMessageSize = fullLength - offsetSize;
                    var expectedSize        = int.Parse(messageParts[1]);
                    if (remainedMessageSize > 0)
                    {
                        customFileHash.FileStream.Write(readMessage, offsetSize, remainedMessageSize);
                        expectedSize -= remainedMessageSize;
                    }

                    // Writing the DataContent in file until we get the entire expected size.
                    await _tcpCommunication.CommandResponseBuffer.OutputAvailableAsync();

                    while (expectedSize > 0)
                    {
                        var buffer = _tcpCommunication.CommandResponseBuffer.Receive();
                        customFileHash.FileStream.Write(buffer, 0, buffer.Length);
                        expectedSize -= buffer.Length;
                    }
                }
                else
                {
                    if (customFileHash.FileStream != null)
                    {
                        customFileHash.FileStream.SetLength(0);
                    }
                }

                if (customFileHash.FileStream != null)
                {
                    customFileHash.FileStream.Dispose();
                }

                // Applying the file details.
                return(Helper.ChangeFileAttributes(customFileHash, messageParts[2], messageParts[3], messageParts[4]));
            }

            if (customFileHash.FileStream != null)
            {
                customFileHash.FileStream.Dispose();
            }

            if (!Context.InAutoMode)
            {
                throw new Exception(messageParts[1]);
            }
            Logger.WriteLine("Error message in GET Command: " + messageParts[1]);
            return(false);
        }
Ejemplo n.º 14
0
        public async Task <bool> Put(CustomFileHash customFileHash)
        {
            // Prepare and send the PUT command
            var fileSize        = new FileInfo(customFileHash.FullLocalPath).Length;
            var putCommandBytes = Encoding.UTF8.GetBytes("PUT:" + customFileHash.RelativePath + ":" + customFileHash.HashCode + ":" + fileSize + ":");

            _tcpCommunication.SendCommand(putCommandBytes, 0, putCommandBytes.Length);

            // Processing the response for the PUT command
            string message;
            await _tcpCommunication.CommandResponseBuffer.OutputAvailableAsync();

            var readMessage  = _tcpCommunication.CommandResponseBuffer.Receive();
            var messageParts = Encoding.UTF8.GetString(readMessage).Split(':');

            if (messageParts[0].Equals("ACKNOWLEDGE"))
            {
                // Sending the entire DataContent
                if (fileSize != 0)
                {
                    var buffer = new byte[Helper.BufferSize];
                    int readBytes;
                    while ((readBytes = customFileHash.FileStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        _tcpCommunication.SendCommand(buffer, 0, readBytes);
                    }
                }
                customFileHash.FileStream.Dispose();

                // Processing the response for sent data
                await _tcpCommunication.CommandResponseBuffer.OutputAvailableAsync();

                readMessage  = _tcpCommunication.CommandResponseBuffer.Receive();
                messageParts = Encoding.UTF8.GetString(readMessage).Split(':');
                if (messageParts[0].Equals("ACKNOWLEDGE"))
                {
                    // Sending the FileHashDetails for the transmited data
                    Logger.WriteLine(customFileHash.GetFileHashDetails());
                    var fileHashDetails = Encoding.UTF8.GetBytes(customFileHash.GetFileHashDetails());
                    _tcpCommunication.SendCommand(fileHashDetails, 0, fileHashDetails.Length);

                    // Processing the response for the FileHashDetails that were sent
                    await _tcpCommunication.CommandResponseBuffer.OutputAvailableAsync();

                    readMessage  = _tcpCommunication.CommandResponseBuffer.Receive();
                    messageParts = Encoding.UTF8.GetString(readMessage).Split(':');
                    if (messageParts[0].Equals("ACKNOWLEDGE"))
                    {
                        Logger.WriteLine("The FileHash of \"" + customFileHash.RelativePath + "\" was sent successfully.");
                        return(true);
                    }
                    else
                    {
                        message = messageParts[1];
                    }
                }
                else
                {
                    message = messageParts[1];
                }
            }
            else
            {
                message = messageParts[1];
            }

            customFileHash.FileStream.Dispose();
            if (!Context.InAutoMode)
            {
                throw new Exception(message);
            }
            Logger.WriteLine("Error message in PUT Command: " + message);
            return(false);
        }
Ejemplo n.º 15
0
        public async Task ChangedFileManager()
        {
            On = true;
            while (true)
            {
                CustomFileHash fileHash = null;
                try
                {
                    if (_changedFilesList.Count != 0)
                    {
                        fileHash = _changedFilesList.First();
                        var processed = false;
                        switch (fileHash.ChangeType)
                        {
                        // Changes on CLIENT
                        case FileChangeTypes.CreatedOnClient:
                            if (Helper.IsDirectory(fileHash.FullLocalPath))
                            {
                                await _commandHandler.Mkdir(fileHash);
                            }
                            else
                            {
                                await _commandHandler.Put(fileHash);
                            }
                            Logger.WriteLine(string.Format("{0}. Succes la ștergerea din coadă: {1}. (Trimis pe Server)",
                                                           _dequeuedFilesCounter++, fileHash.RelativePath));
                            break;

                        case FileChangeTypes.ChangedOnClient:
                            await _commandHandler.Put(fileHash);

                            Logger.WriteLine(string.Format("{0}. Succes la ștergerea din coadă: {1}. (Trimis pe Server)",
                                                           _dequeuedFilesCounter++, fileHash.RelativePath));
                            break;

                        case FileChangeTypes.RenamedOnClient:
                            await _commandHandler.Rename(fileHash);

                            Logger.WriteLine(string.Format("{0}. Succes la ștergerea din coadă: {1} redenumit la {2}. (Redenumit pe Client)",
                                                           _dequeuedFilesCounter++, fileHash.OldRelativePath, fileHash.RelativePath));
                            break;

                        case FileChangeTypes.DeletedOnClient:
                            await _commandHandler.Delete(fileHash);

                            Logger.WriteLine(string.Format("{0}. Succes la ștergerea din coadă: {1}. (Șters pe Server)",
                                                           _dequeuedFilesCounter++, fileHash.RelativePath));
                            break;


                        // Changes on SERVER
                        case FileChangeTypes.CreatedOnServer:
                            //if (Helper.IsDirectory(fileHash.FullLocalPath))
                            //{
                            Directory.CreateDirectory(fileHash.FullLocalPath);
                            Logger.WriteLine(string.Format("{0}. Succes la ștergerea din coadă: {1}. (Creat pe Server)",
                                                           _dequeuedFilesCounter++, fileHash.RelativePath));
                            //}
                            //else
                            //{
                            //    Logger.WriteLine(string.Format("{0}. Fail on dequeue: {1} ==> {2} - It should've been a folder here.",
                            //        _dequeuedFilesCounter++, fileHash.RelativePath, fileHash.ChangeType));
                            //}
                            break;

                        case FileChangeTypes.ChangedOnServer:
                            var fileCreated = _commandHandler.Get(fileHash);
                            if (await fileCreated)
                            {
                                Logger.WriteLine(string.Format("{0}. Succes la ștergerea din coadă: {1} (Obține de pe server)",
                                                               _dequeuedFilesCounter++, fileHash.RelativePath, fileHash.ChangeType));
                            }
                            else
                            {
                                Logger.WriteLine(string.Format("{0}. Eșec la ștergerea din coadă: {1}. (Obține  de pe Server)",
                                                               _dequeuedFilesCounter++, fileHash.RelativePath));
                            }
                            break;

                        case FileChangeTypes.RenamedOnServer:
                            if (Helper.IsDirectory(fileHash.OldFullLocalPath))
                            {
                                Directory.Move(fileHash.OldFullLocalPath, fileHash.FullLocalPath);
                            }
                            else
                            {
                                File.Move(fileHash.OldFullLocalPath, fileHash.FullLocalPath);
                            }

                            Logger.WriteLine(string.Format("{0}. Succes la ștergerea din coadă: {1}. (Redenumit pe Server)",
                                                           _dequeuedFilesCounter++, fileHash.RelativePath));
                            break;

                        case FileChangeTypes.DeletedOnServer:
                            if (Helper.IsDirectory(fileHash.FullLocalPath))
                            {
                                if (Directory.Exists(fileHash.FullLocalPath))
                                {
                                    Directory.Delete(fileHash.FullLocalPath, true);
                                    Logger.WriteLine(string.Format("{0}. Succes la ștergerea din coadă: {1} ==> {2}",
                                                                   _dequeuedFilesCounter++, fileHash.RelativePath, fileHash.ChangeType));
                                }
                                else
                                {
                                    Logger.WriteLine(string.Format("{0}. Eșec la ștergerea din coadă: {1} (Stergere pe Server: Directorul {3} nu există)",
                                                                   _dequeuedFilesCounter++, fileHash.RelativePath, fileHash.ChangeType, fileHash.FullLocalPath));
                                }
                            }
                            else if (File.Exists(fileHash.FullLocalPath))
                            {
                                fileHash.FileStream.Close();
                                File.Delete(fileHash.FullLocalPath);
                                Logger.WriteLine(string.Format("{0}. Succes la ștergerea din coadă: {1} ==> {2}",
                                                               _dequeuedFilesCounter++, fileHash.RelativePath, fileHash.ChangeType));
                            }
                            else
                            {
                                Logger.WriteLine(string.Format("{0}. Eșec la ștergerea din coadă: {1}. (Stergere pe Server: Fișierul {3} nu există)",
                                                               _dequeuedFilesCounter++, fileHash.RelativePath, fileHash.ChangeType, fileHash.FullLocalPath));
                            }
                            break;
                        }
                        processed = true;

                        _changedFilesList.Remove(fileHash);
                        if (!processed)
                        {
                            _changedFilesList.Add(fileHash);
                        }

                        Thread.Sleep(500);
                    }
                    else
                    {
                        On = false;
                        return;
                    }
                }
                catch (Exception ex)
                {
                    string exMessage;
                    if (fileHash != null)
                    {
                        exMessage = string.Format("Excepție la Procesorul de Sincronizare:" +
                                                  "\n\tFileHash:\n{0}\n\tMessage: {1}\n\n\tType: {2}\n\n\tSource: {3}\n\n\tStackTrace:\n {4}\n",
                                                  fileHash, ex.Message, ex.GetType(), ex.Source, ex.StackTrace);

                        if (fileHash.FileStream != null)
                        {
                            fileHash.FileStream.Dispose();
                        }

                        if (_changedFilesList != null)
                        {
                            _changedFilesList.Remove(fileHash);
                        }
                        else
                        {
                            exMessage += "\n!!! _listăFișiereSchimbate a fost NULL !!! De ce?";
                        }
                    }
                    else
                    {
                        exMessage = "Excepție la Procesorul de Sincronizare: înregistrareFișier a fost NULL !!! Cum ?!";
                    }

                    Logger.WriteLine(exMessage);
                }
            }
        }