Beispiel #1
0
 public static void Remove(string key)
 {
     if (string.IsNullOrEmpty(key))
     {
         throw new ArgumentNullException("key");
     }
     _cache.Remove(key);
 }
Beispiel #2
0
        public void StopTracking(string downloadId)
        {
            var trackedDownload = _cache.Find(downloadId);

            _cache.Remove(downloadId);
            _eventAggregator.PublishEvent(new TrackedDownloadsRemovedEvent(new List <TrackedDownload> {
                trackedDownload
            }));
        }
Beispiel #3
0
        private void Authenticate(string baseUrl, string arl)
        {
            var requestBuilder = BuildRequest(baseUrl);

            var user = Connect(baseUrl);

            if (user?.CurrentUser?.Name != null)
            {
                _userCache.Set(baseUrl, user.CurrentUser);
                _logger.Debug("Already logged in to Deemix.");
                return;
            }

            var cookie = _sessionCookieCache.Find(baseUrl);

            if (cookie == null)
            {
                _sessionCookieCache.Remove(baseUrl);
                _userCache.Remove(baseUrl);
            }

            var authLoginRequest = requestBuilder
                                   .Resource("api/loginArl")
                                   .Post()
                                   .AddFormParameter("arl", arl)
                                   .Accept(HttpAccept.Json)
                                   .Build();

            var response = _httpClient.Execute(authLoginRequest);
            var cookies  = response.GetCookies();

            if (cookies.ContainsKey("connect.sid"))
            {
                cookie = cookies["connect.sid"];
                _sessionCookieCache.Set(baseUrl, cookie);

                _logger.Debug("Got cookie {0}", cookie);

                user = Connect(baseUrl);
                if (user?.CurrentUser?.Name != null)
                {
                    _userCache.Set(baseUrl, user.CurrentUser);
                    _logger.Debug("Deemix authentication succeeded");
                    return;
                }

                _sessionCookieCache.Remove(baseUrl);
                _userCache.Remove(baseUrl);
            }

            throw new DownloadClientException("Failed to authenticate with Deemix");
        }
        public void SearchForRecentlyAdded(int artistId)
        {
            var allAlbums = _albumService.GetAlbumsByArtist(artistId);
            var toSearch  = allAlbums.Where(x => x.AddOptions.SearchForNewAlbum).ToList();

            if (toSearch.Any())
            {
                toSearch.ForEach(x => x.AddOptions.SearchForNewAlbum = false);

                _albumService.SetAddOptions(toSearch);
            }

            var recentlyAddedIds = _addedAlbumsCache.Find(artistId.ToString());

            if (recentlyAddedIds != null)
            {
                toSearch.AddRange(allAlbums.Where(x => recentlyAddedIds.Contains(x.Id)));
            }

            if (toSearch.Any())
            {
                _commandQueueManager.Push(new AlbumSearchCommand(toSearch.Select(e => e.Id).ToList()));
            }

            _addedAlbumsCache.Remove(artistId.ToString());
        }
Beispiel #5
0
        private void PerformHealthCheck(IProvideHealthCheck[] healthChecks, IEvent message = null)
        {
            var results = new List <HealthCheck>();

            foreach (var healthCheck in healthChecks)
            {
                if (healthCheck is IProvideHealthCheckWithMessage && message != null)
                {
                    results.Add(((IProvideHealthCheckWithMessage)healthCheck).Check(message));
                }
                else
                {
                    results.Add(healthCheck.Check());
                }
            }

            foreach (var result in results)
            {
                if (result.Type == HealthCheckResult.Ok)
                {
                    _healthCheckResults.Remove(result.Source.Name);
                }
                else
                {
                    if (_healthCheckResults.Find(result.Source.Name) == null)
                    {
                        _eventAggregator.PublishEvent(new HealthCheckFailedEvent(result));
                    }

                    _healthCheckResults.Set(result.Source.Name, result);
                }
            }

            _eventAggregator.PublishEvent(new HealthCheckCompleteEvent());
        }
Beispiel #6
0
        private void AuthenticateClient(HttpRequestBuilder requestBuilder, QBittorrentSettings settings, bool reauthenticate = false)
        {
            if (settings.Username.IsNullOrWhiteSpace() || settings.Password.IsNullOrWhiteSpace())
            {
                if (reauthenticate)
                {
                    throw new DownloadClientAuthenticationException("Failed to authenticate with qBittorrent.");
                }
                return;
            }

            var authKey = string.Format("{0}:{1}", requestBuilder.BaseUrl, settings.Password);

            var cookies = _authCookieCache.Find(authKey);

            if (cookies == null || reauthenticate)
            {
                _authCookieCache.Remove(authKey);

                var authLoginRequest = BuildRequest(settings).Resource("/api/v2/auth/login")
                                       .Post()
                                       .AddFormParameter("username", settings.Username ?? string.Empty)
                                       .AddFormParameter("password", settings.Password ?? string.Empty)
                                       .Build();

                HttpResponse response;
                try
                {
                    response = _httpClient.Execute(authLoginRequest);
                }
                catch (HttpException ex)
                {
                    _logger.Debug("qbitTorrent authentication failed.");
                    if (ex.Response.StatusCode == HttpStatusCode.Forbidden)
                    {
                        throw new DownloadClientAuthenticationException("Failed to authenticate with qBittorrent.", ex);
                    }

                    throw new DownloadClientException("Failed to connect to qBittorrent, please check your settings.", ex);
                }
                catch (WebException ex)
                {
                    throw new DownloadClientUnavailableException("Failed to connect to qBittorrent, please check your settings.", ex);
                }

                if (response.Content != "Ok.") // returns "Fails." on bad login
                {
                    _logger.Debug("qbitTorrent authentication failed.");
                    throw new DownloadClientAuthenticationException("Failed to authenticate with qBittorrent.");
                }

                _logger.Debug("qBittorrent authentication succeeded.");

                cookies = response.GetCookies();

                _authCookieCache.Set(authKey, cookies);
            }

            requestBuilder.SetCookies(cookies);
        }
Beispiel #7
0
        protected void RemoveCache <T>(string funcName, params object[] args)
        {
            var    cacheName = "<" + funcName + ">" + ":" + GetFriendlyTypeName(typeof(T));
            string cacheKey  = KeyCacheHelper.GenCacheKeySerialize(cacheName, args);

            cacheClient.Remove(cacheKey);
        }
Beispiel #8
0
        public void SearchForRecentlyAdded(int authorId)
        {
            var allBooks = _bookService.GetBooksByAuthor(authorId);
            var toSearch = allBooks.Where(x => x.AddOptions.SearchForNewBook).ToList();

            if (toSearch.Any())
            {
                toSearch.ForEach(x => x.AddOptions.SearchForNewBook = false);

                _bookService.SetAddOptions(toSearch);
            }

            var recentlyAddedIds = _addedBooksCache.Find(authorId.ToString());

            if (recentlyAddedIds != null)
            {
                toSearch.AddRange(allBooks.Where(x => recentlyAddedIds.Contains(x.Id)));
            }

            if (toSearch.Any())
            {
                _commandQueueManager.Push(new BookSearchCommand(toSearch.Select(e => e.Id).ToList()));
            }

            _addedBooksCache.Remove(authorId.ToString());
        }
Beispiel #9
0
        private DiskStationResponse <T> ProcessRequest <T>(HttpRequestBuilder requestBuilder,
                                                           string operation,
                                                           DiskStationApi api,
                                                           DownloadStationSettings settings)
            where T : new()
        {
            var          request = requestBuilder.Build();
            HttpResponse response;

            try
            {
                response = _httpClient.Execute(request);
            }
            catch (HttpException ex)
            {
                throw new DownloadClientException("Unable to connect to Diskstation, please check your settings", ex);
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.TrustFailure)
                {
                    throw new DownloadClientUnavailableException("Unable to connect to Diskstation, certificate validation failed.", ex);
                }

                throw new DownloadClientUnavailableException("Unable to connect to Diskstation, please check your settings", ex);
            }

            _logger.Debug("Trying to {0}", operation);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var responseContent = Json.Deserialize <DiskStationResponse <T> >(response.Content);

                if (responseContent.Success)
                {
                    return(responseContent);
                }
                else
                {
                    var msg = $"Failed to {operation}. Reason: {responseContent.Error.GetMessage(api)}";
                    _logger.Error(msg);

                    if (responseContent.Error.SessionError)
                    {
                        _sessionCache.Remove(GenerateSessionCacheKey(settings));

                        if (responseContent.Error.Code == 105)
                        {
                            throw new DownloadClientAuthenticationException(msg);
                        }
                    }

                    throw new DownloadClientException(msg);
                }
            }
            else
            {
                throw new HttpException(request, response);
            }
        }
Beispiel #10
0
        private TimeSpan?GetRemainingTime(DeemixQueueItem x, long size)
        {
            if (x.Progress == 100)
            {
                _startTimeCache.Remove(x.Id);
                return(null);
            }

            if (x.Progress == 0)
            {
                return(null);
            }

            var started = _startTimeCache.Find(x.Id);

            if (started == null)
            {
                started = DateTime.UtcNow;
                _startTimeCache.Set(x.Id, started);
                return(null);
            }

            var elapsed  = DateTime.UtcNow - started;
            var progress = Math.Min(x.Progress, 100) / 100.0;

            _bytesPerSecond = (progress * size) / elapsed.Value.TotalSeconds;

            return(TimeSpan.FromTicks((long)(elapsed.Value.Ticks * (1 - progress) / progress)));
        }
Beispiel #11
0
        private void PerformHealthCheck(IProvideHealthCheck[] healthChecks)
        {
            var results = healthChecks.Select(c => c.Check())
                          .ToList();

            foreach (var result in results)
            {
                if (result.Type == HealthCheckResult.Ok)
                {
                    _healthCheckResults.Remove(result.Source.Name);
                }

                else
                {
                    if (_healthCheckResults.Find(result.Source.Name) == null)
                    {
                        _eventAggregator.PublishEvent(new HealthCheckFailedEvent(result, !_hasRunHealthChecksAfterGracePeriod));
                    }

                    _healthCheckResults.Set(result.Source.Name, result);
                }
            }

            _eventAggregator.PublishEvent(new HealthCheckCompleteEvent());
        }
Beispiel #12
0
        private void PerformHealthCheck(IProvideHealthCheck[] healthChecks)
        {
            var results = healthChecks.Select(c => c.Check())
                          .ToList();

            results.AddRange(_serverSideNotificationService.GetServerChecks());

            foreach (var result in results)
            {
                if (result.Type == HealthCheckResult.Ok)
                {
                    _healthCheckResults.Remove(result.Source.Name);
                }
                else
                {
                    if (_healthCheckResults.Find(result.Source.Name) == null)
                    {
                        _eventAggregator.PublishEvent(new HealthCheckFailedEvent(result));
                    }

                    _healthCheckResults.Set(result.Source.Name, result);
                }
            }

            _eventAggregator.PublishEvent(new HealthCheckCompleteEvent());
        }
Beispiel #13
0
        public ValidationFailure Test(PlexServerSettings settings)
        {
            try
            {
                _versionCache.Remove(settings.Host);
                _partialUpdateCache.Remove(settings.Host);
                var sections = GetSections(settings);

                if (sections.Empty())
                {
                    return(new ValidationFailure("Host", "At least one TV library is required"));
                }
            }
            catch (PlexAuthenticationException ex)
            {
                _logger.Error(ex, "Unable to connect to Plex Server");
                return(new ValidationFailure("AuthToken", "Invalid authentication token"));
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Unable to connect to Plex Server");
                return(new ValidationFailure("Host", "Unable to connect to Plex Server"));
            }

            return(null);
        }
Beispiel #14
0
        private void AuthenticateClient(JsonRpcRequestBuilder requestBuilder, DelugeSettings settings, bool reauthenticate = false)
        {
            var authKey = string.Format("{0}:{1}", requestBuilder.BaseUrl, settings.Password);

            var cookies = _authCookieCache.Find(authKey);

            if (cookies == null || reauthenticate)
            {
                _authCookieCache.Remove(authKey);

                var authLoginRequest = requestBuilder.Call("auth.login", settings.Password).Build();
                var response         = _httpClient.Execute(authLoginRequest);
                var result           = Json.Deserialize <JsonRpcResponse <bool> >(response.Content);
                if (!result.Result)
                {
                    _logger.Debug("Deluge authentication failed.");
                    throw new DownloadClientAuthenticationException("Failed to authenticate with Deluge.");
                }
                _logger.Debug("Deluge authentication succeeded.");

                cookies = response.GetCookies();

                _authCookieCache.Set(authKey, cookies);

                requestBuilder.SetCookies(cookies);

                ConnectDaemon(requestBuilder);
            }
            else
            {
                requestBuilder.SetCookies(cookies);
            }
        }
Beispiel #15
0
        private void PerformUpdate(Series series)
        {
            _logger.Debug("Updating scene numbering mapping for: {0}", series);

            try
            {
                var mappings = _xemProxy.GetSceneTvdbMappings(series.TvdbId);

                if (!mappings.Any() && !series.UseSceneNumbering)
                {
                    _logger.Debug("Mappings for: {0} are empty, skipping", series);
                    _cache.Remove(series.TvdbId.ToString());
                    return;
                }

                var episodes = _episodeService.GetEpisodeBySeries(series.Id);

                foreach (var episode in episodes)
                {
                    episode.SceneAbsoluteEpisodeNumber = null;
                    episode.SceneSeasonNumber          = null;
                    episode.SceneEpisodeNumber         = null;
                    episode.UnverifiedSceneNumbering   = false;
                }

                foreach (var mapping in mappings)
                {
                    _logger.Debug("Setting scene numbering mappings for {0} S{1:00}E{2:00}", series, mapping.Tvdb.Season, mapping.Tvdb.Episode);

                    var episode = episodes.SingleOrDefault(e => e.SeasonNumber == mapping.Tvdb.Season && e.EpisodeNumber == mapping.Tvdb.Episode);

                    if (episode == null)
                    {
                        _logger.Debug("Information hasn't been added to TheTVDB yet, skipping.");
                        continue;
                    }

                    episode.SceneAbsoluteEpisodeNumber = mapping.Scene.Absolute;
                    episode.SceneSeasonNumber          = mapping.Scene.Season;
                    episode.SceneEpisodeNumber         = mapping.Scene.Episode;
                }

                if (episodes.Any(v => v.SceneEpisodeNumber.HasValue && v.SceneSeasonNumber != 0))
                {
                    ExtrapolateMappings(series, episodes, mappings);
                }

                _episodeService.UpdateEpisodes(episodes);
                series.UseSceneNumbering = mappings.Any();
                _seriesService.UpdateSeries(series);

                _logger.Debug("XEM mapping updated for {0}", series);
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error updating scene numbering mappings for: " + series, ex);
            }
        }
Beispiel #16
0
 /// <summary>
 /// 注销
 /// </summary>
 /// <returns></returns>
 public bool Logout()
 {
     try
     {
         HttpCookie cookie = HttpContext.Current.Request.Cookies["Token"];
         if (cookie == null)
         {
             return(true);
         }
         _cached.Remove(cookie.Value + CacheString);
         _cached.Remove(cookie.Value);
         return(true);
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
Beispiel #17
0
        public void Execute(TrackedCommandCleanupCommand message)
        {
            var old = _cache.Values.Where(c => c.State != CommandStatus.Running && c.StateChangeTime < DateTime.UtcNow.AddMinutes(-5));

            foreach (var trackedCommand in old)
            {
                _cache.Remove(trackedCommand.Id.ToString());
            }
        }
        public IQBittorrentProxy GetProxy(QBittorrentSettings settings, bool force)
        {
            var proxyKey = $"{settings.Host}_{settings.Port}";

            if (force)
            {
                _proxyCache.Remove(proxyKey);
            }

            return(_proxyCache.Get(proxyKey, () => FetchProxy(settings), TimeSpan.FromMinutes(10.0)));
        }
Beispiel #19
0
        private string GetSessionId(bool force, NzbVortexSettings settings)
        {
            var authCacheKey = string.Format("{0}_{1}_{2}", settings.Host, settings.Port, settings.ApiKey);

            if (force)
            {
                _authCache.Remove(authCacheKey);
            }

            var sessionId = _authCache.Get(authCacheKey, () => Authenticate(settings));

            return(sessionId);
        }
Beispiel #20
0
        public void CleanCommands()
        {
            _logger.Trace("Cleaning up old commands");

            var old = _commandCache.Values.Where(c => c.EndedAt < DateTime.UtcNow.AddMinutes(-5));

            foreach (var command in old)
            {
                _commandCache.Remove(command.Id.ToString());
            }

            _repository.Trim();
        }
Beispiel #21
0
        private void AuthenticateClient(HttpRequestBuilder requestBuilder, UTorrentSettings settings, bool reauthenticate = false)
        {
            var authKey = string.Format("{0}:{1}", requestBuilder.BaseUrl, settings.Password);

            var cookies   = _authCookieCache.Find(authKey);
            var authToken = _authTokenCache.Find(authKey);

            if (cookies == null || authToken == null || reauthenticate)
            {
                _authCookieCache.Remove(authKey);
                _authTokenCache.Remove(authKey);

                var authLoginRequest = BuildRequest(settings).Resource("/gui/token.html").Build();

                HttpResponse response;
                try
                {
                    response = _httpClient.Execute(authLoginRequest);
                    _logger.Debug("uTorrent authentication succeeded.");

                    var xmlDoc = new System.Xml.XmlDocument();
                    xmlDoc.LoadXml(response.Content);

                    authToken = xmlDoc.FirstChild.FirstChild.InnerText;
                }
                catch (HttpException ex)
                {
                    if (ex.Response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        _logger.Debug("uTorrent authentication failed.");
                        throw new DownloadClientAuthenticationException("Failed to authenticate with uTorrent.");
                    }

                    throw new DownloadClientException("Unable to connect to uTorrent, please check your settings", ex);
                }
                catch (WebException ex)
                {
                    throw new DownloadClientException("Unable to connect to uTorrent, please check your settings", ex);
                }

                cookies = response.GetCookies();

                _authCookieCache.Set(authKey, cookies);
                _authTokenCache.Set(authKey, authToken);
            }

            requestBuilder.SetCookies(cookies);
            requestBuilder.AddPrefixQueryParam("token", authToken, true);
        }
Beispiel #22
0
        private void PerformUpdate(Series series)
        {
            _logger.Trace("Updating scene numbering mapping for: {0}", series);
            try
            {
                var episodesToUpdate = new List <Episode>();
                var mappings         = _xemProxy.GetSceneTvdbMappings(series.TvdbId);

                if (!mappings.Any())
                {
                    _logger.Trace("Mappings for: {0} are empty, skipping", series);
                    _cache.Remove(series.TvdbId.ToString());
                    return;
                }

                var episodes = _episodeService.GetEpisodeBySeries(series.Id);

                foreach (var mapping in mappings)
                {
                    _logger.Trace("Setting scene numbering mappings for {0} S{1:00}E{2:00}", series, mapping.Tvdb.Season, mapping.Tvdb.Episode);

                    var episode = episodes.SingleOrDefault(e => e.SeasonNumber == mapping.Tvdb.Season && e.EpisodeNumber == mapping.Tvdb.Episode);

                    if (episode == null)
                    {
                        _logger.Trace("Information hasn't been added to TheTVDB yet, skipping.");
                        continue;
                    }

                    episode.AbsoluteEpisodeNumber = mapping.Scene.Absolute;
                    episode.SceneSeasonNumber     = mapping.Scene.Season;
                    episode.SceneEpisodeNumber    = mapping.Scene.Episode;
                    episodesToUpdate.Add(episode);
                }

                _logger.Trace("Committing scene numbering mappings to database for: {0}", series);
                _episodeService.UpdateEpisodes(episodesToUpdate);

                _logger.Trace("Setting UseSceneMapping for {0}", series);
                series.UseSceneNumbering = true;
                _seriesService.UpdateSeries(series);
            }

            catch (Exception ex)
            {
                _logger.ErrorException("Error updating scene numbering mappings for: " + series, ex);
            }
        }
Beispiel #23
0
        public void SearchForRecentlyAdded(int artistId)
        {
            var previouslyReleased = _addedAlbumsCache.Find(artistId.ToString());

            if (previouslyReleased != null && previouslyReleased.Any())
            {
                var missing = previouslyReleased.Select(e => _albumService.GetAlbum(e)).ToList();

                if (missing.Any())
                {
                    _commandQueueManager.Push(new AlbumSearchCommand(missing.Select(e => e.Id).ToList()));
                }
            }

            _addedAlbumsCache.Remove(artistId.ToString());
        }
Beispiel #24
0
        public void SearchForRecentlyAdded(int seriesId)
        {
            var previouslyAired = _addedEpisodesCache.Find(seriesId.ToString());

            if (previouslyAired != null && previouslyAired.Any())
            {
                var missing = previouslyAired.Select(e => _episodeService.GetEpisode(e)).Where(e => !e.HasFile).ToList();

                if (missing.Any())
                {
                    _commandQueueManager.Push(new EpisodeSearchCommand(missing.Select(e => e.Id).ToList()));
                }
            }

            _addedEpisodesCache.Remove(seriesId.ToString());
        }
        private void UpdateLocalDefinitions()
        {
            var startupFolder = _appFolderInfo.AppDataFolder;

            var request  = new HttpRequest($"https://indexers.prowlarr.com/{DEFINITION_BRANCH}/{DEFINITION_VERSION}");
            var response = _httpClient.Get <List <CardigannMetaDefinition> >(request);

            var currentDefs = _versionService.All().ToDictionary(x => x.DefinitionId, x => x.Sha);

            try
            {
                EnsureDefinitionsFolder();

                foreach (var def in response.Resource)
                {
                    try
                    {
                        var saveFile = Path.Combine(startupFolder, "Definitions", $"{def.File}.yml");

                        if (currentDefs.TryGetValue(def.Id, out var defSha) && defSha == def.Sha)
                        {
                            _logger.Trace("Indexer already up to date: {0}", def.File);

                            continue;
                        }

                        _httpClient.DownloadFile($"https://indexers.prowlarr.com/{DEFINITION_BRANCH}/{DEFINITION_VERSION}/{def.File}", saveFile);

                        _versionService.Upsert(new IndexerDefinitionVersion {
                            Sha = def.Sha, DefinitionId = def.Id, File = def.File, LastUpdated = DateTime.UtcNow
                        });

                        _cache.Remove(def.File);
                        _logger.Debug("Updated definition: {0}", def.File);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error("Definition download failed: {0}, {1}", def.File, ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Definition download failed, error creating definitions folder in {0}", startupFolder);
            }
        }
Beispiel #26
0
        private void PerformHealthCheck(IProvideHealthCheck[] healthChecks)
        {
            var results = healthChecks.Select(c => c.Check())
                          .ToList();

            foreach (var result in results)
            {
                if (result.Type == HealthCheckResult.Ok)
                {
                    _healthCheckResults.Remove(result.Source.Name);
                }

                else
                {
                    _healthCheckResults.Set(result.Source.Name, result);
                }
            }

            _eventAggregator.PublishEvent(new HealthCheckCompleteEvent());
        }
Beispiel #27
0
        private void AuthenticateClient(HttpRequestBuilder requestBuilder, TransmissionSettings settings, bool reauthenticate = false)
        {
            var authKey = string.Format("{0}:{1}", requestBuilder.BaseUrl, settings.Password);

            var sessionId = _authSessionIDCache.Find(authKey);

            if (sessionId == null || reauthenticate)
            {
                _authSessionIDCache.Remove(authKey);

                var authLoginRequest = BuildRequest(settings).Build();
                authLoginRequest.SuppressHttpError = true;

                var response = _httpClient.Execute(authLoginRequest);
                if (response.StatusCode == HttpStatusCode.MovedPermanently)
                {
                    var url = response.Headers.GetSingleValue("Location");

                    throw new DownloadClientException("Remote site redirected to " + url);
                }
                else if (response.StatusCode == HttpStatusCode.Conflict)
                {
                    sessionId = response.Headers.GetSingleValue("X-Transmission-Session-Id");

                    if (sessionId == null)
                    {
                        throw new DownloadClientException("Remote host did not return a Session Id.");
                    }
                }
                else
                {
                    throw new DownloadClientAuthenticationException("Failed to authenticate with Transmission.");
                }

                _logger.Debug("Transmission authentication succeeded.");

                _authSessionIDCache.Set(authKey, sessionId);
            }

            requestBuilder.SetHeader("X-Transmission-Session-Id", sessionId);
        }
Beispiel #28
0
        private DiskStationResponse <T> ProcessRequest <T>(HttpRequestBuilder requestBuilder,
                                                           string operation,
                                                           DiskStationApi api,
                                                           DownloadStationSettings settings) where T : new()
        {
            var request  = requestBuilder.Build();
            var response = _httpClient.Execute(request);

            _logger.Debug("Trying to {0}", operation);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var responseContent = Json.Deserialize <DiskStationResponse <T> >(response.Content);

                if (responseContent.Success)
                {
                    return(responseContent);
                }
                else
                {
                    var msg = $"Failed to {operation}. Reason: {responseContent.Error.GetMessage(api)}";
                    _logger.Error(msg);

                    if (responseContent.Error.SessionError)
                    {
                        _sessionCache.Remove(GenerateSessionCacheKey(settings));

                        if (responseContent.Error.Code == 105)
                        {
                            throw new DownloadClientAuthenticationException(msg);
                        }
                    }

                    throw new DownloadClientException(msg);
                }
            }
            else
            {
                throw new HttpException(request, response);
            }
        }
Beispiel #29
0
        private void AuthenticateClient(HttpRequestBuilder requestBuilder, NzbVortexSettings settings, bool reauthenticate = false)
        {
            var authKey = string.Format("{0}:{1}", requestBuilder.BaseUrl, settings.ApiKey);

            var sessionId = _authSessionIdCache.Find(authKey);

            if (sessionId == null || reauthenticate)
            {
                _authSessionIdCache.Remove(authKey);

                var nonceRequest  = BuildRequest(settings).Resource("auth/nonce").Build();
                var nonceResponse = _httpClient.Execute(nonceRequest);

                var nonce = Json.Deserialize <NzbVortexAuthNonceResponse>(nonceResponse.Content).AuthNonce;

                var cnonce = Guid.NewGuid().ToString();

                var hashString = string.Format("{0}:{1}:{2}", nonce, cnonce, settings.ApiKey);
                var hash       = Convert.ToBase64String(hashString.SHA256Hash().HexToByteArray());

                var authRequest = BuildRequest(settings).Resource("auth/login")
                                  .AddQueryParam("nonce", nonce)
                                  .AddQueryParam("cnonce", cnonce)
                                  .AddQueryParam("hash", hash)
                                  .Build();
                var authResponse = _httpClient.Execute(authRequest);
                var authResult   = Json.Deserialize <NzbVortexAuthResponse>(authResponse.Content);

                if (authResult.LoginResult == NzbVortexLoginResultType.Failed)
                {
                    throw new NzbVortexAuthenticationException("Authentication failed, check your API Key");
                }

                sessionId = authResult.SessionId;

                _authSessionIdCache.Set(authKey, sessionId);
            }

            requestBuilder.AddQueryParam("sessionid", sessionId);
        }
Beispiel #30
0
        private HttpResponse HandleRequest(HttpRequest request, FloodSettings settings)
        {
            try
            {
                return(_httpClient.Execute(request));
            }
            catch (HttpException ex)
            {
                if (ex.Response.StatusCode == HttpStatusCode.Forbidden ||
                    ex.Response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    _authCookieCache.Remove(BuildCachedCookieKey(settings));
                    throw new DownloadClientAuthenticationException("Failed to authenticate with Flood.");
                }

                throw new DownloadClientException("Unable to connect to Flood, please check your settings");
            }
            catch
            {
                throw new DownloadClientException("Unable to connect to Flood, please check your settings");
            }
        }