Пример #1
0
        private IEnumerable <ControlFileItem> ListAllItems()
        {
            var originalHashes = new Dictionary <string, string>();

            Console.Write("generating md5 hashes...");
            foreach (var file in _folder.DirectoryInfo.EnumerateFiles("*", SearchOption.AllDirectories))
            {
                var fileHash = file.FullName.GetFileHash();
                originalHashes.Add(file.FullName + ".jar.zsync.jar", fileHash);
            }
            Console.WriteLine($"\b\b\b - {originalHashes.Count} files");
            GZipFiles();
            ZSyncMake();
            foreach (var file in _folder.DirectoryInfo.EnumerateFiles("*.jar.zsync", SearchOption.AllDirectories))
            {
                file.MoveTo(file.Directory.FullName.ToAbsoluteDirectoryPath().GetChildFileWithName(file.Name + ".jar").ToString());
            }
            return(_folder.DirectoryInfo.EnumerateFiles("*.zsync.jar", SearchOption.AllDirectories).Select(file =>
            {
                var substring = file.FullName.Substring(_folder.ToString().Length);
                var baseUri = new Uri(_url);
                var contentUrl = new Uri(baseUri, substring.Replace("\\", "/")
                                         .Replace(" ", "%20"));
                var relativeFilePath = file.FullName.ToAbsoluteFilePath().GetRelativePathFrom(_folder);
                var originalHash = originalHashes[file.FullName];
                return new ControlFileItem()
                {
                    RelativeContentUrl = baseUri.MakeRelativeUri(contentUrl),
                    InstallPath = relativeFilePath,
                    FileHash = originalHash
                };
            }));
        }
Пример #2
0
 public IAbsoluteDirectoryPath GetRepoPath(string repoDirectory, IAbsoluteDirectoryPath directory,
     bool local = false) {
     if (string.IsNullOrWhiteSpace(repoDirectory)) {
         repoDirectory = directory.GetChildDirectoryWithName(Repository.DefaultRepoRootDirectory).ToString();
         if (!Directory.Exists(repoDirectory)) {
             var dir = Tools.FileUtil.FindPathInParents(directory.ToString(), Repository.DefaultRepoRootDirectory);
             if (dir != null && Directory.Exists(dir))
                 repoDirectory = dir;
             else if (local)
                 repoDirectory = directory.ToString();
         }
     }
     return Legacy.SixSync.Repository.RepoTools.GetRootedPath(repoDirectory);
 }
Пример #3
0
 public void MoveDirectory(IAbsoluteDirectoryPath sourcePath, IAbsoluteDirectoryPath destinationPath)
 {
     if (IsSameRoot(sourcePath, destinationPath))
     {
         var tmp = destinationPath + GenericTools.TmpExtension;
         Directory.Move(sourcePath.ToString(), tmp);
         Directory.Move(tmp, destinationPath.ToString());
     }
     else
     {
         CopyDirectoryWithRetry(sourcePath, destinationPath, true);
         Directory.Delete(sourcePath.ToString(), true);
     }
 }
Пример #4
0
        public Repository OpenRepositoryWithRetry(IAbsoluteDirectoryPath path, bool createWhenNotExisting = false,
            Action failAction = null) {
            if (createWhenNotExisting && !path.Exists)
                return new Repository(path, createWhenNotExisting);

            using (var autoResetEvent = new AutoResetEvent(false))
            using (var fileSystemWatcher =
                new FileSystemWatcher(path.ToString(), "*.lock") {
                    EnableRaisingEvents = true
                }) {
                var lockFile = path.GetChildFileWithName(Repository.LockFile);
                var fp = Path.GetFullPath(lockFile.ToString());
                fileSystemWatcher.Deleted +=
                    (o, e) => {
                        if (Path.GetFullPath(e.FullPath) == fp)
                            autoResetEvent.Set();
                    };

                while (true) {
                    using (var timer = UnlockTimer(lockFile, autoResetEvent)) {
                        try {
                            return new Repository(path, createWhenNotExisting);
                        } catch (RepositoryLockException) {
                            if (failAction != null)
                                failAction();
                            timer.Start();
                            autoResetEvent.WaitOne();
                            lock (timer)
                                timer.Stop();
                            autoResetEvent.Reset();
                        }
                    }
                }
            }
        }
Пример #5
0
        bool WriteClientSideConfig(IAbsoluteDirectoryPath path)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }

            var acePath = Path.Combine(path.ToString(), @"userconfig\ace");
            var file    = Path.Combine(acePath, "ace_clientside_config.hpp");

            if (!Directory.Exists(acePath))
            {
                if (!TryCreatePath(acePath))
                {
                    return(false);
                }
            }

            var file2 = Path.Combine(acePath, "ace_serverconfig.hpp");

            if (!File.Exists(file2))
            {
                TryWriteNewConfig(file2);
            }

            return(TryWriteConfig(file));
        }
Пример #6
0
        public Repository Init(IAbsoluteDirectoryPath directory, RepositoryOperationMode?mode = null)
        {
            if (directory == null)
            {
                throw new ArgumentNullException(nameof(directory));
            }

            if (File.Exists(directory.ToString()))
            {
                throw new SynqPathException("Already exists file with same name");
            }

            ConfirmEmpty(directory);

            directory.MakeSurePathExists();
            var repo = new Repository(directory, true);

            try {
                if (mode != null)
                {
                    repo.Config.OperationMode = mode.Value;
                }
                repo.Save();
            } catch {
                repo.Dispose();
                throw;
            }
            return(repo);
        }
        // TODO: Progress reporting
        protected override async Task <IAbsoluteFilePath> DownloadFileImpl(Uri url, IAbsoluteDirectoryPath destination,
                                                                           Action <long?, double> progressAction, CancellationToken token)
        {
            var  lastTime  = DateTime.UtcNow;
            uint lastBytes = 0;

            State.Clear();
            using (Observable.Interval(TimeSpan.FromMilliseconds(500)).Select(x => State.Current).Where(x => x != null)
                   .Where(x => x.Item2 > 0)
                   .Do(x => {
                long?speed = null;
                if (lastBytes != 0)
                {
                    var timeSpan = DateTime.UtcNow - lastTime;
                    if (timeSpan.TotalMilliseconds > 0)
                    {
                        var bytesChange = x.Item1 - lastBytes;
                        speed = (long)(bytesChange / (timeSpan.TotalMilliseconds / 1000.0));
                    }
                }
                progressAction(speed, x.Item1 / (double)x.Item2 * 100);
                lastTime = DateTime.UtcNow;
                lastBytes = x.Item1;
            }).Subscribe())
                return(await _api.DownloadFile(url, destination.ToString(), token).ConfigureAwait(false));
        }
            internal static bool TryGetRelativePath(IAbsoluteDirectoryPath pathFrom, IAbsolutePath pathTo, out string relativePath, out string failureMessage)
            {
                //Argument.IsNotNull(nameof(pathFrom), pathFrom);
                //Argument.IsNotNull(nameof(pathTo), pathTo);

                if (!pathFrom.OnSameVolumeThan(pathTo))
                {
                    failureMessage = @"Cannot compute relative path from 2 paths that are not on the same volume 
   PathFrom = """ + pathFrom + @"""
   PathTo   = """ + pathTo + @"""";

                    relativePath = null;

                    return(false);
                }

                // Only work with Directory
                if (pathTo.IsFilePath)
                {
                    pathTo = pathTo.ParentDirectoryPath;
                }

                relativePath   = GetPathRelativeTo(pathFrom.ToString(), pathTo.ToString());
                failureMessage = null;

                return(true);
            }
Пример #9
0
        public Package Open(Repository repo, IAbsoluteDirectoryPath directory, string packageName = null)
        {
            if (repo == null)
            {
                throw new ArgumentNullException(nameof(repo));
            }
            if (directory == null)
            {
                throw new ArgumentNullException(nameof(directory));
            }

            if (string.IsNullOrWhiteSpace(packageName))
            {
                packageName = PackifyPath(directory.ToString());
            }

            var match = BaseVersion.RxPackageName.Match(packageName);

            if (!match.Success)
            {
                var packDi  = repo.PackagesPath.DirectoryInfo;
                var package = packDi.EnumerateFiles(packageName + "-*.json").LastOrDefault();
                if (package == null)
                {
                    throw new PackageNotFoundException("No package found that matches " + packageName);
                }
                packageName = Path.GetFileNameWithoutExtension(package.FullName);
            }

            return(new Package(directory, packageName, repo));
        }
Пример #10
0
        static IAbsoluteFilePath[] CheckForDlls(IAbsoluteDirectoryPath path)
        {
            var fileEntries = Directory.EnumerateFiles(path.ToString(), "*.dll",
                                                       SearchOption.AllDirectories);

            return(fileEntries.Where(file => file.EndsWith(".dll")).Select(x => x.ToAbsoluteFilePath()).ToArray());
        }
Пример #11
0
        static DriveInfo GetDrive(IAbsoluteDirectoryPath path)
        {
            var lower = path.ToString().ToLower();

            return(DriveInfo.GetDrives()
                   .Single(d => lower.StartsWith(d.Name.ToLower())));
        }
Пример #12
0
        static bool InstallDll(IAbsoluteFilePath pluginPath, IAbsoluteDirectoryPath gamePluginFolder,
                               bool force = true)
        {
            if (gamePluginFolder == null)
            {
                throw new ArgumentNullException(nameof(gamePluginFolder));
            }
            if (pluginPath == null)
            {
                throw new ArgumentNullException(nameof(pluginPath));
            }

            if (!pluginPath.IsNotNullAndExists())
            {
                throw new PathDoesntExistException(pluginPath.ToString());
            }

            if (!gamePluginFolder.IsNotNullAndExists())
            {
                throw new PathDoesntExistException(gamePluginFolder.ToString());
            }

            var fullPath = gamePluginFolder.GetChildFileWithName(pluginPath.FileName);

            if (!force && fullPath.Exists)
            {
                return(false);
            }

            return(TryCopyDll(pluginPath, fullPath));
        }
Пример #13
0
        static bool InstallDll(IAbsoluteFilePath fi, IAbsoluteDirectoryPath destination, string subPath = null,
                               bool force = true)
        {
            if (destination == null)
            {
                throw new ArgumentNullException(nameof(destination));
            }

            if (!destination.Exists)
            {
                throw new PathDoesntExistException(destination.ToString());
            }
            if (subPath != null)
            {
                destination = destination.GetChildDirectoryWithName(subPath);
            }
            var fullPath = destination.GetChildFileWithName(fi.FileName);

            if (!force && fullPath.Exists)
            {
                return(false);
            }

            return(TryCopyDll(fi, fullPath));
        }
Пример #14
0
        Repository TryGetRepository(IAbsoluteDirectoryPath folder, SyncOptions opts,
                                    IAbsoluteDirectoryPath rsyncFolder)
        {
            try {
                var repo = GetRepository(folder, opts);

                if (opts.MaxThreads.HasValue)
                {
                    repo.MultiThreadingSettings.MaxThreads = opts.MaxThreads.Value;
                }

                if (opts.RequiredVersion.HasValue)
                {
                    repo.RequiredVersion = opts.RequiredVersion;
                }

                if (opts.RequiredGuid != null)
                {
                    repo.RequiredGuid = opts.RequiredGuid;
                }

                if (opts.Output != null)
                {
                    repo.Output = opts.Output;
                }

                repo.LoadHosts();
                return(repo);
            } catch (Exception) {
                Tools.FileUtil.Ops.DeleteWithRetry(rsyncFolder.ToString());
                throw;
            }
        }
Пример #15
0
        public Package Init(Repository repo, IAbsoluteDirectoryPath directory, PackageMetaData initialMetaData = null)
        {
            if (directory == null)
            {
                throw new ArgumentNullException(nameof(directory));
            }

            if (initialMetaData == null)
            {
                initialMetaData = new PackageMetaData(PackifyPath(directory.ToString()));
            }

            if (string.IsNullOrWhiteSpace(initialMetaData.Name))
            {
                throw new Exception("Initial metadata lacks Package Name");
            }

            if (initialMetaData.Version == null)
            {
                throw new Exception("Initial metadata lacks Version");
            }

            var depName = initialMetaData.GetFullName();

            if (repo.HasPackage(depName))
            {
                throw new Exception("Package and version already exists: " + depName);
            }

            return(new Package(directory, initialMetaData, repo));
        }
            internal static bool TryGetAbsolutePathFrom(IAbsoluteDirectoryPath pathFrom, IPath pathTo, out string pathResult, out string failureReason)
            {
                Debug.Assert(pathFrom != null);
                Debug.Assert(pathTo != null);
                Debug.Assert(pathTo.IsRelativePath);

                if (pathFrom.Kind == AbsolutePathKind.DriveLetter)
                {
                    // Only work with Directory
                    if (pathTo.IsFilePath)
                    {
                        pathTo = pathTo.ParentDirectoryPath;
                    }
                    return(TryGetAbsolutePath(pathFrom.ToString(), pathTo.ToString(), out pathResult, out failureReason));
                }


                //
                // Special case when a relative path is asked from a UNC path like ".." from "\\Server\Share".
                // In such case we cannot return "\\Server" that is not a valis UNC path
                // To address this we create a temporary drive letter absolute path and do the TryGetAbsolutePathFrom() on it!
                //
                Debug.Assert(pathFrom.Kind == AbsolutePathKind.UNC);
                var    pathFromString = pathFrom.ToString();
                string uncServerShareStart;
                var    fakePathFromString = UNCPathHelper.TranformUNCIntoDriveLetter(pathFromString, out uncServerShareStart);

                Debug.Assert(fakePathFromString.IsValidAbsoluteDirectoryPath());
                var fakePathFrom = fakePathFromString.ToAbsoluteDirectoryPath();

                // Call me, but this time with a DriveLetter path (no risk of infinite recursion!)
                string pathResultDriveLetter;

                if (!TryGetAbsolutePathFrom(fakePathFrom, pathTo, out pathResultDriveLetter, out failureReason))
                {
                    failureReason = failureReason.Replace(UNCPathHelper.FAKE_DRIVE_LETTER_PREFIX, uncServerShareStart);
                    pathResult    = null;
                    return(false);
                }

                Debug.Assert(pathResultDriveLetter != null);
                Debug.Assert(pathResultDriveLetter.Length > 0);
                Debug.Assert(pathResultDriveLetter.StartsWith(UNCPathHelper.FAKE_DRIVE_LETTER_PREFIX));
                pathResult = UNCPathHelper.TranformDriveLetterIntoUNC(pathResultDriveLetter, uncServerShareStart);

                return(true);
            }
Пример #17
0
        static DlcEdition GetDlcType(IAbsoluteDirectoryPath dlcPath)
        {
            var file = Path.Combine(dlcPath.ToString(), "addons", "france_data.ifa").ToAbsoluteFilePath();

            return(ConfirmChecksum(file, OfficialGameInfo.DigitalDlcSha)
                ? DlcEdition.Digitial
                : DlcEdition.Steam);
        }
         //
         //  Relative/absolute computation
         //

         internal static bool TryGetRelativePath(IAbsoluteDirectoryPath pathFrom, IAbsolutePath pathTo, out string pathResult, out string failurereason) {
            Debug.Assert(pathFrom != null);
            Debug.Assert(pathTo != null);

            if (!pathFrom.OnSameVolumeThan(pathTo)) {
               failurereason = @"Cannot compute relative path from 2 paths that are not on the same volume 
   PathFrom = """ + pathFrom.ToString() + @"""
   PathTo   = """ + pathTo.ToString() + @"""";
               pathResult = null;
               return false;
            }
            // Only work with Directory 
            if (pathTo.IsFilePath) { pathTo = pathTo.ParentDirectoryPath; }
            pathResult = GetPathRelativeTo(pathFrom.ToString(), pathTo.ToString());
            failurereason = null;
            return true;
         }
Пример #19
0
 void SignFolderNotRecursively(IAbsoluteDirectoryPath folder, IAbsoluteFilePath privateFile,
                               bool repackOnFailure = false)
 {
     foreach (var f in Directory.EnumerateFiles(folder.ToString(), "*.pbo"))
     {
         SignFile(f.ToAbsoluteFilePath(), privateFile, repackOnFailure);
     }
 }
 static void MigrateServerModFolder(IAbsoluteDirectoryPath modFolder, IAbsoluteDirectoryPath modPath) {
     var folderName = modFolder.DirectoryName;
     var destination = modPath.GetChildDirectoryWithName(folderName);
     if (!destination.Exists)
         Tools.FileUtil.Ops.MoveDirectory(modFolder, destination);
     else
         Directory.Delete(modFolder.ToString(), true);
 }
Пример #21
0
 void SignFolderRecursively(IAbsoluteDirectoryPath folder, IAbsoluteFilePath privateFile,
                            bool repackOnFailure = false)
 {
     foreach (var f in Directory.EnumerateFiles(folder.ToString(), "*.pbo", SearchOption.AllDirectories))
     {
         _biSigner.SignFile(f.ToAbsoluteFilePath(), privateFile, repackOnFailure);
     }
 }
Пример #22
0
                public void MoveDirectoryWithUpdaterFallbackAndRetry(IAbsoluteDirectoryPath source,
                                                                     IAbsoluteDirectoryPath destination)
                {
                    AddIORetryDialog(() => {
                        if (IsSameRoot(source, destination))
                        {
                            try {
                                var tmp = destination + GenericTools.TmpExtension;
                                Directory.Move(source.ToString(), tmp);
                                Directory.Move(tmp, destination.ToString());
                            } catch (UnauthorizedAccessException ex) {
                                this.Logger()
                                .FormattedWarnException(ex,
                                                        "Exception during move directory, trying through updater if not elevated");
                                if (!UacHelper.CheckUac())
                                {
                                    throw;
                                }
                                MoveDirectoryWithUpdater(source, destination);
                            }
                        }
                        else
                        {
                            var doneCopy = false;
                            try {
                                CopyDirectoryWithRetry(source, destination, true);
                                doneCopy = true;
                            } catch (UnauthorizedAccessException ex) {
                                this.Logger()
                                .FormattedWarnException(ex,
                                                        "Exception during move directory, trying through updater if not elevated");
                                if (!UacHelper.CheckUac())
                                {
                                    throw;
                                }
                                MoveDirectoryWithUpdater(source, destination);
                            }

                            if (doneCopy)
                            {
                                DeleteWithUpdaterFallbackAndRetry(source.ToString());
                            }
                        }
                    }, source.ToString(), destination.ToString());
                }
Пример #23
0
 static IDictionary <FileFetchInfo, ITransferStatus> SumMissions(
     IAbsoluteDirectoryPath destination,
     Dictionary <Mission, ITransferStatus> missionsDictionary) => missionsDictionary.Where(m => {
     m.Value.Action = RepoStatus.Summing;
     var filePath   = Path.Combine(destination.ToString(), m.Key.FileName).ToAbsoluteFilePath();
     return(!filePath.Exists || Tools.HashEncryption.MD5FileHash(filePath) != m.Key.Md5);
 })
 .ToDictionary(x => new FileFetchInfo(x.Key.FileName),
               x => x.Value);
Пример #24
0
            public void HandleDowncaseFolder(IAbsoluteDirectoryPath entry, IReadOnlyCollection <string> excludes = null)
            {
                if (excludes == null)
                {
                    excludes = new List <string>();
                }

                foreach (var file in Directory.EnumerateFiles(entry.ToString(), "*.*", SearchOption.TopDirectoryOnly)
                         .Concat(Directory.EnumerateDirectories(entry.ToString(), "*.*",
                                                                SearchOption.TopDirectoryOnly)))
                {
                    if (excludes.Any(x => x == Path.GetFileName(file)))
                    {
                        continue;
                    }
                    HandleDowncase(file, excludes);
                }
            }
Пример #25
0
        static IAbsoluteFilePath GetLatestSettingsPath(IAbsoluteDirectoryPath pwsPath)
        {
            var versions =
                GetParsedVersions(Directory.EnumerateFiles(pwsPath.ToString(), "settings-*.xml"));

            var compatibleVersion = versions.FirstOrDefault();

            return(compatibleVersion == null ? null : GetVersionedSettingsPath(compatibleVersion, pwsPath));
        }
            public virtual void UnpackUpdater(IAbsoluteFilePath sourceFile, IAbsoluteDirectoryPath outputFolder,
                bool overwrite = false, bool fullPath = true) {
                Contract.Requires<ArgumentNullException>(sourceFile != null);
                Contract.Requires<ArgumentNullException>(outputFolder != null);

                Generic.RunUpdater(UpdaterCommands.Unpack, sourceFile.ToString(), outputFolder.ToString(),
                    overwrite ? "--overwrite" : null,
                    fullPath.ToString());
            }
Пример #27
0
        public void MoveModFolders(IAbsoluteDirectoryPath oldModsPath, IAbsoluteDirectoryPath newModsPath) {
            newModsPath.MakeSurePathExists();

            foreach (var dir in Directory.EnumerateDirectories(oldModsPath.ToString())
                .Where(x => !excludeFolders.Contains(Path.GetFileName(x).ToLower()))
                .Where(x => File.Exists(Path.Combine(x, Package.SynqInfoFile)) ||
                            Directory.Exists(Path.Combine(x, Repository.RepoFolderName))))
                TryMoveDir(dir.ToAbsoluteDirectoryPath(), newModsPath);
        }
            internal static bool TryGetAbsolutePathFrom(IAbsoluteDirectoryPath pathFrom, IPath pathTo, out string result, out string failureMessage)
            {
                //Argument.IsNotNull(nameof(pathFrom), pathFrom);
                //Argument.IsNotNull(nameof(pathTo), pathTo);
                //Debug.Assert(pathTo.IsRelativePath);

                if (pathFrom.Kind == AbsolutePathKind.DriveLetter)
                {
                    // Only work with Directory
                    if (pathTo.IsFilePath)
                    {
                        pathTo = pathTo.ParentDirectoryPath;
                    }

                    return(TryGetAbsolutePath(pathFrom.ToString(), pathTo.ToString(), out result, out failureMessage));
                }

                //Debug.Assert(pathFrom.Kind == AbsolutePathKind.UNC);

                string uncServerShareStart;
                string pathResultDriveLetter;

                var pathFromString     = pathFrom.ToString();
                var fakePathFromString = UNCPathHelper.TranformUNCIntoDriveLetter(pathFromString, out uncServerShareStart);
                var fakePathFrom       = fakePathFromString.ToAbsoluteDirectoryPath();

                //Debug.Assert(fakePathFromString.IsValidAbsoluteDirectoryPath());

                if (!TryGetAbsolutePathFrom(fakePathFrom, pathTo, out pathResultDriveLetter, out failureMessage))
                {
                    failureMessage = failureMessage.Replace(UNCPathHelper.FakeDriveLetterPrefix, uncServerShareStart);
                    result         = null;

                    return(false);
                }

                //Debug.Assert(pathResultDriveLetter != null);
                //Debug.Assert(pathResultDriveLetter.Length > 0);
                //Debug.Assert(pathResultDriveLetter.StartsWith(UNCPathHelper.FAKE_DRIVE_LETTER_PREFIX));

                result = UNCPathHelper.TranformDriveLetterIntoUNC(pathResultDriveLetter, uncServerShareStart);

                return(true);
            }
        void TryUserconfigUpdate(string path, IAbsoluteDirectoryPath gamePath, IAbsoluteDirectoryPath uconfig,
            IAbsoluteDirectoryPath uconfigPath) {
            if (!ConfirmUserconfigIsNotFile(uconfig.ToString()))
                return;

            if (Directory.Exists(path))
                TryUserconfigDirectory(path.ToAbsoluteDirectoryPath(), uconfigPath);
            else if (File.Exists(path))
                TryUserconfigUnpack(path.ToAbsoluteFilePath(), gamePath);
        }
Пример #30
0
 public void CreateDirectoryAndSetACL(IAbsoluteDirectoryPath location, string user = null,
                                      FileSystemRights rights = FileSystemRights.FullControl)
 {
     if (user == null)
     {
         user = GetCurrentUserSDDL();
     }
     location.ToString().MakeSurePathExists();
     SetACLHandleInvalidOperation(location, user, rights);
 }
        void TryUserconfigClean(string path, IAbsoluteDirectoryPath gamePath, IAbsoluteDirectoryPath uconfig,
            IAbsoluteDirectoryPath uconfigPath) {
            if (!ConfirmUserconfigIsNotFile(uconfig.ToString()))
                return;

            if (Directory.Exists(path))
                TryUserconfigDirectoryOverwrite(path.ToAbsoluteDirectoryPath(), uconfigPath);
            else
                TryUserconfigUnpackOverwrite(path.ToAbsoluteFilePath(), gamePath);
        }
Пример #32
0
 private void CreateZsyncFiles(IAbsoluteDirectoryPath rootDirectory)
 {
     foreach (var path in Directory.EnumerateFiles(rootDirectory.ToString(), "*.*", SearchOption.AllDirectories)
              .Where(x => !x.EndsWith(".zsync", StringComparison.CurrentCultureIgnoreCase))
              .Select(x => x.ToAbsoluteFilePath())
              .Where(x => !ExcludeFileNames.Contains(x.FileName)))
     {
         CreateZsyncFile(path);
     }
 }
Пример #33
0
        public void RunExtractPboWithParameters(IAbsoluteFilePath input, IAbsoluteDirectoryPath output,
            params string[] parameters) {
            if (!input.Exists)
                throw new IOException("File doesn't exist: " + input);
            var startInfo =
                new ProcessStartInfoBuilder(_extractPboBin,
                    BuildParameters(input.ToString(), output.ToString(), parameters)).Build();

            ProcessExitResult(_processManager.LaunchAndGrabTool(startInfo));
        }
Пример #34
0
        public ArchiveContent CreateFromExisting(IAbsoluteDirectoryPath destination, IAbsoluteFilePath file,
                                                 IFileDownloader downloader)
        {
            var name = GetName(file.ToString());

            var ac = new ArchiveContent(name, destination.ToString(), downloader);

            ac.ImportFromArchive(file);
            return(ac);
        }
Пример #35
0
        private async Task InstallNew(GroupContent mod, IAuthProvider provider, Action <SyncOptions> config,
                                      IAbsoluteDirectoryPath folder)
        {
            SetupHosts(mod, provider);
            var opts = new SyncOptions();

            config(opts);
            await
            Repository.Factory.Clone(opts.Hosts, folder.ToString(), config)
            .ConfigureAwait(false);
        }
Пример #36
0
        public static string GetRelativeDirectory(this IAbsoluteDirectoryPath path,
                                                  IAbsoluteDirectoryPath possibleRoot)
        {
            if (path.Equals(possibleRoot) || !path.CanGetRelativePathFrom(possibleRoot) ||
                !path.IsRootedIn(possibleRoot))
            {
                return(path.ToString());
            }

            return(path.GetRelativePathFrom(possibleRoot).Join());
        }
Пример #37
0
 static void UnpackArchive(IAbsoluteFilePath sourceFile, IAbsoluteDirectoryPath outputFolder, bool overwrite,
     bool checkFileIntegrity,
     SevenZipExtractor extracter) {
     if (checkFileIntegrity && !extracter.Check())
         throw new Exception(String.Format("Appears to be an invalid archive: {0}", sourceFile));
     outputFolder.MakeSurePathExists();
     extracter.ExtractFiles(outputFolder.ToString(), overwrite
         ? extracter.ArchiveFileNames.ToArray()
         : extracter.ArchiveFileNames.Where(x => !outputFolder.GetChildFileWithName(x).Exists)
             .ToArray());
 }
Пример #38
0
            public long GetDirectorySize(IAbsoluteDirectoryPath p, string filter = null, string selector = "*.*",
                                         bool recurse = true)
            {
                var sum =
                    Directory.EnumerateFiles(p.ToString(), selector,
                                             recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)
                    .Select(name => new FileInfo(name).Length)
                    .Sum();

                if (filter != null)
                {
                    sum = sum -
                          Directory.EnumerateFiles(p.ToString(), filter,
                                                   recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)
                          .Select(name => new FileInfo(name).Length)
                          .Sum();
                }

                return(sum);
            }
Пример #39
0
        async Task PerformMoveModAndSynq(IAbsoluteDirectoryPath oldModsPath, IAbsoluteDirectoryPath newModPath,
                                         IAbsoluteDirectoryPath oldSynqPath, IAbsoluteDirectoryPath newSynqPath, ISupportModding game)
        {
            await _updateManager.MoveModFoldersIfValidAndExists(oldModsPath, newModPath).ConfigureAwait(false);

            if (oldSynqPath != null && newSynqPath != null &&
                !Tools.FileUtil.ComparePathsOsCaseSensitive(oldSynqPath.ToString(), newSynqPath.ToString()))
            {
                game.Controller.BundleManager.Repo.Dispose(); // Unlock
                await _updateManager.MovePathIfValidAndExists(oldSynqPath, newSynqPath);
            }
        }
Пример #40
0
 public IAbsoluteDirectoryPath GetRepoPath(string repoDirectory, IAbsoluteDirectoryPath directory,
                                           bool local = false)
 {
     if (string.IsNullOrWhiteSpace(repoDirectory))
     {
         repoDirectory = directory.GetChildDirectoryWithName(Repository.DefaultRepoRootDirectory).ToString();
         if (!Directory.Exists(repoDirectory))
         {
             var dir = Tools.FileUtil.FindPathInParents(directory.ToString(), Repository.DefaultRepoRootDirectory);
             if ((dir != null) && Directory.Exists(dir))
             {
                 repoDirectory = dir;
             }
             else if (local)
             {
                 repoDirectory = directory.ToString();
             }
         }
     }
     return(Legacy.SixSync.Repository.RepoTools.GetRootedPath(repoDirectory));
 }
Пример #41
0
        public Repository Init(IAbsoluteDirectoryPath folder, IReadOnlyCollection<Uri> hosts,
            Dictionary<string, object> opts = null) {
            Contract.Requires<ArgumentNullException>(folder != null);
            Contract.Requires<ArgumentNullException>(hosts != null);

            if (opts == null)
                opts = new Dictionary<string, object>();

            var rsyncFolder = folder.GetChildDirectoryWithName(Repository.RepoFolderName);
            if (rsyncFolder.Exists)
                throw new Exception("Already appears to be a repository");

            var packFolder = Path.Combine(opts.ContainsKey("pack_path")
                ? ((string) opts["pack_path"])
                : rsyncFolder.ToString(),
                Repository.PackFolderName).ToAbsoluteDirectoryPath();

            var configFile = rsyncFolder.GetChildFileWithName(Repository.ConfigFileName);
            var wdVersionFile = rsyncFolder.GetChildFileWithName(Repository.VersionFileName);
            var packVersionFile = packFolder.GetChildFileWithName(Repository.VersionFileName);

            this.Logger().Info("Initializing {0}", folder);
            rsyncFolder.MakeSurePathExists();
            packFolder.MakeSurePathExists();

            var config = new RepoConfig {Hosts = hosts.ToArray()};

            if (opts.ContainsKey("pack_path"))
                config.PackPath = (string) opts["pack_path"];

            if (opts.ContainsKey("include"))
                config.Include = (string[]) opts["include"];

            if (opts.ContainsKey("exclude"))
                config.Exclude = (string[]) opts["exclude"];

            var guid = opts.ContainsKey("required_guid")
                ? (string) opts["required_guid"]
                : Guid.NewGuid().ToString();

            var packVersion = new RepoVersion {Guid = guid};
            if (opts.ContainsKey("archive_format"))
                packVersion.ArchiveFormat = (string) opts["archive_format"];

            var wdVersion = YamlExtensions.NewFromYaml<RepoVersion>(packVersion.ToYaml());

            config.SaveYaml(configFile);
            packVersion.SaveYaml(packVersionFile);
            wdVersion.SaveYaml(wdVersionFile);

            return TryGetRepository(folder.ToString(), opts, rsyncFolder.ToString());
        }
         internal static bool TryGetAbsolutePathFrom(IAbsoluteDirectoryPath pathFrom, IPath pathTo, out string pathResult, out string failureReason) {
            Debug.Assert(pathFrom != null);
            Debug.Assert(pathTo != null);
            Debug.Assert(pathTo.IsRelativePath);
           
            if (pathFrom.Kind == AbsolutePathKind.DriveLetter) {
               // Only work with Directory 
               if (pathTo.IsFilePath) { pathTo = pathTo.ParentDirectoryPath; }
               return TryGetAbsolutePath(pathFrom.ToString(), pathTo.ToString(), out pathResult, out failureReason);
            }


            //
            // Special case when a relative path is asked from a UNC path like ".." from "\\Server\Share".
            // In such case we cannot return "\\Server" that is not a valis UNC path
            // To address this we create a temporary drive letter absolute path and do the TryGetAbsolutePathFrom() on it!
            //
            Debug.Assert(pathFrom.Kind == AbsolutePathKind.UNC);
            var pathFromString = pathFrom.ToString();
            string uncServerShareStart;
            var fakePathFromString = UNCPathHelper.TranformUNCIntoDriveLetter(pathFromString, out uncServerShareStart);
            Debug.Assert(fakePathFromString.IsValidAbsoluteDirectoryPath());
            var fakePathFrom = fakePathFromString.ToAbsoluteDirectoryPath();

            // Call me, but this time with a DriveLetter path (no risk of infinite recursion!)
            string pathResultDriveLetter;
            if (!TryGetAbsolutePathFrom(fakePathFrom, pathTo, out pathResultDriveLetter, out failureReason)) {
               failureReason = failureReason.Replace(UNCPathHelper.FAKE_DRIVE_LETTER_PREFIX, uncServerShareStart);
               pathResult = null;
               return false;
            }

            Debug.Assert(pathResultDriveLetter != null);
            Debug.Assert(pathResultDriveLetter.Length > 0);
            Debug.Assert(pathResultDriveLetter.StartsWith(UNCPathHelper.FAKE_DRIVE_LETTER_PREFIX));
            pathResult = UNCPathHelper.TranformDriveLetterIntoUNC(pathResultDriveLetter, uncServerShareStart);

            return true;
         }
Пример #43
0
        public Repository Init(IAbsoluteDirectoryPath directory, RepositoryOperationMode? mode = null) {
            Contract.Requires<ArgumentNullException>(directory != null);

            if (File.Exists(directory.ToString()))
                throw new SynqPathException("Already exists file with same name");

            ConfirmEmpty(directory);

            directory.MakeSurePathExists();
            var repo = new Repository(directory, true);
            if (mode != null)
                repo.Config.OperationMode = mode.Value;
            repo.Save();
            return repo;
        }
        static bool InstallDll(IAbsoluteFilePath pluginPath, IAbsoluteDirectoryPath gamePluginFolder,
            bool force = true) {
            Contract.Requires<ArgumentNullException>(gamePluginFolder != null);
            Contract.Requires<ArgumentNullException>(pluginPath != null);

            if (!pluginPath.IsNotNullAndExists())
                throw new PathDoesntExistException(pluginPath.ToString());

            if (!gamePluginFolder.IsNotNullAndExists())
                throw new PathDoesntExistException(gamePluginFolder.ToString());

            var fullPath = gamePluginFolder.GetChildFileWithName(pluginPath.FileName);

            if (!force && fullPath.Exists)
                return false;

            return TryCopyDll(pluginPath, fullPath);
        }
Пример #45
0
        public Package Init(Repository repo, IAbsoluteDirectoryPath directory, PackageMetaData initialMetaData = null) {
            Contract.Requires<ArgumentNullException>(directory != null);

            if (initialMetaData == null)
                initialMetaData = new PackageMetaData(PackifyPath(directory.ToString()));

            if (string.IsNullOrWhiteSpace(initialMetaData.Name))
                throw new Exception("Initial metadata lacks Package Name");

            if (initialMetaData.Version == null)
                throw new Exception("Initial metadata lacks Version");

            var depName = initialMetaData.GetFullName();
            if (repo.HasPackage(depName))
                throw new Exception("Package and version already exists: " + depName);

            return new Package(directory, initialMetaData, repo);
        }
 // TODO: Progress reporting
 protected override async Task<IAbsoluteFilePath> DownloadFileImpl(Uri url, IAbsoluteDirectoryPath destination,
     Action<long?, double> progressAction, CancellationToken token) {
     var lastTime = DateTime.UtcNow;
     uint lastBytes = 0;
     State.Clear();
     using (Observable.Interval(TimeSpan.FromMilliseconds(500)).Select(x => State.Current).Where(x => x != null)
         .Where(x => x.Item2 > 0)
         .Do(x => {
             long? speed = null;
             if (lastBytes != 0) {
                 var timeSpan = DateTime.UtcNow - lastTime;
                 if (timeSpan.TotalMilliseconds > 0) {
                     var bytesChange = x.Item1 - lastBytes;
                     speed = (long) (bytesChange/(timeSpan.TotalMilliseconds/1000.0));
                 }
             }
             progressAction(speed, x.Item1/(double) x.Item2*100);
             lastTime = DateTime.UtcNow;
             lastBytes = x.Item1;
         }).Subscribe())
         return await _api.DownloadFile(url, destination.ToString(), token).ConfigureAwait(false);
 }
        public async Task ConvertOrInstallOrUpdateInternal(IAbsoluteDirectoryPath path, bool force,
            StatusRepo statusRepo, ModState modState, IAbsoluteDirectoryPath packPath) {
            Contract.Requires<ArgumentNullException>(path != null);
            Contract.Requires<ArgumentNullException>(statusRepo != null);
            Contract.Requires<ArgumentNullException>(modState != null);

            _path = path;

            var opts = GetOptions(statusRepo, packPath.ToString(), force);
            if (!modState.Exists) {
                await Install(opts).ConfigureAwait(false);
                return;
            }

            var updateAvailable = modState.State != ContentState.Uptodate;
            if (modState.DoesRepoExist())
                await Update(opts, null, !updateAvailable).ConfigureAwait(false);
            else {
                var repo = Convert(opts);
                await Update(opts, repo).ConfigureAwait(false);
            }
        }
Пример #48
0
            public void HandleDowncaseFolder(IAbsoluteDirectoryPath entry, string[] excludes = null) {
                if (excludes == null)
                    excludes = new string[0];

                foreach (var file in Directory.EnumerateFiles(entry.ToString(), "*.*", SearchOption.TopDirectoryOnly)
                    .Concat(Directory.EnumerateDirectories(entry.ToString(), "*.*",
                        SearchOption.TopDirectoryOnly))) {
                    if (excludes.Any(x => x == Path.GetFileName(file)))
                        continue;
                    HandleDowncase(file, excludes);
                }
            }
Пример #49
0
 void SignFolderRecursively(IAbsoluteDirectoryPath folder, IAbsoluteFilePath privateFile,
     bool repackOnFailure = false) {
     foreach (var f in Directory.EnumerateFiles(folder.ToString(), "*.pbo", SearchOption.AllDirectories))
         _biSigner.SignFile(f.ToAbsoluteFilePath(), privateFile, repackOnFailure);
 }
Пример #50
0
        bool WriteClientSideConfig(IAbsoluteDirectoryPath path) {
            Contract.Requires<ArgumentNullException>(path != null);

            var acePath = Path.Combine(path.ToString(), @"userconfig\ace");
            var file = Path.Combine(acePath, "ace_clientside_config.hpp");

            if (!Directory.Exists(acePath)) {
                if (!TryCreatePath(acePath))
                    return false;
            }

            var file2 = Path.Combine(acePath, "ace_serverconfig.hpp");
            if (!File.Exists(file2))
                TryWriteNewConfig(file2);

            return TryWriteConfig(file);
        }
 public void ProcessBackupAndCleanInstall(string path, IAbsoluteDirectoryPath gamePath,
     IAbsoluteDirectoryPath uconfig, IAbsoluteDirectoryPath uconfigPath) {
     BackupExistingUserconfig(uconfigPath.ToString());
     TryUserconfigClean(path, gamePath, uconfig, uconfigPath);
 }
 static DriveInfo GetDrive(IAbsoluteDirectoryPath path) {
     var lower = path.ToString().ToLower();
     return DriveInfo.GetDrives()
         .Single(d => lower.StartsWith(d.Name.ToLower()));
 }
 static DlcEdition GetDlcType(IAbsoluteDirectoryPath dlcPath) {
     var file = Path.Combine(dlcPath.ToString(), "addons", "france_data.ifa").ToAbsoluteFilePath();
     return ConfirmChecksum(file, OfficialGameInfo.DigitalDlcSha)
         ? DlcEdition.Digitial
         : DlcEdition.Steam;
 }
 void ExtractFolder(IAbsoluteDirectoryPath rootPath, IAbsoluteDirectoryPath tempPath,
     IAbsoluteDirectoryPath destination, IStatus status) {
     destination = destination.GetChildDirectoryWithName("addons");
     destination.MakeSurePathExists();
     var files = Directory.GetFiles(Path.Combine(rootPath.ToString(), "addons"), "*.ifa");
     var i = 0;
     foreach (var f in files) {
         ProcessPbo(f, tempPath, destination);
         i++;
         status.Update(null, ((double)i / files.Length) * 100);
     }
 }
Пример #55
0
 public bool IsDirectoryEmpty(IAbsoluteDirectoryPath path) {
     return !Directory.EnumerateFileSystemEntries(path.ToString()).Any();
 }
Пример #56
0
            public long GetDirectorySize(IAbsoluteDirectoryPath p, string filter = null, string selector = "*.*",
                bool recurse = true) {
                var sum =
                    Directory.EnumerateFiles(p.ToString(), selector,
                        recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)
                        .Select(name => new FileInfo(name).Length)
                        .Sum();

                if (filter != null) {
                    sum = sum -
                          Directory.EnumerateFiles(p.ToString(), filter,
                              recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)
                              .Select(name => new FileInfo(name).Length)
                              .Sum();
                }

                return sum;
            }
Пример #57
0
 static bool IsSameRoot(IAbsoluteDirectoryPath sourcePath, IAbsoluteDirectoryPath destinationPath) {
     return Directory.GetDirectoryRoot(sourcePath.ToString()) ==
            Directory.GetDirectoryRoot(destinationPath.ToString());
 }
Пример #58
0
 public bool IsPathRootedDirectlyIn(IAbsoluteDirectoryPath path, IAbsoluteDirectoryPath root,
     bool mayBeEqual = false) {
     if (ComparePathsOsCaseSensitive(path, root))
         return mayBeEqual;
     return path.HasParentDirectory &&
            ComparePathsOsCaseSensitive(path.ParentDirectoryPath.ToString(), root.ToString());
 }
Пример #59
0
            public bool IsPathRootedIn(IAbsoluteDirectoryPath path, IAbsoluteDirectoryPath root, bool mayBeEqual = false) {
                if (ComparePathsOsCaseSensitive(path, root))
                    return mayBeEqual;

                var rt = root.ToString();
                var dir = path;
                while (dir != null && dir.HasParentDirectory) {
                    var parent = dir.ParentDirectoryPath;
                    if (ComparePathsOsCaseSensitive(parent.ToString(), rt))
                        return true;
                    dir = parent;
                }
                return false;
            }
Пример #60
0
 private async Task InstallNew(GroupContent mod, IAuthProvider provider, Action<SyncOptions> config,
     IAbsoluteDirectoryPath folder) {
     SetupHosts(mod, provider);
     var opts = new SyncOptions();
     config(opts);
     await
         Repository.Factory.Clone(opts.Hosts, folder.ToString(), config)
             .ConfigureAwait(false);
 }