Esempio n. 1
0
        public ICached <T> GetCache <T>(Type host, string name)
        {
            Ensure.That(host, () => host).IsNotNull();
            Ensure.That(name, () => name).IsNotNullOrWhiteSpace();

            return((ICached <T>)_cache.Get(host.FullName + "_" + name, () => new Cached <T>()));
        }
Esempio n. 2
0
        public void UpdateLibrary(Series series, PlexServerSettings settings)
        {
            try
            {
                _logger.Debug("Sending Update Request to Plex Server");

                var version = _versionCache.Get(settings.Host, () => GetVersion(settings), TimeSpan.FromHours(2));
                ValidateVersion(version);

                var sections       = GetSections(settings);
                var partialUpdates = _partialUpdateCache.Get(settings.Host, () => PartialUpdatesAllowed(settings, version), TimeSpan.FromHours(2));

                if (partialUpdates)
                {
                    UpdatePartialSection(series, sections, settings);
                }

                else
                {
                    sections.ForEach(s => UpdateSection(s.Id, settings));
                }
            }

            catch (Exception ex)
            {
                _logger.Warn(ex, "Failed to Update Plex host: " + settings.Host);
                throw;
            }
        }
Esempio n. 3
0
        public void GetStringFromRedis()
        {
            string result = cacheClient.Get("kitchen:test");

            Assert.IsTrue(!string.IsNullOrEmpty(result));
            Console.WriteLine(result);
        }
Esempio n. 4
0
        private CookieContainer PrepareRequestCookies(HttpRequest request)
        {
            lock (_cookieContainerCache)
            {
                var persistentCookieContainer = _cookieContainerCache.Get("container", () => new CookieContainer());

                if (request.Cookies.Count != 0)
                {
                    foreach (var pair in request.Cookies)
                    {
                        persistentCookieContainer.Add(new Cookie(pair.Key, pair.Value, "/", request.Url.Host)
                        {
                            // Use Now rather than UtcNow to work around Mono cookie expiry bug.
                            // See https://gist.github.com/ta264/7822b1424f72e5b4c961
                            Expires = DateTime.Now.AddHours(1)
                        });
                    }
                }

                var requestCookies = persistentCookieContainer.GetCookies((Uri)request.Url);

                var cookieContainer = new CookieContainer();

                cookieContainer.Add(requestCookies);

                return(cookieContainer);
            }
        }
Esempio n. 5
0
        private void PrepareRequestCookies(HttpRequest request, HttpWebRequest webRequest)
        {
            lock (_cookieContainerCache)
            {
                var persistentCookieContainer = _cookieContainerCache.Get("container", () => new CookieContainer());

                if (request.Cookies.Count != 0)
                {
                    foreach (var pair in request.Cookies)
                    {
                        persistentCookieContainer.Add(new Cookie(pair.Key, pair.Value, "/", request.Url.Host)
                        {
                            Expires = DateTime.UtcNow.AddHours(1)
                        });
                    }
                }

                var requestCookies = persistentCookieContainer.GetCookies(request.Url);

                if (requestCookies.Count == 0 && !request.StoreResponseCookie)
                {
                    return;
                }

                if (webRequest.CookieContainer == null)
                {
                    webRequest.CookieContainer = new CookieContainer();
                }

                webRequest.CookieContainer.Add(requestCookies);
            }
        }
        private HttpRequestBuilder BuildRequest(DownloadStationSettings settings, DiskStationApiInfo apiInfo, string methodName, int apiVersion, HttpMethod httpVerb = null)
        {
            httpVerb ??= HttpMethod.Get;

            var requestBuilder = new HttpRequestBuilder(settings.UseSsl, settings.Host, settings.Port).Resource($"webapi/{apiInfo.Path}");

            requestBuilder.Method              = httpVerb;
            requestBuilder.LogResponseContent  = true;
            requestBuilder.SuppressHttpError   = true;
            requestBuilder.AllowAutoRedirect   = false;
            requestBuilder.Headers.ContentType = "application/json";

            if (apiVersion < apiInfo.MinVersion || apiVersion > apiInfo.MaxVersion)
            {
                throw new ArgumentOutOfRangeException(nameof(apiVersion));
            }

            if (httpVerb == HttpMethod.Post)
            {
                if (apiInfo.NeedsAuthentication)
                {
                    if (_apiType == DiskStationApi.DownloadStation2Task)
                    {
                        requestBuilder.AddQueryParam("_sid", _sessionCache.Get(GenerateSessionCacheKey(settings), () => AuthenticateClient(settings), TimeSpan.FromHours(6)));
                    }
                    else
                    {
                        requestBuilder.AddFormParameter("_sid", _sessionCache.Get(GenerateSessionCacheKey(settings), () => AuthenticateClient(settings), TimeSpan.FromHours(6)));
                    }
                }

                requestBuilder.AddFormParameter("api", apiInfo.Name);
                requestBuilder.AddFormParameter("version", apiVersion);
                requestBuilder.AddFormParameter("method", methodName);
            }
            else
            {
                if (apiInfo.NeedsAuthentication)
                {
                    requestBuilder.AddQueryParam("_sid", _sessionCache.Get(GenerateSessionCacheKey(settings), () => AuthenticateClient(settings), TimeSpan.FromHours(6)));
                }

                requestBuilder.AddQueryParam("api", apiInfo.Name);
                requestBuilder.AddQueryParam("version", apiVersion);
                requestBuilder.AddQueryParam("method", methodName);
            }

            return(requestBuilder);
        }
Esempio n. 7
0
        private CookieContainer InitializeRequestCookies(HttpRequest request)
        {
            lock (_cookieContainerCache)
            {
                var sourceContainer = new CookieContainer();

                var presistentContainer = _cookieContainerCache.Get("container", () => new CookieContainer());

                if (!request.IgnorePersistentCookies)
                {
                    var persistentCookies = presistentContainer.GetCookies((Uri)request.Url);
                    sourceContainer.Add(persistentCookies);
                }

                if (request.Cookies.Count != 0)
                {
                    foreach (var pair in request.Cookies)
                    {
                        Cookie cookie;
                        if (pair.Value == null)
                        {
                            cookie = new Cookie(pair.Key, "", "/")
                            {
                                Expires = DateTime.Now.AddDays(-1)
                            };
                        }
                        else
                        {
                            cookie = new Cookie(pair.Key, pair.Value, "/")
                            {
                                // Use Now rather than UtcNow to work around Mono cookie expiry bug.
                                // See https://gist.github.com/ta264/7822b1424f72e5b4c961
                                Expires = DateTime.Now.AddHours(1)
                            };
                        }

                        sourceContainer.Add((Uri)request.Url, cookie);

                        if (request.StoreRequestCookie)
                        {
                            presistentContainer.Add((Uri)request.Url, cookie);
                        }
                    }
                }

                return(sourceContainer);
            }
        }
Esempio n. 8
0
        public virtual Decision IsSatisfiedBy(RemoteAlbum subject, SearchCriteriaBase searchCriteria)
        {
            foreach (var album in subject.Albums)
            {
                var tracksMissing = _missingFilesCache.Get(album.Id.ToString(),
                                                           () => _trackService.TracksWithoutFiles(album.Id).Any(),
                                                           TimeSpan.FromSeconds(30));
                var trackFiles = _mediaFileService.GetFilesByAlbum(album.Id);

                if (!tracksMissing && trackFiles.Any())
                {
                    var currentQualities = trackFiles.Select(c => c.Quality).Distinct().ToList();

                    if (!_upgradableSpecification.IsUpgradable(subject.Artist.QualityProfile,
                                                               currentQualities,
                                                               _preferredWordServiceCalculator.Calculate(subject.Artist, trackFiles[0].GetSceneOrFileName(), subject.Release?.IndexerId ?? 0),
                                                               subject.ParsedAlbumInfo.Quality,
                                                               subject.PreferredWordScore))
                    {
                        return(Decision.Reject("Existing files on disk is of equal or higher preference: {0}", currentQualities.ConcatToString()));
                    }
                }
            }

            return(Decision.Accept());
        }
Esempio n. 9
0
 public List <CounterPartyGroupModel> getListCounterPartyGroup()
 {
     try
     {
         var rsCache = _cached.Get <List <CounterPartyGroupModel> >(CachedKey.counterPartyGroupList);
         if (rsCache != null)
         {
             return((List <CounterPartyGroupModel>)rsCache);
         }
         else
         {
             SqlParameter[] prms = new SqlParameter[]
             {
                 new SqlParameter {
                     ParameterName = "resultMessage", DbType = DbType.String, Direction = ParameterDirection.Output, Size = Int32.MaxValue
                 },
                 new SqlParameter {
                     ParameterName = "resultCode", DbType = DbType.Int32, Direction = ParameterDirection.Output, Size = Int32.MaxValue
                 }
             };
             var result       = _Repository.ExecWithStoreProcedureCommand(Store_GetList, prms);
             var resultObject = JsonConvert.DeserializeObject <List <CounterPartyGroupModel> >(result.errorMessage);
             _cached.Set(CacheModeEnum.Add, CachedKey.counterPartyGroupList, resultObject, new TimeSpan(1, 0, 0, 0));
             return(resultObject);
         }
     }
     catch (Exception ex)
     {
         HDBH.Log.WriteLog.Error("CounterPartyService => getListCounterPartyGroup", ex);
         return(null);
     }
 }
Esempio n. 10
0
        public bool RequiresEpisodeTitle(Series series, List <Episode> episodes)
        {
            var namingConfig = _namingConfigService.GetConfig();
            var pattern      = namingConfig.StandardEpisodeFormat;

            if (series.SeriesType == SeriesTypes.Daily)
            {
                pattern = namingConfig.DailyEpisodeFormat;
            }

            if (series.SeriesType == SeriesTypes.Anime && episodes.All(e => e.AbsoluteEpisodeNumber.HasValue))
            {
                pattern = namingConfig.AnimeEpisodeFormat;
            }

            return(_requiresEpisodeTitleCache.Get(pattern, () =>
            {
                var matches = TitleRegex.Matches(pattern);

                foreach (Match match in matches)
                {
                    var token = match.Groups["token"].Value;

                    if (FileNameBuilderTokenEqualityComparer.Instance.Equals(token, "{Episode Title}") ||
                        FileNameBuilderTokenEqualityComparer.Instance.Equals(token, "{Episode CleanTitle}"))
                    {
                        return true;
                    }
                }

                return false;
            }));
        }
Esempio n. 11
0
        public string GetValue(string key, object defaultValue, bool persist = true)
        {
            return(_cache.Get(key, () =>
            {
                var xDoc = LoadConfigFile();
                var config = xDoc.Descendants(CONFIG_ELEMENT_NAME).Single();

                var parentContainer = config;

                var valueHolder = parentContainer.Descendants(key).ToList();

                if (valueHolder.Count() == 1)
                {
                    return valueHolder.First().Value.Trim();
                }

                //Save the value
                if (persist)
                {
                    SetValue(key, defaultValue);
                }

                //return the default value
                return defaultValue.ToString();
            }));
        }
        public virtual Decision IsSatisfiedBy(RemoteAlbum subject, SearchCriteriaBase searchCriteria)
        {
            var qualityProfile = subject.Artist.QualityProfile.Value;

            foreach (var album in subject.Albums)
            {
                var tracksMissing = _missingFilesCache.Get(album.Id.ToString(),
                                                           () => _trackService.TracksWithoutFiles(album.Id).Any(),
                                                           TimeSpan.FromSeconds(30));

                var trackFiles = _mediaFileService.GetFilesByAlbum(album.Id);

                if (!tracksMissing && trackFiles.Any())
                {
                    // Get a distinct list of all current track qualities for a given album
                    var currentQualities = trackFiles.Select(c => c.Quality).Distinct().ToList();

                    _logger.Debug("Comparing file quality with report. Existing files contain {0}", currentQualities.ConcatToString());

                    if (!_upgradableSpecification.IsUpgradeAllowed(qualityProfile,
                                                                   currentQualities,
                                                                   subject.ParsedAlbumInfo.Quality))
                    {
                        _logger.Debug("Upgrading is not allowed by the quality profile");

                        return(Decision.Reject("Existing files and the Quality profile does not allow upgrades"));
                    }
                }
            }

            return(Decision.Accept());
        }
        public NewznabCapabilities GetCapabilities(NewznabSettings indexerSettings)
        {
            var key          = indexerSettings.ToJson();
            var capabilities = _capabilitiesCache.Get(key, () => FetchCapabilities(indexerSettings), TimeSpan.FromDays(7));

            return(capabilities);
        }
Esempio n. 14
0
        public TorrentSeedConfiguration GetSeedConfiguration(int indexerId)
        {
            if (indexerId == 0)
            {
                return(null);
            }

            var seedCriteria = _cache.Get(indexerId.ToString(), () => FetchSeedCriteria(indexerId));

            if (seedCriteria == null)
            {
                return(null);
            }

            var seedConfig = new TorrentSeedConfiguration
            {
                Ratio = seedCriteria.SeedRatio
            };

            var seedTime = seedCriteria.SeedTime;

            if (seedTime.HasValue)
            {
                seedConfig.SeedTime = TimeSpan.FromMinutes(seedTime.Value);
            }

            return(seedConfig);
        }
Esempio n. 15
0
        public void UpdateLibrary(Series series, PlexServerSettings settings)
        {
            try
            {
                _logger.Debug("Sending Update Request to Plex Server");

                var sections = GetSections(settings);

                //TODO: How long should we cache this for?
                var partialUpdates = _partialUpdateCache.Get(settings.Host, () => PartialUpdatesAllowed(settings), TimeSpan.FromHours(2));

                if (partialUpdates)
                {
                    sections.ForEach(s => UpdateSeries(s.Id, series, s.Language, settings));
                }

                else
                {
                    sections.ForEach(s => UpdateSection(s.Id, settings));
                }
            }

            catch (Exception ex)
            {
                _logger.WarnException("Failed to Update Plex host: " + settings.Host, ex);
                throw;
            }
        }
Esempio n. 16
0
        public IndexerCapabilities GetCapabilities(NewznabSettings indexerSettings, ProviderDefinition definition)
        {
            var key          = indexerSettings.ToJson();
            var capabilities = _capabilitiesCache.Get(key, () => FetchCapabilities(indexerSettings, definition), TimeSpan.FromDays(7));

            return(capabilities);
        }
Esempio n. 17
0
        public IEnumerable <QueueItem> GetQueue()
        {
            return(_queueCache.Get("queue", () =>
            {
                string action = String.Format("mode=queue&output=json&start={0}&limit={1}", 0, 0);
                string request = GetSabRequest(action);
                string response = _httpProvider.DownloadString(request);

                CheckForError(response);

                var sabQueue = Json.Deserialize <SabQueue>(JObject.Parse(response).SelectToken("queue").ToString()).Items;

                var queueItems = new List <QueueItem>();

                foreach (var sabQueueItem in sabQueue)
                {
                    var queueItem = new QueueItem();
                    queueItem.Id = sabQueueItem.Id;
                    queueItem.Title = sabQueueItem.Title;
                    queueItem.Size = sabQueueItem.Size;
                    queueItem.SizeLeft = sabQueueItem.Size;

                    queueItems.Add(queueItem);
                }

                return queueItems;
            }, TimeSpan.FromSeconds(10)));
        }
Esempio n. 18
0
        private SonarrIndexer BuildSonarrIndexer(IndexerDefinition indexer, DownloadProtocol protocol, int id = 0)
        {
            var cacheKey = $"{Settings.BaseUrl}";
            var schemas  = _schemaCache.Get(cacheKey, () => _sonarrV3Proxy.GetIndexerSchema(Settings), TimeSpan.FromDays(7));

            var newznab = schemas.Where(i => i.Implementation == "Newznab").First();
            var torznab = schemas.Where(i => i.Implementation == "Torznab").First();

            var schema = protocol == DownloadProtocol.Usenet ? newznab : torznab;

            var sonarrIndexer = new SonarrIndexer
            {
                Id                      = id,
                Name                    = $"{indexer.Name} (Prowlarr)",
                EnableRss               = indexer.Enable && indexer.AppProfile.Value.EnableRss,
                EnableAutomaticSearch   = indexer.Enable && indexer.AppProfile.Value.EnableAutomaticSearch,
                EnableInteractiveSearch = indexer.Enable && indexer.AppProfile.Value.EnableInteractiveSearch,
                Priority                = indexer.Priority,
                Implementation          = indexer.Protocol == DownloadProtocol.Usenet ? "Newznab" : "Torznab",
                ConfigContract          = schema.ConfigContract,
                Fields                  = schema.Fields,
            };

            sonarrIndexer.Fields.FirstOrDefault(x => x.Name == "baseUrl").Value         = $"{Settings.ProwlarrUrl.TrimEnd('/')}/{indexer.Id}/";
            sonarrIndexer.Fields.FirstOrDefault(x => x.Name == "apiPath").Value         = "/api";
            sonarrIndexer.Fields.FirstOrDefault(x => x.Name == "apiKey").Value          = _configFileProvider.ApiKey;
            sonarrIndexer.Fields.FirstOrDefault(x => x.Name == "categories").Value      = JArray.FromObject(indexer.Capabilities.Categories.SupportedCategories(Settings.SyncCategories.ToArray()));
            sonarrIndexer.Fields.FirstOrDefault(x => x.Name == "animeCategories").Value = JArray.FromObject(indexer.Capabilities.Categories.SupportedCategories(Settings.AnimeSyncCategories.ToArray()));

            return(sonarrIndexer);
        }
Esempio n. 19
0
        public virtual Decision IsSatisfiedBy(RemoteAlbum subject, SearchCriteriaBase searchCriteria)
        {
            var qualityProfile = subject.Artist.QualityProfile.Value;

            foreach (var album in subject.Albums)
            {
                var tracksMissing = _missingFilesCache.Get(album.Id.ToString(), () => _trackService.TracksWithoutFiles(album.Id).Any(),
                                                           TimeSpan.FromSeconds(30));
                var trackFiles = _mediaFileService.GetFilesByAlbum(album.Id);

                if (!tracksMissing && trackFiles.Any())
                {
                    // Get a distinct list of all current track qualities for a given album
                    var currentQualities = trackFiles.Select(c => c.Quality).Distinct().ToList();

                    _logger.Debug("Comparing file quality with report. Existing files contain {0}", currentQualities.ConcatToString());

                    if (!_upgradableSpecification.CutoffNotMet(qualityProfile,
                                                               currentQualities,
                                                               _preferredWordServiceCalculator.Calculate(subject.Artist, trackFiles[0].GetSceneOrFileName()),
                                                               subject.ParsedAlbumInfo.Quality,
                                                               subject.PreferredWordScore))
                    {
                        _logger.Debug("Cutoff already met by existing files, rejecting.");

                        var qualityCutoffIndex = qualityProfile.GetIndex(qualityProfile.Cutoff);
                        var qualityCutoff      = qualityProfile.Items[qualityCutoffIndex.Index];

                        return(Decision.Reject("Existing files meets cutoff: {0}", qualityCutoff));
                    }
                }
            }

            return(Decision.Accept());
        }
Esempio n. 20
0
        private XbmcVersion GetJsonVersion(XbmcSettings settings)
        {
            try
            {
                return(_xbmcVersionCache.Get(settings.Address, () =>
                {
                    var response = _proxy.GetJsonVersion(settings);

                    _logger.Debug("Getting version from response: " + response);
                    var result = Json.Deserialize <XbmcJsonResult <JObject> >(response);

                    var versionObject = result.Result.Property("version");

                    if (versionObject.Value.Type == JTokenType.Integer)
                    {
                        return new XbmcVersion((int)versionObject.Value);
                    }

                    if (versionObject.Value.Type == JTokenType.Object)
                    {
                        return Json.Deserialize <XbmcVersion>(versionObject.Value.ToString());
                    }

                    throw new InvalidCastException("Unknown Version structure!: " + versionObject);
                }, TimeSpan.FromHours(12)));
            }

            catch (Exception ex)
            {
                _logger.DebugException(ex.Message, ex);
            }

            return(new XbmcVersion());
        }
Esempio n. 21
0
        public IWebProxy GetWebProxy(HttpProxySettings proxySettings)
        {
            var proxy = _webProxyCache.Get(proxySettings.Key, () => CreateWebProxy(proxySettings), TimeSpan.FromMinutes(5));

            _webProxyCache.ClearExpired();

            return(proxy);
        }
Esempio n. 22
0
        protected virtual System.Net.Http.HttpClient GetClient(HttpUri uri)
        {
            var proxySettings = _proxySettingsProvider.GetProxySettings(uri);

            var key = proxySettings?.Key ?? NO_PROXY_KEY;

            return(_httpClientCache.Get(key, () => CreateHttpClient(proxySettings)));
        }
Esempio n. 23
0
 public static object Get(string key)
 {
     if (string.IsNullOrEmpty(key))
     {
         throw new ArgumentNullException("key");
     }
     return(_cache.Get(key));
 }
Esempio n. 24
0
 private AbsoluteEpisodeFormat[] GetAbsoluteFormat(string pattern)
 {
     return(_absoluteEpisodeFormatCache.Get(pattern, () => AbsoluteEpisodePatternRegex.Matches(pattern).OfType <Match>()
                                            .Select(match => new AbsoluteEpisodeFormat
     {
         Separator = match.Groups["separator"].Value.IsNotNullOrWhiteSpace() ? match.Groups["separator"].Value : "-",
         AbsoluteEpisodePattern = match.Groups["absolute"].Value
     }).ToArray()));
 }
Esempio n. 25
0
        public static V_xy_sp_userView GetUserViewFromCache(string tokenValue)
        {
            V_tm_pm_userinfo userInfo = _cached.Get(tokenValue) as V_tm_pm_userinfo;

            if (userInfo == null)
            {
                userInfo = new tm_pm_userinfoBLL().GetLoginInfo(tokenValue);
            }

            V_xy_sp_userView userView = (V_xy_sp_userView)_cached.Get(tokenValue + "V_xy_sp_userView");

            if (userView == null)
            {
                userView = new xy_sp_userspiritBLL().GetCurrentUserStatebyUserID(userInfo.USERID);
                cacheuserView(tokenValue + "V_xy_sp_userView", userView);
            }
            return(userView);
        }
Esempio n. 26
0
 private Dictionary <int, CustomFormat> AllDictionary()
 {
     return(_cache.Get("all", () =>
     {
         var all = _formatRepository.All().ToDictionary(m => m.Id);
         AllCustomFormats = all;
         return all;
     }));
 }
Esempio n. 27
0
        /// <summary>
        /// 根据令牌获取用户登录信息(没有则返回null)
        /// </summary>
        /// <param name="tokenValue">令牌</param>
        /// <returns></returns>
        public UserInfo GetLoginInfo(string tokenValue)
        {
            if (string.IsNullOrEmpty(tokenValue))
            {
                return(null);
            }
            UserInfo userInfo = _cached.Get(tokenValue) as UserInfo;

            return(userInfo);
        }
Esempio n. 28
0
        /// <summary>
        /// 根据令牌获取用户登录信息(没有则返回null)
        /// </summary>
        /// <param name="tokenValue">令牌</param>
        /// <returns></returns>
        public V_ctms_sys_userinfo GetLoginInfo(string tokenValue)
        {
            if (string.IsNullOrEmpty(tokenValue))
            {
                return(null);
            }
            V_ctms_sys_userinfo userInfo = _cached.Get(tokenValue) as V_ctms_sys_userinfo;

            return(userInfo);
        }
Esempio n. 29
0
 private TrackFormat[] GetTrackFormat(string pattern)
 {
     return(_trackFormatCache.Get(pattern, () => SeasonEpisodePatternRegex.Matches(pattern).OfType <Match>()
                                  .Select(match => new TrackFormat
     {
         TrackSeparator = match.Groups["episodeSeparator"].Value,
         Separator = match.Groups["separator"].Value,
         TrackPattern = match.Groups["episode"].Value,
     }).ToArray()));
 }
Esempio n. 30
0
        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)));
        }