Exemple #1
0
        /// <summary>
        /// Copy the contents of a stored file into a physical file
        /// </summary>
        /// <param name="_zfe">Entry information of file to extract</param>
        /// <param name="_filename">Name of file to store uncompressed data</param>
        /// <returns>True if success, false if not.</returns>
        /// <remarks>Unique compression methods are Store and Deflate</remarks>
        public bool ExtractFile(ZipFileEntry _zfe, string _filename)
        {
            // Make sure the parent directory exist
            string path = LongDirectory.GetDirectoryName(_filename);

            if (!LongDirectory.Exists(path))
            {
                LongDirectory.CreateDirectory(path);
            }
            // Check it is directory. If so, do nothing
            if (LongDirectory.Exists(_filename))
            {
                return(true);
            }

            Stream output = new FileStream(_filename, FileMode.Create, FileAccess.Write);
            bool   result = ExtractFile(_zfe, output);

            if (result)
            {
                output.Close();
            }

            LongFile.SetCreationTime(_filename, _zfe.ModifyTime);
            LongFile.SetLastWriteTime(_filename, _zfe.ModifyTime);

            return(result);
        }
Exemple #2
0
        public static State GetCurrentState(string path, Connection share)
        {
            if (share.isChanged == false &&
                share.CurrentState.Files.Count > 0 &&
                share.CurrentState.Folders.Count > 0)
            {
                return(share.CurrentState);
            }

            DateTime dt    = FastDateTime.Now;
            State    state = new State();

            foreach (var f in LongDirectory.GetDirectories(path, "*.*", SearchOption.AllDirectories))
            {
                string p = f.Replace(path, "")
                           .Replace("/", "\\"); // for unix systems
                if (share.Allowed(p))
                {
                    state.Folders.Add(p);
                }
            }

            if (Global.isWindows == false)
            {
                foreach (var f in Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
                {
                    var    fi = new FileInfo(f);
                    string fn = fi.FullName.Replace(path, "")
                                .Replace("/", "\\"); // for unix systems
                    if (share.Allowed(fi.FullName))
                    {
                        state.Files.Add(new SyncFile {
                            F = fn, D = fi.LastWriteTime, S = fi.Length
                        });
                    }
                }
            }
            else
            {
                foreach (var f in FastDirectoryEnumerator.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
                {
                    string fn = f.Path.Replace(path, "")
                                .Replace("/", "\\"); // for unix systems
                    if (share.Allowed(f.Path))
                    {
                        state.Files.Add(new SyncFile {
                            F = fn, D = f.LastWriteTime, S = f.Size
                        });
                    }
                }
            }
            _log.Info("GetCurrentState total secs = " + FastDateTime.Now.Subtract(dt).TotalSeconds);
            share.CurrentState = state;
            return(state);
        }
Exemple #3
0
    public static string[] GetFiles(string path, string searchPattern, System.IO.SearchOption searchOption)
    {
        if (TorpedoSync.Global.isWindows == false)
        {
            return(System.IO.Directory.GetFiles(path.Replace("\\", "/"), searchPattern, searchOption));
        }

        searchPattern = searchPattern ?? "*";

        var files = new List <string>();
        var dirs  = new List <string> {
            path
        };

        if (searchOption == SearchOption.AllDirectories)
        {
            //Add all the subpaths
            dirs.AddRange(LongDirectory.GetDirectories(path, null, SearchOption.AllDirectories));
        }

        foreach (var dir in dirs)
        {
            NativeMethods.WIN32_FIND_DATA findData;
            IntPtr findHandle = NativeMethods.FindFirstFile(System.IO.Path.Combine(GetWin32LongPath(dir), searchPattern), out findData);

            try
            {
                if (findHandle != new IntPtr(-1))
                {
                    do
                    {
                        if ((findData.dwFileAttributes & System.IO.FileAttributes.Directory) == 0)
                        {
                            string filename = System.IO.Path.Combine(dir, findData.cFileName);
                            files.Add(GetCleanPath(filename));
                        }
                    } while (NativeMethods.FindNextFile(findHandle, out findData));
                    NativeMethods.FindClose(findHandle);
                }
            }
            catch (Exception)
            {
                NativeMethods.FindClose(findHandle);
                throw;
            }
        }

        return(files.ToArray());
    }
Exemple #4
0
        private static void docompressdirectory(ZipStorer zip, string dir, string prefix, bool recursive, Action <string> log)
        {
            if (recursive)
            {
                foreach (var d in LongDirectory.GetDirectories(dir))
                {
                    docompressdirectory(zip, d, prefix, recursive, log);
                }
            }

            foreach (string path in LongDirectory.GetFiles(dir))
            {
                var fn = path.Replace(prefix, "");
                zip.AddFile(ZipStorer.Compression.Deflate, path, fn, "");
                log?.Invoke(fn);
            }
        }
Exemple #5
0
        public void Delete(Parameters parameters)
        {
            if (LongDirectory.Exists(Path))
            {
                string[] paths = LongDirectory.GetFiles(Path);
                foreach (string filePath in paths)
                {
                    if (parameters.Verbose)
                    {
                        Console.Out.WriteLine("{0}", filePath);
                    }
                    LongFile.Delete(filePath);
                }
                if (parameters.Recursive)
                {
                    string[] subDirs = LongDirectory.GetDirectories(Path);
                    foreach (string subDir in subDirs)
                    {
                        PFolder pFolder = new PFolder(subDir);
                        pFolder.Delete(parameters);
                    }
                }
                if (parameters.Verbose)
                {
                    Console.Out.WriteLine("{0}", Path);
                }
                LongDirectory.Delete(Path);
            }
            else if (LongFile.Exists(Path))
            {
                if (parameters.Verbose)
                {
                    Console.Out.WriteLine("{0}", Path);
                }
                LongFile.Delete(Path);
            }

            if (Path == parameters.Path)
            {
                if (parameters.RequireEnterToExit)
                {
                    Console.Out.WriteLine("Press enter to exit");
                    Console.In.ReadLine();
                }
            }
        }
Exemple #6
0
 private static void DeleteDirectories(string[] directories)
 {
     foreach (string directory in directories)
     {
         string[] files = LongDirectory.GetFiles(directory, null, System.IO.SearchOption.TopDirectoryOnly);
         foreach (string file in files)
         {
             LongFile.Delete(file);
         }
         directories = LongDirectory.GetDirectories(directory, null, System.IO.SearchOption.TopDirectoryOnly);
         DeleteDirectories(directories);
         bool ok = NativeMethods.RemoveDirectory(GetWin32LongPath(directory));
         if (!ok)
         {
             ThrowWin32Exception();
         }
     }
 }
Exemple #7
0
        private void ProcessFile(SyncFile file)
        {
            string fn = _conn.Path + file.F;

            //_log.Info("create dir : " + LongDirectory.GetDirectoryName(fn));
            LongDirectory.CreateDirectory(LongDirectory.GetDirectoryName(fn));

            if (LongFile.Exists(fn))
            {
                // kludge : for seconds resolution
                var fi = new LongFileInfo(fn);
                var d1 = fi.LastWriteTime.Ticks / _tickfilter;
                var d2 = file.D.Ticks / _tickfilter;
                if (d1 >= d2) // skip if already copied or newer
                {
                    return;
                }
            }
            _connInfo.LastFileNameDownloaded = fn;
            fn += ".!torpedosync";
            // FEATURE : resume semi downloaded file

            // remove old semi downloaded file
            LongFile.Delete(fn);

            if (TorpedoSync.Global.isWindows == false)
            {
                fn = fn.Replace("\\", "/");
            }

            _downloading = true;

            if (downloadfile(file, fn, ClientCommands.Download))
            {
                MoveExistingFileToArchive(file.F);
                // rename downloaded file
                LongFile.Move(fn, _conn.Path + file.F);

                LongFile.SetLastWriteTime(_conn.Path + file.F, file.D);
            }
            _downloading = false;
        }
Exemple #8
0
        private void AnalyseFolder(string folder1, string folder2)
        {
            string[] files1 = !LongDirectory.Exists(folder1) ? new string[] { } : LongDirectory.GetFiles(folder1).Select(f => LongFile.GetName(f)).ToArray();
            string[] files2 = !LongDirectory.Exists(folder2) ? new string[] { } : LongDirectory.GetFiles(folder2).Select(f => LongFile.GetName(f)).ToArray();
            foreach (string file1 in files1)
            {
                SyncItems.Add(new SyncItem(LongFile.Combine(folder1, file1), LongFile.Combine(folder2, file1), SyncItemType.File));
            }
            foreach (string file2 in files2)
            {
                if (files1.FirstOrDefault(f => f == file2) == null)
                {
                    SyncItems.Add(new SyncItem(LongFile.Combine(folder1, file2), LongFile.Combine(folder2, file2), SyncItemType.File));
                }
            }

            string[] subs1 = !LongDirectory.Exists(folder1) ? new string[] { } : LongDirectory.GetDirectories(folder1).Select(f => LongDirectory.GetName(f)).ToArray();
            string[] subs2 = !LongDirectory.Exists(folder2) ? new string[] { } : LongDirectory.GetDirectories(folder2).Select(f => LongDirectory.GetName(f)).ToArray();
            foreach (string sub1 in subs1)
            {
                string fullSub1 = LongDirectory.Combine(folder1, sub1);
                string fullSub2 = LongDirectory.Combine(folder2, sub1);
                SyncItems.Add(new SyncItem(fullSub1, fullSub2, SyncItemType.Folder));
                AnalyseFolder(fullSub1, fullSub2);
            }
            foreach (string sub2 in subs2)
            {
                if (subs1.FirstOrDefault(f => f == sub2) == null)
                {
                    string fullSub1 = LongDirectory.Combine(folder1, sub2);
                    string fullSub2 = LongDirectory.Combine(folder2, sub2);
                    SyncItems.Add(new SyncItem(fullSub1, fullSub2, SyncItemType.Folder));
                    AnalyseFolder(fullSub1, fullSub2);
                }
            }
        }
Exemple #9
0
        public void DoAction()
        {
            try
            {
                if (ItemType == SyncItemType.Folder)
                {
                    SyncedFile past1 = MainDbContext.DB.SyncedFiles.FirstOrDefault(f => f.Path == Path1);
                    SyncedFile past2 = MainDbContext.DB.SyncedFiles.FirstOrDefault(f => f.Path == Path2);

                    if (Action == SyncActions.CopyFrom1To2)
                    {
                        if (!LongDirectory.Exists(Path2))
                        {
                            LongDirectory.CreateDirectory(Path2);
                        }
                        if (past1 == null)
                        {
                            MainDbContext.DB.SyncedFiles.Add(new SyncedFile()
                            {
                                LastModified = DateTime.MinValue, Path = Path1
                            });
                        }
                        if (past2 == null)
                        {
                            MainDbContext.DB.SyncedFiles.Add(new SyncedFile()
                            {
                                LastModified = DateTime.MinValue, Path = Path2
                            });
                        }
                        Status = SyncItemStatus.ActionOK;
                    }
                    else if (Action == SyncActions.CopyFrom2To1)
                    {
                        if (!LongDirectory.Exists(Path1))
                        {
                            LongDirectory.CreateDirectory(Path1);
                        }
                        if (past1 == null)
                        {
                            MainDbContext.DB.SyncedFiles.Add(new SyncedFile()
                            {
                                LastModified = DateTime.MinValue, Path = Path1
                            });
                        }
                        if (past2 == null)
                        {
                            MainDbContext.DB.SyncedFiles.Add(new SyncedFile()
                            {
                                LastModified = DateTime.MinValue, Path = Path2
                            });
                        }
                        Status = SyncItemStatus.ActionOK;
                    }
                    else if (Action == SyncActions.Delete1 || Action == SyncActions.Delete2 || Action == SyncActions.DeleteBoth)
                    {
                        if (LongDirectory.Exists(Path1))
                        {
                            LongDirectory.Delete(Path1, true);
                        }
                        if (LongDirectory.Exists(Path2))
                        {
                            LongDirectory.Delete(Path2, true);
                        }
                        if (past1 != null)
                        {
                            MainDbContext.DB.SyncedFiles.Remove(past1);
                        }
                        if (past2 != null)
                        {
                            MainDbContext.DB.SyncedFiles.Remove(past2);
                        }
                        Status = SyncItemStatus.ActionOK;
                    }
                }
                else if (ItemType == SyncItemType.File)
                {
                    SyncedFile past1 = MainDbContext.DB.SyncedFiles.FirstOrDefault(f => f.Path == Path1);
                    SyncedFile past2 = MainDbContext.DB.SyncedFiles.FirstOrDefault(f => f.Path == Path2);

                    if (Action == SyncActions.CopyFrom1To2)
                    {
                        LongFile.Copy(Path1, Path2);
                        DateTime lastModified = LongFile.GetLastWriteTime(Path1);

                        if (past1 == null)
                        {
                            past1 = new SyncedFile()
                            {
                                LastModified = lastModified, Path = Path1
                            };
                            MainDbContext.DB.SyncedFiles.Add(past1);
                        }
                        else if (!lastModified.Equals(past1.LastModified))
                        {
                            past1.LastModified = lastModified;
                        }

                        if (past2 == null)
                        {
                            past2 = new SyncedFile()
                            {
                                LastModified = lastModified, Path = Path2
                            };
                            MainDbContext.DB.SyncedFiles.Add(past2);
                        }
                        else if (!lastModified.Equals(past2.LastModified))
                        {
                            past2.LastModified = lastModified;
                        }
                        Status = SyncItemStatus.ActionOK;
                    }
                    else if (Action == SyncActions.CopyFrom2To1)
                    {
                        LongFile.Copy(Path2, Path1);
                        DateTime lastModified = LongFile.GetLastWriteTime(Path2);

                        if (past1 == null)
                        {
                            past1 = new SyncedFile()
                            {
                                LastModified = lastModified, Path = Path1
                            };
                            MainDbContext.DB.SyncedFiles.Add(past1);
                        }
                        else if (!lastModified.Equals(past1.LastModified))
                        {
                            past1.LastModified = lastModified;
                        }

                        if (past2 == null)
                        {
                            past2 = new SyncedFile()
                            {
                                LastModified = lastModified, Path = Path2
                            };
                            MainDbContext.DB.SyncedFiles.Add(past2);
                        }
                        else if (!lastModified.Equals(past2.LastModified))
                        {
                            past2.LastModified = lastModified;
                        }
                        Status = SyncItemStatus.ActionOK;
                    }
                    else if (Action == SyncActions.Delete1)
                    {
                        if (LongFile.Exists(Path1))
                        {
                            LongFile.Delete(Path1);
                        }
                        if (past1 != null)
                        {
                            MainDbContext.DB.SyncedFiles.Remove(past1);
                        }

                        if (past2 != null)
                        {
                            MainDbContext.DB.SyncedFiles.Remove(past2);
                        }
                        Status = SyncItemStatus.ActionOK;
                    }
                    else if (Action == SyncActions.Delete2)
                    {
                        if (LongFile.Exists(Path2))
                        {
                            LongFile.Delete(Path2);
                        }
                        if (past1 != null)
                        {
                            MainDbContext.DB.SyncedFiles.Remove(past1);
                        }

                        if (past2 != null)
                        {
                            MainDbContext.DB.SyncedFiles.Remove(past2);
                        }
                        Status = SyncItemStatus.ActionOK;
                    }
                    else if (Action == SyncActions.DeleteBoth)
                    {
                        if (LongFile.Exists(Path1))
                        {
                            LongFile.Delete(Path1);
                        }
                        if (LongFile.Exists(Path2))
                        {
                            LongFile.Delete(Path2);
                        }
                        if (past1 != null)
                        {
                            MainDbContext.DB.SyncedFiles.Remove(past1);
                        }
                        if (past2 != null)
                        {
                            MainDbContext.DB.SyncedFiles.Remove(past2);
                        }
                        Status = SyncItemStatus.ActionOK;
                    }
                }
                MainDbContext.DB.SaveChanges();
            }
            catch (Exception ex)
            {
                //TODO What to do when a copy/delete doesnt work?
            }
        }
Exemple #10
0
        private bool downloadfile(SyncFile file, string saveto, Func <Connection, SyncFile, long, int, DFile> func)
        {
            long left  = file.S;
            int  retry = 0;
            int  mb    = Global.DownloadBlockSizeMB * Global.MB;

            //Stopwatch sw = new Stopwatch();
            //sw.Start();
            while (left > 0)
            {
                long len   = left;
                long start = file.S - left;
                if (len > mb)
                {
                    len = mb;
                }
                //sw.Reset();
                DFile df = func(_conn, file, start, (int)len);
                //_connInfo.Mbs = (len / sw.ElapsedTicks) / (1000*TimeSpan.TicksPerSecond) ;
                if (df == null)
                {
                    retry++;
                    Thread.Sleep(new Random((int)FastDateTime.Now.Ticks).Next(2000) + 500);
                    if (retry > 10)
                    {
                        _log.Info(" null ");
                        _que.Enqueue(file);
                        //if (LongFile.Exists(saveto))
                        LongFile.Delete(saveto);
                        return(false);
                    }
                }
                else if (df.err == DownloadError.OK)
                {
                    retry = 0;
                    string ifn = saveto;
                    if (TorpedoSync.Global.isWindows == false)
                    {
                        ifn = saveto.Replace("\\", "/");
                    }
                    _log.Info("len = " + len + " , " + saveto.Replace(".!torpedosync", ""));
                    left -= len;
                    LongDirectory.CreateDirectory(LongDirectory.GetDirectoryName(ifn));
                    // save to disk
                    var fs = new FileStream(ifn, FileMode.OpenOrCreate);
                    fs.Seek(0L, SeekOrigin.End);
                    fs.Write(df.data, 0, df.data.Length);
                    fs.Close();
                    if (left == 0)
                    {
                        var fi = new LongFileInfo(saveto);
                        if (fi.Length != file.S)
                        {
                            // FEATURE : file length don't match
                            _log.Info("file length don't match.");
                            return(false);
                        }
                    }
                }
                else if (df.err == DownloadError.OLDER || df.err == DownloadError.LOCKED)
                {
                    _ErrorQue.Enqueue(file);
                    _connInfo.LastFileNameDownloaded = "";
                    _log.Info("Locked/Older : " + saveto);
                    return(false);
                }
                else if (df.err == DownloadError.NOTFOUND)
                {
                    _log.Info("Not Found : " + saveto);
                    _connInfo.LastFileNameDownloaded = "";
                    _ErrorQue.Enqueue(file);
                    LongFile.Delete(saveto);
                    return(false);
                }
            }
            return(true);
        }
Exemple #11
0
        private void DownloadAsZipFile()
        {
            SyncFile file = null;

            if (Global.BatchZip)
            {
                int             size    = 0;
                int             mb      = Global.BatchZipFilesUnderMB * Global.MB;
                List <SyncFile> ziplist = new List <SyncFile>();
                while (_que.Count > 10)
                {
                    if (_que.TryPeek(out file))
                    {
                        if (file.S + size < mb &&
                            file.S < Global.SmallFileSize) // small files
                        {
                            _que.TryDequeue(out file);
                            ziplist.Add(file);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                if (ziplist.Count > 0)
                {
                    try
                    {
                        _downloading = true;
                        var sf = ClientCommands.CreateZip(_conn, ziplist);
                        if (sf != null)
                        {
                            string path = _conn.Path + ".ts" + _S + "Temp" + _S;
                            LongDirectory.CreateDirectory(path);

                            if (downloadfile(sf, path + sf.F, ClientCommands.DownloadZip))
                            {
                                string zfn = path + sf.F;
                                string fn  = sf.F;

                                if (TorpedoSync.Global.isWindows == false)
                                {
                                    zfn = zfn.Replace("\\", "/");
                                }

                                var zf = ZipStorer.Open(zfn, FileAccess.Read);
                                foreach (var z in zf.ReadCentralDir())
                                {
                                    if (TorpedoSync.Global.isWindows)
                                    {
                                        fn = z.FilenameInZip.Replace("/", "\\");
                                    }
                                    else
                                    {
                                        fn = z.FilenameInZip;
                                    }

                                    MoveExistingFileToArchive(fn);
                                    LongDirectory.CreateDirectory(LongDirectory.GetDirectoryName(_conn.Path + fn));
                                    try
                                    {
                                        _log.Info("unzip : " + fn);
                                        //_log.Debug("unzip : " + fn);
                                        using (var fs = new FileStream(_conn.Path + fn, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                                        {
                                            _connInfo.LastFileNameDownloaded = fn;
                                            zf.ExtractFile(z, fs);
                                            fs.Close();
                                        }
                                        var dt = z.ModifyTime;
                                        if (z.Comment != "")
                                        {
                                            //_log.Info($"date {z.Comment}");
                                            if (DateTime.TryParse(z.Comment, out dt) == false)
                                            {
                                                dt = z.ModifyTime;
                                            }
                                        }
                                        var dtt = dt;
                                        if (TorpedoSync.Global.isWindows)
                                        {
                                            dtt = dt.ToUniversalTime();
                                        }
                                        LongFile.SetLastWriteTime(_conn.Path + fn, dtt);
                                    }
                                    catch (Exception ex) { _log.Error(ex); }
                                }
                                zf.Close();
                                ClientCommands.DeleteZip(_conn, sf);
                                _log.Info("Decompress zip done : " + sf.F);
                                LongFile.Delete(zfn);
                            }
                        }
                        _downloading = false;
                    }
                    catch (Exception ex) { _log.Error(ex); }
                }
            }
        }
Exemple #12
0
        internal void QueueDelta(Delta d)
        {
            string archivefolder = _conn.Path + ".ts" + _S + "old" + _S;

            Directory.CreateDirectory(archivefolder);
            if (d != null)
            {
                // empty old error queue
                _ErrorQue = new ConcurrentQueue <SyncFile>();

                d.FilesDeleted.ForEach(x =>
                {
                    try
                    {
                        if (LongFile.Exists(_conn.Path + x))
                        {
                            _log.Info("Deleting file : " + _conn.Path + x);
                            string fn = archivefolder + x;
                            LongFile.Move(_conn.Path + x, fn);
                        }
                    }
                    catch (Exception ex)
                    {
                        _log.Error(ex);
                    }
                });
                d.FoldersDeleted.ForEach(x =>
                {
                    _log.Info("Deleting folder : " + _conn.Path + x);
                    if (LongDirectory.Exists(_conn.Path + x))
                    {
                        try
                        {
                            LongDirectory.Move(_conn.Path + x, archivefolder + x);
                        }
                        catch { }
                        try
                        {
                            var f = LongDirectory.GetFiles(_conn.Path + x, "*.*", SearchOption.AllDirectories);
                            if (f.Length == 0)
                            {
                                LongDirectory.Delete(_conn.Path + x, true);
                            }
                        }
                        catch (Exception ex)
                        {
                            _log.Error(ex);
                        }
                    }
                });
                d.FilesAdded.ForEach(x =>
                {
                    _que.Enqueue(x);
                });
                d.FilesChanged.ForEach(x =>
                {
                    _que.Enqueue(x);
                });

                _log.Info("delfolders = " + d.FoldersDeleted.Count);
                _log.Info("delfiles = " + d.FilesDeleted.Count);
                _log.Info("files added = " + d.FilesAdded.Count);
                _log.Info("files changed = " + d.FilesChanged.Count);
                _log.Info("que count = " + _que.Count);

                SaveQueue();
            }
        }
Exemple #13
0
        public void Backup()
        {
            bool backupRequired = false;

            try
            {
                DateTime currentFileTimestamp = LongFile.GetLastWriteTime(Path).ToLocalTime();

                BackupFile backupFile = BackupDbContext.DB.BackupFiles
                                        .Where(f => f.Path == Path)
                                        .OrderByDescending(f => f.BackupTimestamp)
                                        .FirstOrDefault(f => true);

                if (backupFile == null)
                {
                    backupRequired = true;
                }
                else if (backupFile.LastModified.CompareTo(currentFileTimestamp) != 0)
                {
                    backupRequired = true;
                }
                else if (backupFile.Size != LongFile.GetFileSize(Path))
                {
                    backupRequired = true;
                }

                if (backupRequired)
                {
                    backupFile = new BackupFile
                    {
                        Path            = Path,
                        BackupFileType  = BackupFileType.File,
                        LastModified    = currentFileTimestamp,
                        Size            = LongFile.GetFileSize(Path),
                        BackupTimestamp = DateTime.Now,
                        BackupLocation  = GetBackupLocation(),
                        Parent          = LongFile.GetParent(Path),
                        Name            = LongFile.GetName(Path),
                    };
                    string destPath   = LongFile.Combine(BackupDbContext.Destination, LongFile.Combine("Files", backupFile.BackupLocation));
                    string destFolder = LongFile.GetParent(destPath);
                    if (!LongDirectory.Exists(destFolder))
                    {
                        LongDirectory.CreateDirectory(destFolder);
                    }
                    LongFile.Copy(Path, destPath, true);
                    LongFile.SetAttributes(destPath, LongFile.GetAttributes(destPath) & ~System.IO.FileAttributes.ReadOnly & ~System.IO.FileAttributes.Hidden);
                    BackupDbContext.DB.BackupFiles.Add(backupFile);
                    BackupDbContext.DB.SaveChanges();
                    if (FileBackupFinished != null)
                    {
                        FileBackupFinished(this, new FileEventArgs()
                        {
                            Path = Path, Cancelled = false, Success = true
                        });
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
Exemple #14
0
        public SyncActions GetAction()
        {
            if (ItemType == SyncItemType.File)
            {
                bool exists1 = LongFile.Exists(Path1);
                bool exists2 = LongFile.Exists(Path2);
                LastModified1 = exists1 ? LongFile.GetLastWriteTime(Path1) : DateTime.MinValue;
                LastModified2 = exists2 ? LongFile.GetLastWriteTime(Path2) : DateTime.MinValue;
                SyncedFile past1 = MainDbContext.DB.SyncedFiles.FirstOrDefault(f => f.Path == Path1);
                SyncedFile past2 = MainDbContext.DB.SyncedFiles.FirstOrDefault(f => f.Path == Path2);

                if (!exists1 && !exists2)
                {
                    return(SyncActions.None);
                }
                else if (exists1 && !exists2)
                {
                    if (past1 != null && past2 != null)
                    {
                        // File 2 has been deleted
                        Status = SyncItemStatus.ActionPending;
                        return(SyncActions.Delete1);
                    }
                    else
                    {
                        // File 1 is new
                        Status = SyncItemStatus.ActionPending;
                        return(SyncActions.CopyFrom1To2);
                    }
                }
                else if (!exists1 && exists2)
                {
                    if (past1 != null && past2 != null)
                    {
                        // File 1 has been deleted
                        Status = SyncItemStatus.ActionPending;
                        return(SyncActions.Delete2);
                    }
                    else
                    {
                        // File 2 is new
                        Status = SyncItemStatus.ActionPending;
                        return(SyncActions.CopyFrom2To1);
                    }
                }
                else if (exists1 && exists2)
                {
                    int  comp     = LastModified1.CompareTo(LastModified2);
                    int  newest   = comp > 0 ? 1 : comp < 0 ? 2 : 0;
                    bool changed1 = past1 == null || !LastModified1.Equals(past1.LastModified);
                    bool changed2 = past2 == null || !LastModified2.Equals(past2.LastModified);

                    if (changed1 && changed2)
                    {
                        if (newest == 1)
                        {
                            return(SyncActions.CopyFrom1To2);
                        }
                        if (newest == 2)
                        {
                            return(SyncActions.CopyFrom2To1);
                        }
                        return(SyncActions.None);
                    }
                    else if (changed1 && !changed2)
                    {
                        Status = SyncItemStatus.ActionPending;
                        return(SyncActions.CopyFrom1To2);
                    }
                    else if (!changed1 && changed2)
                    {
                        Status = SyncItemStatus.ActionPending;
                        return(SyncActions.CopyFrom2To1);
                    }
                    else if (!changed1 && !changed2)
                    {
                        return(SyncActions.None);
                    }
                }
            }
            else if (ItemType == SyncItemType.Folder)
            {
                bool       exists1 = LongDirectory.Exists(Path1);
                bool       exists2 = LongDirectory.Exists(Path2);
                SyncedFile past1   = MainDbContext.DB.SyncedFiles.FirstOrDefault(f => f.Path == Path1);
                SyncedFile past2   = MainDbContext.DB.SyncedFiles.FirstOrDefault(f => f.Path == Path2);

                if (!exists1 && !exists2)
                {
                    if (past1 != null || past2 != null)
                    {
                        return(SyncActions.None);
                    }
                    else
                    {
                        return(SyncActions.None);
                    }
                }
                else if (exists1 && exists2)
                {
                    return(SyncActions.None);
                }
                else if (exists1 && !exists2)
                {
                    if (past2 != null)
                    {
                        Status = SyncItemStatus.ActionPending;
                        return(SyncActions.Delete1);
                    }
                    else
                    {
                        Status = SyncItemStatus.ActionPending;
                        return(SyncActions.CopyFrom1To2);
                    }
                }
                else if (!exists1 && exists2)
                {
                    if (past1 != null)
                    {
                        Status = SyncItemStatus.ActionPending;
                        return(SyncActions.Delete2);
                    }
                    else
                    {
                        Status = SyncItemStatus.ActionPending;
                        return(SyncActions.CopyFrom2To1);
                    }
                }
            }
            return(SyncActions.None);
        }
Exemple #15
0
        public void Backup()
        {
            if (FolderBackupStarted != null)
            {
                FolderBackupStarted(this, new FolderEventArgs()
                {
                    Path = Path
                });
            }

            try
            {
                if (Excludes == null)
                {
                    Excludes = MainDbContext.DB.ExcludePaths.ToArray();
                }

                foreach (string filename in LongDirectory.GetFiles(Path).OrderBy(f => f))
                {
                    if (ExcludePath(filename))
                    {
                        continue;
                    }
                    FFile ffile = new FFile(filename);
                    ffile.Excludes            = Excludes;
                    ffile.FileBackupStarted  += FileBackupStarted;
                    ffile.FileBackupFinished += FileBackupFinished;

                    ffile.Backup();

                    if (BackgroundWorker != null && BackgroundWorker.CancellationPending)
                    {
                        return;
                    }
                }

                foreach (string folder in LongDirectory.GetDirectories(Path).OrderBy(f => f))
                {
                    if (ExcludePath(folder))
                    {
                        continue;
                    }

                    FFolder ffolder = new FFolder(folder);
                    ffolder.Excludes              = Excludes;
                    ffolder.BackgroundWorker      = BackgroundWorker;
                    ffolder.FolderBackupStarted  += new FolderBackupStartedHandler(FolderBackupStarted);
                    ffolder.FolderBackupFinished += new FFolder.FolderBackupFinishedHandler(FolderBackupFinished);
                    ffolder.FileBackupStarted    += new FFile.FileBackupStartedHandler(FileBackupStarted);
                    ffolder.FileBackupFinished   += new FFile.FileBackupFinishedHandler(FileBackupFinished);
                    ffolder.Backup();
                    if (BackgroundWorker != null && BackgroundWorker.CancellationPending)
                    {
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
            }

            if (FolderBackupFinished != null)
            {
                FolderBackupFinished(this, new FolderEventArgs()
                {
                    Path = Path, Success = true
                });
            }
        }
Exemple #16
0
        public void Copy(Parameters parameters)
        {
            if (!LongDirectory.Exists(DestPath))
            {
                LongDirectory.CreateDirectory(DestPath);
            }

            if (parameters.Verbose)
            {
                Console.Out.WriteLine("{0}", SourcePath);
            }
            string[] sourceFilePaths = LongDirectory.GetFiles(SourcePath);
            string[] destFilePaths   = LongDirectory.GetFiles(DestPath);

            foreach (string sourceFilePath in sourceFilePaths)
            {
                string copyFileComment = string.Empty;
                bool   copyFile        = false;
                string sourceFilename  = LongFile.GetName(sourceFilePath);
                string destFilePath    = LongFile.Combine(DestPath, sourceFilename);
                if (destFilePaths.FirstOrDefault(f => f.Equals(destFilePath, StringComparison.CurrentCultureIgnoreCase)) == null)
                {
                    copyFile        = true;
                    copyFileComment = "new   ";
                }
                else
                {
                    DateTime sourceModified = LongFile.GetLastWriteTime(sourceFilePath);
                    DateTime destModified   = LongFile.GetLastWriteTime(destFilePath);
                    int      modComp        = sourceModified.CompareTo(destModified);
                    if (modComp > 0)
                    {
                        copyFile        = true;
                        copyFileComment = "newer ";
                    }
                    else if (modComp < 0)
                    {
                        copyFile        = true;
                        copyFileComment = "older ";
                    }
                    else
                    {
                        copyFileComment = "same  ";
                    }
                }

                if (copyFile)
                {
                    if (parameters.Verbose)
                    {
                        Console.Out.WriteLine("     {0} : {1} ", copyFileComment, sourceFilename);
                    }
                    try
                    {
                        LongFile.Copy(sourceFilePath, destFilePath, true);
                    }
                    catch (Exception ex)
                    {
                        Console.Out.WriteLine("{0}", ex.Message);
                    }
                }
            }

            if (parameters.Recursive)
            {
                string[] sourceDirs = LongDirectory.GetDirectories(SourcePath);
                foreach (string sourceDir in sourceDirs)
                {
                    string sourceName = LongFile.GetName(sourceDir);
                    string destDir    = LongFile.Combine(DestPath, sourceName);
                    if (!LongDirectory.Exists(destDir))
                    {
                        LongDirectory.CreateDirectory(destDir);
                    }

                    PFolder pFolder = new PFolder(sourceDir, destDir);
                    pFolder.Copy(parameters);
                }
            }

            if (SourcePath == parameters.SourceDirectory)
            {
                if (parameters.RequireEnterToExit)
                {
                    Console.Out.WriteLine("Press enter to exit");
                    Console.In.ReadLine();
                }
            }
        }
Exemple #17
0
 private static void CreateDir(string filename)
 {
     LongDirectory.CreateDirectory(LongDirectory.GetDirectoryName(filename));
 }