Example #1
0
        public override string Download(RemoteEpisode remoteEpisode)
        {
            var url      = remoteEpisode.Release.DownloadUrl;
            var filename = FileNameBuilder.CleanFileName(remoteEpisode.Release.Title) + ".nzb";

            byte[] nzbData;

            try
            {
                nzbData = _httpClient.Get(new HttpRequest(url)).ResponseData;

                _logger.Debug("Downloaded nzb for episode '{0}' finished ({1} bytes from {2})", remoteEpisode.Release.Title, nzbData.Length, url);
            }
            catch (HttpException ex)
            {
                if (ex.Response.StatusCode == HttpStatusCode.NotFound)
                {
                    _logger.Error(ex, "Downloading nzb file for episode '{0}' failed since it no longer exists ({1})", remoteEpisode.Release.Title, url);
                    throw new ReleaseUnavailableException(remoteEpisode.Release, "Downloading torrent failed", ex);
                }

                if ((int)ex.Response.StatusCode == 429)
                {
                    _logger.Error("API Grab Limit reached for {0}", url);
                }
                else
                {
                    _logger.Error(ex, "Downloading nzb for episode '{0}' failed ({1})", remoteEpisode.Release.Title, url);
                }

                throw new ReleaseDownloadException(remoteEpisode.Release, "Downloading nzb failed", ex);
            }
            catch (WebException ex)
            {
                _logger.Error(ex, "Downloading nzb for episode '{0}' failed ({1})", remoteEpisode.Release.Title, url);

                throw new ReleaseDownloadException(remoteEpisode.Release, "Downloading nzb failed", ex);
            }

            _logger.Info("Adding report [{0}] to the queue.", remoteEpisode.Release.Title);
            return(AddFromNzbFile(remoteEpisode, filename, nzbData));
        }
        public void Setup()
        {
            _pass1 = new Mock <IDecisionEngineSpecification>();
            _pass2 = new Mock <IDecisionEngineSpecification>();
            _pass3 = new Mock <IDecisionEngineSpecification>();

            _fail1 = new Mock <IDecisionEngineSpecification>();
            _fail2 = new Mock <IDecisionEngineSpecification>();
            _fail3 = new Mock <IDecisionEngineSpecification>();

            _pass1.Setup(c => c.IsSatisfiedBy(It.IsAny <RemoteEpisode>(), null)).Returns(true);
            _pass1.Setup(c => c.RejectionReason).Returns("_pass1");

            _pass2.Setup(c => c.IsSatisfiedBy(It.IsAny <RemoteEpisode>(), null)).Returns(true);
            _pass2.Setup(c => c.RejectionReason).Returns("_pass2");

            _pass3.Setup(c => c.IsSatisfiedBy(It.IsAny <RemoteEpisode>(), null)).Returns(true);
            _pass3.Setup(c => c.RejectionReason).Returns("_pass3");


            _fail1.Setup(c => c.IsSatisfiedBy(It.IsAny <RemoteEpisode>(), null)).Returns(false);
            _fail1.Setup(c => c.RejectionReason).Returns("_fail1");

            _fail2.Setup(c => c.IsSatisfiedBy(It.IsAny <RemoteEpisode>(), null)).Returns(false);
            _fail2.Setup(c => c.RejectionReason).Returns("_fail2");

            _fail3.Setup(c => c.IsSatisfiedBy(It.IsAny <RemoteEpisode>(), null)).Returns(false);
            _fail3.Setup(c => c.RejectionReason).Returns("_fail3");

            _reports = new List <ReleaseInfo> {
                new ReleaseInfo {
                    Title = "The.Office.S03E115.DVDRip.XviD-OSiTV"
                }
            };
            _remoteEpisode = new RemoteEpisode {
                Series = new Series()
            };

            Mocker.GetMock <IParsingService>()
            .Setup(c => c.Map(It.IsAny <ParsedEpisodeInfo>(), It.IsAny <int>(), It.IsAny <SearchCriteriaBase>()))
            .Returns(_remoteEpisode);
        }
Example #3
0
        public override string DownloadNzb(RemoteEpisode remoteEpisode)
        {
            var url      = remoteEpisode.Release.DownloadUrl;
            var title    = remoteEpisode.Release.Title;
            var category = Settings.TvCategory;
            var priority = remoteEpisode.IsRecentEpisode() ? Settings.RecentTvPriority : Settings.OlderTvPriority;

            using (var nzb = _httpProvider.DownloadStream(url))
            {
                _logger.Info("Adding report [{0}] to the queue.", title);
                var response = _proxy.DownloadNzb(nzb, title, category, priority, Settings);

                if (response != null && response.Ids.Any())
                {
                    return(response.Ids.First());
                }

                return(null);
            }
        }
        public bool IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCriteria)
        {
            var downloadClient = _downloadClientProvider.GetDownloadClient();

            if (downloadClient == null)
            {
                _logger.Warn("Download client isn't configured yet.");
                return(true);
            }

            var queue = downloadClient.GetQueue().Select(q => q.RemoteEpisode);

            if (IsInQueue(subject, queue))
            {
                _logger.Debug("Already in queue, rejecting.");
                return(false);
            }

            return(true);
        }
Example #5
0
        public virtual Decision IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCriteria)
        {
            foreach (var file in subject.Episodes.Where(c => c.EpisodeFileId != 0).Select(c => c.EpisodeFile.Value))
            {
                if (file == null)
                {
                    _logger.Debug("File is no longer available, skipping this file.");
                    continue;
                }

                _logger.Debug("Comparing file quality with report. Existing file is {0}", file.Quality);

                if (!_qualityUpgradableSpecification.IsUpgradable(subject.Series.Profile, file.Quality, subject.ParsedEpisodeInfo.Quality))
                {
                    return(Decision.Reject("Quality for existing file on disk is of equal or higher preference: {0}", file.Quality));
                }
            }

            return(Decision.Accept());
        }
Example #6
0
        public void Setup()
        {
            LanguageProfile _profile = new LazyLoaded <LanguageProfile> (new LanguageProfile
            {
                Languages = LanguageFixture.GetDefaultLanguages(Language.English, Language.Spanish),
                Cutoff    = Language.Spanish
            });

            _remoteEpisode = new RemoteEpisode
            {
                ParsedEpisodeInfo = new ParsedEpisodeInfo
                {
                    Language = Language.English
                },
                Series = new Series
                {
                    LanguageProfile = _profile
                }
            };
        }
Example #7
0
        public virtual Decision IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCriteria)
        {
            if (subject.Release.DownloadProtocol != Indexers.DownloadProtocol.Usenet)
            {
                _logger.Debug("Not checking retention requirement for non-usenet report");
                return(Decision.Accept());
            }

            var age       = subject.Release.Age;
            var retention = _configService.Retention;

            _logger.Debug("Checking if report meets retention requirements. {0}", age);
            if (retention > 0 && age > retention)
            {
                _logger.Debug("Report age: {0} rejected by user's retention limit", age);
                return(Decision.Reject("Older than configured retention"));
            }

            return(Decision.Accept());
        }
        private bool IsInQueue(RemoteEpisode newEpisode, IEnumerable <ParsedEpisodeInfo> queue)
        {
            var matchingTitle = queue.Where(q => String.Equals(q.SeriesTitle, newEpisode.Series.CleanTitle, StringComparison.InvariantCultureIgnoreCase));

            var matchingTitleWithQuality = matchingTitle.Where(q => q.Quality >= newEpisode.ParsedEpisodeInfo.Quality);

            if (newEpisode.Series.SeriesType == SeriesTypes.Daily)
            {
                return(matchingTitleWithQuality.Any(q => q.AirDate.Value.Date == newEpisode.ParsedEpisodeInfo.AirDate.Value.Date));
            }

            var matchingSeason = matchingTitleWithQuality.Where(q => q.SeasonNumber == newEpisode.ParsedEpisodeInfo.SeasonNumber);

            if (newEpisode.ParsedEpisodeInfo.FullSeason)
            {
                return(matchingSeason.Any());
            }

            return(matchingSeason.Any(q => q.EpisodeNumbers != null && q.EpisodeNumbers.Any(e => newEpisode.ParsedEpisodeInfo.EpisodeNumbers.Contains(e))));
        }
        protected override string AddFromTorrentFile(RemoteEpisode remoteEpisode, string hash, string filename, byte[] fileContent)
        {
            var hashedSerialNumber = _serialNumberProvider.GetSerialNumber(Settings);

            _dsTaskProxy.AddTaskFromData(fileContent, filename, GetDownloadDirectory(), Settings);

            var items = GetTasks().Where(t => t.Additional.Detail["uri"] == Path.GetFileNameWithoutExtension(filename));

            var item = items.SingleOrDefault();

            if (item != null)
            {
                _logger.Debug("{0} added correctly", remoteEpisode);
                return(CreateDownloadId(item.Id, hashedSerialNumber));
            }

            _logger.Debug("No such task {0} in Download Station", filename);

            throw new DownloadClientException("Failed to add torrent task to Download Station");
        }
Example #10
0
        public RemoteEpisode Map(ParsedEpisodeInfo parsedEpisodeInfo, Int32 tvRageId, SearchCriteriaBase searchCriteria = null)
        {
            var remoteEpisode = new RemoteEpisode
            {
                ParsedEpisodeInfo = parsedEpisodeInfo,
            };

            var series = searchCriteria == null?GetSeries(parsedEpisodeInfo, tvRageId) :
                             GetSeries(parsedEpisodeInfo, tvRageId, searchCriteria);

            if (series == null)
            {
                return(remoteEpisode);
            }

            remoteEpisode.Series   = series;
            remoteEpisode.Episodes = GetEpisodes(parsedEpisodeInfo, series, true, searchCriteria);

            return(remoteEpisode);
        }
Example #11
0
        public bool IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCriteria)
        {
            if (!_configService.EnableFailedDownloadHandling)
            {
                _logger.Debug("Failed Download Handling is not enabled");
                return(true);
            }

            var history = _historyService.FindBySourceTitle(subject.Release.Title);

            if (history.Count(h => h.EventType == HistoryEventType.Grabbed &&
                              HasSamePublishedDate(h, subject.Release.PublishDate)) >
                _configService.BlacklistRetryLimit)
            {
                _logger.Debug("Release has been attempted more times than allowed, rejecting");
                return(false);
            }

            return(true);
        }
Example #12
0
        public void Setup()
        {
            Mocker.GetMock <IProvideDownloadClient>()
            .Setup(c => c.GetDownloadClient()).Returns(Mocker.GetMock <IDownloadClient>().Object);

            var episodes = Builder <Episode> .CreateListOfSize(2)
                           .TheFirst(1).With(s => s.Id = 12)
                           .TheNext(1).With(s => s.Id  = 99)
                           .All().With(s => s.SeriesId = 5)
                           .Build().ToList();

            _parseResult = Builder <RemoteEpisode> .CreateNew()
                           .With(c => c.Series   = Builder <Series> .CreateNew().Build())
                           .With(c => c.Release  = Builder <ReleaseInfo> .CreateNew().Build())
                           .With(c => c.Episodes = episodes)
                           .Build();


            Mocker.GetMock <IDownloadClient>().Setup(c => c.IsConfigured).Returns(true);
        }
        public virtual Decision IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCriteria)
        {
            if (searchCriteria != null)
            {
                if (!searchCriteria.MonitoredEpisodesOnly)
                {
                    _logger.Debug("Skipping monitored check during search");
                    return(Decision.Accept());
                }
            }

            if (!subject.Series.Monitored)
            {
                _logger.Debug("{0} is present in the DB but not tracked. Rejecting", subject.Series);
                return(Decision.Reject("Series is not monitored"));
            }

            var monitoredCount = subject.Episodes.Count(episode => episode.Monitored);

            if (monitoredCount == subject.Episodes.Count)
            {
                return(Decision.Accept());
            }

            if (subject.Episodes.Count == 1)
            {
                _logger.Debug("Episode is not monitored. Rejecting", monitoredCount, subject.Episodes.Count);
                return(Decision.Reject("Episode is not monitored"));
            }

            if (monitoredCount == 0)
            {
                _logger.Debug("No episodes in the release are monitored. Rejecting", monitoredCount, subject.Episodes.Count);
            }
            else
            {
                _logger.Debug("Only {0}/{1} episodes in the release are monitored. Rejecting", monitoredCount, subject.Episodes.Count);
            }

            return(Decision.Reject("One or more episodes is not monitored"));
        }
Example #14
0
        public virtual Decision IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCriteria)
        {
            foreach (var file in subject.Episodes.Where(c => c.EpisodeFileId != 0).Select(c => c.EpisodeFile.Value))
            {
                if (file == null)
                {
                    _logger.Debug("File is no longer available, skipping this file.");
                    continue;
                }

                _logger.Debug("Comparing file quality with report. Existing file is {0}", file.Quality);

                if (!_qualityUpgradableSpecification.CutoffNotMet(subject.Series.Profile, file.Quality, subject.ParsedEpisodeInfo.Quality))
                {
                    _logger.Debug("Cutoff already met, rejecting.");
                    return(Decision.Reject("Existing file meets cutoff: {0}", subject.Series.Profile.Value.Cutoff));
                }
            }

            return(Decision.Accept());
        }
Example #15
0
        protected override string AddFromMagnetLink(RemoteEpisode remoteEpisode, string hash, string magnetLink)
        {
            _proxy.AddTorrentFromUrl(magnetLink, Settings);

            if (Settings.TvCategory.IsNotNullOrWhiteSpace())
            {
                _proxy.SetTorrentLabel(hash.ToLower(), Settings.TvCategory, Settings);
            }

            var isRecentEpisode = remoteEpisode.IsRecentEpisode();

            if (isRecentEpisode && Settings.RecentTvPriority == (int)QBittorrentPriority.First ||
                !isRecentEpisode && Settings.OlderTvPriority == (int)QBittorrentPriority.First)
            {
                _proxy.MoveTorrentToTopInQueue(hash.ToLower(), Settings);
            }

            SetInitialState(hash.ToLower());

            return(hash);
        }
Example #16
0
        public override string Download(RemoteEpisode remoteEpisode)
        {
            var client      = CreateClient();
            var request     = new RestRequest("/api/addPackage", Method.POST);
            var urlArray    = new[] { remoteEpisode.Release.DownloadUrl };
            var packageName = remoteEpisode.Release.Title + "_" + DateTime.Now.ToFileTime();

            request.AddParameter("links", JsonConvert.SerializeObject(urlArray), ParameterType.GetOrPost);
            request.AddParameter("name", JsonConvert.SerializeObject(packageName), ParameterType.GetOrPost);
            var response = client.Execute(request);

            if (response.ResponseStatus != ResponseStatus.Completed)
            {
                throw new DownloadClientException("Error downloading file", response.ErrorException);
            }

            var downloadId = $"pyload_{packageName.GetHashCode()}_{response.Content}";

            _logger.Info($"DownloadId: {downloadId}");
            return(downloadId);
        }
        private Rejection EvaluateSpec(IDecisionEngineSpecification spec, RemoteEpisode remoteEpisode, SearchCriteriaBase searchCriteriaBase = null)
        {
            try
            {
                var result = spec.IsSatisfiedBy(remoteEpisode, searchCriteriaBase);

                if (!result.Accepted)
                {
                    return(new Rejection(result.Reason, spec.Type));
                }
            }
            catch (Exception e)
            {
                e.Data.Add("report", remoteEpisode.Release.ToJson());
                e.Data.Add("parsed", remoteEpisode.ParsedEpisodeInfo.ToJson());
                _logger.Error(e, "Couldn't evaluate decision on {0}", remoteEpisode.Release.Title);
                return(new Rejection($"{spec.GetType().Name}: {e.Message}"));
            }

            return(null);
        }
Example #18
0
        protected override string AddFromTorrentFile(RemoteEpisode remoteEpisode, string hash, string filename, byte[] fileContent)
        {
            var actualHash = _proxy.AddTorrentFromFile(filename, fileContent, Settings);

            if (!Settings.TvCategory.IsNullOrWhiteSpace())
            {
                _proxy.SetLabel(actualHash, Settings.TvCategory, Settings);
            }

            _proxy.SetTorrentConfiguration(actualHash, "remove_at_ratio", false, Settings);

            var isRecentEpisode = remoteEpisode.IsRecentEpisode();

            if (isRecentEpisode && Settings.RecentTvPriority == (int)DelugePriority.First ||
                !isRecentEpisode && Settings.OlderTvPriority == (int)DelugePriority.First)
            {
                _proxy.MoveTorrentToTopInQueue(actualHash, Settings);
            }

            return(actualHash.ToUpper());
        }
        private RemoteEpisode GetRemoteEpisode(List <Episode> episodes, QualityModel quality)
        {
            var remoteEpisode = new RemoteEpisode();

            remoteEpisode.ParsedEpisodeInfo         = new ParsedEpisodeInfo();
            remoteEpisode.ParsedEpisodeInfo.Quality = quality;

            remoteEpisode.Episodes = new List <Episode>();
            remoteEpisode.Episodes.AddRange(episodes);

            remoteEpisode.Release             = new ReleaseInfo();
            remoteEpisode.Release.PublishDate = DateTime.UtcNow;

            remoteEpisode.Series = Builder <Series> .CreateNew()
                                   .With(e => e.QualityProfile = new QualityProfile {
                Items = Qualities.QualityFixture.GetDefaultQualities()
            })
                                   .Build();

            return(remoteEpisode);
        }
Example #20
0
        public virtual Decision IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCriteria)
        {
            if (subject.Release == null || subject.Release.Container.IsNullOrWhiteSpace())
            {
                return(Decision.Accept());
            }

            if (_dvdContainerTypes.Contains(subject.Release.Container.ToLower()))
            {
                _logger.Debug("Release contains raw DVD, rejecting.");
                return(Decision.Reject("Raw DVD release"));
            }

            if (_blurayContainerTypes.Contains(subject.Release.Container.ToLower()))
            {
                _logger.Debug("Release contains raw Bluray, rejecting.");
                return(Decision.Reject("Raw Bluray release"));
            }

            return(Decision.Accept());
        }
Example #21
0
        protected override string AddFromTorrentFile(RemoteEpisode remoteEpisode, string hash, string filename, Byte[] fileContent)
        {
            Proxy.AddTorrentFromFile(filename, fileContent, Settings);

            try
            {
                if (Settings.TvCategory.IsNotNullOrWhiteSpace())
                {
                    Proxy.SetTorrentLabel(hash.ToLower(), Settings.TvCategory, Settings);
                }
            }
            catch (Exception ex)
            {
                _logger.Warn(ex, "Failed to set the torrent label for {0}.", filename);
            }

            try
            {
                var isRecentEpisode = remoteEpisode.IsRecentEpisode();

                if (isRecentEpisode && Settings.RecentTvPriority == (int)QBittorrentPriority.First ||
                    !isRecentEpisode && Settings.OlderTvPriority == (int)QBittorrentPriority.First)
                {
                    Proxy.MoveTorrentToTopInQueue(hash.ToLower(), Settings);
                }
            }
            catch (Exception ex)
            {
                _logger.Warn(ex, "Failed to set the torrent priority for {0}.", filename);
            }

            SetInitialState(hash.ToLower());

            if (remoteEpisode.SeedConfiguration != null && (remoteEpisode.SeedConfiguration.Ratio.HasValue || remoteEpisode.SeedConfiguration.SeedTime.HasValue))
            {
                Proxy.SetTorrentSeedingConfiguration(hash.ToLower(), remoteEpisode.SeedConfiguration, Settings);
            }

            return(hash);
        }
Example #22
0
        public virtual Decision IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCriteria)
        {
            var releaseGroup = subject.ParsedEpisodeInfo.ReleaseGroup;

            if (subject.Series.SeriesType != SeriesTypes.Anime)
            {
                return(Decision.Accept());
            }

            foreach (var file in subject.Episodes.Where(c => c.EpisodeFileId != 0).Select(c => c.EpisodeFile.Value))
            {
                if (file == null)
                {
                    continue;
                }

                if (_upgradableSpecification.IsRevisionUpgrade(file.Quality, subject.ParsedEpisodeInfo.Quality))
                {
                    if (file.ReleaseGroup.IsNullOrWhiteSpace())
                    {
                        _logger.Debug("Unable to compare release group, existing file's release group is unknown");
                        return(Decision.Reject("Existing release group is unknown"));
                    }

                    if (releaseGroup.IsNullOrWhiteSpace())
                    {
                        _logger.Debug("Unable to compare release group, release's release group is unknown");
                        return(Decision.Reject("Release group is unknown"));
                    }

                    if (file.ReleaseGroup != releaseGroup)
                    {
                        _logger.Debug("Existing Release group is: {0} - release's release group is: {1}", file.ReleaseGroup, releaseGroup);
                        return(Decision.Reject("{0} does not match existing release group {1}", releaseGroup, file.ReleaseGroup));
                    }
                }
            }

            return(Decision.Accept());
        }
Example #23
0
        protected override string AddFromMagnetLink(RemoteEpisode remoteEpisode, string hash, string magnetLink)
        {
            _proxy.AddTorrentFromUrl(magnetLink, Settings);

            // Wait until url has been resolved before returning
            var TRIES       = 5;
            var RETRY_DELAY = 500; //ms
            var ready       = false;

            for (var i = 0; i < TRIES; i++)
            {
                ready = _proxy.HasHashTorrent(hash, Settings);
                if (ready)
                {
                    break;
                }

                Thread.Sleep(RETRY_DELAY);
            }

            if (ready)
            {
                _proxy.SetTorrentLabel(hash, Settings.TvCategory, Settings);

                SetPriority(remoteEpisode, hash);
                SetDownloadDirectory(hash);

                _proxy.StartTorrent(hash, Settings);

                return(hash);
            }
            else
            {
                _logger.Debug("Magnet {0} could not be resolved in {1} tries at {2} ms intervals.", magnetLink, TRIES, RETRY_DELAY);
                // Remove from client, since it is discarded
                RemoveItem(hash, true);

                return(null);
            }
        }
Example #24
0
        public override String Download(RemoteEpisode remoteEpisode)
        {
            var torrentInfo = remoteEpisode.Release as TorrentInfo;

            String magnetUrl  = null;
            String torrentUrl = null;

            if (remoteEpisode.Release.DownloadUrl.StartsWith("magnet:"))
            {
                magnetUrl = remoteEpisode.Release.DownloadUrl;
            }
            else
            {
                torrentUrl = remoteEpisode.Release.DownloadUrl;
            }

            if (torrentInfo != null && !torrentInfo.MagnetUrl.IsNullOrWhiteSpace())
            {
                magnetUrl = torrentInfo.MagnetUrl;
            }

            String hash = null;

            if (magnetUrl.IsNotNullOrWhiteSpace())
            {
                hash = DownloadFromMagnetUrl(remoteEpisode, magnetUrl);
            }

            if (hash == null && !torrentUrl.IsNullOrWhiteSpace())
            {
                hash = DownloadFromWebUrl(remoteEpisode, torrentUrl);
            }

            if (hash == null)
            {
                throw new ReleaseDownloadException(remoteEpisode.Release, "Downloading torrent failed");
            }

            return(hash);
        }
Example #25
0
        public void Setup()
        {
            var singleEpisodeList = new List <Episode>
            {
                new Episode
                {
                    Id            = FIRST_EPISODE_ID,
                    SeasonNumber  = 12,
                    EpisodeNumber = 3,
                    EpisodeFileId = 1
                }
            };

            _series = Builder <Series> .CreateNew()
                      .Build();

            _hdtv720p  = new QualityModel(Quality.HDTV720p, new Revision(version: 1));
            _hdtv1080p = new QualityModel(Quality.HDTV1080p, new Revision(version: 1));

            _remoteEpisode = new RemoteEpisode
            {
                Series            = _series,
                ParsedEpisodeInfo = new ParsedEpisodeInfo {
                    Quality = _hdtv720p
                },
                Episodes = singleEpisodeList,
                Release  = Builder <ReleaseInfo> .CreateNew()
                           .Build()
            };

            _history = new List <EpisodeHistory>();

            Mocker.GetMock <IConfigService>()
            .SetupGet(s => s.EnableCompletedDownloadHandling)
            .Returns(true);

            Mocker.GetMock <IHistoryService>()
            .Setup(s => s.FindByEpisodeId(It.IsAny <int>()))
            .Returns(_history);
        }
Example #26
0
        public TorrentSeedConfiguration GetSeedConfiguration(RemoteEpisode remoteEpisode)
        {
            if (remoteEpisode.Release.DownloadProtocol != DownloadProtocol.Torrent)
            {
                return(null);
            }
            if (remoteEpisode.Release.IndexerId == 0)
            {
                return(null);
            }

            try
            {
                var indexer = _indexerFactory.Get(remoteEpisode.Release.IndexerId);
                var torrentIndexerSettings = indexer.Settings as ITorrentIndexerSettings;

                if (torrentIndexerSettings != null && torrentIndexerSettings.SeedCriteria != null)
                {
                    var seedConfig = new TorrentSeedConfiguration
                    {
                        Ratio = torrentIndexerSettings.SeedCriteria.SeedRatio
                    };

                    var seedTime = remoteEpisode.ParsedEpisodeInfo.FullSeason ? torrentIndexerSettings.SeedCriteria.SeasonPackSeedTime : torrentIndexerSettings.SeedCriteria.SeedTime;
                    if (seedTime.HasValue)
                    {
                        seedConfig.SeedTime = TimeSpan.FromMinutes(seedTime.Value);
                    }

                    return(seedConfig);
                }
            }
            catch (ModelNotFoundException)
            {
                return(null);
            }

            return(null);
        }
        public virtual Decision IsSatisfiedBy(RemoteEpisode subject, SearchCriteriaBase searchCriteria)
        {
            _logger.Debug("Checking if release meets restrictions: {0}", subject);

            var title           = subject.Release.Title;
            var releaseProfiles = _releaseProfileService.EnabledForTags(subject.Series.Tags, subject.Release.IndexerId);

            var required = releaseProfiles.Where(r => r.Required.IsNotNullOrWhiteSpace());
            var ignored  = releaseProfiles.Where(r => r.Ignored.IsNotNullOrWhiteSpace());

            foreach (var r in required)
            {
                var requiredTerms = r.Required.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();

                var foundTerms = ContainsAny(requiredTerms, title);
                if (foundTerms.Empty())
                {
                    var terms = string.Join(", ", requiredTerms);
                    _logger.Debug("[{0}] does not contain one of the required terms: {1}", title, terms);
                    return(Decision.Reject("Does not contain one of the required terms: {0}", terms));
                }
            }

            foreach (var r in ignored)
            {
                var ignoredTerms = r.Ignored.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();

                var foundTerms = ContainsAny(ignoredTerms, title);
                if (foundTerms.Any())
                {
                    var terms = string.Join(", ", foundTerms);
                    _logger.Debug("[{0}] contains these ignored terms: {1}", title, terms);
                    return(Decision.Reject("Contains these ignored terms: {0}", terms));
                }
            }

            _logger.Debug("[{0}] No restrictions apply, allowing", subject);
            return(Decision.Accept());
        }
Example #28
0
        public override String Download(RemoteEpisode remoteEpisode)
        {
            var url      = remoteEpisode.Release.DownloadUrl;
            var filename = FileNameBuilder.CleanFileName(remoteEpisode.Release.Title) + ".nzb";

            Byte[] nzbData;

            try
            {
                nzbData = _httpClient.Get(new HttpRequest(url)).ResponseData;
            }
            catch (WebException ex)
            {
                _logger.ErrorException(String.Format("Downloading nzb for episode '{0}' failed ({1})",
                                                     remoteEpisode.Release.Title, url), ex);

                throw new ReleaseDownloadException(remoteEpisode.Release, "Downloading nzb failed", ex);
            }

            _logger.Info("Adding report [{0}] to the queue.", remoteEpisode.Release.Title);
            return(AddFromNzbFile(remoteEpisode, filename, nzbData));
        }
        public void Setup()
        {
            _pass1 = new Mock <IDecisionEngineSpecification>();
            _pass2 = new Mock <IDecisionEngineSpecification>();
            _pass3 = new Mock <IDecisionEngineSpecification>();

            _fail1 = new Mock <IDecisionEngineSpecification>();
            _fail2 = new Mock <IDecisionEngineSpecification>();
            _fail3 = new Mock <IDecisionEngineSpecification>();

            _failDelayed1 = new Mock <IDecisionEngineSpecification>();

            _pass1.Setup(c => c.IsSatisfiedBy(It.IsAny <RemoteEpisode>(), null)).Returns(Decision.Accept);
            _pass2.Setup(c => c.IsSatisfiedBy(It.IsAny <RemoteEpisode>(), null)).Returns(Decision.Accept);
            _pass3.Setup(c => c.IsSatisfiedBy(It.IsAny <RemoteEpisode>(), null)).Returns(Decision.Accept);

            _fail1.Setup(c => c.IsSatisfiedBy(It.IsAny <RemoteEpisode>(), null)).Returns(Decision.Reject("fail1"));
            _fail2.Setup(c => c.IsSatisfiedBy(It.IsAny <RemoteEpisode>(), null)).Returns(Decision.Reject("fail2"));
            _fail3.Setup(c => c.IsSatisfiedBy(It.IsAny <RemoteEpisode>(), null)).Returns(Decision.Reject("fail3"));

            _failDelayed1.Setup(c => c.IsSatisfiedBy(It.IsAny <RemoteEpisode>(), null)).Returns(Decision.Reject("failDelayed1"));
            _failDelayed1.SetupGet(c => c.Priority).Returns(SpecificationPriority.Disk);

            _reports = new List <ReleaseInfo> {
                new ReleaseInfo {
                    Title = "The.Office.S03E115.DVDRip.XviD-OSiTV"
                }
            };
            _remoteEpisode = new RemoteEpisode {
                Series   = new Series(),
                Episodes = new List <Episode> {
                    new Episode()
                }
            };

            Mocker.GetMock <IParsingService>()
            .Setup(c => c.Map(It.IsAny <ParsedEpisodeInfo>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <SearchCriteriaBase>()))
            .Returns(_remoteEpisode);
        }
Example #30
0
        protected override string AddFromTorrentFile(RemoteEpisode remoteEpisode, string hash, string filename, byte[] fileContent)
        {
            _proxy.AddTorrentFromFile(filename, fileContent, Settings);
            _proxy.SetTorrentSeedingConfiguration(hash, remoteEpisode.SeedConfiguration, Settings);

            if (Settings.TvCategory.IsNotNullOrWhiteSpace())
            {
                _proxy.SetTorrentLabel(hash, Settings.TvCategory, Settings);
            }

            var isRecentEpisode = remoteEpisode.IsRecentEpisode();

            if (isRecentEpisode && Settings.RecentTvPriority == (int)UTorrentPriority.First ||
                !isRecentEpisode && Settings.OlderTvPriority == (int)UTorrentPriority.First)
            {
                _proxy.MoveTorrentToTopInQueue(hash, Settings);
            }

            _proxy.SetState(hash, (UTorrentState)Settings.IntialState, Settings);

            return(hash);
        }