Beispiel #1
0
        protected override string AddFromTorrentFile(RemoteEpisode remoteEpisode, string hash, string filename, byte[] fileContent)
        {
            var title = remoteEpisode.Release.Title;

            title = FileNameBuilder.CleanFileName(title);

            var filepath = Path.Combine(Settings.TorrentFolder, String.Format("{0}.torrent", title));

            using (var stream = _diskProvider.OpenWriteStream(filepath))
            {
                stream.Write(fileContent, 0, fileContent.Length);
            }

            _logger.Debug("Torrent Download succeeded, saved to: {0}", filepath);

            return(hash);
        }
Beispiel #2
0
        protected override string AddFromNzbFile(RemoteEpisode remoteEpisode, string filename, byte[] fileContent)
        {
            var title = remoteEpisode.Release.Title;

            title = FileNameBuilder.CleanFileName(title);

            var filepath = Path.Combine(Settings.NzbFolder, title + ".nzb");

            using (var stream = _diskProvider.OpenWriteStream(filepath))
            {
                stream.Write(fileContent, 0, fileContent.Length);
            }

            _logger.Debug("NZB Download succeeded, saved to: {0}", filepath);

            return(null);
        }
Beispiel #3
0
        public override string Download(RemoteMovie remoteMovie)
        {
            var url      = remoteMovie.Release.DownloadUrl;
            var filename = FileNameBuilder.CleanFileName(remoteMovie.Release.Title) + ".nzb";

            byte[] nzbData;

            try
            {
                var request = new HttpRequest(url);
                request.RateLimitKey = remoteMovie?.Release?.IndexerId.ToString();
                nzbData = _httpClient.Get(request).ResponseData;

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

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

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

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

            _nzbValidationService.Validate(filename, nzbData);

            _logger.Info("Adding report [{0}] to the queue.", remoteMovie.Release.Title);
            return(AddFromNzbFile(remoteMovie, filename, nzbData));
        }
Beispiel #4
0
 public override void EditFileName(ExportJob job, FileNameBuilder nameBuilder)
 {
     if (job.format.IsFormat("IMG_PNG-HM"))
     {
         nameBuilder.suffix = "_height";
     }
     if (job.format.IsFormat("IMG_PNG-HM-S"))
     {
         nameBuilder.suffix = "_height_s";
     }
     else if (job.format.IsFormat("IMG_PNG-NM"))
     {
         nameBuilder.suffix = "_normal";
     }
     else if (job.format.IsFormat("IMG_PNG-HS"))
     {
         nameBuilder.suffix = "_hillshade";
     }
 }
Beispiel #5
0
        /// <summary>
        /// Builds the path of the file without the extension.
        /// </summary>
        /// <param name="screenshotInfo">The screenshot information.</param>
        /// <returns>The file path without the extension.</returns>
        protected override string BuildFilePath(ScreenshotInfo screenshotInfo)
        {
            if (FilePathBuilder != null)
            {
                return(FilePathBuilder(screenshotInfo));
            }

            string folderPath = FolderPathBuilder?.Invoke()
                                ?? $@"Logs\{AtataContext.BuildStart:yyyy-MM-dd HH_mm_ss}\{AtataContext.Current.TestName}";

            folderPath = folderPath.SanitizeForPath();

            string fileName = FileNameBuilder?.Invoke(screenshotInfo)
                              ?? $"{screenshotInfo.Number:D2} - {screenshotInfo.PageObjectFullName}{screenshotInfo.Title?.Prepend(" - ")}";

            fileName = fileName.SanitizeForFileName();

            return(Path.Combine(folderPath, fileName));
        }
Beispiel #6
0
    public VerifyEngine(
        string extension,
        VerifySettings settings,
        Type testType,
        string directory,
        string testName)
    {
        this.settings = settings;
        var verifiedPattern = FileNameBuilder.GetVerifiedPattern(extension, settings.Namer, testType, testName);

        danglingVerified = Directory.EnumerateFiles(directory, verifiedPattern).ToList();

        RenameBadNamespacePrefixedFiles(testType, directory, extension, testName);

        var receivedPattern = FileNameBuilder.GetReceivedPattern(extension, settings.Namer, testType, testName);

        foreach (var file in Directory.EnumerateFiles(directory, receivedPattern))
        {
            File.Delete(file);
        }
    }
        private string BuildFilePath()
        {
            AtataContext context = AtataContext.Current;

            if (FilePathBuilder != null)
            {
                return(FilePathBuilder.Invoke(context).SanitizeForPath());
            }

            string folderPath = FolderPathBuilder?.Invoke(context)
                                ?? BuildDefaultFolderPath();

            folderPath = folderPath.SanitizeForPath();

            string fileName = FileNameBuilder?.Invoke(context)
                              ?? BuildDefaultFileName(context);

            fileName = fileName.SanitizeForFileName();

            return(Path.Combine(folderPath, fileName));
        }
Beispiel #8
0
        public override IEnumerable <DownloadClientItem> GetItems()
        {
            foreach (var file in _diskProvider.GetFiles(Settings.StrmFolder, SearchOption.TopDirectoryOnly))
            {
                if (Path.GetExtension(file) != ".strm")
                {
                    continue;
                }

                var title = FileNameBuilder.CleanFileName(Path.GetFileName(file));

                var historyItem = new DownloadClientItem
                {
                    DownloadClient   = Definition.Name,
                    DownloadClientId = GetDownloadClientId(file),
                    Title            = title,

                    TotalSize = _diskProvider.GetFileSize(file),

                    OutputPath = file
                };

                if (_diskProvider.IsFileLocked(file))
                {
                    historyItem.Status = DownloadItemStatus.Downloading;
                }
                else
                {
                    historyItem.Status = DownloadItemStatus.Completed;
                }

                historyItem.RemoteEpisode = GetRemoteEpisode(historyItem.Title);
                if (historyItem.RemoteEpisode == null)
                {
                    continue;
                }

                yield return(historyItem);
            }
        }
Beispiel #9
0
    public async Task Simple()
    {
        var settings = new VerifySettings();

        settings.UseMethodName("Foo");
        settings.DisableDiff();

        await Verifier.Verify(
            @"The
before
text", settings)
        .AutoVerify();

        FileNameBuilder.ClearPrefixList();
        await Verifier.ThrowsTask(() =>
                                  Verifier.Verify(
                                      @"The
after
text",
                                      settings))
        .ScrubLinesContaining("DiffEngineTray");
    }
Beispiel #10
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));
        }
Beispiel #11
0
        public Series AddSeries(Series newSeries)
        {
            Ensure.That(() => newSeries).IsNotNull();

            if (String.IsNullOrWhiteSpace(newSeries.Path))
            {
                var folderName = FileNameBuilder.CleanFilename(newSeries.Title);
                newSeries.Path = Path.Combine(newSeries.RootFolderPath, folderName);
            }

            _logger.Info("Adding Series {0} Path: [{1}]", newSeries, newSeries.Path);

            newSeries.Monitored  = true;
            newSeries.CleanTitle = Parser.Parser.CleanSeriesTitle(newSeries.Title);

            newSeries.SeasonFolder = _configService.UseSeasonFolder;

            _seriesRepository.Insert(newSeries);
            _eventAggregator.PublishEvent(new SeriesAddedEvent(newSeries));

            return(newSeries);
        }
Beispiel #12
0
    public VerifyEngine(
        string extension,
        VerifySettings settings,
        Type testType,
        string directory,
        string testName)
    {
        this.settings = settings;
        this.testType = testType;
        this.testName = testName;
        diffTool      = DiffTools.Find(extension);
        var verifiedPattern = FileNameBuilder.GetVerifiedPattern(extension, settings.Namer, this.testType, this.testName);

        danglingVerified = Directory.EnumerateFiles(directory, verifiedPattern).ToList();
        var receivedPattern = FileNameBuilder.GetReceivedPattern(extension, settings.Namer, this.testType, this.testName);

        foreach (var file in Directory.EnumerateFiles(directory, receivedPattern))
        {
            File.Delete(file);
        }
        diffTool = DiffTools.Find(extension);
    }
Beispiel #13
0
    public async Task StringWithDifferingNewline()
    {
        var fullPath = Path.GetFullPath("../../../Tests.StringWithDifferingNewline.verified.txt");

        File.Delete(fullPath);
        File.WriteAllText(fullPath, "a\r\nb");
        await Verifier.Verify("a\r\nb");

        FileNameBuilder.ClearPrefixList();
        await Verifier.Verify("a\rb");

        FileNameBuilder.ClearPrefixList();
        await Verifier.Verify("a\nb");

        FileNameBuilder.ClearPrefixList();

        File.Delete(fullPath);
        File.WriteAllText(fullPath, "a\nb");
        await Verifier.Verify("a\r\nb");

        FileNameBuilder.ClearPrefixList();
        await Verifier.Verify("a\rb");

        FileNameBuilder.ClearPrefixList();
        await Verifier.Verify("a\nb");

        FileNameBuilder.ClearPrefixList();

        File.Delete(fullPath);
        File.WriteAllText(fullPath, "a\rb");
        await Verifier.Verify("a\r\nb");

        FileNameBuilder.ClearPrefixList();
        await Verifier.Verify("a\rb");

        FileNameBuilder.ClearPrefixList();
        await Verifier.Verify("a\nb");
    }
Beispiel #14
0
        private async void BoxScoreList_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            if (e.Position >= 0 && e.Position < _boxScoreUrls?.Length)
            {
                var boxScore = _boxScoreUrls[e.Position];

                try
                {
                    var reddit = await _client.GetRedditAsync(new PlayRequest
                    {
                        Season   = _model.Year,
                        Week     = _model.Filter.Week,
                        AwayCode = boxScore.AwayCode,
                        HomeCode = boxScore.HomeCode,
                        GameId   = boxScore.GetGameId()
                    }).ConfigureAwait(true);

                    var returnIntent = new Intent();
                    returnIntent.PutExtra(ResultData, reddit);

                    if (reddit?.Length > 0)
                    {
                        returnIntent.PutExtra(ResultName, FileNameBuilder.GetFileName(reddit[0], _model.Year, _model.Filter.Week));
                    }
                    SetResult(Result.Ok, returnIntent);

                    Finish();
                }
                catch (Exception ex) when
                (
                    ex is HttpRequestException ||
                    ex is System.OperationCanceledException
                )
                {
                    AlertHelper.ShowException(this, ex);
                }
            }
        }
Beispiel #15
0
        public override IEnumerable <DownloadClientItem> GetItems()
        {
            foreach (var file in _diskProvider.GetFiles(Settings.StrmFolder, SearchOption.TopDirectoryOnly))
            {
                if (Path.GetExtension(file) != ".strm")
                {
                    continue;
                }

                var title = FileNameBuilder.CleanFileName(Path.GetFileName(file));

                var historyItem = new DownloadClientItem
                {
                    DownloadClientInfo = DownloadClientItemClientInfo.FromDownloadClient(this),
                    DownloadId         = GetDownloadClientId(file),
                    Title = title,

                    CanBeRemoved = true,
                    CanMoveFiles = true,

                    TotalSize = _diskProvider.GetFileSize(file),

                    OutputPath = new OsPath(file)
                };

                if (_diskProvider.IsFileLocked(file))
                {
                    historyItem.Status = DownloadItemStatus.Downloading;
                }
                else
                {
                    historyItem.Status = DownloadItemStatus.Completed;
                }

                yield return(historyItem);
            }
        }
Beispiel #16
0
        public override string Download(RemoteBook remoteBook)
        {
            var url   = remoteBook.Release.DownloadUrl;
            var title = remoteBook.Release.Title;

            if (remoteBook.ParsedBookInfo.Discography)
            {
                throw new NotSupportedException("Discography releases are not supported with Pneumatic.");
            }

            title = FileNameBuilder.CleanFileName(title);

            //Save to the Pneumatic directory (The user will need to ensure its accessible by XBMC)
            var nzbFile = Path.Combine(Settings.NzbFolder, title + ".nzb");

            _logger.Debug("Downloading NZB from: {0} to: {1}", url, nzbFile);
            _httpClient.DownloadFile(url, nzbFile);

            _logger.Debug("NZB Download succeeded, saved to: {0}", nzbFile);

            var strmFile = WriteStrmFile(title, nzbFile);

            return(GetDownloadClientId(strmFile));
        }
Beispiel #17
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 ((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));
        }
Beispiel #18
0
        public override string Download(RemoteMovie remoteMovie)
        {
            var url   = remoteMovie.Release.DownloadUrl;
            var title = remoteMovie.Release.Title;

            // We don't have full seasons in movies.
            //if (remoteMovie.ParsedEpisodeInfo.FullSeason)
            //{
            //    throw new NotSupportedException("Full season releases are not supported with Pneumatic.");
            //}
            title = FileNameBuilder.CleanFileName(title);

            //Save to the Pneumatic directory (The user will need to ensure its accessible by XBMC)
            var nzbFile = Path.Combine(Settings.NzbFolder, title + ".nzb");

            _logger.Debug("Downloading NZB from: {0} to: {1}", url, nzbFile);
            _httpClient.DownloadFile(url, nzbFile);

            _logger.Debug("NZB Download succeeded, saved to: {0}", nzbFile);

            var strmFile = WriteStrmFile(title, nzbFile);

            return(GetDownloadClientId(strmFile));
        }
Beispiel #19
0
        protected override string AddFromMagnetLink(RemoteBook remoteBook, string hash, string magnetLink)
        {
            if (!Settings.SaveMagnetFiles)
            {
                throw new NotSupportedException("Blackhole does not support magnet links.");
            }

            var title = remoteBook.Release.Title;

            title = FileNameBuilder.CleanFileName(title);

            var filepath = Path.Combine(Settings.TorrentFolder, $"{title}.{Settings.MagnetFileExtension.Trim('.')}");

            var fileContent = Encoding.UTF8.GetBytes(magnetLink);

            using (var stream = _diskProvider.OpenWriteStream(filepath))
            {
                stream.Write(fileContent, 0, fileContent.Length);
            }

            _logger.Debug("Saving magnet link succeeded, saved to: {0}", filepath);

            return(null);
        }
Beispiel #20
0
        private string DownloadFromWebUrl(RemoteEpisode remoteEpisode, string torrentUrl)
        {
            byte[] torrentFile = null;

            try
            {
                var request = new HttpRequest(torrentUrl);
                request.Headers.Accept    = "application/x-bittorrent";
                request.AllowAutoRedirect = false;

                var response = _httpClient.Get(request);

                if (response.StatusCode == HttpStatusCode.SeeOther || response.StatusCode == HttpStatusCode.Found)
                {
                    var locationHeader = (string)response.Headers.GetValueOrDefault("Location", null);

                    _logger.Trace("Torrent request is being redirected to: {0}", locationHeader);

                    if (locationHeader != null)
                    {
                        if (locationHeader.StartsWith("magnet:"))
                        {
                            return(DownloadFromMagnetUrl(remoteEpisode, locationHeader));
                        }

                        return(DownloadFromWebUrl(remoteEpisode, locationHeader));
                    }

                    throw new WebException("Remote website tried to redirect without providing a location.");
                }

                torrentFile = response.ResponseData;

                _logger.Debug("Downloading torrent for episode '{0}' finished ({1} bytes from {2})", remoteEpisode.Release.Title, torrentFile.Length, torrentUrl);
            }
            catch (HttpException ex)
            {
                _logger.Error(ex, "Downloading torrent file for episode '{0}' failed ({1})", remoteEpisode.Release.Title, torrentUrl);

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

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

            var filename   = string.Format("{0}.torrent", FileNameBuilder.CleanFileName(remoteEpisode.Release.Title));
            var hash       = _torrentFileInfoReader.GetHashFromTorrentFile(torrentFile);
            var actualHash = AddFromTorrentFile(remoteEpisode, hash, filename, torrentFile);

            if (actualHash.IsNotNullOrWhiteSpace() && hash != actualHash)
            {
                _logger.Debug(
                    "{0} did not return the expected InfoHash for '{1}', Sonarr could potentially lose track of the download in progress.",
                    Definition.Implementation, remoteEpisode.Release.DownloadUrl);
            }

            return(actualHash);
        }
        public void Setup()
        {
            _remoteEpisode = CreateRemoteEpisode();

            _settings = new DownloadStationSettings()
            {
                Host     = "127.0.0.1",
                Port     = 5000,
                Username = "******",
                Password = "******"
            };

            Subject.Definition          = new DownloadClientDefinition();
            Subject.Definition.Settings = _settings;

            _queued = new DownloadStationTask()
            {
                Id         = "id1",
                Size       = 1000,
                Status     = DownloadStationTaskStatus.Waiting,
                Type       = DownloadStationTaskType.NZB,
                Username   = "******",
                Title      = "title",
                Additional = new DownloadStationTaskAdditional
                {
                    Detail = new Dictionary <string, string>
                    {
                        { "destination", "shared/folder" },
                        { "uri", FileNameBuilder.CleanFileName(_remoteEpisode.Release.Title) + ".nzb" }
                    },
                    Transfer = new Dictionary <string, string>
                    {
                        { "size_downloaded", "0" },
                        { "speed_download", "0" }
                    }
                }
            };

            _completed = new DownloadStationTask()
            {
                Id         = "id2",
                Size       = 1000,
                Status     = DownloadStationTaskStatus.Finished,
                Type       = DownloadStationTaskType.NZB,
                Username   = "******",
                Title      = "title",
                Additional = new DownloadStationTaskAdditional
                {
                    Detail = new Dictionary <string, string>
                    {
                        { "destination", "shared/folder" },
                        { "uri", FileNameBuilder.CleanFileName(_remoteEpisode.Release.Title) + ".nzb" }
                    },
                    Transfer = new Dictionary <string, string>
                    {
                        { "size_downloaded", "1000" },
                        { "speed_download", "0" }
                    },
                }
            };

            _seeding = new DownloadStationTask()
            {
                Id         = "id2",
                Size       = 1000,
                Status     = DownloadStationTaskStatus.Seeding,
                Type       = DownloadStationTaskType.NZB,
                Username   = "******",
                Title      = "title",
                Additional = new DownloadStationTaskAdditional
                {
                    Detail = new Dictionary <string, string>
                    {
                        { "destination", "shared/folder" },
                        { "uri", FileNameBuilder.CleanFileName(_remoteEpisode.Release.Title) + ".nzb" }
                    },
                    Transfer = new Dictionary <string, string>
                    {
                        { "size_downloaded", "1000" },
                        { "speed_download", "0" }
                    }
                }
            };

            _downloading = new DownloadStationTask()
            {
                Id         = "id3",
                Size       = 1000,
                Status     = DownloadStationTaskStatus.Downloading,
                Type       = DownloadStationTaskType.NZB,
                Username   = "******",
                Title      = "title",
                Additional = new DownloadStationTaskAdditional
                {
                    Detail = new Dictionary <string, string>
                    {
                        { "destination", "shared/folder" },
                        { "uri", FileNameBuilder.CleanFileName(_remoteEpisode.Release.Title) + ".nzb" }
                    },
                    Transfer = new Dictionary <string, string>
                    {
                        { "size_downloaded", "100" },
                        { "speed_download", "50" }
                    }
                }
            };

            _failed = new DownloadStationTask()
            {
                Id         = "id4",
                Size       = 1000,
                Status     = DownloadStationTaskStatus.Error,
                Type       = DownloadStationTaskType.NZB,
                Username   = "******",
                Title      = "title",
                Additional = new DownloadStationTaskAdditional
                {
                    Detail = new Dictionary <string, string>
                    {
                        { "destination", "shared/folder" },
                        { "uri", FileNameBuilder.CleanFileName(_remoteEpisode.Release.Title) + ".nzb" }
                    },
                    Transfer = new Dictionary <string, string>
                    {
                        { "size_downloaded", "10" },
                        { "speed_download", "0" }
                    }
                }
            };

            Mocker.GetMock <IHttpClient>()
            .Setup(s => s.Get(It.IsAny <HttpRequest>()))
            .Returns <HttpRequest>(r => new HttpResponse(r, new HttpHeader(), new byte[0]));

            _downloadStationConfigItems = new Dictionary <string, object>
            {
                { "default_destination", _defaultDestination },
            };

            Mocker.GetMock <IDownloadStationProxy>()
            .Setup(v => v.GetConfig(It.IsAny <DownloadStationSettings>()))
            .Returns(_downloadStationConfigItems);
        }
Beispiel #22
0
        public override IEnumerable <DownloadClientItem> GetItems()
        {
            foreach (var folder in _diskProvider.GetDirectories(Settings.WatchFolder))
            {
                var title = FileNameBuilder.CleanFileName(Path.GetFileName(folder));

                var files = _diskProvider.GetFiles(folder, SearchOption.AllDirectories);

                var historyItem = new DownloadClientItem
                {
                    DownloadClient   = Definition.Name,
                    DownloadClientId = Definition.Name + "_" + Path.GetFileName(folder) + "_" + _diskProvider.FolderGetCreationTimeUtc(folder).Ticks,
                    Title            = title,

                    TotalSize = files.Select(_diskProvider.GetFileSize).Sum(),

                    OutputPath = folder
                };

                if (files.Any(_diskProvider.IsFileLocked))
                {
                    historyItem.Status = DownloadItemStatus.Downloading;
                }
                else
                {
                    historyItem.Status = DownloadItemStatus.Completed;

                    historyItem.RemainingTime = TimeSpan.Zero;
                }

                historyItem.RemoteEpisode = GetRemoteEpisode(historyItem.Title);
                if (historyItem.RemoteEpisode == null)
                {
                    continue;
                }

                yield return(historyItem);
            }

            foreach (var videoFile in _diskScanService.GetVideoFiles(Settings.WatchFolder, false))
            {
                var title = FileNameBuilder.CleanFileName(Path.GetFileName(videoFile));

                var historyItem = new DownloadClientItem
                {
                    DownloadClient   = Definition.Name,
                    DownloadClientId = Definition.Name + "_" + Path.GetFileName(videoFile) + "_" + _diskProvider.FileGetLastWriteUtc(videoFile).Ticks,
                    Title            = title,

                    TotalSize = _diskProvider.GetFileSize(videoFile),

                    OutputPath = videoFile
                };

                if (_diskProvider.IsFileLocked(videoFile))
                {
                    historyItem.Status = DownloadItemStatus.Downloading;
                }
                else
                {
                    historyItem.Status        = DownloadItemStatus.Completed;
                    historyItem.RemainingTime = TimeSpan.Zero;
                }

                historyItem.RemoteEpisode = GetRemoteEpisode(historyItem.Title);
                if (historyItem.RemoteEpisode == null)
                {
                    continue;
                }

                yield return(historyItem);
            }
        }
Beispiel #23
0
 public void buildLayer(Size s, Button but, int preP)
 {
     fb = new FileNameBuilder(false);
     tb = new ThumbnailBuilder();
     butt = but;
     prePage = preP;
     layoutPanel = new TableLayoutPanel();
     ClosePanelButton = new Button();
     nextSetButton = new Button();
     nextSetButton.Text = "More...";
     panel4 = new Panel();
     this.panel4.Controls.Add(nextSetButton); // New
     this.panel4.Controls.Add(ClosePanelButton);
     this.panel4.Dock = DockStyle.Fill;
     ClosePanelButton.Image = new Bitmap(global ::SortImage.Properties.Resources.buttonCancel.GetThumbnailImage(ClosePanelButton.Size.Height, ClosePanelButton.Size.Height, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero));
     ClosePanelButton.ImageAlign = ContentAlignment.MiddleRight;
     nextSetButton.Image = new Bitmap(global ::SortImage.Properties.Resources.next.GetThumbnailImage(nextSetButton.Size.Height, nextSetButton.Size.Height, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero));
     nextSetButton.ImageAlign = ContentAlignment.MiddleRight;
     this.panel4.Controls.Add(layoutPanel);
     panel4.Size = s;
     panel4.BackColor = Color.Silver;
     this.layoutPanel.ColumnCount = 6;
     this.layoutPanel.GrowStyle = TableLayoutPanelGrowStyle.AddRows;
     this.layoutPanel.Size = new Size(s.Width, s.Height - ClosePanelButton.Height);
     this.layoutPanel.Location = new System.Drawing.Point(50, 50);
     this.layoutPanel.Name = "layoutPanel";
     this.layoutPanel.AutoScroll = true;
     nextSetButton.Left = 50;
     ClosePanelButton.Left = panel4.Width - ClosePanelButton.Width + 5;
 }
Beispiel #24
0
    public async Task Split(
        bool hasExistingReceived,
        bool autoVerify)
    {
        TypeToSplit initialTarget = new("info1", "value1", "value2");
        TypeToSplit secondTarget  = new("info2", "value1.1", "value2.1");
        var         settings      = new VerifySettings();

        if (autoVerify)
        {
            settings.AutoVerify();
        }

        var method = GetType().GetMethod("Split") !;

        var concat         = ParameterBuilder.Concat(method, new object[] { hasExistingReceived, autoVerify });
        var uniqueTestName = $"Tests.Split_{concat}";

        settings.UseParameters(hasExistingReceived, autoVerify);
        var      prefix       = Path.Combine(AttributeReader.GetProjectDirectory(), $"{uniqueTestName}.");
        var      danglingFile = $"{prefix}03.verified.txt";
        FilePair file0        = new("txt", $"{prefix}00");
        FilePair file1        = new("txt", $"{prefix}01");
        FilePair file2        = new("txt", $"{prefix}02");

        DeleteAll(danglingFile, file0.Received, file0.Verified, file1.Verified, file1.Received, file2.Verified, file2.Received);
        await File.WriteAllTextAsync(danglingFile, "");

        if (hasExistingReceived)
        {
            await File.WriteAllTextAsync(file0.Received, "");

            await File.WriteAllTextAsync(file1.Received, "");

            await File.WriteAllTextAsync(file2.Received, "");
        }

        FileNameBuilder.ClearPrefixList();
        await InitialVerifySplit(initialTarget, true, settings, file0, file1, file2);

        if (!autoVerify)
        {
            RunClipboardCommand();
        }

        AssertNotExists(danglingFile);

        FileNameBuilder.ClearPrefixList();
        await ReVerifySplit(initialTarget, settings, file0, file1, file2);

        FileNameBuilder.ClearPrefixList();
        await InitialVerifySplit(secondTarget, true, settings, file0, file1, file2);

        if (!autoVerify)
        {
            RunClipboardCommand();
        }

        FileNameBuilder.ClearPrefixList();
        await ReVerifySplit(secondTarget, settings, file0, file1, file2);
    }
Beispiel #25
0
 public virtual void EditFileName(ExportJob exportJob, FileNameBuilder nameBuilder)
 {
 }
Beispiel #26
0
        private IEnumerable <WatchFolderItem> GetDownloadItems(string watchFolder, Dictionary <string, WatchFolderItem> lastWatchItems, TimeSpan waitPeriod)
        {
            // get a fresh naming config each time, in case the user has made changes
            foreach (var folder in _diskProvider.GetDirectories(watchFolder))
            {
                var title = FileNameBuilder.CleanFileName(Path.GetFileName(folder));

                var newWatchItem = new WatchFolderItem
                {
                    DownloadId = Path.GetFileName(folder) + "_" + _diskProvider.FolderGetCreationTime(folder).Ticks,
                    Title      = title,

                    OutputPath = new OsPath(folder),

                    Status        = DownloadItemStatus.Completed,
                    RemainingTime = TimeSpan.Zero
                };

                var oldWatchItem = lastWatchItems.GetValueOrDefault(newWatchItem.DownloadId);

                if (PreCheckWatchItemExpiry(newWatchItem, oldWatchItem))
                {
                    var files = _diskProvider.GetFiles(folder, SearchOption.AllDirectories);

                    newWatchItem.TotalSize = files.Select(_diskProvider.GetFileSize).Sum();
                    newWatchItem.Hash      = GetHash(folder, files);

                    if (files.Any(_diskProvider.IsFileLocked))
                    {
                        newWatchItem.Status        = DownloadItemStatus.Downloading;
                        newWatchItem.RemainingTime = null;
                    }

                    UpdateWatchItemExpiry(newWatchItem, oldWatchItem, waitPeriod);
                }

                yield return(newWatchItem);
            }

            foreach (var videoFile in _diskScanService.GetVideoFiles(watchFolder, false))
            {
                var title = FileNameBuilder.CleanFileName(Path.GetFileName(videoFile));

                var newWatchItem = new WatchFolderItem
                {
                    DownloadId = Path.GetFileName(videoFile) + "_" + _diskProvider.FileGetLastWrite(videoFile).Ticks,
                    Title      = title,

                    OutputPath = new OsPath(videoFile),

                    Status        = DownloadItemStatus.Completed,
                    RemainingTime = TimeSpan.Zero
                };

                var oldWatchItem = lastWatchItems.GetValueOrDefault(newWatchItem.DownloadId);

                if (PreCheckWatchItemExpiry(newWatchItem, oldWatchItem))
                {
                    newWatchItem.TotalSize = _diskProvider.GetFileSize(videoFile);
                    newWatchItem.Hash      = GetHash(videoFile);

                    if (_diskProvider.IsFileLocked(videoFile))
                    {
                        newWatchItem.Status = DownloadItemStatus.Downloading;
                    }

                    UpdateWatchItemExpiry(newWatchItem, oldWatchItem, waitPeriod);
                }

                yield return(newWatchItem);
            }
        }
Beispiel #27
0
        private IEnumerable <WatchFolderItem> GetDownloadItems(string watchFolder, Dictionary <string, WatchFolderItem> lastWatchItems, TimeSpan waitPeriod)
        {
            foreach (var folder in _diskScanService.FilterPaths(watchFolder, _diskProvider.GetDirectories(watchFolder)))
            {
                var title = FileNameBuilder.CleanFileName(Path.GetFileName(folder));

                var newWatchItem = new WatchFolderItem
                {
                    DownloadId = Path.GetFileName(folder) + "_" + _diskProvider.FolderGetCreationTime(folder).Ticks,
                    Title      = title,

                    OutputPath = new OsPath(folder),

                    Status        = DownloadItemStatus.Completed,
                    RemainingTime = TimeSpan.Zero
                };

                var oldWatchItem = lastWatchItems.GetValueOrDefault(newWatchItem.DownloadId);

                if (PreCheckWatchItemExpiry(newWatchItem, oldWatchItem))
                {
                    var files = _diskProvider.GetFiles(folder, SearchOption.AllDirectories);

                    newWatchItem.TotalSize = files.Select(_diskProvider.GetFileSize).Sum();
                    newWatchItem.Hash      = GetHash(folder, files);

                    if (files.Any(_diskProvider.IsFileLocked))
                    {
                        newWatchItem.Status        = DownloadItemStatus.Downloading;
                        newWatchItem.RemainingTime = null;
                    }

                    UpdateWatchItemExpiry(newWatchItem, oldWatchItem, waitPeriod);
                }

                yield return(newWatchItem);
            }

            foreach (var audioFile in _diskScanService.FilterFiles(watchFolder, _diskScanService.GetAudioFiles(watchFolder, false)))
            {
                var title = FileNameBuilder.CleanFileName(audioFile.Name);

                var newWatchItem = new WatchFolderItem
                {
                    DownloadId = audioFile.Name + "_" + audioFile.LastWriteTimeUtc.Ticks,
                    Title      = title,

                    OutputPath = new OsPath(audioFile.FullName),

                    Status        = DownloadItemStatus.Completed,
                    RemainingTime = TimeSpan.Zero
                };

                var oldWatchItem = lastWatchItems.GetValueOrDefault(newWatchItem.DownloadId);

                if (PreCheckWatchItemExpiry(newWatchItem, oldWatchItem))
                {
                    newWatchItem.TotalSize = audioFile.Length;
                    newWatchItem.Hash      = GetHash(audioFile.FullName);

                    if (_diskProvider.IsFileLocked(audioFile.FullName))
                    {
                        newWatchItem.Status = DownloadItemStatus.Downloading;
                    }

                    UpdateWatchItemExpiry(newWatchItem, oldWatchItem, waitPeriod);
                }

                yield return(newWatchItem);
            }
        }
Beispiel #28
0
        private string DownloadFromWebUrl(RemoteBook remoteBook, string torrentUrl)
        {
            byte[] torrentFile = null;

            try
            {
                var request = new HttpRequest(torrentUrl);
                request.RateLimitKey      = remoteBook?.Release?.IndexerId.ToString();
                request.Headers.Accept    = "application/x-bittorrent";
                request.AllowAutoRedirect = false;

                var response = _httpClient.Get(request);

                if (response.StatusCode == HttpStatusCode.MovedPermanently ||
                    response.StatusCode == HttpStatusCode.Found ||
                    response.StatusCode == HttpStatusCode.SeeOther)
                {
                    var locationHeader = response.Headers.GetSingleValue("Location");

                    _logger.Trace("Torrent request is being redirected to: {0}", locationHeader);

                    if (locationHeader != null)
                    {
                        if (locationHeader.StartsWith("magnet:"))
                        {
                            return(DownloadFromMagnetUrl(remoteBook, locationHeader));
                        }

                        return(DownloadFromWebUrl(remoteBook, locationHeader));
                    }

                    throw new WebException("Remote website tried to redirect without providing a location.");
                }

                torrentFile = response.ResponseData;

                _logger.Debug("Downloading torrent for release '{0}' finished ({1} bytes from {2})", remoteBook.Release.Title, torrentFile.Length, torrentUrl);
            }
            catch (HttpException ex)
            {
                if (ex.Response.StatusCode == HttpStatusCode.NotFound)
                {
                    _logger.Error(ex, "Downloading torrent file for book '{0}' failed since it no longer exists ({1})", remoteBook.Release.Title, torrentUrl);
                    throw new ReleaseUnavailableException(remoteBook.Release, "Downloading torrent failed", ex);
                }

                if ((int)ex.Response.StatusCode == 429)
                {
                    _logger.Error("API Grab Limit reached for {0}", torrentUrl);
                }
                else
                {
                    _logger.Error(ex, "Downloading torrent file for release '{0}' failed ({1})", remoteBook.Release.Title, torrentUrl);
                }

                throw new ReleaseDownloadException(remoteBook.Release, "Downloading torrent failed", ex);
            }
            catch (WebException ex)
            {
                _logger.Error(ex, "Downloading torrent file for release '{0}' failed ({1})", remoteBook.Release.Title, torrentUrl);

                throw new ReleaseDownloadException(remoteBook.Release, "Downloading torrent failed", ex);
            }

            var filename   = string.Format("{0}.torrent", FileNameBuilder.CleanFileName(remoteBook.Release.Title));
            var hash       = _torrentFileInfoReader.GetHashFromTorrentFile(torrentFile);
            var actualHash = AddFromTorrentFile(remoteBook, hash, filename, torrentFile);

            if (actualHash.IsNotNullOrWhiteSpace() && hash != actualHash)
            {
                _logger.Debug(
                    "{0} did not return the expected InfoHash for '{1}', Readarr could potentially lose track of the download in progress.",
                    Definition.Implementation,
                    remoteBook.Release.DownloadUrl);
            }

            return(actualHash);
        }
Beispiel #29
0
 protected static string CleanFileName(String name)
 {
     return(FileNameBuilder.CleanFileName(name) + ".nzb");
 }
Beispiel #30
0
 public void CleanFileName(string name, string expectedName)
 {
     FileNameBuilder.CleanFilename(name).Should().Be(expectedName);
 }
Beispiel #31
0
    public Task Test(
        bool run,
        bool runG,
        bool config,
        bool configG,
        bool runVersion,
        bool runVersionG,
        bool method,
        bool type,
        bool dir)
    {
        var sharedNamer = VerifierSettings.SharedNamer;

        sharedNamer.UniqueForAssemblyConfiguration = false;
        sharedNamer.UniqueForRuntime           = false;
        sharedNamer.UniqueForRuntimeAndVersion = false;

        var directory = Path.Combine(Path.GetTempPath(), "VerifyNamer");

        if (Directory.Exists(directory))
        {
            Directory.Delete(directory, true);
        }
        Directory.CreateDirectory(directory);

        VerifySettings settings = new();

        if (run)
        {
            settings.UniqueForRuntime();
        }

        if (runG)
        {
            VerifierSettings.UniqueForRuntime();
        }

        if (config)
        {
            settings.UniqueForAssemblyConfiguration();
        }

        if (configG)
        {
            VerifierSettings.UniqueForAssemblyConfiguration();
        }

        if (runVersion)
        {
            settings.UniqueForRuntimeAndVersion();
        }

        if (runVersionG)
        {
            VerifierSettings.UniqueForRuntimeAndVersion();
        }

        if (method)
        {
            settings.UseMethodName("CustomMethod");
        }

        if (type)
        {
            settings.UseMethodName("CustomType");
        }

        if (dir)
        {
            settings.UseDirectory("customDir");
        }

        var builder            = Builder(directory, settings);
        var fileNames          = builder.GetFileNames("txt");
        var fileNamesWithIndex = builder.GetFileNames("txt", 2);

        File.WriteAllText(fileNames.Received, "");
        File.WriteAllText(fileNames.Verified, "");
        File.WriteAllText(fileNamesWithIndex.Received, "");
        File.WriteAllText(fileNamesWithIndex.Verified, "");
        FileNameBuilder.ClearPrefixList();
        builder = Builder(directory, settings);

        var receivedFiles = builder.ReceivedFiles.OrderBy(x => x);
        var verifiedFiles = builder.VerifiedFiles.OrderBy(x => x);

        FileNameBuilder.ClearPrefixList();
        return(Verifier.Verify(new
        {
            fileNames,
            fileNamesWithIndex,
            receivedFiles,
            verifiedFiles
        })
               .UseParameters(
                   run,
                   runG,
                   config,
                   configG,
                   runVersion,
                   runVersionG,
                   method,
                   type,
                   dir)
               .UseMethodName("_")
               .UseTypeName("_")
               .AddScrubber(_ => _.Replace('/', '\\')));
    }
Beispiel #32
0
        private string[] workingFolders = new string[64]; // 0-31 are source folders, 32 is dup folder, 33-63 are destination folders

        #endregion Fields

        #region Constructors

        //Main constructor for the form
        public SortImg()
        {
            InitializeComponent();

            string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            this.Text = String.Format("SortImg (Ver. {0})", version);

            DoubleBuffered = true;
            is64bit = Utils.Is64BitOperatingSystem(); //Check address space for recycle bin strut construction diffrences.
            if (is64bit)
            {
                util64 = new Utils64();
            }
            else
            {
                util32 = new Utils32();
            }
            pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
            tnb = new ThumbnailBuilder();
            addImage = new DelegateAddImage(this.AddImage);
            thumbController = new ThumbnailController();
            thumbController.OnStart += new ThumbnailControllerEventHandler(thumbControllerStart);
            thumbController.OnAdd += new ThumbnailControllerEventHandler(thumbControllerAdd);
            thumbController.OnEnd += new ThumbnailControllerEventHandler(thumbControllerEnd);

            this.KeyUp += new KeyEventHandler(Key);
            ImageInfo = new ToolTip();
            imageMatcher = new ImageMatcherSpeed();
            logger = new Logging();
            buttonbuilder = new DynamicButtons();
            this.Closing += new CancelEventHandler(SortImg_Closing);
            FileCopyedsource = new ArrayList();
            FileCopyeddest = new ArrayList();
            ButtonDispose = new ArrayList();
            fileNameCreator = new FileNameBuilder(false);
            checkedTags = new List<string>();
            currentTagsList = new List<string>();
            selected = new List<ImageViewer>();
            storedSettings = new SortImgSettings(Application.StartupPath, logger);
            storedSettings.loadSettings(true, true);
            sourceAdd = new SourceDialog(storedSettings);
        }