Exemple #1
0
        public RemoteData(string appSecret)
        {
            Checks.ArgumentNotNullOrEmpty(appSecret, "appSecret");

            DebugLogger.LogConstructor();
            DebugLogger.LogVariable(appSecret, "appSecret");

            _appSecret = appSecret;

            var mainSettings = Settings.GetMainApiConnectionSettings();

            string overrideMainUrl;

            if (EnvironmentInfo.TryReadEnvironmentVariable(EnvironmentVariables.MainUrlEnvironmentVariable, out overrideMainUrl))
            {
                var overrideMainUri = new Uri(overrideMainUrl);

                mainSettings.MainServer.Host     = overrideMainUri.Host;
                mainSettings.MainServer.Port     = overrideMainUri.Port;
                mainSettings.MainServer.UseHttps = overrideMainUri.Scheme == Uri.UriSchemeHttps;
            }

            _mainApiConnection = new MainApiConnection(mainSettings)
            {
                HttpWebRequestFactory = new UnityWebRequestFactory(),
                Logger = PatcherLogManager.DefaultLogger
            };
        }
        public int GetEntryVersionId(string fileName)
        {
            Checks.ArgumentNotNullOrEmpty(fileName, "fileName");
            Assert.IsTrue(IsEntryRegistered(fileName), string.Format("File doesn't exist in meta data - {0}", fileName));

            return(_data.FileVersionIds[fileName]);
        }
Exemple #3
0
        public TemporaryDirectory(string path, string prefix) : base(path.PathCombine(prefix + "_" + System.IO.Path.GetRandomFileName()))
        {
            Checks.ArgumentNotNullOrEmpty(prefix, "prefix");

            _prefix    = prefix;
            _createdAt = DateTime.Now;
        }
        public RemoteData(string appSecret, IRequestTimeoutCalculator requestTimeoutCalculator)
        {
            Checks.ArgumentNotNullOrEmpty(appSecret, "appSecret");

            DebugLogger.LogConstructor();
            DebugLogger.LogVariable(appSecret, "appSecret");

            _appSecret = appSecret;

            var mainSettings = Settings.GetMainApiConnectionSettings();

            string overrideMainUrl;

            if (EnvironmentInfo.TryReadEnvironmentVariable(EnvironmentVariables.ApiUrlEnvironmentVariable, out overrideMainUrl))
            {
                var overrideMainUri = new Uri(overrideMainUrl);

                mainSettings.MainServer.Host     = overrideMainUri.Host;
                mainSettings.MainServer.Port     = overrideMainUri.Port;
                mainSettings.MainServer.UseHttps = overrideMainUri.Scheme == Uri.UriSchemeHttps;
            }

            _mainApiConnection = new MainApiConnection(mainSettings)
            {
                HttpClient = new UnityHttpClient(),
                RequestTimeoutCalculator = requestTimeoutCalculator,
                RequestRetryStrategy     = new SimpleInfiniteRequestRetryStrategy(),
                Logger = PatcherLogManager.DefaultLogger
            };
        }
        public string GetKeySecret(string key, string cachedKeySecret)
        {
            Checks.ArgumentNotNullOrEmpty(key, "key");
            DebugLogger.Log(string.Format("Getting key secret from key {0}.", key));

            var keySecret = _keysApiConnection.GetKeyInfo(key, _appSecret, cachedKeySecret).KeySecret;

            return(keySecret);
        }
        public void UnregisterEntry(string fileName)
        {
            Checks.ArgumentNotNullOrEmpty(fileName, "fileName");

            DebugLogger.Log(string.Format("Removing file {0}", fileName));

            _data.FileVersionIds.Remove(fileName);

            SaveData();
        }
        public LocalMetaData(string filePath)
        {
            Checks.ArgumentNotNullOrEmpty(filePath, "filePath");

            DebugLogger.LogConstructor();
            DebugLogger.LogVariable(filePath, "filePath");

            _filePath = filePath;
            LoadData();
        }
        public RemoteData(string appSecret, MainApiConnection mainApiConnection)
        {
            Checks.ArgumentNotNullOrEmpty(appSecret, "appSecret");
            Checks.ArgumentNotNull(mainApiConnection, "mainApiConnection");

            DebugLogger.LogConstructor();
            DebugLogger.LogVariable(appSecret, "appSecret");

            _appSecret         = appSecret;
            _mainApiConnection = mainApiConnection;
        }
Exemple #9
0
        public ChunkedFileStream(string path, long fileSize, ChunksData chunksData, HashFunction hashFunction,
                                 WorkFlags workFlags = WorkFlags.None)
        {
            Checks.ArgumentNotNullOrEmpty(path, "path");
            Checks.ArgumentMoreThanZero(fileSize, "fileSize");
            Checks.ArgumentNotNull(hashFunction, "hashFunction");

            DebugLogger.LogConstructor();
            DebugLogger.LogVariable(path, "path");
            DebugLogger.LogVariable(fileSize, "fileSize");

            _fileSize     = fileSize;
            _chunksData   = chunksData;
            _hashFunction = hashFunction;

            _buffer = new byte[_chunksData.ChunkSize];

            if ((workFlags | WorkFlags.PreservePreviousFile) != 0)
            {
                // Often you may want to continue downloading of a file if this exists
                // It tries to open a file and re-download it from the verified position.
                // It does not check the hash of the file. It trusts that the file is already valid up to that point.
                // Because the only way to download the file should be using Chunked Downloader.

                _fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
                _fileStream.Seek(0, SeekOrigin.End); // seek and stay at the end, so we can append
                long currentFileSize = _fileStream.Position;

                // Let's make sure that file size is a multiply of chunk size.
                // If not, something is wrong with the file.
                if (currentFileSize % chunksData.ChunkSize == 0)
                {
                    _chunkIndex = (int)(currentFileSize / chunksData.ChunkSize);
                }
                else
                {
                    DebugLogger.LogWarningFormat(
                        "File {0} size {1} is not a multiply of chunk size: {2}. Will recreate it.", path,
                        currentFileSize, chunksData.ChunkSize);

                    _fileStream.Close();
                    _fileStream.Dispose();

                    _fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
                }
            }
            else
            {
                _fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
            }
        }
Exemple #10
0
        protected BaseWritableDirectory(string path)
        {
            Assert.IsFalse(UsedPaths.Contains(path),
                           string.Format("You cannot create two instances of {0} pointing to the same path.", typeof(T)));
            Checks.ArgumentNotNullOrEmpty(path, "path");

            DebugLogger.LogConstructor();
            DebugLogger.LogVariable(path, "path");

            _path = path;

            // Register path as used.
            UsedPaths.Add(_path);
        }
        public void RegisterEntry(string entryName, int versionId)
        {
            Checks.ArgumentNotNullOrEmpty(entryName, "fileName");
            Checks.ArgumentValidVersionId(versionId, "versionId");

            // TODO: Uncomment this after fixing directory registration in install content command
            Assert.IsFalse(entryName.EndsWith("/"),
                           "Cannot register directory as entry due to problem with content installation command. See code to learn more.");

            DebugLogger.Log(string.Format("Adding or updating file {0} to version {1}.", entryName, versionId));

            _data.FileVersionIds[entryName] = versionId;

            SaveData();
        }
        public DownloadPackageCommand(RemoteResource resource, string destinationPackagePath, string destinationMetaPath, bool useTorrents)
        {
            Checks.ArgumentValidRemoteResource(resource, "resource");
            Checks.ArgumentNotNullOrEmpty(destinationPackagePath, "destinationPackagePath");
            Checks.ParentDirectoryExists(destinationPackagePath);

            DebugLogger.LogConstructor();
            DebugLogger.LogVariable(resource, "resource");
            DebugLogger.LogVariable(destinationPackagePath, "destinationPackagePath");
            DebugLogger.LogVariable(useTorrents, "useTorrents");

            _resource = resource;
            _destinationPackagePath = destinationPackagePath;
            _destinationMetaPath    = destinationMetaPath;
            _useTorrents            = useTorrents;
        }
        /// <summary>
        /// Creates the directory.
        /// </summary>
        /// <param name="dirPath">The directory path.</param>
        /// <exception cref="ArgumentException"><paramref name="dirPath"/> is null or empty.</exception>
        /// <exception cref="UnauthorizedAccessException">Unauthorized access.</exception>
        public static void CreateDirectory(string dirPath)
        {
            Checks.ArgumentNotNullOrEmpty(dirPath, "dirPath");

            try
            {
                DebugLogger.Log(string.Format("Creating directory <{0}>.", dirPath));

                Directory.CreateDirectory(dirPath);

                DebugLogger.Log("Directory created.");
            }
            catch (Exception)
            {
                DebugLogger.LogError("Error while creating directory: an exception occured. Rethrowing exception.");
                throw;
            }
        }
        /// <summary>
        /// Deletes file.
        /// </summary>
        /// <param name="filePath">The file path.</param>
        /// <exception cref="ArgumentException"><paramref name="filePath"/> is null or empty.</exception>
        /// <exception cref="FileNotFoundException"><paramref name="filePath"/> doesn't exist.</exception>
        /// <exception cref="UnauthorizedAccessException">Unauthorized access.</exception>
        public static void Delete(string filePath)
        {
            Checks.ArgumentNotNullOrEmpty(filePath, "filePath");
            Checks.FileExists(filePath);

            try
            {
                DebugLogger.Log(string.Format("Deleting file <{0}>.", filePath));

                File.Delete(filePath);

                DebugLogger.Log("File deleted.");
            }
            catch (Exception)
            {
                DebugLogger.LogError("Error while deleting file: an exception occured. Rethrowing exception.");
                throw;
            }
        }
        /// <summary>
        /// Moves file from <paramref name="sourceFilePath" /> to <paramref name="destinationFilePath" />.
        /// </summary>
        /// <param name="sourceFilePath">The source file path.</param>
        /// <param name="destinationFilePath">The destination file path.</param>
        /// <exception cref="ArgumentException"><paramref name="sourceFilePath"/> is null or empty.</exception>
        /// <exception cref="ArgumentException"><paramref name="destinationFilePath"/> is null or empty.</exception>
        /// <exception cref="FileNotFoundException"><paramref name="sourceFilePath"/> doesn't exist.</exception>
        /// <exception cref="DirectoryNotFoundException"><paramref name="destinationFilePath"/> parent directory doesn't exist.</exception>
        /// <exception cref="UnauthorizedAccessException">Unauthorized access.</exception>
        public static void Move(string sourceFilePath, string destinationFilePath)
        {
            Checks.ArgumentNotNullOrEmpty(sourceFilePath, "sourceFilePath");
            Checks.ArgumentNotNullOrEmpty(destinationFilePath, "destinationFilePath");
            Checks.FileExists(sourceFilePath);
            Checks.ParentDirectoryExists(destinationFilePath);

            try
            {
                DebugLogger.Log(string.Format("Moving file from <{0}> to <{1}>.", sourceFilePath, destinationFilePath));

                File.Move(sourceFilePath, destinationFilePath);

                DebugLogger.Log("File moved.");
            }
            catch (Exception)
            {
                DebugLogger.LogError("Error while moving file: an exception occured. Rethrowing exception.");
                throw;
            }
        }
        /// <summary>
        /// Creates the directory.
        /// </summary>
        /// <param name="dirPath">The directory path.</param>
        /// <param name="recursive">if set to <c>true</c> then directory content is also removed recursively.</param>
        /// <exception cref="ArgumentException"><paramref name="dirPath" /> is null or empty.</exception>
        /// <exception cref="DirectoryNotFoundException"><paramref name="dirPath" /> doesn't exist.</exception>
        /// <exception cref="UnauthorizedAccessException">Unauthorized access.</exception>
        public static void Delete(string dirPath, bool recursive)
        {
            Checks.ArgumentNotNullOrEmpty(dirPath, "dirPath");
            Checks.DirectoryExists(dirPath);

            try
            {
                DebugLogger.Log(string.Format("Deleting directory {0}<{1}>.",
                                              recursive ? "recursively " : string.Empty,
                                              dirPath));

                Directory.Delete(dirPath, recursive);

                DebugLogger.Log("Directory deleted.");
            }
            catch (Exception)
            {
                DebugLogger.LogError("Error while deleting directory: an exception occured. Rethrowing exception.");
                throw;
            }
        }
        /// <summary>
        /// Determines whether directory is empty (does not contain any files or directories).
        /// </summary>
        /// <param name="dirPath">The directory path.</param>
        /// <returns>
        ///   <c>true</c> if directory is empty; otherwise, <c>false</c>.
        /// </returns>
        /// <exception cref="ArgumentException"><paramref name="dirPath"/> is null or empty.</exception>
        /// <exception cref="DirectoryNotFoundException"><paramref name="dirPath"/> doesn't exist.</exception>
        /// <exception cref="UnauthorizedAccessException">Unauthorized access.</exception>
        public static bool IsDirectoryEmpty(string dirPath)
        {
            Checks.ArgumentNotNullOrEmpty(dirPath, "dirPath");
            Checks.DirectoryExists(dirPath);

            try
            {
                DebugLogger.Log(string.Format("Checking whether directory is empty <{0}>...", dirPath));

                bool isEmpty = Directory.GetFiles(dirPath, "*", SearchOption.TopDirectoryOnly).Length == 0 &&
                               Directory.GetDirectories(dirPath, "*", SearchOption.TopDirectoryOnly).Length == 0;

                DebugLogger.Log(string.Format("Check complete: directory is {0}.", isEmpty ? "empty" : "not empty"));

                return(isEmpty);
            }
            catch (Exception)
            {
                DebugLogger.LogError("Error while checking whether directory is empty: an exception occured. Rethrowing exception.");
                throw;
            }
        }
        public BaseHttpDownloader(string url, int timeout, int bufferSize,
                                  CreateNewHttpWebRequest createNewHttpWebRequest)
        {
            Checks.ArgumentNotNullOrEmpty(url, "url");
            Checks.ArgumentMoreThanZero(timeout, "timeout");
            Checks.ArgumentMoreThanZero(bufferSize, "bufferSize");
            Checks.ArgumentNotNull(createNewHttpWebRequest, "createNewHttpWebRequest");

            DebugLogger.LogConstructor();
            DebugLogger.LogVariable(url, "url");
            DebugLogger.LogVariable(timeout, "timeout");
            DebugLogger.LogVariable(bufferSize, "bufferSize");

            _url        = url;
            _timeout    = timeout;
            _bufferSize = bufferSize;
            _createNewHttpWebRequest = createNewHttpWebRequest;
            _buffer = new byte[_bufferSize];

            ServicePointManager.ServerCertificateValidationCallback =
                (sender, certificate, chain, errors) => true;
            ServicePointManager.DefaultConnectionLimit = 65535;
        }
        /// <summary>
        /// Creates parent directory for specified <paramref name="path"/>.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <exception cref="ArgumentException"><paramref name="path"/> is null or empty.</exception>
        /// <exception cref="UnauthorizedAccessException">Unauthorized access.</exception>
        public static void CreateParentDirectory(string path)
        {
            Checks.ArgumentNotNullOrEmpty(path, "path");

            try
            {
                DebugLogger.Log(string.Format("Creating parent directory for <{0}>.", path));

                string dirPath = Path.GetDirectoryName(path);

                if (!string.IsNullOrEmpty(dirPath))
                {
                    CreateDirectory(dirPath);
                }

                DebugLogger.Log("Parent directory created.");
            }
            catch (Exception)
            {
                DebugLogger.LogError("Error while creating parent directory: an exception occured. Rethrowing exception.");
                throw;
            }
        }
        /// <summary>
        /// Copies file from <paramref name="sourceFilePath" /> to <paramref name="destinationFilePath" />.
        /// </summary>
        /// <param name="sourceFilePath">The source file path.</param>
        /// <param name="destinationFilePath">The destination file path.</param>
        /// <param name="overwrite">if set to <c>true</c> and destination file exists then it is overwritten.</param>
        /// <exception cref="ArgumentException"><paramref name="sourceFilePath"/> is null or empty.</exception>
        /// <exception cref="ArgumentException"><paramref name="destinationFilePath"/> is null or empty.</exception>
        /// <exception cref="FileNotFoundException"><paramref name="sourceFilePath"/> doesn't exist.</exception>
        /// <exception cref="DirectoryNotFoundException"><paramref name="destinationFilePath"/> parent directory doesn't exist.</exception>
        /// <exception cref="UnauthorizedAccessException">Unauthorized access.</exception>
        public static void Copy(string sourceFilePath, string destinationFilePath, bool overwrite)
        {
            Checks.ArgumentNotNullOrEmpty(sourceFilePath, "sourceFilePath");
            Checks.ArgumentNotNullOrEmpty(destinationFilePath, "destinationFilePath");
            Checks.FileExists(sourceFilePath);
            Checks.ParentDirectoryExists(destinationFilePath);

            try
            {
                DebugLogger.Log(string.Format("Copying file from <{0}> to <{1}> {2}...",
                                              sourceFilePath,
                                              destinationFilePath,
                                              overwrite ? "(overwriting)" : string.Empty));

                File.Copy(sourceFilePath, destinationFilePath, overwrite);

                DebugLogger.Log("File copied.");
            }
            catch (Exception)
            {
                DebugLogger.LogError("Error while copying file: an exception occured. Rethrowing exception.");
                throw;
            }
        }
        public bool IsEntryRegistered(string fileName)
        {
            Checks.ArgumentNotNullOrEmpty(fileName, "fileName");

            return(_data.FileVersionIds.ContainsKey(fileName));
        }