From f02fa629ccbd79b1ee9489370f112a89f70fe830 Mon Sep 17 00:00:00 2001 From: ta264 Date: Sun, 22 Dec 2019 22:08:53 +0000 Subject: [PATCH] Reformat and apply Stylecop rules --- .editorconfig | 29 ++++ .gitignore | 1 - src/Directory.Build.props | 4 +- .../Converters/BooleanYNConverter.cs | 2 +- src/Marr.Data/Converters/CastConverter.cs | 1 - src/Marr.Data/DataHelper.cs | 2 +- src/Marr.Data/Mapping/IColumnInfo.cs | 4 +- src/Marr.Data/QGen/WhereBuilder.cs | 2 +- src/MonoTorrent/BEncoding/BEncodedList.cs | 6 +- src/MonoTorrent/BEncoding/BEncodedNumber.cs | 6 +- src/MonoTorrent/BEncoding/BEncodedString.cs | 6 +- src/MonoTorrent/BEncoding/IBEncodedValue.cs | 6 +- src/MonoTorrent/BitField.cs | 2 +- src/MonoTorrent/Check.cs | 28 ++-- src/MonoTorrent/InfoHash.cs | 21 +-- src/MonoTorrent/MagnetLink.cs | 96 +++++++------ src/MonoTorrent/Messages/IMessage.cs | 2 +- src/MonoTorrent/RawTrackerTier.cs | 66 +++++---- src/MonoTorrent/RawTrackerTiers.cs | 75 +++++----- src/MonoTorrent/ToolBox.cs | 3 +- src/MonoTorrent/Torrent.cs | 22 +-- src/MonoTorrent/TorrentFile.cs | 8 +- src/MonoTorrent/UriHelper.cs | 134 +++++++++-------- .../ClientSchemaTests/SchemaBuilderFixture.cs | 17 +-- .../Blacklist/BlacklistResource.cs | 9 +- .../Calendar/CalendarFeedModule.cs | 29 ++-- src/NzbDrone.Api/Calendar/CalendarModule.cs | 23 ++- src/NzbDrone.Api/Commands/CommandModule.cs | 5 +- src/NzbDrone.Api/Commands/CommandResource.cs | 50 ++++--- .../Config/DownloadClientConfigModule.cs | 1 - .../Config/DownloadClientConfigResource.cs | 2 +- src/NzbDrone.Api/Config/HostConfigResource.cs | 5 +- .../Config/IndexerConfigModule.cs | 3 +- .../Config/IndexerConfigResource.cs | 2 +- .../Config/MediaManagementConfigResource.cs | 2 +- src/NzbDrone.Api/Config/NamingConfigModule.cs | 6 +- .../Config/NamingConfigResource.cs | 3 +- .../Config/NetImportConfigModule.cs | 3 +- .../Config/NetImportConfigResource.cs | 4 +- .../Config/NzbDroneConfigModule.cs | 9 +- src/NzbDrone.Api/Config/UiConfigModule.cs | 1 - src/NzbDrone.Api/Config/UiConfigResource.cs | 4 +- src/NzbDrone.Api/DiskSpace/DiskSpaceModule.cs | 3 +- .../DiskSpace/DiskSpaceResource.cs | 5 +- .../DownloadClient/DownloadClientModule.cs | 6 +- .../ExtraFiles/ExtraFileModule.cs | 2 +- .../ExtraFiles/ExtraFileResource.cs | 18 ++- .../FileSystem/FileSystemModule.cs | 11 +- src/NzbDrone.Api/Health/HealthResource.cs | 7 +- src/NzbDrone.Api/History/HistoryModule.cs | 4 +- src/NzbDrone.Api/History/HistoryResource.cs | 11 +- src/NzbDrone.Api/Indexers/IndexerModule.cs | 6 +- src/NzbDrone.Api/Indexers/ReleaseModule.cs | 14 +- .../Indexers/ReleasePushModule.cs | 12 +- src/NzbDrone.Api/Indexers/ReleaseResource.cs | 14 +- src/NzbDrone.Api/Logs/LogFileModuleBase.cs | 4 +- src/NzbDrone.Api/Logs/LogResource.cs | 5 +- src/NzbDrone.Api/Logs/UpdateLogFileModule.cs | 5 +- .../ManualImport/ManualImportResource.cs | 8 +- .../MediaCovers/MediaCoverModule.cs | 9 +- src/NzbDrone.Api/Metadata/MetadataModule.cs | 6 +- .../MovieFiles/MovieFileModule.cs | 5 +- .../MovieFiles/MovieFileResource.cs | 17 ++- .../Movies/AlternativeTitleModule.cs | 2 +- .../Movies/AlternativeTitleResource.cs | 16 ++- .../Movies/AlternativeYearResource.cs | 2 - .../Movies/FetchMovieListModule.cs | 8 +- .../Movies/MovieBulkImportModule.cs | 33 ++--- .../Movies/MovieDiscoverModule.cs | 13 +- src/NzbDrone.Api/Movies/MovieEditorModule.cs | 16 ++- src/NzbDrone.Api/Movies/MovieLookupModule.cs | 12 +- src/NzbDrone.Api/Movies/MovieModule.cs | 39 ++--- .../Movies/MovieModuleWithSignalR.cs | 1 - src/NzbDrone.Api/Movies/MovieResource.cs | 27 ++-- src/NzbDrone.Api/Movies/RenameMovieModule.cs | 7 +- .../Movies/RenameMovieResource.cs | 7 +- .../NetImport/ImportExclusionsModule.cs | 5 +- .../NetImport/ImportExclusionsResource.cs | 5 +- .../NetImport/ListImportModule.cs | 8 +- src/NzbDrone.Api/NetImport/NetImportModule.cs | 9 +- .../Notifications/NotificationModule.cs | 6 +- src/NzbDrone.Api/Parse/ParseModule.cs | 1 - src/NzbDrone.Api/Parse/ParseResource.cs | 2 +- .../Profiles/Delay/DelayProfileModule.cs | 4 +- .../Profiles/Delay/DelayProfileResource.cs | 12 +- .../Profiles/Languages/LanguageModule.cs | 10 +- .../Profiles/LegacyProfileModule.cs | 2 +- src/NzbDrone.Api/Profiles/ProfileResource.cs | 44 ++++-- .../Profiles/ProfileSchemaModule.cs | 3 +- .../Profiles/ProfileValidation.cs | 1 - src/NzbDrone.Api/ProviderModuleBase.cs | 11 +- src/NzbDrone.Api/ProviderResource.cs | 2 +- .../Qualities/CustomFormatModule.cs | 16 ++- .../Qualities/CustomFormatResource.cs | 2 +- .../Qualities/FormatTagMatchResultResource.cs | 7 +- .../Qualities/FormatTagValidator.cs | 10 +- .../Qualities/QualityDefinitionModule.cs | 2 +- .../Qualities/QualityDefinitionResource.cs | 12 +- src/NzbDrone.Api/Queue/QueueActionModule.cs | 10 +- src/NzbDrone.Api/Queue/QueueResource.cs | 11 +- .../RemotePathMappingResource.cs | 12 +- .../Restrictions/RestrictionModule.cs | 1 - .../Restrictions/RestrictionResource.cs | 12 +- .../RootFolders/RootFolderModule.cs | 5 +- .../RootFolders/RootFolderResource.cs | 12 +- .../System/Backup/BackupModule.cs | 17 +-- .../System/Backup/BackupResource.cs | 2 +- src/NzbDrone.Api/System/SystemModule.cs | 11 +- src/NzbDrone.Api/System/Tasks/TaskModule.cs | 16 +-- src/NzbDrone.Api/Tags/TagResource.cs | 12 +- src/NzbDrone.Api/Update/UpdateResource.cs | 8 +- .../Wanted/LegacyMissingModule.cs | 5 +- src/NzbDrone.Api/Wanted/MovieCutoffModule.cs | 4 +- src/NzbDrone.Api/Wanted/MovieMissingModule.cs | 4 +- .../AutomationTest.cs | 3 +- .../AutomationTestAttribute.cs | 1 - src/NzbDrone.Automation.Test/MainPagesTest.cs | 42 +++--- .../CacheTests/CachedFixture.cs | 16 +-- .../ConfigFileProviderTest.cs | 15 -- .../DiskTests/DiskProviderFixtureBase.cs | 13 +- .../DiskTests/DiskTransferServiceFixture.cs | 28 +++- .../DiskTests/FreeSpaceFixtureBase.cs | 7 +- .../EnsureTest/PathExtensionFixture.cs | 1 - .../EnvironmentProviderTest.cs | 2 - .../EnvironmentProviderTest.cs | 2 - .../StartupArgumentsFixture.cs | 3 - .../ExceptByFixture.cs | 2 +- .../IPAddressExtensionsFixture.cs | 1 - .../Http/HttpClientFixture.cs | 16 ++- .../Http/HttpHeaderFixture.cs | 12 +- .../Http/HttpRequestBuilderFixture.cs | 1 - .../CleanseLogMessageFixture.cs | 9 +- .../SentryTargetFixture.cs | 53 ++++--- src/NzbDrone.Common.Test/OsPathFixture.cs | 4 +- .../PathExtensionFixture.cs | 10 +- .../ProcessProviderFixture.cs | 19 ++- .../ServiceFactoryFixture.cs | 2 +- .../ServiceProviderTests.cs | 6 +- .../TPLTests/DebouncerFixture.cs | 5 - .../TPLTests/RateLimitServiceFixture.cs | 2 +- src/NzbDrone.Common/ArchiveService.cs | 5 +- src/NzbDrone.Common/Cache/CacheManager.cs | 1 - src/NzbDrone.Common/Cache/Cached.cs | 2 - src/NzbDrone.Common/Cache/CachedDictionary.cs | 3 +- src/NzbDrone.Common/Composition/Container.cs | 15 +- .../Composition/ContainerBuilderBase.cs | 16 +-- src/NzbDrone.Common/Composition/IContainer.cs | 12 +- src/NzbDrone.Common/ConvertBase32.cs | 2 +- .../Disk/DestinationAlreadyExistsException.cs | 12 +- src/NzbDrone.Common/Disk/DiskProviderBase.cs | 18 +-- .../Disk/DiskTransferService.cs | 34 ++++- .../Disk/FileSystemLookupService.cs | 1 - .../Disk/NotParentException.cs | 6 +- src/NzbDrone.Common/Disk/OsPath.cs | 43 +++++- .../EnsureThat/EnsureBoolExtensions.cs | 4 + .../EnsureThat/EnsureCollectionExtensions.cs | 16 ++- .../EnsureThat/EnsureDateTimeExtensions.cs | 17 ++- .../EnsureThat/EnsureDecimalExtensions.cs | 12 ++ .../EnsureThat/EnsureDoubleExtensions.cs | 12 ++ .../EnsureThat/EnsureGuidExtensions.cs | 2 + .../EnsureThat/EnsureIntExtensions.cs | 14 ++ .../EnsureThat/EnsureLongExtensions.cs | 12 ++ .../EnsureNullableValueTypeExtensions.cs | 5 +- .../EnsureThat/EnsureObjectExtensions.cs | 5 +- .../EnsureThat/EnsureShortExtensions.cs | 12 ++ .../EnsureThat/EnsureStringExtensions.cs | 24 +++- .../EnsureThat/EnsureTypeExtensions.cs | 4 +- .../EnsureThat/ExpressionExtensions.cs | 8 ++ src/NzbDrone.Common/EnsureThat/Param.cs | 3 +- .../Resources/ExceptionMessages.Designer.cs | 135 ++++++++++++------ .../EnvironmentInfo/AppFolderFactory.cs | 27 ++-- .../EnvironmentInfo/AppFolderInfo.cs | 6 +- .../EnvironmentInfo/BuildInfo.cs | 2 +- .../EnvironmentInfo/IOsVersionAdapter.cs | 1 - src/NzbDrone.Common/EnvironmentInfo/OsInfo.cs | 5 +- .../EnvironmentInfo/OsVersionModel.cs | 2 - .../EnvironmentInfo/PlatformInfo.cs | 10 +- .../EnvironmentInfo/RuntimeInfo.cs | 70 +++++++-- .../Exceptions/NotParentException.cs | 6 +- .../Exceptions/NzbDroneException.cs | 3 - src/NzbDrone.Common/Expansive/Expansive.cs | 47 +++--- src/NzbDrone.Common/Expansive/TreeNode.cs | 21 +-- src/NzbDrone.Common/Expansive/TreeNodeList.cs | 17 ++- .../Extensions/DictionaryExtensions.cs | 11 +- .../Extensions/ExceptionExtensions.cs | 26 ++-- .../Extensions/IEnumerableExtensions.cs | 23 ++- .../Extensions/Int64Extensions.cs | 11 +- .../Extensions/LevenstheinExtensions.cs | 17 ++- .../Extensions/ObjectExtensions.cs | 3 +- .../Extensions/PathExtensions.cs | 10 +- .../Extensions/StreamExtensions.cs | 1 + .../Extensions/StringExtensions.cs | 14 +- .../Extensions/UrlExtensions.cs | 1 - src/NzbDrone.Common/HashUtil.cs | 3 +- .../Http/Dispatchers/ManagedHttpDispatcher.cs | 1 + src/NzbDrone.Common/Http/HttpClient.cs | 12 +- src/NzbDrone.Common/Http/HttpException.cs | 2 - src/NzbDrone.Common/Http/HttpHeader.cs | 16 ++- src/NzbDrone.Common/Http/HttpRequest.cs | 1 - .../Http/HttpRequestBuilder.cs | 25 +++- .../Http/HttpRequestBuilderFactory.cs | 1 - src/NzbDrone.Common/Http/HttpResponse.cs | 5 +- src/NzbDrone.Common/Http/HttpUri.cs | 11 +- .../Http/JsonRpcRequestBuilder.cs | 2 +- .../Http/Proxy/HttpProxySettings.cs | 6 +- .../Http/Proxy/ManagedWebProxyFactory.cs | 2 + .../Http/TlsFailureException.cs | 2 - .../Http/UnexpectedHtmlContentException.cs | 1 - .../Instrumentation/CleansingJsonVisitor.cs | 1 + .../GlobalExceptionHandlers.cs | 7 +- .../Instrumentation/LogEventExtensions.cs | 1 - .../Instrumentation/NzbDroneLogger.cs | 8 +- .../Instrumentation/Sentry/SentryCleanser.cs | 7 +- .../Instrumentation/Sentry/SentryTarget.cs | 48 ++++--- src/NzbDrone.Common/OAuth/OAuthRequest.cs | 16 +-- src/NzbDrone.Common/OAuth/OAuthTools.cs | 18 +-- .../OAuth/WebParameterCollection.cs | 17 +-- src/NzbDrone.Common/PathEqualityComparer.cs | 1 - .../Processes/ProcessProvider.cs | 30 ++-- .../Reflection/ReflectionExtensions.cs | 7 +- .../Serializer/IntConverter.cs | 1 + src/NzbDrone.Common/Serializer/Json.cs | 6 +- src/NzbDrone.Common/Serializer/JsonVisitor.cs | 3 +- .../UnderscoreStringEnumConverter.cs | 2 + src/NzbDrone.Common/ServiceFactory.cs | 14 +- src/NzbDrone.Common/ServiceProvider.cs | 3 +- src/NzbDrone.Common/TPL/Debouncer.cs | 2 +- .../LimitedConcurrencyLevelTaskScheduler.cs | 53 +++++-- src/NzbDrone.Common/TPL/RateLimitService.cs | 2 +- src/NzbDrone.Common/TinyIoC.cs | 45 ++++-- src/NzbDrone.Console/ConsoleApp.cs | 6 +- .../BlacklistRepositoryFixture.cs | 14 +- .../Blacklisting/BlacklistServiceFixture.cs | 14 +- .../BulkImport/AddMultiMoviesFixture.cs | 25 ++-- .../Configuration/ConfigCachingFixture.cs | 3 - .../Configuration/ConfigServiceFixture.cs | 1 - .../CustomFormat/CustomFormatsFixture.cs | 2 +- .../CustomFormat/QualityTagFixture.cs | 14 +- .../Datastore/BasicRepositoryFixture.cs | 9 +- .../Converters/BooleanIntConverterFixture.cs | 18 +-- .../Converters/CommandConverterFixture.cs | 16 +-- .../Converters/DoubleConverterFixture.cs | 18 +-- .../Converters/EnumIntConverterFixture.cs | 16 +-- .../Converters/GuidConverterFixture.cs | 12 +- .../Converters/Int32ConverterFixture.cs | 18 +-- .../Converters/OsPathConverterFixture.cs | 12 +- .../ProviderSettingConverterFixture.cs | 8 +- .../Converters/QualityIntConverterFixture.cs | 12 +- .../Converters/TimeSpanConverterFixture.cs | 18 +-- .../Converters/UtcConverterFixture.cs | 10 +- .../Datastore/DatabaseFixture.cs | 3 +- .../Datastore/DatabaseRelationshipFixture.cs | 16 +-- .../Datastore/MappingExtentionFixture.cs | 4 - .../Datastore/MarrDataLazyLoadingFixture.cs | 22 ++- .../Migration/070_delay_profileFixture.cs | 44 +++--- .../072_history_downloadIdFixture.cs | 23 ++- .../Migration/075_force_lib_updateFixture.cs | 25 ++-- ..._prefix_to_transmission_categoryFixture.cs | 2 +- .../090_update_kickass_urlFixture.cs | 1 + .../Migration/147_custom_formatsFixture.cs | 31 ++-- .../149_regex_required_tagsFixture.cs | 11 +- ...ix_format_tags_double_underscoreFixture.cs | 7 +- .../Datastore/ObjectDatabaseFixture.cs | 15 +- .../PagingOffsetFixture.cs | 13 +- .../ToSortDirectionFixture.cs | 12 +- .../ReflectionStrategyFixture/Benchmarks.cs | 45 +++--- .../SqliteSchemaDumperFixture.cs | 1 - .../AcceptableSizeSpecificationFixture.cs | 75 +++++----- ...matAllowedByProfileSpecificationFixture.cs | 43 +++--- .../CutoffSpecificationFixture.cs | 20 +-- .../DownloadDecisionMakerFixture.cs | 18 +-- .../HistorySpecificationFixture.cs | 22 +-- .../LanguageSpecificationFixture.cs | 22 +-- .../MonitoredMovieSpecificationFixture.cs | 6 +- .../PrioritizeDownloadDecisionFixture.cs | 40 +++--- .../ProtocolSpecificationFixture.cs | 2 +- ...ityAllowedByProfileSpecificationFixture.cs | 24 ++-- .../QualityUpgradeSpecificationFixture.cs | 7 +- .../QueueSpecificationFixture.cs | 24 ++-- .../RawDiskSpecificationFixture.cs | 13 +- ...ReleaseRestrictionsSpecificationFixture.cs | 20 +-- .../RepackSpecificationFixture.cs | 6 +- .../RssSync/DelaySpecificationFixture.cs | 4 +- .../RssSync/ProperSpecificationFixture.cs | 5 +- .../Search/MovieSpecificationFixture.cs | 2 +- .../TorrentSeedingSpecificationFixture.cs | 4 +- .../UpgradeDiskSpecificationFixture.cs | 2 +- .../DiskSpace/DiskSpaceServiceFixture.cs | 2 +- .../CompletedDownloadServiceFixture.cs | 42 +++--- .../DownloadApprovedFixture.cs | 33 ++--- .../Blackhole/UsenetBlackholeFixture.cs | 3 - .../DelugeTests/DelugeFixture.cs | 94 ++++++------ .../DownloadClientFixtureBase.cs | 26 ++-- .../TorrentDownloadStationFixture.cs | 56 ++++---- .../UsenetDownloadStationFixture.cs | 25 ++-- .../HadoukenTests/HadoukenFixture.cs | 14 +- .../NzbVortexTests/NzbVortexFixture.cs | 70 ++++----- .../NzbgetTests/NzbgetFixture.cs | 92 ++++++------ .../PneumaticProviderFixture.cs | 1 - .../QBittorrentTests/QBittorrentFixture.cs | 29 ++-- .../RTorrentTests/RTorrentFixture.cs | 5 +- .../SabnzbdQueueTimeConverterFixture.cs | 6 +- .../SabnzbdTests/SabnzbdFixture.cs | 66 ++++----- .../TransmissionTests/TransmissionFixture.cs | 4 +- .../TransmissionFixtureBase.cs | 5 +- .../UTorrentTests/UTorrentFixture.cs | 106 +++++++------- .../VuzeTests/VuzeFixture.cs | 1 - .../Download/DownloadServiceFixture.cs | 11 +- .../Download/FailedDownloadServiceFixture.cs | 5 +- .../PendingReleaseServiceTests/AddFixture.cs | 15 +- .../PendingReleaseServiceFixture.cs | 9 +- .../RemoveGrabbedFixture.cs | 15 +- .../RemovePendingFixture.cs | 15 +- .../RemoveRejectedFixture.cs | 15 +- .../TrackedDownloadServiceFixture.cs | 22 +-- .../Roksbox/FindMetadataFileFixture.cs | 2 +- .../Consumers/Wdtv/FindMetadataFileFixture.cs | 2 +- .../Consumers/Xbmc/FindMetadataFileFixture.cs | 2 +- src/NzbDrone.Core.Test/FluentTest.cs | 35 +---- src/NzbDrone.Core.Test/Framework/CoreTest.cs | 13 +- src/NzbDrone.Core.Test/Framework/DbTest.cs | 5 +- .../Framework/DirectDataMapper.cs | 9 +- .../Framework/MigrationTest.cs | 3 +- .../Framework/NBuilderExtensions.cs | 10 +- .../Framework/TestDatabase.cs | 36 +++-- .../Checks/DeleteBadMediaCovers.cs | 20 +-- .../Checks/DownloadClientCheckFixture.cs | 2 +- .../Checks/IndexerSearchCheckFixture.cs | 1 - .../Checks/IndexerStatusCheckFixture.cs | 15 +- .../Checks/MonoVersionCheckFixture.cs | 1 - .../Checks/RootFolderCheckFixture.cs | 2 +- .../HistoryTests/HistoryRepositoryFixture.cs | 8 +- .../HistoryTests/HistoryServiceFixture.cs | 18 +-- .../CleanupOrphanedBlacklistFixture.cs | 10 +- .../CleanupOrphanedHistoryItemsFixture.cs | 7 +- .../CleanupOrphanedMetadataFilesFixture.cs | 6 +- .../CleanupOrphanedMovieFilesFixture.cs | 8 +- .../CleanupOrphanedPendingReleasesFixture.cs | 2 +- .../Housekeepers/CleanupUnusedTagsFixture.cs | 4 +- ...xFutureDownloadClientStatusTimesFixture.cs | 18 +-- .../FixFutureIndexerStatusTimesFixture.cs | 18 +-- .../Http/HttpProxySettingsProviderFixture.cs | 8 +- .../TorCacheHttpRequestInterceptorFixture.cs | 4 +- .../IndexerTests/BasicRssParserFixture.cs | 1 - .../IndexerTests/HDBitsTests/HDBitsFixture.cs | 3 +- .../IPTorrentsTests/IPTorrentsFixture.cs | 20 +-- .../IndexerTests/IndexerServiceFixture.cs | 2 +- .../IndexerIntegrationTests.cs | 7 +- .../NewznabTests/NewznabFixture.cs | 16 +-- .../NewznabRequestGeneratorFixture.cs | 9 +- .../NewznabTests/NewznabSettingFixture.cs | 7 - .../IndexerTests/NyaaTests/NyaaFixture.cs | 10 +- .../OmgwtfnzbsTests/OmgwtfnzbsFixture.cs | 14 +- .../IndexerTests/PTPTests/PTPFixture.cs | 5 +- .../IndexerTests/RarbgTests/RarbgFixture.cs | 8 +- .../IndexerTests/TestIndexer.cs | 1 - .../TestTorrentRssIndexer.cs | 6 +- .../TorrentRssIndexerFixture.cs | 3 +- .../TorrentRssParserFactoryFixture.cs | 8 +- .../TorrentRssSettingsDetectorFixture.cs | 16 +-- .../TorznabTests/TorznabFixture.cs | 14 +- .../DatabaseTargetFixture.cs | 6 +- .../Languages/LanguageFixture.cs | 96 +++++++------ .../CoverExistsSpecificationFixture.cs | 5 - .../MediaCoverServiceFixture.cs | 11 +- .../DiskScanServiceTests/ScanFixture.cs | 2 +- .../DownloadedMoviesCommandServiceFixture.cs | 2 +- .../DownloadedMoviesImportServiceFixture.cs | 6 +- .../MediaFiles/ImportApprovedMoviesFixture.cs | 16 +-- .../MediaFiles/MediaFileRepositoryFixture.cs | 4 +- .../MediaFileServiceTests/FilterFixture.cs | 20 ++- .../MediaFileTableCleanupServiceFixture.cs | 5 +- .../FormatAudioChannelsFixture.cs | 4 +- .../UpdateMediaInfoServiceFixture.cs | 18 +-- .../MediaInfo/VideoFileInfoReaderFixture.cs | 1 - .../MoveMovieFileFixture.cs | 2 +- .../Aggregators/AggregateLanguageFixture.cs | 3 +- .../AugmentQualityFromMediaInfoFixture.cs | 4 +- .../MovieImport/DetectSampleFixture.cs | 5 +- .../MovieImport/ImportDecisionMakerFixture.cs | 11 +- .../FreeSpaceSpecificationFixture.cs | 13 +- .../MatchesFolderSpecificationFixture.cs | 1 - .../NotSampleSpecificationFixture.cs | 10 +- .../NotUnpackingSpecificationFixture.cs | 2 +- .../SameFileSpecificationFixture.cs | 2 +- .../UpgradeSpecificationFixture.cs | 21 ++- .../RenameMovieFileServiceFixture.cs | 4 +- .../UpdateMovieFileQualityServiceFixture.cs | 8 +- .../UpgradeMediaFileServiceFixture.cs | 11 +- .../CommandEqualityComparerFixture.cs | 2 +- .../Commands/CommandExecutorFixture.cs | 3 - .../Events/EventAggregatorFixture.cs | 95 +++--------- .../SearchMovieComparerFixture.cs | 2 +- .../SkyHook/SkyHookProxyFixture.cs | 3 +- .../SkyHook/SkyHookProxySearchFixture.cs | 1 + .../AlternativeTitleServiceFixture.cs | 18 +-- .../MovieTests/MoveMovieServiceFixture.cs | 5 +- .../MovieRepositoryFixture.cs | 18 ++- .../MovieServiceTests/AddMovieFixture.cs | 18 ++- .../MovieTests/RefreshMovieServiceFixture.cs | 4 +- .../CouchPotato/CouchPotatoParserFixture.cs | 1 - .../NetImport/RSSImportFixture.cs | 2 +- .../NetImport/RSSImportParserFixture.cs | 1 - .../NotificationBaseFixture.cs | 19 +-- .../SynologyIndexerFixture.cs | 4 +- .../Xbmc/GetMoviePathFixture.cs | 2 +- .../Xbmc/OnDownloadFixture.cs | 16 +-- .../Xbmc/UpdateMovieFixture.cs | 6 +- .../OrganizerTests/CleanFixture.cs | 1 - .../FileNameBuilderTests/CleanTitleFixture.cs | 3 +- .../FileNameBuilderFixture.cs | 88 ++++++------ .../FileNameBuilderTests/IdFixture.cs | 4 +- .../OrganizerTests/GetMovieFolderFixture.cs | 12 +- .../ParserTests/NormalizeTitleFixture.cs | 4 +- .../ParserTests/ParserFixture.cs | 1 - .../AugmentMovieInfoFixture.cs | 3 +- .../AugmentWithHistoryFixture.cs | 9 +- .../AugmentWithParsedMovieInfo.cs | 4 +- .../AugmentWithReleaseInfoFixture.cs | 5 +- .../ParsingServiceTests/GetMovieFixture.cs | 4 +- .../ParsingServiceTests/MapFixture.cs | 7 +- .../ParserTests/QualityParserFixture.cs | 8 +- .../ParserTests/ReleaseGroupParserFixture.cs | 5 +- .../RomanNumeralConversionFixture.cs | 7 +- .../ParserTests/SceneCheckerFixture.cs | 3 - .../Delay/DelayProfileServiceFixture.cs | 1 - .../Profiles/ProfileRepositoryFixture.cs | 16 +-- .../Profiles/ProfileServiceFixture.cs | 13 +- .../ArchiveProviderFixture.cs | 4 +- .../GetVideoFilesFixture.cs | 1 - .../RecycleBinProviderTests/CleanupFixture.cs | 4 +- .../DeleteFileFixture.cs | 1 - .../RecycleBinProviderTests/EmptyFixture.cs | 4 +- .../QualityDefinitionServiceFixture.cs | 4 +- .../Qualities/QualityFixture.cs | 64 +++++---- .../Qualities/QualityModelComparerFixture.cs | 14 +- .../Qualities/RevisionComparableFixture.cs | 8 +- .../QueueTests/QueueServiceFixture.cs | 8 +- .../RemotePathMappingServiceFixture.cs | 4 +- .../RootFolderServiceFixture.cs | 8 +- .../ThingiProvider/ProviderBaseFixture.cs | 3 +- .../ProviderBaseFixture.cs | 2 +- .../ProviderStatusServiceFixture.cs | 1 - .../UpdatePackageProviderFixture.cs | 3 +- .../UpdateTests/UpdateServiceFixture.cs | 11 +- .../SystemFolderValidatorFixture.cs | 4 +- .../Analytics/AnalyticsService.cs | 2 +- .../Authentication/UserService.cs | 10 +- src/NzbDrone.Core/Backup/BackupService.cs | 10 +- .../Backup/MakeDatabaseBackup.cs | 2 + .../Backup/RestoreBackupFailedException.cs | 6 +- src/NzbDrone.Core/Blacklisting/Blacklist.cs | 4 +- .../Blacklisting/BlacklistRepository.cs | 6 +- .../Blacklisting/BlacklistService.cs | 44 +++--- .../Configuration/ConfigFileProvider.cs | 7 +- .../Configuration/ConfigRepository.cs | 4 +- .../Configuration/ConfigService.cs | 9 +- .../Configuration/IConfigService.cs | 2 +- .../InvalidConfigFileException.cs | 6 +- .../CustomFormats/CustomFormat.cs | 40 ++++-- .../CustomFormats/CustomFormatRepository.cs | 1 - .../CustomFormats/CustomFormatService.cs | 56 +++++--- src/NzbDrone.Core/CustomFormats/FormatTag.cs | 50 +++++-- .../CustomFormats/FormatTagMatchResult.cs | 2 + .../Datastore/BasicRepository.cs | 7 +- .../Converters/BooleanIntConverter.cs | 2 +- .../Datastore/Converters/CommandConverter.cs | 2 +- .../Converters/CustomFormatIntConverter.cs | 9 +- .../Converters/EmbeddedDocumentConverter.cs | 28 ++-- .../Converters/LanguageIntConverter.cs | 5 +- .../Converters/ProviderSettingConverter.cs | 4 +- .../Converters/QualityIntConverter.cs | 7 +- .../Converters/QualityTagStringConverter.cs | 9 +- .../Datastore/CorruptDatabaseException.cs | 12 +- src/NzbDrone.Core/Datastore/Database.cs | 1 + src/NzbDrone.Core/Datastore/DbFactory.cs | 3 +- .../Datastore/Events/ModelEvent.cs | 2 +- .../Datastore/Extensions/MappingExtensions.cs | 18 ++- .../Extensions/PagingSpecExtensions.cs | 8 +- .../Extensions/RelationshipExtensions.cs | 3 +- src/NzbDrone.Core/Datastore/LazyList.cs | 2 - src/NzbDrone.Core/Datastore/LogDatabase.cs | 1 - src/NzbDrone.Core/Datastore/MainDatabase.cs | 1 - .../Datastore/Migration/001_initial_setup.cs | 2 - .../Migration/004_updated_history.cs | 1 - .../Migration/018_remove_duplicates.cs | 10 +- .../019_restore_unique_constraints.cs | 1 - .../020_add_year_and_seasons_to_series.cs | 2 +- .../Datastore/Migration/027_fix_omgwtfnzbs.cs | 8 +- .../029_add_formats_to_naming_config.cs | 17 ++- .../Migration/033_add_api_key_to_pushover.cs | 4 +- .../036_update_with_quality_converters.cs | 16 +-- .../037_add_configurable_qualities.cs | 6 +- .../043_convert_config_to_download_clients.cs | 42 +++--- .../048_add_title_to_scenemappings.cs | 4 +- .../050_add_hash_to_metadata_files.cs | 4 +- .../Migration/051_download_client_import.cs | 42 +++--- .../Migration/052_add_columns_for_anime.cs | 4 +- ...7_convert_episode_file_path_to_relative.cs | 1 - .../Migration/062_convert_quality_models.cs | 3 + .../Datastore/Migration/069_quality_proper.cs | 14 +- .../Datastore/Migration/070_delay_profile.cs | 23 +-- .../071_unknown_quality_in_profile.cs | 23 ++- .../Datastore/Migration/072_history_grabid.cs | 1 - .../Datastore/Migration/073_clear_ratings.cs | 2 +- .../Datastore/Migration/079_dedupe_tags.cs | 8 +- .../085_expand_transmission_urlbase.cs | 2 + .../Migration/086_pushbullet_device_ids.cs | 2 + .../088_pushbullet_devices_channels_list.cs | 4 +- .../Migration/090_update_kickass_url.cs | 3 +- .../Migration/104_add_moviefiles_table.cs | 2 - .../109_add_movie_formats_to_naming_config.cs | 11 +- .../110_add_physical_release_to_table.cs | 4 - .../Migration/117_update_movie_file.cs | 1 + .../119_add_youtube_trailer_id_table .cs | 2 - .../Migration/120_add_studio_to_table.cs | 1 - .../Migration/121_update_filedate_config.cs | 4 +- .../Migration/122_add_movieid_to_blacklist.cs | 1 - .../Migration/123_create_netimport_table.cs | 2 +- .../124_add_preferred_tags_to_profile.cs | 1 - .../Migration/125_fix_imdb_unique.cs | 5 +- .../Migration/133_add_minimumavailability.cs | 6 +- .../137_add_import_exclusions_table.cs | 21 +-- .../140_add_alternative_titles_table.cs | 2 +- .../Migration/141_fix_duplicate_alt_titles.cs | 1 - .../144_add_cookies_to_indexer_status.cs | 1 - .../Migration/147_add_custom_formats.cs | 1 - .../149_convert_regex_required_tags.cs | 24 +++- ..._add_language_to_file_history_blacklist.cs | 16 ++- .../156_add_download_client_priority.cs | 1 - .../Migration/159_add_webrip_qualities.cs | 11 +- .../Framework/MigrationController.cs | 9 +- .../Migration/Framework/SqliteSchemaDumper.cs | 16 ++- .../Migration/Framework/SqliteSyntaxReader.cs | 32 ++++- .../Migration/Framework/TableDefinition.cs | 5 - .../Datastore/ModelConflictException.cs | 2 - .../Datastore/ModelNotFoundException.cs | 1 - src/NzbDrone.Core/Datastore/TableMapping.cs | 61 ++++---- .../DownloadDecisionComparer.cs | 8 +- .../DecisionEngine/DownloadDecisionMaker.cs | 22 ++- .../DownloadDecisionPriorizationService.cs | 4 +- .../AcceptableSizeSpecification.cs | 4 +- .../AlreadyImportedSpecification.cs | 3 +- .../Specifications/BlacklistSpecification.cs | 1 - .../Specifications/MinimumAgeSpecification.cs | 1 - .../Specifications/QueueSpecification.cs | 1 - .../Specifications/RepackSpecification.cs | 6 +- .../RequiredIndexerFlagsSpecification.cs | 7 +- .../RssSync/AvailabilitySpecification.cs | 3 +- .../RssSync/DelaySpecification.cs | 22 ++- .../RssSync/HistorySpecification.cs | 63 ++++---- .../RssSync/ProperSpecification.cs | 23 ++- .../Specifications/UpgradableSpecification.cs | 1 - .../UpgradeDiskSpecification.cs | 11 +- .../DiskSpace/DiskSpaceService.cs | 12 +- .../Clients/Blackhole/ScanWatchFolder.cs | 2 +- .../Clients/Blackhole/WatchFolderItem.cs | 5 +- .../Download/Clients/Deluge/Deluge.cs | 22 ++- .../Clients/Deluge/DelugeException.cs | 2 +- .../Download/Clients/Deluge/DelugeProxy.cs | 33 +++-- .../Clients/Deluge/DelugeTorrentStatus.cs | 2 +- .../DownloadClientAuthenticationException.cs | 3 - .../DownloadStation/DiskStationApiInfo.cs | 5 +- .../DownloadStationSettings.cs | 4 +- .../DownloadStation/DownloadStationTask.cs | 9 +- .../DownloadStationTaskAdditional.cs | 4 +- .../DownloadStation/Proxies/DSMInfoProxy.cs | 4 +- .../Proxies/DiskStationProxyBase.cs | 6 +- .../Proxies/DownloadStationInfoProxy.cs | 10 +- .../Responses/DiskStationError.cs | 4 +- .../Responses/DiskStationInfoResponse.cs | 1 - .../Responses/DiskStationResponse.cs | 3 +- .../DownloadStationTaskInfoResponse.cs | 2 +- .../FileStationListFileInfoResponse.cs | 2 +- .../DownloadStation/SerialNumberProvider.cs | 2 +- .../DownloadStation/SharedFolderResolver.cs | 2 +- .../DownloadStation/TorrentDownloadStation.cs | 11 +- .../DownloadStation/UsenetDownloadStation.cs | 14 +- .../Download/Clients/Hadouken/Hadouken.cs | 12 +- .../Clients/Hadouken/HadoukenProxy.cs | 2 +- .../Download/Clients/NzbVortex/NzbVortex.cs | 40 +++--- .../NzbVortexAuthenticationException.cs | 14 +- .../NzbVortexNotLoggedInException.cs | 17 ++- .../Clients/NzbVortex/NzbVortexProxy.cs | 1 - .../Download/Clients/Nzbget/Nzbget.cs | 16 ++- .../Download/Clients/Nzbget/NzbgetProxy.cs | 8 +- .../Download/Clients/Nzbget/NzbgetResponse.cs | 1 - .../Download/Clients/Pneumatic/Pneumatic.cs | 4 +- .../Clients/QBittorrent/QBittorrent.cs | 61 ++++---- .../QBittorrent/QBittorrentProxySelector.cs | 7 +- .../Clients/QBittorrent/QBittorrentProxyV1.cs | 13 +- .../Clients/QBittorrent/QBittorrentProxyV2.cs | 11 +- .../SabnzbdPriorityTypeConverter.cs | 2 +- .../SabnzbdQueueTimeConverter.cs | 4 +- .../Download/Clients/Sabnzbd/Sabnzbd.cs | 19 ++- .../Download/Clients/Sabnzbd/SabnzbdProxy.cs | 8 +- .../Clients/Transmission/Transmission.cs | 6 +- .../Clients/Transmission/TransmissionBase.cs | 36 +++-- .../Transmission/TransmissionException.cs | 1 - .../Clients/Transmission/TransmissionProxy.cs | 19 +-- .../Transmission/TransmissionSettings.cs | 2 +- .../Download/Clients/rTorrent/RTorrent.cs | 30 ++-- .../Clients/rTorrent/RTorrentProxy.cs | 9 +- .../Download/Clients/uTorrent/UTorrent.cs | 29 ++-- .../Clients/uTorrent/UTorrentProxy.cs | 5 +- .../Clients/uTorrent/UTorrentTorrent.cs | 7 +- .../Download/CompletedDownloadService.cs | 3 +- .../Download/DownloadClientBase.cs | 11 +- .../Download/DownloadClientProvider.cs | 13 +- .../Download/DownloadClientRepository.cs | 1 - .../Download/DownloadClientStatus.cs | 1 - .../DownloadClientStatusRepository.cs | 1 - .../Download/DownloadClientStatusService.cs | 1 - .../Download/DownloadEventHub.cs | 1 - .../Download/DownloadFailedEvent.cs | 2 +- src/NzbDrone.Core/Download/DownloadService.cs | 2 +- .../Download/InvalidNzbException.cs | 12 +- .../Download/Pending/PendingReleaseService.cs | 14 +- .../Download/ProcessDownloadDecisions.cs | 5 +- .../RedownloadFailedDownloadService.cs | 2 +- .../Download/TorrentClientBase.cs | 12 +- .../DownloadMonitoringService.cs | 3 - .../TrackedDownloads/TrackedDownload.cs | 2 +- .../TrackedDownloadService.cs | 13 +- .../TrackedDownloadStatusMessage.cs | 1 - .../Download/UsenetClientBase.cs | 6 +- .../Exceptions/BadRequestException.cs | 6 +- .../Exceptions/DownstreamException.cs | 3 +- .../Exceptions/NzbDroneClientException.cs | 3 +- .../Exceptions/ReleaseDownloadException.cs | 3 +- .../Exceptions/SearchFailedException.cs | 3 +- src/NzbDrone.Core/Extras/ExtraService.cs | 3 +- .../Extras/Files/ExtraFileManager.cs | 2 - .../Extras/Files/ExtraFileRepository.cs | 3 +- .../Extras/Files/ExtraFileService.cs | 1 - .../MediaBrowser/MediaBrowserMetadata.cs | 15 +- .../Consumers/Roksbox/RoksboxMetadata.cs | 52 +++---- .../Metadata/Consumers/Wdtv/WdtvMetadata.cs | 52 +++---- .../Metadata/Consumers/Xbmc/XbmcMetadata.cs | 9 +- .../Metadata/ExistingMetadataImporter.cs | 4 +- .../Extras/Metadata/IMetadata.cs | 2 +- .../Extras/Metadata/MetadataBase.cs | 10 +- .../Extras/Metadata/MetadataService.cs | 3 +- .../Others/ExistingOtherExtraImporter.cs | 3 +- .../Subtitles/ExistingSubtitleImporter.cs | 19 ++- .../Extras/Subtitles/SubtitleService.cs | 6 +- src/NzbDrone.Core/Fluent.cs | 26 +++- .../HealthCheck/CheckOnAttribute.cs | 2 +- .../HealthCheck/Checks/DotnetVersionCheck.cs | 6 +- .../Checks/ImportMechanismCheck.cs | 1 - .../HealthCheck/Checks/IndexerRssCheck.cs | 2 +- .../HealthCheck/Checks/MonoVersionCheck.cs | 12 +- .../HealthCheck/Checks/ProxyCheck.cs | 8 +- .../HealthCheck/Checks/UpdateCheck.cs | 9 +- .../HealthCheck/HealthCheckService.cs | 3 - src/NzbDrone.Core/History/History.cs | 7 +- .../History/HistoryRepository.cs | 7 +- src/NzbDrone.Core/History/HistoryService.cs | 29 ++-- .../CleanupAdditionalNamingSpecs.cs | 1 - .../Housekeepers/CleanupAdditionalUsers.cs | 2 - ...ownloadClientUnavailablePendingReleases.cs | 8 +- .../CleanupDuplicateMetadataFiles.cs | 2 - .../CleanupOrphanedAlternativeTitles.cs | 1 - .../Housekeepers/CleanupOrphanedBlacklist.cs | 1 - .../CleanupOrphanedHistoryItems.cs | 1 - .../CleanupOrphanedIndexerStatus.cs | 1 - .../CleanupOrphanedMetadataFiles.cs | 3 - .../CleanupOrphanedPendingReleases.cs | 1 - .../Housekeepers/CleanupUnusedTags.cs | 3 +- .../Housekeepers/DeleteBadMediaCovers.cs | 12 +- .../FixFutureProviderStatusTimes.cs | 3 +- .../Housekeeping/HousekeepingService.cs | 3 +- .../CloudFlare/CloudFlareHttpInterceptor.cs | 3 +- .../Definitions/MovieSearchCriteria.cs | 1 - .../Definitions/SearchCriteriaBase.cs | 2 +- .../IndexerSearch/MoviesSearchCommand.cs | 4 +- .../IndexerSearch/MoviesSearchService.cs | 17 +-- .../IndexerSearch/NzbSearchService.cs | 17 +-- .../Indexers/AwesomeHD/AwesomeHD.cs | 3 +- .../AwesomeHD/AwesomeHDRequestGenerator.cs | 1 - .../Indexers/AwesomeHD/AwesomeHDRssParser.cs | 11 +- .../Indexers/Exceptions/ApiKeyException.cs | 6 +- .../Exceptions/SizeParsingException.cs | 3 +- .../Indexers/FetchAndParseRssService.cs | 7 +- src/NzbDrone.Core/Indexers/HDBits/HDBits.cs | 3 +- .../Indexers/HDBits/HDBitsParser.cs | 3 +- .../Indexers/HDBits/HDBitsRequestGenerator.cs | 1 + .../Indexers/HDBits/HDBitsSettings.cs | 2 +- src/NzbDrone.Core/Indexers/HttpIndexerBase.cs | 8 +- .../Indexers/IIndexerSettings.cs | 1 + .../Indexers/IPTorrents/IPTorrents.cs | 3 +- src/NzbDrone.Core/Indexers/IndexerBase.cs | 5 +- .../Indexers/IndexerPageableRequestChain.cs | 10 +- .../Indexers/IndexerRepository.cs | 1 - src/NzbDrone.Core/Indexers/IndexerStatus.cs | 1 - .../Indexers/IndexerStatusRepository.cs | 1 - .../Indexers/IndexerStatusService.cs | 3 - src/NzbDrone.Core/Indexers/Newznab/Newznab.cs | 33 +++-- .../Newznab/NewznabCapabilitiesProvider.cs | 2 +- .../Newznab/NewznabRequestGenerator.cs | 5 +- .../Indexers/Newznab/NewznabRssParser.cs | 11 +- .../Indexers/Newznab/NewznabSettings.cs | 15 +- src/NzbDrone.Core/Indexers/Nyaa/Nyaa.cs | 1 - .../Indexers/Nyaa/NyaaSettings.cs | 2 +- .../Indexers/Omgwtfnzbs/Omgwtfnzbs.cs | 1 - .../Omgwtfnzbs/OmgwtfnzbsRssParser.cs | 15 +- .../Indexers/PassThePopcorn/PassThePopcorn.cs | 8 +- .../PassThePopcorn/PassThePopcornApi.cs | 2 - .../PassThePopcorn/PassThePopcornParser.cs | 17 ++- .../PassThePopcornRequestGenerator.cs | 5 +- .../Indexers/Rarbg/RarbgParser.cs | 4 +- .../Indexers/Rarbg/RarbgRequestGenerator.cs | 3 +- .../Indexers/Rarbg/RarbgTokenProvider.cs | 6 +- .../Indexers/RssIndexerRequestGenerator.cs | 1 - src/NzbDrone.Core/Indexers/RssParser.cs | 12 +- src/NzbDrone.Core/Indexers/RssSyncCommand.cs | 1 - src/NzbDrone.Core/Indexers/RssSyncService.cs | 1 - .../Indexers/SeedConfigProvider.cs | 11 +- .../Indexers/TorrentPotato/TorrentPotato.cs | 3 - .../TorrentPotato/TorrentPotatoParser.cs | 4 +- .../TorrentPotatoRequestGenerator.cs | 2 - .../TorrentPotato/TorrentPotatoResponse.cs | 2 - .../TorrentRss/TorrentRssIndexerSettings.cs | 6 +- .../TorrentRss/TorrentRssSettingsDetector.cs | 9 +- src/NzbDrone.Core/Indexers/Torznab/Torznab.cs | 32 +++-- .../Indexers/Torznab/TorznabException.cs | 6 +- .../Indexers/Torznab/TorznabRssParser.cs | 13 +- .../Indexers/XElementExtensions.cs | 7 +- src/NzbDrone.Core/Indexers/XmlCleaner.cs | 1 - .../Instrumentation/DatabaseTarget.cs | 9 +- src/NzbDrone.Core/Instrumentation/Log.cs | 2 - .../Instrumentation/LogRepository.cs | 1 - .../Instrumentation/ReconfigureLogging.cs | 9 +- .../SlowRunningAsyncTargetWrapper.cs | 2 - .../Jobs/ScheduledTaskRepository.cs | 12 +- src/NzbDrone.Core/Jobs/Scheduler.cs | 3 +- src/NzbDrone.Core/Jobs/TaskManager.cs | 23 +-- src/NzbDrone.Core/Languages/Language.cs | 83 ++++++----- .../Lifecycle/ApplicationStartedEvent.cs | 1 - .../Lifecycle/LifecycleService.cs | 1 - .../CoverAlreadyExistsSpecification.cs | 4 +- .../MediaCover/EnsureMediaCoversCommand.cs | 1 - src/NzbDrone.Core/MediaCover/ImageResizer.cs | 6 +- src/NzbDrone.Core/MediaCover/MediaCover.cs | 1 - .../MediaCover/MediaCoverService.cs | 3 +- .../MediaFiles/Commands/RenameMovieCommand.cs | 2 +- .../Commands/RenameMovieFolderCommand.cs | 6 +- .../MediaFiles/DiskScanService.cs | 5 +- .../DownloadedMovieCommandService.cs | 6 +- .../DownloadedMovieImportService.cs | 8 +- .../MediaFiles/Events/MovieDownloadedEvent.cs | 2 +- .../MediaFiles/MediaFileAttributeService.cs | 3 - .../MediaFiles/MediaFileExtensions.cs | 6 +- .../MediaFiles/MediaFileRepository.cs | 2 - .../MediaFiles/MediaFileService.cs | 13 +- .../MediaFileTableCleanupService.cs | 3 +- .../MediaInfo/MediaInfoFormatter.cs | 15 +- .../MediaFiles/MediaInfo/MediaInfoLib.cs | 13 +- .../MediaFiles/MediaInfo/MediaInfoModel.cs | 1 + .../MediaInfo/UpdateMediaInfoService.cs | 4 +- .../MediaInfo/VideoFileInfoReader.cs | 4 +- src/NzbDrone.Core/MediaFiles/MovieFile.cs | 10 +- .../MediaFiles/MovieFileMovingService.cs | 10 +- .../Aggregation/AggregationFailedException.cs | 12 +- .../Aggregation/AggregationService.cs | 2 +- .../Aggregators/AggregateLanguage.cs | 2 - .../Aggregators/AggregateQuality.cs | 6 +- .../Quality/AugmentQualityResult.cs | 2 +- .../MovieImport/ImportApprovedMovie.cs | 9 +- .../MediaFiles/MovieImport/ImportDecision.cs | 1 + .../MovieImport/ImportDecisionMaker.cs | 5 +- .../MovieImport/Manual/ManualImportItem.cs | 4 +- .../MovieImport/Manual/ManualImportService.cs | 18 +-- .../Specifications/FreeSpaceSpecification.cs | 2 +- .../GrabbedReleaseQualitySpecification.cs | 3 +- .../MediaFiles/RecycleBinProvider.cs | 3 - .../MediaFiles/RenameMovieFileService.cs | 64 ++++----- .../MediaFiles/SameFilenameException.cs | 3 +- .../TorrentInfo/TorrentFileInfoReader.cs | 2 +- .../UpdateMovieFileQualityService.cs | 4 +- .../MediaFiles/UpdateMovieFileService.cs | 5 - .../MediaFiles/UpgradeMediaFileService.cs | 11 +- .../Commands/CommandEqualityComparer.cs | 9 +- .../Messaging/Commands/CommandExecutor.cs | 17 ++- .../Commands/CommandFailedException.cs | 12 +- .../Commands/CommandNotFoundException.cs | 1 - .../Messaging/Commands/CommandQueue.cs | 6 + .../Messaging/Commands/CommandQueueManager.cs | 24 ++-- .../Messaging/Commands/CommandRepository.cs | 5 +- .../Messaging/Commands/IExecute.cs | 3 +- .../Messaging/Events/EventAggregator.cs | 15 +- .../Messaging/Events/IEventAggregator.cs | 3 +- src/NzbDrone.Core/Messaging/Events/IHandle.cs | 6 +- .../Messaging/IProcessMessage.cs | 16 ++- .../MetadataSource/IProvideMovieInfo.cs | 6 +- .../MetadataSource/PreDB/PreDBResult.cs | 3 +- .../MetadataSource/PreDB/PreDBService.cs | 57 ++++---- .../MetadataSource/PreDB/PreDBSyncCommand.cs | 1 - .../MetadataSource/PreDB/PreDBSyncEvent.cs | 4 +- .../RadarrAPI/RadarrAPIClient.cs | 24 ++-- .../RadarrAPI/RadarrResources.cs | 14 +- .../MetadataSource/SearchMovieComparer.cs | 32 ++++- .../SkyHook/Resource/ConfigurationResource.cs | 2 - .../SkyHook/Resource/MovieResource.cs | 28 ++-- .../SkyHook/Resource/TMDBResources.cs | 4 +- .../SkyHook/SkyHookException.cs | 3 +- .../MetadataSource/SkyHook/SkyHookProxy.cs | 105 +++++++++----- .../TmdbConfigurationService.cs | 6 +- .../AlternativeTitles/AlternativeTitle.cs | 7 +- .../AlternativeTitleService.cs | 11 +- src/NzbDrone.Core/Movies/Movie.cs | 31 ++-- src/NzbDrone.Core/Movies/MovieRepository.cs | 31 ++-- .../Movies/MovieScannedHandler.cs | 9 +- src/NzbDrone.Core/Movies/MovieService.cs | 53 +++---- src/NzbDrone.Core/Movies/MovieStatusType.cs | 2 +- .../Movies/MovieTitleNormalizer.cs | 2 +- .../Movies/RefreshMovieService.cs | 5 +- .../NetImport/CouchPotato/CouchPotatoAPI.cs | 1 + .../CouchPotato/CouchPotatoImport.cs | 3 +- .../CouchPotato/CouchPotatoParser.cs | 7 +- .../CouchPotatoRequestGenerator.cs | 4 +- .../CouchPotato/CouchPotatoSettings.cs | 2 - .../NetImport/HttpNetImportBase.cs | 17 ++- .../ImportExclusions/ImportExclusion.cs | 2 +- .../ImportExclusionsService.cs | 4 +- src/NzbDrone.Core/NetImport/NetImportBase.cs | 10 +- .../NetImport/NetImportDefinition.cs | 2 +- .../NetImportPageableRequestChain.cs | 10 +- .../NetImport/NetImportRepository.cs | 1 - .../NetImport/NetImportSearchService.cs | 29 ++-- .../NetImport/NetImportSyncCommand.cs | 3 +- .../NetImport/RSSImport/RSSImport.cs | 4 +- .../NetImport/RSSImport/RSSImportParser.cs | 11 +- .../RSSImport/RSSImportRequestGenerator.cs | 1 - .../NetImport/Radarr/RadarrLists.cs | 8 +- .../NetImport/Radarr/RadarrParser.cs | 16 +-- .../Radarr/RadarrRequestGenerator.cs | 2 +- .../NetImport/Radarr/RadarrSettings.cs | 2 - .../NetImport/StevenLu/StevenLuImport.cs | 3 +- .../NetImport/StevenLu/StevenLuParser.cs | 7 +- .../StevenLu/StevenLuRequestGenerator.cs | 4 +- .../NetImport/StevenLu/StevenLuSettings.cs | 3 - .../NetImport/TMDb/TMDbImport.cs | 6 +- .../NetImport/TMDb/TMDbParser.cs | 12 +- .../NetImport/TMDb/TMDbRequestGenerator.cs | 4 +- .../NetImport/TMDb/TMDbSettings.cs | 7 +- .../NetImport/Trakt/TraktImport.cs | 9 +- .../NetImport/Trakt/TraktParser.cs | 14 +- .../NetImport/Trakt/TraktRequestGenerator.cs | 6 +- .../NetImport/Trakt/TraktSettings.cs | 12 +- .../Notifications/Boxcar/Boxcar.cs | 2 +- .../Notifications/Boxcar/BoxcarException.cs | 6 +- .../Notifications/Boxcar/BoxcarProxy.cs | 6 +- .../CustomScript/CustomScript.cs | 3 +- .../Notifications/Discord/Discord.cs | 1 - .../Notifications/Discord/DiscordException.cs | 8 +- .../Notifications/Discord/DiscordProxy.cs | 2 +- .../Notifications/Discord/DiscordSettings.cs | 1 - .../Notifications/Email/Email.cs | 1 - .../Notifications/Email/EmailService.cs | 4 +- .../Notifications/Gotify/GotifyPriority.cs | 1 - .../Notifications/Gotify/GotifyProxy.cs | 2 +- .../Gotify/InvalidResponseException.cs | 3 +- .../Notifications/GrabMessage.cs | 2 +- .../Notifications/INotification.cs | 4 +- .../Notifications/Join/JoinAuthException.cs | 6 +- .../Notifications/Join/JoinException.cs | 6 +- .../Join/JoinInvalidDeviceException.cs | 6 +- .../Notifications/Join/JoinProxy.cs | 18 ++- .../Notifications/Join/JoinSettings.cs | 1 - .../MediaBrowser/MediaBrowser.cs | 1 - .../MediaBrowser/MediaBrowserProxy.cs | 10 +- .../MediaBrowser/MediaBrowserService.cs | 2 +- .../Notifications/NotificationBase.cs | 16 +-- .../Notifications/NotificationRepository.cs | 2 - .../Notifications/NotificationService.cs | 19 ++- .../NotifyMyAndroid/NotifyMyAndroid.cs | 1 - .../NotifyMyAndroid/NotifyMyAndroidProxy.cs | 4 +- .../Plex/PlexAuthenticationException.cs | 3 +- .../Notifications/Plex/PlexException.cs | 9 +- .../Plex/PlexTv/PlexTvService.cs | 16 +-- .../Plex/PlexVersionException.cs | 6 +- .../Notifications/Plex/Server/PlexServer.cs | 8 +- .../Plex/Server/PlexServerProxy.cs | 15 +- .../Plex/Server/PlexServerService.cs | 6 +- .../Notifications/PushBullet/PushBullet.cs | 18 +-- .../PushBullet/PushBulletException.cs | 6 +- .../PushBullet/PushBulletProxy.cs | 7 +- .../Notifications/Pushalot/PushalotProxy.cs | 2 +- .../Pushover/InvalidResponseException.cs | 3 +- .../Notifications/Pushover/PushoverService.cs | 5 +- .../Pushover/PushoverSettings.cs | 6 +- .../Notifications/Slack/Slack.cs | 6 +- .../Notifications/Slack/SlackExeption.cs | 8 +- .../Synology/SynologyException.cs | 6 +- .../Notifications/Synology/SynologyIndexer.cs | 1 - .../Synology/SynologyIndexerSettings.cs | 1 - .../Telegram/InvalidResponseException.cs | 3 +- .../Notifications/Telegram/TelegramService.cs | 6 +- .../Notifications/Twitter/OAuthToken.cs | 1 - .../Notifications/Twitter/Twitter.cs | 5 +- .../Notifications/Twitter/TwitterException.cs | 12 +- .../Notifications/Twitter/TwitterService.cs | 10 +- .../Notifications/Twitter/TwitterSettings.cs | 1 + .../Notifications/Webhook/Webhook.cs | 2 +- .../Notifications/Webhook/WebhookException.cs | 6 +- .../Webhook/WebhookGrabPayload.cs | 2 +- .../Webhook/WebhookImportPayload.cs | 2 +- .../Notifications/Webhook/WebhookMovie.cs | 9 +- .../Notifications/Webhook/WebhookMovieFile.cs | 6 +- .../Notifications/Webhook/WebhookProxy.cs | 3 +- .../Notifications/Webhook/WebhookRelease.cs | 4 +- .../Webhook/WebhookRemoteMovie.cs | 4 +- .../Notifications/Xbmc/XbmcJsonApiProxy.cs | 1 - .../Notifications/Xbmc/XbmcService.cs | 11 +- src/NzbDrone.Core/Organizer/Exception.cs | 6 +- .../Organizer/FileNameBuilder.cs | 33 +++-- .../FileNameBuilderTokenEqualityComparer.cs | 1 - .../Organizer/FileNameSampleService.cs | 4 +- .../Organizer/FileNameValidationService.cs | 2 +- src/NzbDrone.Core/Organizer/NamingConfig.cs | 5 +- .../Organizer/NamingConfigRepository.cs | 2 - .../AugmentWithAdditionalFormats.cs | 3 +- .../Parser/Augmenters/AugmentWithFileSize.cs | 1 - .../Parser/Augmenters/AugmentWithHistory.cs | 1 - .../Parser/Augmenters/AugmentWithMediaInfo.cs | 2 - .../Augmenters/AugmentWithReleaseInfo.cs | 13 +- .../Parser/InvalidDateException.cs | 6 +- src/NzbDrone.Core/Parser/IsoLanguage.cs | 1 - src/NzbDrone.Core/Parser/IsoLanguages.cs | 4 +- src/NzbDrone.Core/Parser/LanguageParser.cs | 126 ++++++++++++---- src/NzbDrone.Core/Parser/Model/LocalMovie.cs | 7 +- .../Parser/Model/ParsedMovieInfo.cs | 21 +-- src/NzbDrone.Core/Parser/Model/ReleaseInfo.cs | 17 +-- src/NzbDrone.Core/Parser/Model/RemoteMovie.cs | 2 +- src/NzbDrone.Core/Parser/Parser.cs | 34 +++-- src/NzbDrone.Core/Parser/ParsingService.cs | 58 ++++---- src/NzbDrone.Core/Parser/QualityParser.cs | 54 +++++-- src/NzbDrone.Core/Parser/RegexReplace.cs | 9 ++ .../Parser/RomanNumerals/RomanNumeral.cs | 66 ++++----- .../RomanNumerals/RomanNumeralParser.cs | 34 +++-- src/NzbDrone.Core/Parser/SceneChecker.cs | 13 +- .../Profiles/Delay/DelayProfileRepository.cs | 1 - .../Profiles/Delay/DelayProfileService.cs | 8 +- .../Delay/DelayProfileTagInUseValidator.cs | 10 +- .../Profiles/ProfileInUseException.cs | 1 - src/NzbDrone.Core/Profiles/ProfileService.cs | 37 +++-- .../ProgressMessageContext.cs | 2 + .../ProgressMessageTarget.cs | 15 +- src/NzbDrone.Core/Qualities/Quality.cs | 31 +++- .../Qualities/QualityDefinition.cs | 1 - .../Qualities/QualityDefinitionRepository.cs | 1 - .../Qualities/QualityDefinitionService.cs | 9 +- src/NzbDrone.Core/Qualities/QualityModel.cs | 31 ++-- src/NzbDrone.Core/Qualities/Revision.cs | 83 +++++++++-- src/NzbDrone.Core/Queue/Queue.cs | 2 +- .../RemotePathMappings/RemotePathMapping.cs | 1 - .../RemotePathMappingRepository.cs | 2 - .../RemotePathMappingService.cs | 6 +- src/NzbDrone.Core/Rest/JsonNetSerializer.cs | 2 +- src/NzbDrone.Core/Rest/RestClientFactory.cs | 3 +- src/NzbDrone.Core/Rest/RestSharpExtensions.cs | 18 ++- src/NzbDrone.Core/Restrictions/TermMatcher.cs | 1 - src/NzbDrone.Core/RootFolders/RootFolder.cs | 1 - .../RootFolders/RootFolderRepository.cs | 2 - .../RootFolders/RootFolderService.cs | 5 +- .../X509CertificateValidationService.cs | 3 +- src/NzbDrone.Core/Tags/TagDetails.cs | 2 +- src/NzbDrone.Core/Tags/TagService.cs | 7 +- .../ConfigContractNotFoundException.cs | 1 - .../ThingiProvider/IProviderRepository.cs | 5 +- .../ThingiProvider/ProviderRepository.cs | 8 +- .../Status/ProviderStatusRepository.cs | 1 - src/NzbDrone.Core/TinyTwitter.cs | 65 ++++----- .../Update/InstallUpdateService.cs | 2 +- .../Update/UpdateCheckService.cs | 1 - .../Update/UpdatePackageProvider.cs | 5 +- .../Validation/FolderValidator.cs | 6 +- .../Validation/NzbDroneValidationFailure.cs | 2 - .../Validation/NzbDroneValidationResult.cs | 1 + .../Paths/FolderWritableValidator.cs | 7 +- .../Paths/MappedNetworkDriveValidator.cs | 22 ++- .../Paths/MovieAncestorValidator.cs | 5 +- .../Validation/Paths/MovieExistsValidator.cs | 7 +- .../Validation/Paths/MoviePathValidation.cs | 7 +- .../Validation/Paths/PathExistsValidator.cs | 7 +- .../Validation/Paths/PathValidator.cs | 6 +- .../Validation/Paths/RootFolderValidator.cs | 7 +- .../Paths/StartupFolderValidator.cs | 6 +- .../Validation/ProfileExistsValidator.cs | 5 +- src/NzbDrone.Core/Validation/UrlValidator.cs | 6 +- src/NzbDrone.Host.Test/ContainerFixture.cs | 16 +-- .../NzbDroneProcessServiceFixture.cs | 13 +- src/NzbDrone.Host.Test/RouterTest.cs | 7 +- .../AccessControl/FirewallAdapter.cs | 6 +- .../AccessControl/RemoteAccessException.cs | 12 +- src/NzbDrone.Host/ApplicationServer.cs | 3 +- src/NzbDrone.Host/Bootstrap.cs | 4 +- src/NzbDrone.Host/CancelHandler.cs | 6 +- src/NzbDrone.Host/MainAppContainerBuilder.cs | 2 +- src/NzbDrone.Host/PlatformValidation.cs | 6 +- src/NzbDrone.Host/Router.cs | 6 +- .../WebHost/Middleware/SignalRMiddleware.cs | 2 +- .../WebHost/WebHostController.cs | 15 +- .../ApiTests/CalendarFixture.cs | 8 +- .../ApiTests/DiskSpaceFixture.cs | 2 +- .../ApiTests/DownloadClientFixture.cs | 25 ++-- .../ApiTests/FileSystemFixture.cs | 16 +-- .../ApiTests/MovieEditorFixture.cs | 4 +- .../ApiTests/MovieFixture.cs | 37 +++-- .../ApiTests/NamingConfigFixture.cs | 2 - .../ApiTests/NotificationFixture.cs | 1 - .../ApiTests/ReleaseFixture.cs | 7 +- .../ApiTests/RootFolderFixture.cs | 2 - .../Client/ClientBase.cs | 19 +-- .../Client/CommandClient.cs | 22 +-- .../Client/MovieClient.cs | 1 - .../GenericApiFixture.cs | 1 - .../IndexHtmlFixture.cs | 1 - .../IntegrationTestBase.cs | 32 +++-- .../DiskProviderTests/DiskProviderFixture.cs | 6 +- .../DiskProviderTests/FreeSpaceFixture.cs | 2 +- .../MacOsVersionAdapterFixture.cs | 1 - .../ReleaseFileVersionAdapterFixture.cs | 2 - src/NzbDrone.Mono/Disk/DiskProvider.cs | 13 +- .../Disk/LinuxPermissionsException.cs | 6 +- src/NzbDrone.Mono/Disk/ProcMountProvider.cs | 12 +- .../Disk/SymbolicLinkResolver.cs | 13 +- .../IssueFileVersionAdapter.cs | 1 - .../VersionAdapters/MacOsVersionAdapter.cs | 12 +- .../ReleaseFileVersionAdapter.cs | 3 +- .../VersionAdapters/SynologyVersionAdapter.cs | 5 +- src/NzbDrone.Test.Common/AutoMoq/AutoMoqer.cs | 50 ++++--- .../Unity/AutoMockingBuilderStrategy.cs | 8 +- .../Unity/AutoMockingContainerExtension.cs | 14 +- .../Categories/DiskAccessTestAttribute.cs | 1 - .../Categories/IntegrationTestAttribute.cs | 1 - .../Categories/ManualTestAttribute.cs | 1 - .../ConcurrencyCounter.cs | 5 +- .../ExceptionVerification.cs | 9 +- src/NzbDrone.Test.Common/LoggingTest.cs | 4 +- src/NzbDrone.Test.Common/NzbDroneRunner.cs | 5 +- src/NzbDrone.Test.Common/StringExtensions.cs | 1 + src/NzbDrone.Test.Common/TestBase.cs | 25 ++-- src/NzbDrone.Test.Dummy/DummyApp.cs | 2 +- .../InstallUpdateServiceFixture.cs | 2 +- src/NzbDrone.Update.Test/ProgramFixture.cs | 13 +- src/NzbDrone.Update/UpdateApp.cs | 5 +- src/NzbDrone.Update/UpdateContainerBuilder.cs | 1 - .../UpdateEngine/InstallUpdateService.cs | 7 +- .../UpdateEngine/StartNzbDrone.cs | 1 - .../DiskProviderTests/DiskProviderFixture.cs | 1 - src/NzbDrone.Windows/Disk/DiskProvider.cs | 10 +- src/NzbDrone/Properties/Resources.Designer.cs | 30 ++-- src/NzbDrone/SysTray/SysTrayApp.cs | 5 +- src/NzbDrone/WindowsApp.cs | 2 +- .../Blacklist/BlacklistResource.cs | 5 +- .../Calendar/CalendarFeedModule.cs | 20 ++- src/Radarr.Api.V3/Calendar/CalendarModule.cs | 24 +++- src/Radarr.Api.V3/Commands/CommandModule.cs | 2 +- src/Radarr.Api.V3/Commands/CommandResource.cs | 33 +++-- .../Config/DownloadClientConfigModule.cs | 1 - .../Config/DownloadClientConfigResource.cs | 2 +- src/Radarr.Api.V3/Config/HostConfigModule.cs | 1 - .../Config/HostConfigResource.cs | 5 +- .../Config/IndexerConfigModule.cs | 3 +- .../Config/IndexerConfigResource.cs | 2 +- .../Config/MediaManagementConfigResource.cs | 2 +- .../Config/NamingConfigModule.cs | 4 +- .../Config/NamingConfigResource.cs | 2 +- .../Config/NamingExampleResource.cs | 1 + .../Config/NetImportConfigModule.cs | 3 +- .../Config/NetImportConfigResource.cs | 2 +- .../Config/RadarrConfigModule.cs | 9 +- src/Radarr.Api.V3/Config/UiConfigModule.cs | 1 - src/Radarr.Api.V3/Config/UiConfigResource.cs | 2 +- .../CustomFilters/CustomFilterResource.cs | 34 +++-- .../DiskSpace/DiskSpaceModule.cs | 2 +- .../DiskSpace/DiskSpaceResource.cs | 5 +- .../DownloadClient/DownloadClientModule.cs | 6 +- .../DownloadClient/DownloadClientResource.cs | 10 +- .../FileSystem/FileSystemModule.cs | 9 +- src/Radarr.Api.V3/Health/HealthResource.cs | 5 +- src/Radarr.Api.V3/History/HistoryModule.cs | 6 +- src/Radarr.Api.V3/History/HistoryResource.cs | 6 +- src/Radarr.Api.V3/Indexers/IndexerModule.cs | 6 +- src/Radarr.Api.V3/Indexers/IndexerResource.cs | 10 +- src/Radarr.Api.V3/Indexers/ReleaseModule.cs | 2 +- .../Indexers/ReleasePushModule.cs | 8 +- src/Radarr.Api.V3/Indexers/ReleaseResource.cs | 7 +- src/Radarr.Api.V3/Logs/LogFileModule.cs | 1 - src/Radarr.Api.V3/Logs/LogFileModuleBase.cs | 4 +- src/Radarr.Api.V3/Logs/LogResource.cs | 5 +- src/Radarr.Api.V3/Logs/UpdateLogFileModule.cs | 5 +- .../ManualImport/ManualImportResource.cs | 7 +- src/Radarr.Api.V3/Metadata/MetadataModule.cs | 6 +- .../Metadata/MetadataResource.cs | 10 +- .../MovieFiles/MediaInfoResource.cs | 33 +++-- .../MovieFiles/MovieFileModule.cs | 16 +-- .../MovieFiles/MovieFileResource.cs | 19 ++- .../Movies/AlternativeTitleModule.cs | 2 +- .../Movies/AlternativeTitleResource.cs | 16 ++- .../Movies/AlternativeYearResource.cs | 2 - .../Movies/FetchMovieListModule.cs | 10 +- .../Movies/MovieDiscoverModule.cs | 15 +- src/Radarr.Api.V3/Movies/MovieEditorModule.cs | 14 +- .../MovieFolderAsRootFolderValidator.cs | 15 +- src/Radarr.Api.V3/Movies/MovieImportModule.cs | 3 +- src/Radarr.Api.V3/Movies/MovieLookupModule.cs | 16 +-- src/Radarr.Api.V3/Movies/MovieModule.cs | 34 +++-- src/Radarr.Api.V3/Movies/MovieResource.cs | 14 +- src/Radarr.Api.V3/Movies/RenameMovieModule.cs | 7 +- .../Movies/RenameMovieResource.cs | 9 +- .../NetImport/ImportExclusionsModule.cs | 6 +- .../NetImport/ImportExclusionsResource.cs | 5 +- .../NetImport/ListImportModule.cs | 10 +- .../NetImport/NetImportModule.cs | 6 +- .../Notifications/NotificationModule.cs | 6 +- .../Notifications/NotificationResource.cs | 10 +- .../Profiles/Delay/DelayProfileModule.cs | 4 +- .../Profiles/Delay/DelayProfileResource.cs | 12 +- .../Profiles/Languages/LanguageModule.cs | 8 +- .../Quality/QualityCutoffValidator.cs | 11 +- .../Profiles/Quality/QualityItemsValidator.cs | 8 -- .../Profiles/Quality/QualityProfileModule.cs | 1 + .../Quality/QualityProfileResource.cs | 26 +++- src/Radarr.Api.V3/ProviderModuleBase.cs | 18 +-- src/Radarr.Api.V3/ProviderResource.cs | 6 +- .../Qualities/CustomFormatModule.cs | 16 ++- .../Qualities/CustomFormatResource.cs | 2 +- .../Qualities/FormatTagMatchResultResource.cs | 7 +- .../Qualities/FormatTagValidator.cs | 10 +- .../Qualities/QualityDefinitionModule.cs | 4 +- .../Qualities/QualityDefinitionResource.cs | 12 +- src/Radarr.Api.V3/Queue/QueueActionModule.cs | 8 +- src/Radarr.Api.V3/Queue/QueueModule.cs | 20 +-- src/Radarr.Api.V3/Queue/QueueResource.cs | 5 +- src/Radarr.Api.V3/Queue/QueueStatusModule.cs | 4 +- .../RemotePathMappingResource.cs | 10 +- .../Restrictions/RestrictionModule.cs | 1 - .../Restrictions/RestrictionResource.cs | 10 +- .../RootFolders/RootFolderModule.cs | 5 +- .../RootFolders/RootFolderResource.cs | 11 +- .../System/Backup/BackupModule.cs | 30 ++-- .../System/Backup/BackupResource.cs | 2 +- src/Radarr.Api.V3/System/SystemModule.cs | 62 ++++---- src/Radarr.Api.V3/System/Tasks/TaskModule.cs | 18 +-- src/Radarr.Api.V3/Tags/TagDetailsResource.cs | 5 +- src/Radarr.Api.V3/Tags/TagResource.cs | 12 +- src/Radarr.Api.V3/Update/UpdateResource.cs | 6 +- .../Authentication/AuthenticationModule.cs | 4 +- .../Authentication/AuthenticationService.cs | 12 +- .../Authentication/EnableAuthInNancy.cs | 13 +- src/Radarr.Http/ClientSchema/SchemaBuilder.cs | 15 +- .../ErrorManagement/RadarrErrorPipeline.cs | 2 + .../Exceptions/InvalidApiKeyException.cs | 3 +- .../Pipelines/CacheHeaderPipeline.cs | 7 +- .../Extensions/Pipelines/GZipPipeline.cs | 1 - .../Pipelines/IfModifiedPipeline.cs | 2 +- .../Pipelines/RadarrVersionPipeline.cs | 2 +- .../Extensions/Pipelines/UrlBasePipeline.cs | 2 +- .../Extensions/ReqResExtensions.cs | 3 +- .../Extensions/RequestExtensions.cs | 4 +- .../Frontend/CacheableSpecification.cs | 38 ++++- .../Frontend/InitializeJsModule.cs | 2 +- .../Frontend/Mappers/FaviconMapper.cs | 2 +- .../Frontend/Mappers/HtmlMapperBase.cs | 4 +- .../Mappers/IMapHttpRequestsToDisk.cs | 3 +- .../Frontend/StaticResourceModule.cs | 5 +- src/Radarr.Http/Mapping/MappingValidation.cs | 2 +- .../Mapping/ResourceMappingException.cs | 1 - src/Radarr.Http/PagingResource.cs | 2 +- src/Radarr.Http/REST/ResourceValidator.cs | 1 - src/Radarr.Http/REST/RestModule.cs | 82 +++++++---- src/Radarr.Http/RadarrBootstrapper.cs | 3 +- src/Radarr.Http/RadarrRestModule.cs | 5 +- .../RadarrRestModuleWithSignalR.cs | 42 ++++-- src/Radarr.Http/ResourceChangeMessage.cs | 4 +- src/Radarr.Http/TinyIoCNancyBootstrapper.cs | 52 +++---- .../Validation/EmptyCollectionValidator.cs | 5 +- src/ServiceHelpers/ServiceInstall/Program.cs | 2 +- .../ServiceInstall/ServiceHelper.cs | 22 ++- .../ServiceUninstall/Program.cs | 2 +- .../ServiceUninstall/ServiceHelper.cs | 22 ++- src/Stylecop.ruleset | 115 +++++++++++++++ src/stylecop.json | 21 +++ 1186 files changed, 7105 insertions(+), 5616 deletions(-) create mode 100644 src/Stylecop.ruleset create mode 100644 src/stylecop.json diff --git a/.editorconfig b/.editorconfig index 5e19cc2d6b..624514a983 100644 --- a/.editorconfig +++ b/.editorconfig @@ -9,6 +9,35 @@ insert_final_newline = true indent_style = space indent_size = 4 +# Sort using and Import directives with System.* appearing first +dotnet_sort_system_directives_first = true + +# Avoid "this." and "Me." if not necessary +dotnet_style_qualification_for_field = false:refactoring +dotnet_style_qualification_for_property = false:refactoring +dotnet_style_qualification_for_method = false:refactoring +dotnet_style_qualification_for_event = false:refactoring + +# Indentation preferences +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_switch_labels = true +csharp_indent_labels = flush_left + +dotnet_style_qualification_for_field = false:suggestion +dotnet_style_qualification_for_property = false:suggestion +dotnet_style_qualification_for_method = false:suggestion +dotnet_style_qualification_for_event = false:suggestion +dotnet_naming_style.instance_field_style.capitalization = camel_case +dotnet_naming_style.instance_field_style.required_prefix = _ + +# Prefer "var" everywhere +csharp_style_var_for_built_in_types = true:suggestion +csharp_style_var_when_type_is_apparent = true:suggestion +csharp_style_var_elsewhere = true:suggestion + [*.{js,html,js,hbs,less,css}] charset = utf-8 trim_trailing_whitespace = true diff --git a/.gitignore b/.gitignore index 304f3c8e2a..eacdd16c7e 100644 --- a/.gitignore +++ b/.gitignore @@ -85,7 +85,6 @@ TestResults [Tt]est[Rr]esult* *.Cache ClientBin -[Ss]tyle[Cc]op.* ~$* *.dbmdl Generated_Code #added for RIA/Silverlight projects diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 9ae001f81d..16461f0e92 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -2,7 +2,7 @@ $(SolutionDir)Stylecop.ruleset - + true AnyCPU true @@ -94,7 +94,7 @@ - + all diff --git a/src/Marr.Data/Converters/BooleanYNConverter.cs b/src/Marr.Data/Converters/BooleanYNConverter.cs index 38003939c0..56d047b062 100644 --- a/src/Marr.Data/Converters/BooleanYNConverter.cs +++ b/src/Marr.Data/Converters/BooleanYNConverter.cs @@ -45,7 +45,7 @@ public object FromDB(ConverterContext context) public object FromDB(ColumnMap map, object dbValue) { - return FromDB(new ConverterContext {ColumnMap = map, DbValue = dbValue}); + return FromDB(new ConverterContext { ColumnMap = map, DbValue = dbValue }); } public object ToDB(object clrValue) diff --git a/src/Marr.Data/Converters/CastConverter.cs b/src/Marr.Data/Converters/CastConverter.cs index 2fa3b8eca1..1be77da455 100644 --- a/src/Marr.Data/Converters/CastConverter.cs +++ b/src/Marr.Data/Converters/CastConverter.cs @@ -50,4 +50,3 @@ public object ToDB(object clrValue) #endregion } } - diff --git a/src/Marr.Data/DataHelper.cs b/src/Marr.Data/DataHelper.cs index 20b5bcfe62..39113ba68d 100644 --- a/src/Marr.Data/DataHelper.cs +++ b/src/Marr.Data/DataHelper.cs @@ -29,7 +29,7 @@ internal static class DataHelper { public static bool HasColumn(this IDataReader dr, string columnName) { - for (int i=0; i < dr.FieldCount; i++) + for (int i = 0; i < dr.FieldCount; i++) { if (dr.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase)) return true; diff --git a/src/Marr.Data/Mapping/IColumnInfo.cs b/src/Marr.Data/Mapping/IColumnInfo.cs index c8058743b0..c22949c463 100644 --- a/src/Marr.Data/Mapping/IColumnInfo.cs +++ b/src/Marr.Data/Mapping/IColumnInfo.cs @@ -19,9 +19,9 @@ namespace Marr.Data.Mapping { public interface IColumnInfo { - string Name { get; set; } + string Name { get; set; } string AltName { get; set; } - int Size { get; set; } + int Size { get; set; } bool IsPrimaryKey { get; set; } bool IsAutoIncrement { get; set; } bool ReturnValue { get; set; } diff --git a/src/Marr.Data/QGen/WhereBuilder.cs b/src/Marr.Data/QGen/WhereBuilder.cs index b2573a26d3..ab7ba2bece 100644 --- a/src/Marr.Data/QGen/WhereBuilder.cs +++ b/src/Marr.Data/QGen/WhereBuilder.cs @@ -167,7 +167,7 @@ private object GetRightValue(Expression expression) var methodExp = memberExp.Expression as MethodCallExpression; if (methodExp != null) { - var errMsg = string.Format("Function calls are not supported by the Where clause expression parser. Please evaluate your function call, '{0}', manually and then use the resulting paremeter value in your Where expression.", methodExp.Method.Name); + var errMsg = string.Format("Function calls are not supported by the Where clause expression parser. Please evaluate your function call, '{0}', manually and then use the resulting paremeter value in your Where expression.", methodExp.Method.Name); throw new NotSupportedException(errMsg); } diff --git a/src/MonoTorrent/BEncoding/BEncodedList.cs b/src/MonoTorrent/BEncoding/BEncodedList.cs index 2b1a3359a9..8d59bb1cef 100644 --- a/src/MonoTorrent/BEncoding/BEncodedList.cs +++ b/src/MonoTorrent/BEncoding/BEncodedList.cs @@ -99,7 +99,7 @@ public override int LengthInBytes() int length = 0; length += 1; // Lists start with 'l' - for (int i=0; i < this.list.Count; i++) + for (int i = 0; i < this.list.Count; i++) length += this.list[i].LengthInBytes(); length += 1; // Lists end with 'e' @@ -147,9 +147,9 @@ public void Add(BEncodedValue item) this.list.Add(item); } - public void AddRange (IEnumerable collection) + public void AddRange(IEnumerable collection) { - list.AddRange (collection); + list.AddRange(collection); } public void Clear() diff --git a/src/MonoTorrent/BEncoding/BEncodedNumber.cs b/src/MonoTorrent/BEncoding/BEncodedNumber.cs index 087be5aa00..6226d9f2fa 100644 --- a/src/MonoTorrent/BEncoding/BEncodedNumber.cs +++ b/src/MonoTorrent/BEncoding/BEncodedNumber.cs @@ -101,16 +101,16 @@ internal override void DecodeInternal(RawReader reader) if (reader.PeekByte() == '-') { sign = -1; - reader.ReadByte (); + reader.ReadByte(); } int letter; while (((letter = reader.PeekByte()) != -1) && letter != 'e') { - if(letter < '0' || letter > '9') + if (letter < '0' || letter > '9') throw new BEncodingException("Invalid number found."); number = number * 10 + (letter - '0'); - reader.ReadByte (); + reader.ReadByte(); } if (reader.ReadByte() != 'e') //remove the trailing 'e' throw new BEncodingException("Invalid data found. Aborting."); diff --git a/src/MonoTorrent/BEncoding/BEncodedString.cs b/src/MonoTorrent/BEncoding/BEncodedString.cs index 80958e5db5..47d11b37d7 100644 --- a/src/MonoTorrent/BEncoding/BEncodedString.cs +++ b/src/MonoTorrent/BEncoding/BEncodedString.cs @@ -97,7 +97,7 @@ public static implicit operator BEncodedString(byte[] value) public override int Encode(byte[] buffer, int offset) { int written = offset; - written += Message.WriteAscii(buffer, written, textBytes.Length.ToString ()); + written += Message.WriteAscii(buffer, written, textBytes.Length.ToString()); written += Message.WriteAscii(buffer, written, ":"); written += Message.Write(buffer, written, textBytes); return written - offset; @@ -144,7 +144,7 @@ public override int LengthInBytes() int prefix = 1; // Account for ':' // Count the number of characters needed for the length prefix - for (int i = textBytes.Length; i != 0; i = i/10) + for (int i = textBytes.Length; i != 0; i = i / 10) prefix += 1; if (textBytes.Length == 0) @@ -164,7 +164,7 @@ public int CompareTo(BEncodedString other) if (other == null) return 1; - int difference=0; + int difference = 0; int length = this.textBytes.Length > other.textBytes.Length ? other.textBytes.Length : this.textBytes.Length; for (int i = 0; i < length; i++) diff --git a/src/MonoTorrent/BEncoding/IBEncodedValue.cs b/src/MonoTorrent/BEncoding/IBEncodedValue.cs index 21dfdf86af..fb05eeef91 100644 --- a/src/MonoTorrent/BEncoding/IBEncodedValue.cs +++ b/src/MonoTorrent/BEncoding/IBEncodedValue.cs @@ -32,11 +32,11 @@ public byte[] Encode() /// public abstract int Encode(byte[] buffer, int offset); - public static T Clone (T value) + public static T Clone(T value) where T : BEncodedValue { - Check.Value (value); - return (T) BEncodedValue.Decode (value.Encode ()); + Check.Value(value); + return (T)BEncodedValue.Decode(value.Encode()); } /// diff --git a/src/MonoTorrent/BitField.cs b/src/MonoTorrent/BitField.cs index dc23bc6269..e2e3edfce7 100644 --- a/src/MonoTorrent/BitField.cs +++ b/src/MonoTorrent/BitField.cs @@ -394,7 +394,7 @@ void Validate() v = (v & 0x33333333) + ((v >> 2) & 0x33333333); count += (((v + (v >> 4) & 0xF0F0F0F) * 0x1010101)) >> 24; } - this.trueCount = (int)count ; + this.trueCount = (int)count; } void ZeroUnusedBits() diff --git a/src/MonoTorrent/Check.cs b/src/MonoTorrent/Check.cs index c6a14fd59a..3a4ded6ff9 100644 --- a/src/MonoTorrent/Check.cs +++ b/src/MonoTorrent/Check.cs @@ -62,9 +62,9 @@ public static void Data(object data) DoCheck(data, "data"); } - public static void Destination (object destination) + public static void Destination(object destination) { - DoCheck (destination, "destination"); + DoCheck(destination, "destination"); } public static void Endpoint(object endpoint) @@ -92,9 +92,9 @@ public static void InfoHash(object infoHash) DoCheck(infoHash, "infoHash"); } - public static void Key (object key) + public static void Key(object key) { - DoCheck (key, "key"); + DoCheck(key, "key"); } public static void Limiter(object limiter) @@ -122,9 +122,9 @@ public static void Manager(object manager) DoCheck(manager, "manager"); } - public static void Mappings (object mappings) + public static void Mappings(object mappings) { - DoCheck (mappings, "mappings"); + DoCheck(mappings, "mappings"); } public static void Metadata(object metadata) @@ -132,9 +132,9 @@ public static void Metadata(object metadata) DoCheck(metadata, "metadata"); } - public static void Name (object name) + public static void Name(object name) { - DoCheck (name, "name"); + DoCheck(name, "name"); } public static void Path(object path) @@ -142,9 +142,9 @@ public static void Path(object path) DoCheck(path, "path"); } - public static void Paths (object paths) + public static void Paths(object paths) { - DoCheck (paths, "paths"); + DoCheck(paths, "paths"); } public static void PathNotEmpty(string path) @@ -152,14 +152,14 @@ public static void PathNotEmpty(string path) IsNullOrEmpty(path, "path"); } - public static void Peer (object peer) + public static void Peer(object peer) { - DoCheck (peer, "peer"); + DoCheck(peer, "peer"); } - public static void Peers (object peers) + public static void Peers(object peers) { - DoCheck (peers, "peers"); + DoCheck(peers, "peers"); } public static void Picker(object picker) diff --git a/src/MonoTorrent/InfoHash.cs b/src/MonoTorrent/InfoHash.cs index e871019096..c44076ccbe 100644 --- a/src/MonoTorrent/InfoHash.cs +++ b/src/MonoTorrent/InfoHash.cs @@ -4,7 +4,7 @@ namespace MonoTorrent { - public class InfoHash : IEquatable + public class InfoHash : IEquatable { static Dictionary base32DecodeTable; @@ -97,24 +97,25 @@ public string UrlEncode() public static InfoHash FromBase32(string infoHash) { - Check.InfoHash (infoHash); + Check.InfoHash(infoHash); if (infoHash.Length != 32) throw new ArgumentException("Infohash must be a base32 encoded 32 character string"); infoHash = infoHash.ToLower(); - int infohashOffset =0 ; + int infohashOffset = 0; byte[] hash = new byte[20]; var temp = new byte[8]; - for (int i = 0; i < hash.Length; ) { - for (int j=0; j < 8; j++) + for (int i = 0; i < hash.Length;) + { + for (int j = 0; j < 8; j++) if (!base32DecodeTable.TryGetValue(infoHash[infohashOffset++], out temp[j])) - throw new ArgumentException ("infoHash", "Value is not a valid base32 encoded string"); + throw new ArgumentException("infoHash", "Value is not a valid base32 encoded string"); //8 * 5bits = 40 bits = 5 bytes - hash[i++] = (byte)((temp[0] << 3) | (temp [1]>> 2)); + hash[i++] = (byte)((temp[0] << 3) | (temp[1] >> 2)); hash[i++] = (byte)((temp[1] << 6) | (temp[2] << 1) | (temp[3] >> 4)); - hash[i++] = (byte)((temp[3] << 4) | (temp [4]>> 1)); - hash[i++] = (byte)((temp[4] << 7) | (temp[5] << 2) | (temp [6]>> 3)); + hash[i++] = (byte)((temp[3] << 4) | (temp[4] >> 1)); + hash[i++] = (byte)((temp[4] << 7) | (temp[5] << 2) | (temp[6] >> 3)); hash[i++] = (byte)((temp[6] << 5) | temp[7]); } @@ -123,7 +124,7 @@ public static InfoHash FromBase32(string infoHash) public static InfoHash FromHex(string infoHash) { - Check.InfoHash (infoHash); + Check.InfoHash(infoHash); if (infoHash.Length != 40) throw new ArgumentException("Infohash must be 40 characters long"); diff --git a/src/MonoTorrent/MagnetLink.cs b/src/MonoTorrent/MagnetLink.cs index 1ee56c4c81..f5a6ea5c7f 100644 --- a/src/MonoTorrent/MagnetLink.cs +++ b/src/MonoTorrent/MagnetLink.cs @@ -7,87 +7,91 @@ namespace MonoTorrent { public class MagnetLink { - public RawTrackerTier AnnounceUrls { - get; private set; - } - - public InfoHash InfoHash { - get; private set; - } - - public string Name { - get; private set; - } - - public List Webseeds { - get; private set; - } - - public MagnetLink (string url) + public RawTrackerTier AnnounceUrls { - Check.Url (url); - AnnounceUrls = new RawTrackerTier (); - Webseeds = new List (); - - ParseMagnetLink (url); + get; private set; } - void ParseMagnetLink (string url) + public InfoHash InfoHash { - string[] splitStr = url.Split ('?'); + get; private set; + } + + public string Name + { + get; private set; + } + + public List Webseeds + { + get; private set; + } + + public MagnetLink(string url) + { + Check.Url(url); + AnnounceUrls = new RawTrackerTier(); + Webseeds = new List(); + + ParseMagnetLink(url); + } + + void ParseMagnetLink(string url) + { + string[] splitStr = url.Split('?'); if (splitStr.Length == 0 || splitStr[0] != "magnet:") - throw new FormatException ("The magnet link must start with 'magnet:?'."); + throw new FormatException("The magnet link must start with 'magnet:?'."); if (splitStr.Length == 1) return;//no parametter - string[] parameters = splitStr[1].Split ('&', ';'); + string[] parameters = splitStr[1].Split('&', ';'); - for (int i = 0; i < parameters.Length ; i++) + for (int i = 0; i < parameters.Length; i++) { - string[] keyval = parameters[i].Split ('='); + string[] keyval = parameters[i].Split('='); if (keyval.Length != 2) - throw new FormatException ("A field-value pair of the magnet link contain more than one equal'."); + throw new FormatException("A field-value pair of the magnet link contain more than one equal'."); switch (keyval[0].Substring(0, 2)) { case "xt"://exact topic if (InfoHash != null) - throw new FormatException ("More than one infohash in magnet link is not allowed."); + throw new FormatException("More than one infohash in magnet link is not allowed."); string val = keyval[1].Substring(9); switch (keyval[1].Substring(0, 9)) { case "urn:sha1:"://base32 hash case "urn:btih:": - if (val.Length == 32) - InfoHash = InfoHash.FromBase32 (val); - else if (val.Length == 40) - InfoHash = InfoHash.FromHex (val); - else - throw new FormatException("Infohash must be base32 or hex encoded."); - break; + if (val.Length == 32) + InfoHash = InfoHash.FromBase32(val); + else if (val.Length == 40) + InfoHash = InfoHash.FromHex(val); + else + throw new FormatException("Infohash must be base32 or hex encoded."); + break; } - break; - case "tr" ://address tracker + break; + case "tr"://address tracker var bytes = UriHelper.UrlDecode(keyval[1]); AnnounceUrls.Add(Encoding.UTF8.GetString(bytes)); - break; + break; case "as"://Acceptable Source - Webseeds.Add (keyval[1]); - break; + Webseeds.Add(keyval[1]); + break; case "dn"://display name var name = UriHelper.UrlDecode(keyval[1]); Name = Encoding.UTF8.GetString(name); - break; + break; case "xl"://exact length case "xs":// eXact Source - P2P link. case "kt"://keyword topic case "mt"://manifest topic - //not supported for moment - break; + //not supported for moment + break; default: //not supported - break; + break; } } } diff --git a/src/MonoTorrent/Messages/IMessage.cs b/src/MonoTorrent/Messages/IMessage.cs index 62512b6c76..e1363cdd51 100644 --- a/src/MonoTorrent/Messages/IMessage.cs +++ b/src/MonoTorrent/Messages/IMessage.cs @@ -2,7 +2,7 @@ namespace MonoTorrent.Messages { interface IMessage { - int ByteLength { get;} + int ByteLength { get; } byte[] Encode(); int Encode(byte[] buffer, int offset); diff --git a/src/MonoTorrent/RawTrackerTier.cs b/src/MonoTorrent/RawTrackerTier.cs index c8efaba748..db024efc93 100644 --- a/src/MonoTorrent/RawTrackerTier.cs +++ b/src/MonoTorrent/RawTrackerTier.cs @@ -7,90 +7,94 @@ namespace MonoTorrent { public class RawTrackerTier : IList { - public string this[int index] { - get { return ((BEncodedString) Tier [index]).Text; } - set { Tier [index] = new BEncodedString (value );} + public string this[int index] + { + get { return ((BEncodedString)Tier[index]).Text; } + set { Tier[index] = new BEncodedString(value); } } - internal BEncodedList Tier { + internal BEncodedList Tier + { get; set; } - public RawTrackerTier () - : this (new BEncodedList ()) + public RawTrackerTier() + : this(new BEncodedList()) { } - public RawTrackerTier (BEncodedList tier) + public RawTrackerTier(BEncodedList tier) { Tier = tier; } - public RawTrackerTier (IEnumerable announces) - : this () + public RawTrackerTier(IEnumerable announces) + : this() { foreach (var v in announces) - Add (v); + Add(v); } - public int IndexOf (string item) + public int IndexOf(string item) { - return Tier.IndexOf ((BEncodedString) item); + return Tier.IndexOf((BEncodedString)item); } - public void Insert (int index, string item) + public void Insert(int index, string item) { - Tier.Insert (index, (BEncodedString) item); + Tier.Insert(index, (BEncodedString)item); } - public void RemoveAt (int index) + public void RemoveAt(int index) { - Tier.RemoveAt (index); + Tier.RemoveAt(index); } - public void Add (string item) + public void Add(string item) { - Tier.Add ((BEncodedString) item); + Tier.Add((BEncodedString)item); } - public void Clear () + public void Clear() { - Tier.Clear (); + Tier.Clear(); } - public bool Contains (string item) + public bool Contains(string item) { - return Tier.Contains ((BEncodedString) item); + return Tier.Contains((BEncodedString)item); } - public void CopyTo (string[] array, int arrayIndex) + public void CopyTo(string[] array, int arrayIndex) { foreach (var s in this) - array [arrayIndex ++] = s; + array[arrayIndex++] = s; } - public bool Remove (string item) + public bool Remove(string item) { - return Tier.Remove ((BEncodedString) item); + return Tier.Remove((BEncodedString)item); } - public int Count { + public int Count + { get { return Tier.Count; } } - public bool IsReadOnly { + public bool IsReadOnly + { get { return Tier.IsReadOnly; } } - public IEnumerator GetEnumerator () + public IEnumerator GetEnumerator() { foreach (BEncodedString v in Tier) yield return v.Text; } - IEnumerator IEnumerable.GetEnumerator () + IEnumerator IEnumerable.GetEnumerator() { - return GetEnumerator (); + return GetEnumerator(); } } } diff --git a/src/MonoTorrent/RawTrackerTiers.cs b/src/MonoTorrent/RawTrackerTiers.cs index a393318c02..af5120faab 100644 --- a/src/MonoTorrent/RawTrackerTiers.cs +++ b/src/MonoTorrent/RawTrackerTiers.cs @@ -7,98 +7,103 @@ namespace MonoTorrent { public class RawTrackerTiers : IList { - BEncodedList Tiers { + BEncodedList Tiers + { get; set; } - public RawTrackerTiers () - : this (new BEncodedList ()) + public RawTrackerTiers() + : this(new BEncodedList()) { } - public RawTrackerTiers (BEncodedList tiers) + public RawTrackerTiers(BEncodedList tiers) { Tiers = tiers; } - public int IndexOf (RawTrackerTier item) + public int IndexOf(RawTrackerTier item) { - if (item != null) { + if (item != null) + { for (int i = 0; i < Tiers.Count; i++) - if (item.Tier == Tiers [i]) + if (item.Tier == Tiers[i]) return i; } return -1; } - public void Insert (int index, RawTrackerTier item) + public void Insert(int index, RawTrackerTier item) { - Tiers.Insert (index, item.Tier); + Tiers.Insert(index, item.Tier); } - public void RemoveAt (int index) + public void RemoveAt(int index) { - Tiers.RemoveAt (index); + Tiers.RemoveAt(index); } - public RawTrackerTier this[int index] { - get { return new RawTrackerTier ((BEncodedList) Tiers [index]); } - set { Tiers [index] = value.Tier; } - } - - public void Add (RawTrackerTier item) + public RawTrackerTier this[int index] { - Tiers.Add (item.Tier); + get { return new RawTrackerTier((BEncodedList)Tiers[index]); } + set { Tiers[index] = value.Tier; } } - public void AddRange (IEnumerable tiers) + public void Add(RawTrackerTier item) + { + Tiers.Add(item.Tier); + } + + public void AddRange(IEnumerable tiers) { foreach (var v in tiers) - Add (v); + Add(v); } - public void Clear () + public void Clear() { - Tiers.Clear (); + Tiers.Clear(); } - public bool Contains (RawTrackerTier item) + public bool Contains(RawTrackerTier item) { - return IndexOf (item) != -1; + return IndexOf(item) != -1; } - public void CopyTo (RawTrackerTier[] array, int arrayIndex) + public void CopyTo(RawTrackerTier[] array, int arrayIndex) { foreach (var v in this) - array [arrayIndex ++] = v; + array[arrayIndex++] = v; } - public bool Remove (RawTrackerTier item) + public bool Remove(RawTrackerTier item) { - int index = IndexOf (item); + int index = IndexOf(item); if (index != -1) - RemoveAt (index); + RemoveAt(index); return index != -1; } - public int Count { + public int Count + { get { return Tiers.Count; } } - public bool IsReadOnly { + public bool IsReadOnly + { get { return Tiers.IsReadOnly; } } - public IEnumerator GetEnumerator () + public IEnumerator GetEnumerator() { foreach (var v in Tiers) - yield return new RawTrackerTier ((BEncodedList) v); + yield return new RawTrackerTier((BEncodedList)v); } - IEnumerator IEnumerable.GetEnumerator () + IEnumerator IEnumerable.GetEnumerator() { - return GetEnumerator (); + return GetEnumerator(); } } } diff --git a/src/MonoTorrent/ToolBox.cs b/src/MonoTorrent/ToolBox.cs index 390f1e5bf6..2dfe261ba0 100644 --- a/src/MonoTorrent/ToolBox.cs +++ b/src/MonoTorrent/ToolBox.cs @@ -36,7 +36,8 @@ public static void RaiseAsyncEvent(EventHandler e, object o, T args) if (e == null) return; - ThreadPool.QueueUserWorkItem(delegate { + ThreadPool.QueueUserWorkItem(delegate + { if (e != null) e(o, args); }); diff --git a/src/MonoTorrent/Torrent.cs b/src/MonoTorrent/Torrent.cs index 481051cfbd..35f4ba1bd7 100644 --- a/src/MonoTorrent/Torrent.cs +++ b/src/MonoTorrent/Torrent.cs @@ -263,7 +263,7 @@ public List GetRightHttpSeeds protected Torrent() { - this.announceUrls = new RawTrackerTiers (); + this.announceUrls = new RawTrackerTiers(); this.comment = string.Empty; this.createdBy = string.Empty; this.creationDate = new DateTime(1970, 1, 1, 0, 0, 0); @@ -298,15 +298,15 @@ public override int GetHashCode() return this.infoHash.GetHashCode(); } - internal byte [] ToBytes () + internal byte[] ToBytes() { - return this.originalDictionary.Encode (); + return this.originalDictionary.Encode(); } - internal BEncodedDictionary ToDictionary () + internal BEncodedDictionary ToDictionary() { // Give the user a copy of the original dictionary. - return BEncodedValue.Clone (this.originalDictionary); + return BEncodedValue.Clone(this.originalDictionary); } public override string ToString() @@ -423,7 +423,7 @@ private void LoadTorrentFiles(BEncodedList list) else { startIndex = (int)(this.size / this.pieceLength); - endIndex = (int)((this.size + length) / this.pieceLength); + endIndex = (int)((this.size + length) / this.pieceLength); if ((this.size + length) % this.pieceLength == 0) endIndex--; } @@ -702,7 +702,7 @@ private static Torrent Load(Stream stream, string path) try { - Torrent t = Torrent.LoadCore ((BEncodedDictionary) BEncodedDictionary.Decode(stream)); + Torrent t = Torrent.LoadCore((BEncodedDictionary)BEncodedDictionary.Decode(stream)); t.torrentPath = path; return t; } @@ -714,7 +714,7 @@ private static Torrent Load(Stream stream, string path) public static Torrent Load(BEncodedDictionary torrentInformation) { - return LoadCore ((BEncodedDictionary)BEncodedValue.Decode (torrentInformation.Encode ())); + return LoadCore((BEncodedDictionary)BEncodedValue.Decode(torrentInformation.Encode())); } internal static Torrent LoadCore(BEncodedDictionary torrentInformation) @@ -743,7 +743,7 @@ protected void LoadInternal(BEncodedDictionary torrentInformation) // Ignore this if we have an announce-list if (torrentInformation.ContainsKey("announce-list")) break; - this.announceUrls.Add(new RawTrackerTier ()); + this.announceUrls.Add(new RawTrackerTier()); this.announceUrls[0].Add(keypair.Value.ToString()); break; @@ -811,7 +811,7 @@ protected void LoadInternal(BEncodedDictionary torrentInformation) case ("info"): using (SHA1 s = HashAlgoFactory.Create()) - this.infoHash = new InfoHash (s.ComputeHash(keypair.Value.Encode())); + this.infoHash = new InfoHash(s.ComputeHash(keypair.Value.Encode())); this.ProcessInfo(((BEncodedDictionary)keypair.Value)); break; @@ -835,7 +835,7 @@ protected void LoadInternal(BEncodedDictionary torrentInformation) Toolbox.Randomize(tier); - RawTrackerTier collection = new RawTrackerTier (); + RawTrackerTier collection = new RawTrackerTier(); for (int k = 0; k < tier.Count; k++) collection.Add(tier[k]); diff --git a/src/MonoTorrent/TorrentFile.cs b/src/MonoTorrent/TorrentFile.cs index 27fc006137..b6deb91a79 100644 --- a/src/MonoTorrent/TorrentFile.cs +++ b/src/MonoTorrent/TorrentFile.cs @@ -125,14 +125,14 @@ public TorrentFile(string path, long length) } - public TorrentFile (string path, long length, string fullPath) - : this (path, length, fullPath, 0, 0) + public TorrentFile(string path, long length, string fullPath) + : this(path, length, fullPath, 0, 0) { } - public TorrentFile (string path, long length, int startIndex, int endIndex) - : this (path, length, path, startIndex, endIndex) + public TorrentFile(string path, long length, int startIndex, int endIndex) + : this(path, length, path, startIndex, endIndex) { } diff --git a/src/MonoTorrent/UriHelper.cs b/src/MonoTorrent/UriHelper.cs index d806e596a8..b4cced9ecc 100644 --- a/src/MonoTorrent/UriHelper.cs +++ b/src/MonoTorrent/UriHelper.cs @@ -14,105 +14,121 @@ namespace MonoTorrent { static class UriHelper { - static readonly char [] hexChars = "0123456789abcdef".ToCharArray (); + static readonly char[] hexChars = "0123456789abcdef".ToCharArray(); - public static string UrlEncode (byte[] bytes) + public static string UrlEncode(byte[] bytes) { if (bytes == null) - throw new ArgumentNullException ("bytes"); + throw new ArgumentNullException("bytes"); - var result = new MemoryStream (bytes.Length); + var result = new MemoryStream(bytes.Length); for (int i = 0; i < bytes.Length; i++) - UrlEncodeChar ((char)bytes [i], result, false); + UrlEncodeChar((char)bytes[i], result, false); - return Encoding.ASCII.GetString (result.ToArray()); + return Encoding.ASCII.GetString(result.ToArray()); } - public static byte [] UrlDecode (string s) + public static byte[] UrlDecode(string s) { if (null == s) return null; var e = Encoding.UTF8; - if (s.IndexOf ('%') == -1 && s.IndexOf ('+') == -1) - return e.GetBytes (s); + if (s.IndexOf('%') == -1 && s.IndexOf('+') == -1) + return e.GetBytes(s); long len = s.Length; - var bytes = new List (); + var bytes = new List(); int xchar; char ch; - for (int i = 0; i < len; i++) { - ch = s [i]; - if (ch == '%' && i + 2 < len && s [i + 1] != '%') { - if (s [i + 1] == 'u' && i + 5 < len) { + for (int i = 0; i < len; i++) + { + ch = s[i]; + if (ch == '%' && i + 2 < len && s[i + 1] != '%') + { + if (s[i + 1] == 'u' && i + 5 < len) + { // unicode hex sequence - xchar = GetChar (s, i + 2, 4); - if (xchar != -1) { - WriteCharBytes (bytes, (char)xchar, e); + xchar = GetChar(s, i + 2, 4); + if (xchar != -1) + { + WriteCharBytes(bytes, (char)xchar, e); i += 5; - } else - WriteCharBytes (bytes, '%', e); - } else if ((xchar = GetChar (s, i + 1, 2)) != -1) { - WriteCharBytes (bytes, (char)xchar, e); + } + else + WriteCharBytes(bytes, '%', e); + } + else if ((xchar = GetChar(s, i + 1, 2)) != -1) + { + WriteCharBytes(bytes, (char)xchar, e); i += 2; - } else { - WriteCharBytes (bytes, '%', e); + } + else + { + WriteCharBytes(bytes, '%', e); } continue; } if (ch == '+') - WriteCharBytes (bytes, ' ', e); + WriteCharBytes(bytes, ' ', e); else - WriteCharBytes (bytes, ch, e); + WriteCharBytes(bytes, ch, e); } - return bytes.ToArray (); + return bytes.ToArray(); } - static void UrlEncodeChar (char c, Stream result, bool isUnicode) { - if (c > ' ' && NotEncoded (c)) { - result.WriteByte ((byte)c); + static void UrlEncodeChar(char c, Stream result, bool isUnicode) + { + if (c > ' ' && NotEncoded(c)) + { + result.WriteByte((byte)c); return; } - if (c==' ') { - result.WriteByte ((byte)'+'); + if (c == ' ') + { + result.WriteByte((byte)'+'); return; } - if ( (c < '0') || + if ((c < '0') || (c < 'A' && c > '9') || (c > 'Z' && c < 'a') || - (c > 'z')) { - if (isUnicode && c > 127) { - result.WriteByte ((byte)'%'); - result.WriteByte ((byte)'u'); - result.WriteByte ((byte)'0'); - result.WriteByte ((byte)'0'); + (c > 'z')) + { + if (isUnicode && c > 127) + { + result.WriteByte((byte)'%'); + result.WriteByte((byte)'u'); + result.WriteByte((byte)'0'); + result.WriteByte((byte)'0'); } else - result.WriteByte ((byte)'%'); + result.WriteByte((byte)'%'); - int idx = ((int) c) >> 4; - result.WriteByte ((byte)hexChars [idx]); - idx = ((int) c) & 0x0F; - result.WriteByte ((byte)hexChars [idx]); + int idx = ((int)c) >> 4; + result.WriteByte((byte)hexChars[idx]); + idx = ((int)c) & 0x0F; + result.WriteByte((byte)hexChars[idx]); } - else { - result.WriteByte ((byte)c); + else + { + result.WriteByte((byte)c); } } - static int GetChar (string str, int offset, int length) + static int GetChar(string str, int offset, int length) { int val = 0; int end = length + offset; - for (int i = offset; i < end; i++) { - char c = str [i]; + for (int i = offset; i < end; i++) + { + char c = str[i]; if (c > 127) return -1; - int current = GetInt ((byte) c); + int current = GetInt((byte)c); if (current == -1) return -1; val = (val << 4) + current; @@ -121,9 +137,9 @@ static int GetChar (string str, int offset, int length) return val; } - static int GetInt (byte b) + static int GetInt(byte b) { - char c = (char) b; + char c = (char)b; if (c >= '0' && c <= '9') return c - '0'; @@ -136,18 +152,20 @@ static int GetInt (byte b) return -1; } - static bool NotEncoded (char c) + static bool NotEncoded(char c) { return c == '!' || c == '(' || c == ')' || c == '*' || c == '-' || c == '.' || c == '_' || c == '\''; } - static void WriteCharBytes (List buf, char ch, Encoding e) + static void WriteCharBytes(List buf, char ch, Encoding e) { - if (ch > 255) { - foreach (byte b in e.GetBytes (new char[] { ch })) - buf.Add (b); - } else - buf.Add ((byte)ch); + if (ch > 255) + { + foreach (byte b in e.GetBytes(new char[] { ch })) + buf.Add(b); + } + else + buf.Add((byte)ch); } } } diff --git a/src/NzbDrone.Api.Test/ClientSchemaTests/SchemaBuilderFixture.cs b/src/NzbDrone.Api.Test/ClientSchemaTests/SchemaBuilderFixture.cs index 24aee8f5e2..5122239b3b 100644 --- a/src/NzbDrone.Api.Test/ClientSchemaTests/SchemaBuilderFixture.cs +++ b/src/NzbDrone.Api.Test/ClientSchemaTests/SchemaBuilderFixture.cs @@ -1,8 +1,8 @@ using FluentAssertions; using NUnit.Framework; -using Radarr.Http.ClientSchema; using NzbDrone.Core.Annotations; using NzbDrone.Test.Common; +using Radarr.Http.ClientSchema; namespace NzbDrone.Api.Test.ClientSchemaTests { @@ -16,25 +16,22 @@ public void should_return_field_for_every_property() schema.Should().HaveCount(2); } - [Test] public void schema_should_have_proper_fields() { var model = new TestModel - { - FirstName = "Bob", - LastName = "Poop" - }; + { + FirstName = "Bob", + LastName = "Poop" + }; var schema = SchemaBuilder.ToSchema(model); - schema.Should().Contain(c => c.Order == 1 && c.Name == "lastName" && c.Label == "Last Name" && c.HelpText == "Your Last Name" && (string) c.Value == "Poop"); - schema.Should().Contain(c => c.Order == 0 && c.Name == "firstName" && c.Label == "First Name" && c.HelpText == "Your First Name" && (string) c.Value == "Bob"); + schema.Should().Contain(c => c.Order == 1 && c.Name == "lastName" && c.Label == "Last Name" && c.HelpText == "Your Last Name" && (string)c.Value == "Poop"); + schema.Should().Contain(c => c.Order == 0 && c.Name == "firstName" && c.Label == "First Name" && c.HelpText == "Your First Name" && (string)c.Value == "Bob"); } - } - public class TestModel { [FieldDefinition(0, Label = "First Name", HelpText = "Your First Name")] diff --git a/src/NzbDrone.Api/Blacklist/BlacklistResource.cs b/src/NzbDrone.Api/Blacklist/BlacklistResource.cs index acb6484e6d..b17e140fe0 100644 --- a/src/NzbDrone.Api/Blacklist/BlacklistResource.cs +++ b/src/NzbDrone.Api/Blacklist/BlacklistResource.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using NzbDrone.Api.Movies; -using Radarr.Http.REST; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Indexers; +using NzbDrone.Core.Qualities; +using Radarr.Http.REST; namespace NzbDrone.Api.Blacklist { @@ -25,7 +25,10 @@ public static class BlacklistResourceMapper { public static BlacklistResource MapToResource(this Core.Blacklisting.Blacklist model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new BlacklistResource { diff --git a/src/NzbDrone.Api/Calendar/CalendarFeedModule.cs b/src/NzbDrone.Api/Calendar/CalendarFeedModule.cs index 5342fdaee8..7e05403f69 100644 --- a/src/NzbDrone.Api/Calendar/CalendarFeedModule.cs +++ b/src/NzbDrone.Api/Calendar/CalendarFeedModule.cs @@ -1,4 +1,3 @@ -using Nancy; using System; using System.Collections.Generic; using System.Linq; @@ -6,10 +5,11 @@ using Ical.Net.CalendarComponents; using Ical.Net.DataTypes; using Ical.Net.Serialization; -using NzbDrone.Core.Movies; +using Nancy; using Nancy.Responses; -using NzbDrone.Core.Tags; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Tags; namespace NzbDrone.Api.Calendar { @@ -24,9 +24,9 @@ public CalendarFeedModule(IMovieService movieService, ITagService tagService) _movieService = movieService; _tagService = tagService; - Get("/NzbDrone.ics", options => GetCalendarFeed()); - Get("/Sonarr.ics", options => GetCalendarFeed()); - Get("/Radarr.ics", options => GetCalendarFeed()); + Get("/NzbDrone.ics", options => GetCalendarFeed()); + Get("/Sonarr.ics", options => GetCalendarFeed()); + Get("/Radarr.ics", options => GetCalendarFeed()); } private object GetCalendarFeed() @@ -36,6 +36,7 @@ private object GetCalendarFeed() var start = DateTime.Today.AddDays(-pastDays); var end = DateTime.Today.AddDays(futureDays); var unmonitored = false; + //var premiersOnly = false; var tags = new List(); @@ -45,11 +46,19 @@ private object GetCalendarFeed() var queryPastDays = Request.Query.PastDays; var queryFutureDays = Request.Query.FutureDays; var queryUnmonitored = Request.Query.Unmonitored; + // var queryPremiersOnly = Request.Query.PremiersOnly; var queryTags = Request.Query.Tags; - if (queryStart.HasValue) start = DateTime.Parse(queryStart.Value); - if (queryEnd.HasValue) end = DateTime.Parse(queryEnd.Value); + if (queryStart.HasValue) + { + start = DateTime.Parse(queryStart.Value); + } + + if (queryEnd.HasValue) + { + end = DateTime.Parse(queryEnd.Value); + } if (queryPastDays.HasValue) { @@ -72,7 +81,6 @@ private object GetCalendarFeed() //{ // premiersOnly = bool.Parse(queryPremiersOnly.Value); //} - if (queryTags.HasValue) { var tagInput = (string)queryTags.Value.ToString(); @@ -98,10 +106,9 @@ private object GetCalendarFeed() CreateEvent(calendar, movie, true); CreateEvent(calendar, movie, false); - } - var serializer = (IStringSerializer) new SerializerFactory().Build(calendar.GetType(), new SerializationContext()); + var serializer = (IStringSerializer)new SerializerFactory().Build(calendar.GetType(), new SerializationContext()); var icalendar = serializer.SerializeToString(calendar); return new TextResponse(icalendar, "text/calendar"); diff --git a/src/NzbDrone.Api/Calendar/CalendarModule.cs b/src/NzbDrone.Api/Calendar/CalendarModule.cs index a0d12195f5..db3e46e8ed 100644 --- a/src/NzbDrone.Api/Calendar/CalendarModule.cs +++ b/src/NzbDrone.Api/Calendar/CalendarModule.cs @@ -20,7 +20,6 @@ public CalendarModule(IBroadcastSignalRMessage signalR, IMapCoversToLocal coverMapper) : base(signalR, "calendar") { - _moviesService = moviesService; _coverMapper = coverMapper; @@ -37,9 +36,20 @@ private List GetCalendar() var queryEnd = Request.Query.End; var queryIncludeUnmonitored = Request.Query.Unmonitored; - if (queryStart.HasValue) start = DateTime.Parse(queryStart.Value); - if (queryEnd.HasValue) end = DateTime.Parse(queryEnd.Value); - if (queryIncludeUnmonitored.HasValue) includeUnmonitored = Convert.ToBoolean(queryIncludeUnmonitored.Value); + if (queryStart.HasValue) + { + start = DateTime.Parse(queryStart.Value); + } + + if (queryEnd.HasValue) + { + end = DateTime.Parse(queryEnd.Value); + } + + if (queryIncludeUnmonitored.HasValue) + { + includeUnmonitored = Convert.ToBoolean(queryIncludeUnmonitored.Value); + } var resources = _moviesService.GetMoviesBetweenDates(start, end, includeUnmonitored).Select(MapToResource); @@ -48,7 +58,10 @@ private List GetCalendar() protected MovieResource MapToResource(Movie movie) { - if (movie == null) return null; + if (movie == null) + { + return null; + } var resource = movie.ToResource(); diff --git a/src/NzbDrone.Api/Commands/CommandModule.cs b/src/NzbDrone.Api/Commands/CommandModule.cs index 1fb7781e5f..6a81fbf148 100644 --- a/src/NzbDrone.Api/Commands/CommandModule.cs +++ b/src/NzbDrone.Api/Commands/CommandModule.cs @@ -2,8 +2,6 @@ using System.Collections.Generic; using System.Linq; using NLog; -using Radarr.Http.Extensions; -using Radarr.Http.Validation; using NzbDrone.Common; using NzbDrone.Core.Datastore.Events; using NzbDrone.Core.Messaging.Commands; @@ -11,7 +9,8 @@ using NzbDrone.Core.ProgressMessaging; using NzbDrone.SignalR; using Radarr.Http; - +using Radarr.Http.Extensions; +using Radarr.Http.Validation; namespace NzbDrone.Api.Commands { diff --git a/src/NzbDrone.Api/Commands/CommandResource.cs b/src/NzbDrone.Api/Commands/CommandResource.cs index 29a72ebe40..82d97ae7ab 100644 --- a/src/NzbDrone.Api/Commands/CommandResource.cs +++ b/src/NzbDrone.Api/Commands/CommandResource.cs @@ -2,8 +2,8 @@ using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; -using Radarr.Http.REST; using NzbDrone.Core.Messaging.Commands; +using Radarr.Http.REST; namespace NzbDrone.Api.Commands { @@ -27,30 +27,21 @@ public class CommandResource : RestResource //Legacy public CommandStatus State { - get - { - return Status; - } + get { return Status; } set { } } public bool Manual { - get - { - return Trigger == CommandTrigger.Manual; - } + get { return Trigger == CommandTrigger.Manual; } set { } } public DateTime StartedOn { - get - { - return Queued; - } + get { return Queued; } set { } } @@ -59,37 +50,51 @@ public DateTime? StateChangeTime { get { - - if (Started.HasValue) return Started.Value; + if (Started.HasValue) + { + return Started.Value; + } return Ended; } - set { } + set + { + } } public bool SendUpdatesToClient { get { - if (Body != null) return (Body as Command).SendUpdatesToClient; + if (Body != null) + { + return (Body as Command).SendUpdatesToClient; + } return false; } - set { } + set + { + } } public bool UpdateScheduledTask { get { - if (Body != null) return (Body as Command).UpdateScheduledTask; + if (Body != null) + { + return (Body as Command).UpdateScheduledTask; + } return false; } - set { } + set + { + } } public DateTime? LastExecutionTime { get; set; } @@ -99,7 +104,10 @@ public static class CommandResourceMapper { public static CommandResource ToResource(this CommandModel model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new CommandResource { diff --git a/src/NzbDrone.Api/Config/DownloadClientConfigModule.cs b/src/NzbDrone.Api/Config/DownloadClientConfigModule.cs index 93afc5dd5a..4162429503 100644 --- a/src/NzbDrone.Api/Config/DownloadClientConfigModule.cs +++ b/src/NzbDrone.Api/Config/DownloadClientConfigModule.cs @@ -7,7 +7,6 @@ public class DownloadClientConfigModule : NzbDroneConfigModule { - public IndexerConfigModule(IConfigService configService) : base(configService) { diff --git a/src/NzbDrone.Api/Config/IndexerConfigResource.cs b/src/NzbDrone.Api/Config/IndexerConfigResource.cs index 71264e9885..80d9f47584 100644 --- a/src/NzbDrone.Api/Config/IndexerConfigResource.cs +++ b/src/NzbDrone.Api/Config/IndexerConfigResource.cs @@ -1,6 +1,6 @@ -using Radarr.Http.REST; using NzbDrone.Core.Configuration; using NzbDrone.Core.Parser; +using Radarr.Http.REST; namespace NzbDrone.Api.Config { diff --git a/src/NzbDrone.Api/Config/MediaManagementConfigResource.cs b/src/NzbDrone.Api/Config/MediaManagementConfigResource.cs index 53e03e87ef..534cda2d6c 100644 --- a/src/NzbDrone.Api/Config/MediaManagementConfigResource.cs +++ b/src/NzbDrone.Api/Config/MediaManagementConfigResource.cs @@ -1,6 +1,6 @@ -using Radarr.Http.REST; using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles; +using Radarr.Http.REST; namespace NzbDrone.Api.Config { diff --git a/src/NzbDrone.Api/Config/NamingConfigModule.cs b/src/NzbDrone.Api/Config/NamingConfigModule.cs index 8047eed0fa..60b486d633 100644 --- a/src/NzbDrone.Api/Config/NamingConfigModule.cs +++ b/src/NzbDrone.Api/Config/NamingConfigModule.cs @@ -2,9 +2,9 @@ using System.Linq; using FluentValidation; using FluentValidation.Results; +using Nancy.ModelBinding; using NzbDrone.Common.Extensions; using NzbDrone.Core.Organizer; -using Nancy.ModelBinding; using Radarr.Http; namespace NzbDrone.Api.Config @@ -30,7 +30,7 @@ public NamingConfigModule(INamingConfigService namingConfigService, GetResourceById = GetNamingConfig; UpdateResource = UpdateNamingConfig; - Get("/samples", x => GetExamples(this.Bind())); + Get("/samples", x => GetExamples(this.Bind())); SharedValidator.RuleFor(c => c.MultiEpisodeStyle).InclusiveBetween(0, 5); SharedValidator.RuleFor(c => c.StandardMovieFormat).ValidMovieFormat(); @@ -87,11 +87,9 @@ private void ValidateFormatResult(NamingConfig nameSpec) var movieSampleResult = _filenameSampleService.GetMovieSample(nameSpec); //var standardMovieValidationResult = _filenameValidationService.ValidateMovieFilename(movieSampleResult); For now, let's hope the user is not stupid enough :/ - var validationFailures = new List(); //validationFailures.AddIfNotNull(standardMovieValidationResult); - if (validationFailures.Any()) { throw new ValidationException(validationFailures.DistinctBy(v => v.PropertyName).ToArray()); diff --git a/src/NzbDrone.Api/Config/NamingConfigResource.cs b/src/NzbDrone.Api/Config/NamingConfigResource.cs index 131f6459cb..b6e4a53521 100644 --- a/src/NzbDrone.Api/Config/NamingConfigResource.cs +++ b/src/NzbDrone.Api/Config/NamingConfigResource.cs @@ -1,5 +1,5 @@ -using Radarr.Http.REST; using NzbDrone.Core.Organizer; +using Radarr.Http.REST; namespace NzbDrone.Api.Config { @@ -33,6 +33,7 @@ public static NamingConfigResource ToResource(this NamingConfig model) MultiEpisodeStyle = model.MultiEpisodeStyle, StandardMovieFormat = model.StandardMovieFormat, MovieFolderFormat = model.MovieFolderFormat + //IncludeSeriesTitle //IncludeEpisodeTitle //IncludeQuality diff --git a/src/NzbDrone.Api/Config/NetImportConfigModule.cs b/src/NzbDrone.Api/Config/NetImportConfigModule.cs index 5925595e87..3c1ce926c1 100644 --- a/src/NzbDrone.Api/Config/NetImportConfigModule.cs +++ b/src/NzbDrone.Api/Config/NetImportConfigModule.cs @@ -1,11 +1,10 @@ -using Radarr.Http.Validation; using NzbDrone.Core.Configuration; +using Radarr.Http.Validation; namespace NzbDrone.Api.Config { public class NetImportConfigModule : NzbDroneConfigModule { - public NetImportConfigModule(IConfigService configService) : base(configService) { diff --git a/src/NzbDrone.Api/Config/NetImportConfigResource.cs b/src/NzbDrone.Api/Config/NetImportConfigResource.cs index 6a5dc48da1..dba6ec52f5 100644 --- a/src/NzbDrone.Api/Config/NetImportConfigResource.cs +++ b/src/NzbDrone.Api/Config/NetImportConfigResource.cs @@ -1,5 +1,5 @@ -using Radarr.Http.REST; -using NzbDrone.Core.Configuration; +using NzbDrone.Core.Configuration; +using Radarr.Http.REST; namespace NzbDrone.Api.Config { diff --git a/src/NzbDrone.Api/Config/NzbDroneConfigModule.cs b/src/NzbDrone.Api/Config/NzbDroneConfigModule.cs index acc29f8bf2..c17e5e72aa 100644 --- a/src/NzbDrone.Api/Config/NzbDroneConfigModule.cs +++ b/src/NzbDrone.Api/Config/NzbDroneConfigModule.cs @@ -1,12 +1,13 @@ using System.Linq; using System.Reflection; +using NzbDrone.Core.Configuration; using Radarr.Http; using Radarr.Http.REST; -using NzbDrone.Core.Configuration; namespace NzbDrone.Api.Config { - public abstract class NzbDroneConfigModule : RadarrRestModule where TResource : RestResource, new() + public abstract class NzbDroneConfigModule : RadarrRestModule + where TResource : RestResource, new() { private readonly IConfigService _configService; @@ -15,8 +16,8 @@ protected NzbDroneConfigModule(IConfigService configService) { } - protected NzbDroneConfigModule(string resource, IConfigService configService) : - base("config/" + resource.Trim('/')) + protected NzbDroneConfigModule(string resource, IConfigService configService) + : base("config/" + resource.Trim('/')) { _configService = configService; diff --git a/src/NzbDrone.Api/Config/UiConfigModule.cs b/src/NzbDrone.Api/Config/UiConfigModule.cs index 9beadc0915..1c40217825 100644 --- a/src/NzbDrone.Api/Config/UiConfigModule.cs +++ b/src/NzbDrone.Api/Config/UiConfigModule.cs @@ -7,7 +7,6 @@ public class UiConfigModule : NzbDroneConfigModule public UiConfigModule(IConfigService configService) : base(configService) { - } protected override UiConfigResource ToResource(IConfigService model) diff --git a/src/NzbDrone.Api/Config/UiConfigResource.cs b/src/NzbDrone.Api/Config/UiConfigResource.cs index d6b1b7dc32..559787e388 100644 --- a/src/NzbDrone.Api/Config/UiConfigResource.cs +++ b/src/NzbDrone.Api/Config/UiConfigResource.cs @@ -1,5 +1,5 @@ -using Radarr.Http.REST; -using NzbDrone.Core.Configuration; +using NzbDrone.Core.Configuration; +using Radarr.Http.REST; namespace NzbDrone.Api.Config { diff --git a/src/NzbDrone.Api/DiskSpace/DiskSpaceModule.cs b/src/NzbDrone.Api/DiskSpace/DiskSpaceModule.cs index 0a43fad9b4..83f54b4b8f 100644 --- a/src/NzbDrone.Api/DiskSpace/DiskSpaceModule.cs +++ b/src/NzbDrone.Api/DiskSpace/DiskSpaceModule.cs @@ -4,7 +4,7 @@ namespace NzbDrone.Api.DiskSpace { - public class DiskSpaceModule :RadarrRestModule + public class DiskSpaceModule : RadarrRestModule { private readonly IDiskSpaceService _diskSpaceService; @@ -15,7 +15,6 @@ public DiskSpaceModule(IDiskSpaceService diskSpaceService) GetResourceAll = GetFreeSpace; } - public List GetFreeSpace() { return _diskSpaceService.GetFreeSpace().ConvertAll(DiskSpaceResourceMapper.MapToResource); diff --git a/src/NzbDrone.Api/DiskSpace/DiskSpaceResource.cs b/src/NzbDrone.Api/DiskSpace/DiskSpaceResource.cs index f95c2d2a49..5847a7a9c2 100644 --- a/src/NzbDrone.Api/DiskSpace/DiskSpaceResource.cs +++ b/src/NzbDrone.Api/DiskSpace/DiskSpaceResource.cs @@ -14,7 +14,10 @@ public static class DiskSpaceResourceMapper { public static DiskSpaceResource MapToResource(this Core.DiskSpace.DiskSpace model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new DiskSpaceResource { diff --git a/src/NzbDrone.Api/DownloadClient/DownloadClientModule.cs b/src/NzbDrone.Api/DownloadClient/DownloadClientModule.cs index 24ffc4f034..d569b5de87 100644 --- a/src/NzbDrone.Api/DownloadClient/DownloadClientModule.cs +++ b/src/NzbDrone.Api/DownloadClient/DownloadClientModule.cs @@ -29,7 +29,11 @@ protected override void MapToModel(DownloadClientDefinition definition, Download protected override void Validate(DownloadClientDefinition definition, bool includeWarnings) { - if (!definition.Enable) return; + if (!definition.Enable) + { + return; + } + base.Validate(definition, includeWarnings); } } diff --git a/src/NzbDrone.Api/ExtraFiles/ExtraFileModule.cs b/src/NzbDrone.Api/ExtraFiles/ExtraFileModule.cs index 040aae79af..f83292b18f 100644 --- a/src/NzbDrone.Api/ExtraFiles/ExtraFileModule.cs +++ b/src/NzbDrone.Api/ExtraFiles/ExtraFileModule.cs @@ -1,10 +1,10 @@ using System.Collections.Generic; -using Radarr.Http.REST; using NzbDrone.Core.Extras.Files; using NzbDrone.Core.Extras.Metadata.Files; using NzbDrone.Core.Extras.Others; using NzbDrone.Core.Extras.Subtitles; using Radarr.Http; +using Radarr.Http.REST; namespace NzbDrone.Api.ExtraFiles { diff --git a/src/NzbDrone.Api/ExtraFiles/ExtraFileResource.cs b/src/NzbDrone.Api/ExtraFiles/ExtraFileResource.cs index b37ec6adef..b082c62dbd 100644 --- a/src/NzbDrone.Api/ExtraFiles/ExtraFileResource.cs +++ b/src/NzbDrone.Api/ExtraFiles/ExtraFileResource.cs @@ -1,10 +1,10 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.Extras.Files; using NzbDrone.Core.Extras.Metadata.Files; using NzbDrone.Core.Extras.Others; using NzbDrone.Core.Extras.Subtitles; +using Radarr.Http.REST; namespace NzbDrone.Api.ExtraFiles { @@ -21,7 +21,10 @@ public static class ExtraFileResourceMapper { public static ExtraFileResource ToResource(this MetadataFile model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ExtraFileResource { @@ -36,7 +39,10 @@ public static ExtraFileResource ToResource(this MetadataFile model) public static ExtraFileResource ToResource(this SubtitleFile model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ExtraFileResource { @@ -51,7 +57,10 @@ public static ExtraFileResource ToResource(this SubtitleFile model) public static ExtraFileResource ToResource(this OtherExtraFile model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ExtraFileResource { @@ -78,6 +87,5 @@ public static List ToResource(this IEnumerable GetContents()); - Get("/type", x => GetEntityType()); - Get("/mediafiles", x => GetMediaFiles()); + Get("/", x => GetContents()); + Get("/type", x => GetEntityType()); + Get("/mediafiles", x => GetMediaFiles()); } private object GetContents() @@ -60,7 +60,8 @@ private object GetMediaFiles() return new string[0]; } - return _diskScanService.GetVideoFiles(path).Select(f => new { + return _diskScanService.GetVideoFiles(path).Select(f => new + { Path = f, RelativePath = path.GetRelativePath(f), Name = Path.GetFileName(f) diff --git a/src/NzbDrone.Api/Health/HealthResource.cs b/src/NzbDrone.Api/Health/HealthResource.cs index 8be8a58997..b3ed472642 100644 --- a/src/NzbDrone.Api/Health/HealthResource.cs +++ b/src/NzbDrone.Api/Health/HealthResource.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Common.Http; using NzbDrone.Core.HealthCheck; +using Radarr.Http.REST; namespace NzbDrone.Api.Health { @@ -17,7 +17,10 @@ public static class HealthResourceMapper { public static HealthResource ToResource(this HealthCheck model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new HealthResource { diff --git a/src/NzbDrone.Api/History/HistoryModule.cs b/src/NzbDrone.Api/History/HistoryModule.cs index 93c02201e2..6c09582d89 100644 --- a/src/NzbDrone.Api/History/HistoryModule.cs +++ b/src/NzbDrone.Api/History/HistoryModule.cs @@ -3,10 +3,10 @@ using Nancy; using NzbDrone.Api.Movies; using NzbDrone.Core.Datastore; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Download; using NzbDrone.Core.History; using Radarr.Http; -using NzbDrone.Core.DecisionEngine.Specifications; namespace NzbDrone.Api.History { @@ -25,7 +25,7 @@ public HistoryModule(IHistoryService historyService, _failedDownloadService = failedDownloadService; GetResourcePaged = GetHistory; - Post("/failed", x => MarkAsFailed()); + Post("/failed", x => MarkAsFailed()); } protected HistoryResource MapToResource(Core.History.History model) diff --git a/src/NzbDrone.Api/History/HistoryResource.cs b/src/NzbDrone.Api/History/HistoryResource.cs index c976a9d2dc..699e7083f5 100644 --- a/src/NzbDrone.Api/History/HistoryResource.cs +++ b/src/NzbDrone.Api/History/HistoryResource.cs @@ -1,10 +1,9 @@ using System; using System.Collections.Generic; -using Radarr.Http.REST; using NzbDrone.Api.Movies; using NzbDrone.Core.History; using NzbDrone.Core.Qualities; - +using Radarr.Http.REST; namespace NzbDrone.Api.History { @@ -27,7 +26,10 @@ public static class HistoryResourceMapper { public static HistoryResource ToResource(this Core.History.History model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new HistoryResource { @@ -35,13 +37,14 @@ public static HistoryResource ToResource(this Core.History.History model) MovieId = model.MovieId, SourceTitle = model.SourceTitle, Quality = model.Quality, + //QualityCutoffNotMet Date = model.Date, DownloadId = model.DownloadId, EventType = model.EventType, - Data = model.Data + Data = model.Data }; } } diff --git a/src/NzbDrone.Api/Indexers/IndexerModule.cs b/src/NzbDrone.Api/Indexers/IndexerModule.cs index 53166381eb..b22c8a7e12 100644 --- a/src/NzbDrone.Api/Indexers/IndexerModule.cs +++ b/src/NzbDrone.Api/Indexers/IndexerModule.cs @@ -31,7 +31,11 @@ protected override void MapToModel(IndexerDefinition definition, IndexerResource protected override void Validate(IndexerDefinition definition, bool includeWarnings) { - if (!definition.Enable) return; + if (!definition.Enable) + { + return; + } + base.Validate(definition, includeWarnings); } } diff --git a/src/NzbDrone.Api/Indexers/ReleaseModule.cs b/src/NzbDrone.Api/Indexers/ReleaseModule.cs index 359e8e79c1..693ba93e3c 100644 --- a/src/NzbDrone.Api/Indexers/ReleaseModule.cs +++ b/src/NzbDrone.Api/Indexers/ReleaseModule.cs @@ -2,15 +2,15 @@ using System.Collections.Generic; using FluentValidation; using Nancy; +using Nancy.ModelBinding; using NLog; +using NzbDrone.Common.Cache; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download; using NzbDrone.Core.Exceptions; -using NzbDrone.Core.IndexerSearch; using NzbDrone.Core.Indexers; +using NzbDrone.Core.IndexerSearch; using NzbDrone.Core.Parser.Model; -using Nancy.ModelBinding; -using NzbDrone.Common.Cache; using HttpStatusCode = System.Net.HttpStatusCode; namespace NzbDrone.Api.Indexers @@ -42,7 +42,7 @@ public ReleaseModule(IFetchAndParseRss rssFetcherAndParser, _logger = logger; GetResourceAll = GetReleases; - Post("/", x => DownloadRelease(this.Bind())); + Post("/", x => DownloadRelease(this.Bind())); //PostValidator.RuleFor(s => s.DownloadAllowed).Equal(true); PostValidator.RuleFor(s => s.Guid).NotEmpty(); @@ -60,6 +60,7 @@ private object DownloadRelease(ReleaseResource release) return new NotFoundResponse(); } + try { _downloadService.DownloadReport(remoteMovie); @@ -115,10 +116,9 @@ private List GetRss() protected override ReleaseResource MapDecision(DownloadDecision decision, int initialWeight) { + _remoteMovieCache.Set(decision.RemoteMovie.Release.Guid, decision.RemoteMovie, TimeSpan.FromMinutes(30)); - _remoteMovieCache.Set(decision.RemoteMovie.Release.Guid, decision.RemoteMovie, TimeSpan.FromMinutes(30)); - - return base.MapDecision(decision, initialWeight); + return base.MapDecision(decision, initialWeight); } } } diff --git a/src/NzbDrone.Api/Indexers/ReleasePushModule.cs b/src/NzbDrone.Api/Indexers/ReleasePushModule.cs index 57c8240e06..a51a40c219 100644 --- a/src/NzbDrone.Api/Indexers/ReleasePushModule.cs +++ b/src/NzbDrone.Api/Indexers/ReleasePushModule.cs @@ -1,17 +1,17 @@ -using FluentValidation; -using NzbDrone.Core.DecisionEngine; -using NzbDrone.Core.Download; using System.Collections.Generic; using System.Linq; -using NzbDrone.Core.Parser.Model; +using FluentValidation; using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Core.Datastore; +using NzbDrone.Core.DecisionEngine; +using NzbDrone.Core.Download; using NzbDrone.Core.Indexers; +using NzbDrone.Core.Parser.Model; namespace NzbDrone.Api.Indexers { - class ReleasePushModule : ReleaseModuleBase + public class ReleasePushModule : ReleaseModuleBase { private readonly IMakeDownloadDecision _downloadDecisionMaker; private readonly IProcessDownloadDecisions _downloadDecisionProcessor; @@ -28,7 +28,7 @@ public ReleasePushModule(IMakeDownloadDecision downloadDecisionMaker, _indexerFactory = indexerFactory; _logger = logger; - Post("/push", x => ProcessRelease(ReadResourceFromRequest())); + Post("/push", x => ProcessRelease(ReadResourceFromRequest())); PostValidator.RuleFor(s => s.Title).NotEmpty(); PostValidator.RuleFor(s => s.DownloadUrl).NotEmpty(); diff --git a/src/NzbDrone.Api/Indexers/ReleaseResource.cs b/src/NzbDrone.Api/Indexers/ReleaseResource.cs index 2a826ea25b..145df50111 100644 --- a/src/NzbDrone.Api/Indexers/ReleaseResource.cs +++ b/src/NzbDrone.Api/Indexers/ReleaseResource.cs @@ -1,14 +1,14 @@ using System; using System.Collections.Generic; +using System.Linq; using Newtonsoft.Json; -using Radarr.Http.REST; +using NzbDrone.Core.DecisionEngine; +using NzbDrone.Core.Indexers; using NzbDrone.Core.Languages; using NzbDrone.Core.Parser; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Indexers; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.DecisionEngine; -using System.Linq; +using NzbDrone.Core.Qualities; +using Radarr.Http.REST; namespace NzbDrone.Api.Indexers { @@ -56,7 +56,6 @@ public class ReleaseResource : RestResource public int? Leechers { get; set; } public DownloadProtocol Protocol { get; set; } - // TODO: Remove in v3 // Used to support the original Release Push implementation // JsonIgnore so we don't serialize it, but can still parse it @@ -122,8 +121,8 @@ public static ReleaseResource ToResource(this DownloadDecision model) DownloadUrl = releaseInfo.DownloadUrl, InfoUrl = releaseInfo.InfoUrl, MappingResult = mappingResult, - //ReleaseWeight + //ReleaseWeight SuspectedMovieId = movieId, MagnetUrl = torrentInfo.MagnetUrl, @@ -136,7 +135,6 @@ public static ReleaseResource ToResource(this DownloadDecision model) //Special = parsedMovieInfo.Special, }; - } public static ReleaseInfo ToModel(this ReleaseResource resource) diff --git a/src/NzbDrone.Api/Logs/LogFileModuleBase.cs b/src/NzbDrone.Api/Logs/LogFileModuleBase.cs index fa1de297e7..7acf4fdf21 100644 --- a/src/NzbDrone.Api/Logs/LogFileModuleBase.cs +++ b/src/NzbDrone.Api/Logs/LogFileModuleBase.cs @@ -26,7 +26,7 @@ public LogFileModuleBase(IDiskProvider diskProvider, _configFileProvider = configFileProvider; GetResourceAll = GetLogFilesResponse; - Get(LOGFILE_ROUTE, options => GetLogFileResponse(options.filename)); + Get(LOGFILE_ROUTE, options => GetLogFileResponse(options.filename)); } private List GetLogFilesResponse() @@ -60,7 +60,9 @@ private object GetLogFileResponse(string filename) var filePath = GetLogFilePath(filename); if (!_diskProvider.FileExists(filePath)) + { return new NotFoundResponse(); + } var data = _diskProvider.ReadAllText(filePath); diff --git a/src/NzbDrone.Api/Logs/LogResource.cs b/src/NzbDrone.Api/Logs/LogResource.cs index 53d9a947a1..675eb033a7 100644 --- a/src/NzbDrone.Api/Logs/LogResource.cs +++ b/src/NzbDrone.Api/Logs/LogResource.cs @@ -17,7 +17,10 @@ public static class LogResourceMapper { public static LogResource ToResource(this Core.Instrumentation.Log model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new LogResource { diff --git a/src/NzbDrone.Api/Logs/UpdateLogFileModule.cs b/src/NzbDrone.Api/Logs/UpdateLogFileModule.cs index d4e19415d2..a8b9ff1b04 100644 --- a/src/NzbDrone.Api/Logs/UpdateLogFileModule.cs +++ b/src/NzbDrone.Api/Logs/UpdateLogFileModule.cs @@ -25,7 +25,10 @@ public UpdateLogFileModule(IAppFolderInfo appFolderInfo, protected override IEnumerable GetLogFiles() { - if (!_diskProvider.FolderExists(_appFolderInfo.GetUpdateLogFolder())) return Enumerable.Empty(); + if (!_diskProvider.FolderExists(_appFolderInfo.GetUpdateLogFolder())) + { + return Enumerable.Empty(); + } return _diskProvider.GetFiles(_appFolderInfo.GetUpdateLogFolder(), SearchOption.TopDirectoryOnly) .Where(f => Regex.IsMatch(Path.GetFileName(f), LOGFILE_ROUTE.TrimStart('/'), RegexOptions.IgnoreCase)) diff --git a/src/NzbDrone.Api/ManualImport/ManualImportResource.cs b/src/NzbDrone.Api/ManualImport/ManualImportResource.cs index fea7987b85..ecd8ef5db0 100644 --- a/src/NzbDrone.Api/ManualImport/ManualImportResource.cs +++ b/src/NzbDrone.Api/ManualImport/ManualImportResource.cs @@ -1,10 +1,10 @@ using System.Collections.Generic; using System.Linq; using NzbDrone.Api.Movies; -using Radarr.Http.REST; using NzbDrone.Common.Crypto; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Qualities; +using Radarr.Http.REST; namespace NzbDrone.Api.ManualImport { @@ -25,7 +25,10 @@ public static class ManualImportResourceMapper { public static ManualImportResource ToResource(this Core.MediaFiles.MovieImport.Manual.ManualImportItem model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ManualImportResource { @@ -37,6 +40,7 @@ public static ManualImportResource ToResource(this Core.MediaFiles.MovieImport.M Size = model.Size, Movie = model.Movie.ToResource(), Quality = model.Quality, + //QualityWeight DownloadId = model.DownloadId, Rejections = model.Rejections diff --git a/src/NzbDrone.Api/MediaCovers/MediaCoverModule.cs b/src/NzbDrone.Api/MediaCovers/MediaCoverModule.cs index 26391be9ab..246bbdd4fe 100644 --- a/src/NzbDrone.Api/MediaCovers/MediaCoverModule.cs +++ b/src/NzbDrone.Api/MediaCovers/MediaCoverModule.cs @@ -10,19 +10,19 @@ namespace NzbDrone.Api.MediaCovers { public class MediaCoverModule : NzbDroneApiModule { + private const string MEDIA_COVER_ROUTE = @"/(?\d+)/(?(.+)\.(jpg|png|gif))"; private static readonly Regex RegexResizedImage = new Regex(@"-\d+\.jpg$", RegexOptions.Compiled | RegexOptions.IgnoreCase); - private const string MEDIA_COVER_ROUTE = @"/(?\d+)/(?(.+)\.(jpg|png|gif))"; - private readonly IAppFolderInfo _appFolderInfo; private readonly IDiskProvider _diskProvider; - public MediaCoverModule(IAppFolderInfo appFolderInfo, IDiskProvider diskProvider) : base("MediaCover") + public MediaCoverModule(IAppFolderInfo appFolderInfo, IDiskProvider diskProvider) + : base("MediaCover") { _appFolderInfo = appFolderInfo; _diskProvider = diskProvider; - Get(MEDIA_COVER_ROUTE, options => GetMediaCover(options.seriesId, options.filename)); + Get(MEDIA_COVER_ROUTE, options => GetMediaCover(options.seriesId, options.filename)); } private object GetMediaCover(int seriesId, string filename) @@ -38,6 +38,7 @@ private object GetMediaCover(int seriesId, string filename) { return new NotFoundResponse(); } + filePath = basefilePath; } diff --git a/src/NzbDrone.Api/Metadata/MetadataModule.cs b/src/NzbDrone.Api/Metadata/MetadataModule.cs index e24c388623..1f941fa1cb 100644 --- a/src/NzbDrone.Api/Metadata/MetadataModule.cs +++ b/src/NzbDrone.Api/Metadata/MetadataModule.cs @@ -25,7 +25,11 @@ protected override void MapToModel(MetadataDefinition definition, MetadataResour protected override void Validate(MetadataDefinition definition, bool includeWarnings) { - if (!definition.Enable) return; + if (!definition.Enable) + { + return; + } + base.Validate(definition, includeWarnings); } } diff --git a/src/NzbDrone.Api/MovieFiles/MovieFileModule.cs b/src/NzbDrone.Api/MovieFiles/MovieFileModule.cs index 1115bbb748..89ff86a9f0 100644 --- a/src/NzbDrone.Api/MovieFiles/MovieFileModule.cs +++ b/src/NzbDrone.Api/MovieFiles/MovieFileModule.cs @@ -1,13 +1,13 @@ using System.IO; using NLog; -using Radarr.Http; using NzbDrone.Core.Datastore.Events; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Movies; using NzbDrone.SignalR; -using NzbDrone.Core.DecisionEngine.Specifications; +using Radarr.Http; namespace NzbDrone.Api.MovieFiles { @@ -44,7 +44,6 @@ private MovieFileResource GetMovieFile(int id) return movie.ToResource(); } - private void SetQuality(MovieFileResource movieFileResource) { var movieFile = _mediaFileService.GetMovie(movieFileResource.Id); diff --git a/src/NzbDrone.Api/MovieFiles/MovieFileResource.cs b/src/NzbDrone.Api/MovieFiles/MovieFileResource.cs index 711013e7d8..78990cdf15 100644 --- a/src/NzbDrone.Api/MovieFiles/MovieFileResource.cs +++ b/src/NzbDrone.Api/MovieFiles/MovieFileResource.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Api.Movies; -using NzbDrone.Core.Qualities; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Qualities; +using Radarr.Http.REST; namespace NzbDrone.Api.MovieFiles { @@ -12,13 +12,11 @@ public class MovieFileResource : RestResource { public MovieFileResource() { - } //Todo: Sorters should be done completely on the client //Todo: Is there an easy way to keep IgnoreArticlesWhenSorting in sync between, Series, History, Missing? //Todo: We should get the entire Profile instead of ID and Name separately - public int MovieId { get; set; } public string RelativePath { get; set; } public string Path { get; set; } @@ -38,7 +36,10 @@ public static class MovieFileResourceMapper { public static MovieFileResource ToResource(this MovieFile model) { - if (model == null) return null; + if (model == null) + { + return null; + } MovieResource movie = null; @@ -69,11 +70,13 @@ public static MovieFileResource ToResource(this MovieFile model) public static MovieFile ToModel(this MovieFileResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new MovieFile { - }; } diff --git a/src/NzbDrone.Api/Movies/AlternativeTitleModule.cs b/src/NzbDrone.Api/Movies/AlternativeTitleModule.cs index ca18bdecba..9be6f6da71 100644 --- a/src/NzbDrone.Api/Movies/AlternativeTitleModule.cs +++ b/src/NzbDrone.Api/Movies/AlternativeTitleModule.cs @@ -1,7 +1,7 @@ using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.MetadataSource.RadarrAPI; -using NzbDrone.Core.Movies.AlternativeTitles; using NzbDrone.Core.Movies; +using NzbDrone.Core.Movies.AlternativeTitles; using NzbDrone.Core.Movies.Events; using Radarr.Http; diff --git a/src/NzbDrone.Api/Movies/AlternativeTitleResource.cs b/src/NzbDrone.Api/Movies/AlternativeTitleResource.cs index 0217619072..412495ad1f 100644 --- a/src/NzbDrone.Api/Movies/AlternativeTitleResource.cs +++ b/src/NzbDrone.Api/Movies/AlternativeTitleResource.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; -using NzbDrone.Core.Movies.AlternativeTitles; using NzbDrone.Core.Languages; +using NzbDrone.Core.Movies.AlternativeTitles; +using Radarr.Http.REST; namespace NzbDrone.Api.Movies { @@ -10,13 +10,11 @@ public class AlternativeTitleResource : RestResource { public AlternativeTitleResource() { - } //Todo: Sorters should be done completely on the client //Todo: Is there an easy way to keep IgnoreArticlesWhenSorting in sync between, Series, History, Missing? //Todo: We should get the entire Profile instead of ID and Name separately - public SourceType SourceType { get; set; } public int MovieId { get; set; } public string Title { get; set; } @@ -33,7 +31,10 @@ public static class AlternativeTitleResourceMapper { public static AlternativeTitleResource ToResource(this AlternativeTitle model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new AlternativeTitleResource { @@ -50,7 +51,10 @@ public static AlternativeTitleResource ToResource(this AlternativeTitle model) public static AlternativeTitle ToModel(this AlternativeTitleResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new AlternativeTitle { diff --git a/src/NzbDrone.Api/Movies/AlternativeYearResource.cs b/src/NzbDrone.Api/Movies/AlternativeYearResource.cs index d7ee8bd9bd..039bbd9b01 100644 --- a/src/NzbDrone.Api/Movies/AlternativeYearResource.cs +++ b/src/NzbDrone.Api/Movies/AlternativeYearResource.cs @@ -6,13 +6,11 @@ public class AlternativeYearResource : RestResource { public AlternativeYearResource() { - } //Todo: Sorters should be done completely on the client //Todo: Is there an easy way to keep IgnoreArticlesWhenSorting in sync between, Series, History, Missing? //Todo: We should get the entire Profile instead of ID and Name separately - public int MovieId { get; set; } public int Year { get; set; } diff --git a/src/NzbDrone.Api/Movies/FetchMovieListModule.cs b/src/NzbDrone.Api/Movies/FetchMovieListModule.cs index fce9175058..8e12f1c8b8 100644 --- a/src/NzbDrone.Api/Movies/FetchMovieListModule.cs +++ b/src/NzbDrone.Api/Movies/FetchMovieListModule.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; +using System.Linq; using Nancy; using NzbDrone.Core.MediaCover; using NzbDrone.Core.MetadataSource; -using System.Linq; using NzbDrone.Core.NetImport; using Radarr.Http; @@ -18,13 +18,12 @@ public FetchMovieListModule(IFetchNetImport netImport, ISearchForNewMovie movieS { _fetchNetImport = netImport; _movieSearch = movieSearch; - Get("/", x => Search()); + Get("/", x => Search()); } - private object Search() { - var results = _fetchNetImport.FetchAndFilter((int) Request.Query.listId, false); + var results = _fetchNetImport.FetchAndFilter((int)Request.Query.listId, false); List realResults = new List(); @@ -41,7 +40,6 @@ private object Search() return MapToResource(results); } - private static IEnumerable MapToResource(IEnumerable movies) { foreach (var currentSeries in movies) diff --git a/src/NzbDrone.Api/Movies/MovieBulkImportModule.cs b/src/NzbDrone.Api/Movies/MovieBulkImportModule.cs index c56aa85791..8bdbd0ba6b 100644 --- a/src/NzbDrone.Api/Movies/MovieBulkImportModule.cs +++ b/src/NzbDrone.Api/Movies/MovieBulkImportModule.cs @@ -1,23 +1,22 @@ -using System.Collections.Generic; -using Nancy; -using NzbDrone.Core.MediaCover; -using NzbDrone.Core.MetadataSource; -using NzbDrone.Core.Parser; -using System.Linq; using System; +using System.Collections.Generic; +using System.Linq; +using Nancy; +using NzbDrone.Common.Cache; using NzbDrone.Common.Extensions; using NzbDrone.Core.Datastore; +using NzbDrone.Core.MediaCover; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.MovieImport; -using NzbDrone.Core.RootFolders; -using NzbDrone.Common.Cache; +using NzbDrone.Core.MetadataSource; using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser; using NzbDrone.Core.Profiles; +using NzbDrone.Core.RootFolders; using Radarr.Http; namespace NzbDrone.Api.Movies { - public class UnmappedComparer : IComparer { public int Compare(UnmappedFolder a, UnmappedFolder b) @@ -37,10 +36,14 @@ public class MovieBulkImportModule : RadarrRestModule private readonly IProfileService _profileService; private readonly IMovieService _movieService; - public MovieBulkImportModule(ISearchForNewMovie searchProxy, IRootFolderService rootFolderService, + public MovieBulkImportModule(ISearchForNewMovie searchProxy, + IRootFolderService rootFolderService, IMakeImportDecision importDecisionMaker, - IDiskScanService diskScanService, ICacheManager cacheManager, - IParsingService parsingService, IProfileService profileService, IMovieService movieService) + IDiskScanService diskScanService, + ICacheManager cacheManager, + IParsingService parsingService, + IProfileService profileService, + IMovieService movieService) : base("/movies/bulkimport") { _searchProxy = searchProxy; @@ -51,10 +54,9 @@ public MovieBulkImportModule(ISearchForNewMovie searchProxy, IRootFolderService _movieService = movieService; _profileService = profileService; _parsingService = parsingService; - Get("/", x => Search()); + Get("/", x => Search()); } - private object Search() { if (Request.Query.Id == 0) @@ -84,7 +86,7 @@ private object Search() max = total_count >= max ? max : total_count; - var paged = unmapped.GetRange(min, max-min); + var paged = unmapped.GetRange(min, max - min); var mapped = paged.Select(f => { @@ -167,7 +169,6 @@ private object Search() }; } - private static IEnumerable MapToResource(IEnumerable movies) { foreach (var currentMovie in movies) diff --git a/src/NzbDrone.Api/Movies/MovieDiscoverModule.cs b/src/NzbDrone.Api/Movies/MovieDiscoverModule.cs index b9335aaa0a..2d22941133 100644 --- a/src/NzbDrone.Api/Movies/MovieDiscoverModule.cs +++ b/src/NzbDrone.Api/Movies/MovieDiscoverModule.cs @@ -1,10 +1,10 @@ using System.Collections.Generic; +using System.Linq; +using NzbDrone.Api.NetImport; using NzbDrone.Core.MediaCover; using NzbDrone.Core.MetadataSource; -using System.Linq; -using Radarr.Http; using NzbDrone.Core.NetImport; -using NzbDrone.Api.NetImport; +using Radarr.Http; namespace NzbDrone.Api.Movies { @@ -18,8 +18,8 @@ public MovieDiscoverModule(IDiscoverNewMovies searchProxy, INetImportFactory net { _searchProxy = searchProxy; _netImportFactory = netImportFactory; - Get("/lists", x => GetLists()); - Get("/{action?recommendations}", x => Search(x.action)); + Get("/lists", x => GetLists()); + Get("/{action?recommendations}", x => Search(x.action)); } private object Search(string action) @@ -32,7 +32,8 @@ private object GetLists() { var lists = _netImportFactory.Discoverable(); - return lists.Select(definition => { + return lists.Select(definition => + { var resource = new NetImportResource(); resource.Id = definition.Definition.Id; diff --git a/src/NzbDrone.Api/Movies/MovieEditorModule.cs b/src/NzbDrone.Api/Movies/MovieEditorModule.cs index c8c50d0947..31c184a406 100644 --- a/src/NzbDrone.Api/Movies/MovieEditorModule.cs +++ b/src/NzbDrone.Api/Movies/MovieEditorModule.cs @@ -2,8 +2,8 @@ using System.Collections.Generic; using System.Linq; using Nancy; -using Radarr.Http.Extensions; using NzbDrone.Core.Movies; +using Radarr.Http.Extensions; namespace NzbDrone.Api.Movies { @@ -15,19 +15,19 @@ public MovieEditorModule(IMovieService movieService) : base("/movie/editor") { _movieService = movieService; - Put("/", Movie => SaveAll()); - Put("/delete", Movie => DeleteSelected()); + Put("/", movie => SaveAll()); + Put("/delete", movie => DeleteSelected()); } private object SaveAll() { var resources = Request.Body.FromJson>(); - var Movie = resources.Select(MovieResource => MovieResource.ToModel(_movieService.GetMovie(MovieResource.Id))).ToList(); + var movie = resources.Select(movieResource => movieResource.ToModel(_movieService.GetMovie(movieResource.Id))).ToList(); - return ResponseWithCode(_movieService.UpdateMovie(Movie) - .ToResource() - , HttpStatusCode.Accepted); + return ResponseWithCode(_movieService.UpdateMovie(movie) + .ToResource(), + HttpStatusCode.Accepted); } private object DeleteSelected() @@ -41,10 +41,12 @@ private object DeleteSelected() { deleteFiles = Convert.ToBoolean(deleteFilesQuery.Value); } + if (addExclusionQuery.HasValue) { addExclusion = Convert.ToBoolean(addExclusionQuery.Value); } + var ids = Request.Body.FromJson>(); foreach (var id in ids) diff --git a/src/NzbDrone.Api/Movies/MovieLookupModule.cs b/src/NzbDrone.Api/Movies/MovieLookupModule.cs index 9a45c24148..2ee8ea9650 100644 --- a/src/NzbDrone.Api/Movies/MovieLookupModule.cs +++ b/src/NzbDrone.Api/Movies/MovieLookupModule.cs @@ -1,9 +1,9 @@ +using System; using System.Collections.Generic; +using System.Linq; using Nancy; using NzbDrone.Core.MediaCover; using NzbDrone.Core.MetadataSource; -using System.Linq; -using System; using Radarr.Http; using Radarr.Http.REST; @@ -19,15 +19,15 @@ public MovieLookupModule(ISearchForNewMovie searchProxy, IProvideMovieInfo movie { _movieInfo = movieInfo; _searchProxy = searchProxy; - Get("/", x => Search()); - Get("/tmdb", x => SearchByTmdbId()); - Get("/imdb", x => SearchByImdbId()); + Get("/", x => Search()); + Get("/tmdb", x => SearchByTmdbId()); + Get("/imdb", x => SearchByImdbId()); } private object SearchByTmdbId() { int tmdbId = -1; - if(Int32.TryParse(Request.Query.tmdbId, out tmdbId)) + if (int.TryParse(Request.Query.tmdbId, out tmdbId)) { var result = _movieInfo.GetMovieInfo(tmdbId, null, true); return result.ToResource(); diff --git a/src/NzbDrone.Api/Movies/MovieModule.cs b/src/NzbDrone.Api/Movies/MovieModule.cs index 5d69f89449..e579f87cb1 100644 --- a/src/NzbDrone.Api/Movies/MovieModule.cs +++ b/src/NzbDrone.Api/Movies/MovieModule.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using FluentValidation; +using Nancy; using NzbDrone.Common.Extensions; using NzbDrone.Core.Datastore.Events; using NzbDrone.Core.MediaCover; @@ -9,10 +10,9 @@ using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Movies; using NzbDrone.Core.Movies.Events; -using NzbDrone.Core.Validation.Paths; using NzbDrone.Core.Validation; +using NzbDrone.Core.Validation.Paths; using NzbDrone.SignalR; -using Nancy; using Radarr.Http; namespace NzbDrone.Api.Movies @@ -25,24 +25,22 @@ public class MovieModule : RadarrRestModuleWithSignalR, IHandle, IHandle, IHandle - { + private const string TITLE_SLUG_ROUTE = "/titleslug/(?[^/]+)"; + protected readonly IMovieService _moviesService; private readonly IMapCoversToLocal _coverMapper; - private const string TITLE_SLUG_ROUTE = "/titleslug/(?[^/]+)"; - public MovieModule(IBroadcastSignalRMessage signalRBroadcaster, - IMovieService moviesService, - IMapCoversToLocal coverMapper, - RootFolderValidator rootFolderValidator, - MoviePathValidator moviesPathValidator, - MovieExistsValidator moviesExistsValidator, - MovieAncestorValidator moviesAncestorValidator, - SystemFolderValidator systemFolderValidator, - ProfileExistsValidator profileExistsValidator - ) - : base(signalRBroadcaster) + IMovieService moviesService, + IMapCoversToLocal coverMapper, + RootFolderValidator rootFolderValidator, + MoviePathValidator moviesPathValidator, + MovieExistsValidator moviesExistsValidator, + MovieAncestorValidator moviesAncestorValidator, + SystemFolderValidator systemFolderValidator, + ProfileExistsValidator profileExistsValidator) + : base(signalRBroadcaster) { _moviesService = moviesService; @@ -84,7 +82,10 @@ private MovieResource GetMovie(int id) protected MovieResource MapToResource(Movie movies) { - if (movies == null) return null; + if (movies == null) + { + return null; + } var resource = movies.ToResource(); MapCoversToLocal(resource); @@ -128,6 +129,7 @@ private void DeleteMovie(int id) { deleteFiles = Convert.ToBoolean(deleteFilesQuery.Value); } + if (addExclusionQuery.HasValue) { addExclusion = Convert.ToBoolean(addExclusionQuery.Value); @@ -151,7 +153,10 @@ public void Handle(MovieImportedEvent message) public void Handle(MovieFileDeletedEvent message) { - if (message.Reason == DeleteMediaFileReason.Upgrade) return; + if (message.Reason == DeleteMediaFileReason.Upgrade) + { + return; + } BroadcastResourceChange(ModelAction.Updated, message.MovieFile.MovieId); } diff --git a/src/NzbDrone.Api/Movies/MovieModuleWithSignalR.cs b/src/NzbDrone.Api/Movies/MovieModuleWithSignalR.cs index 4faa585b54..8205183066 100644 --- a/src/NzbDrone.Api/Movies/MovieModuleWithSignalR.cs +++ b/src/NzbDrone.Api/Movies/MovieModuleWithSignalR.cs @@ -65,7 +65,6 @@ public void Handle(MovieGrabbedEvent message) //add a grabbed field in MovieResource? //resource.Grabbed = true; - BroadcastResourceChange(ModelAction.Updated, resource); } diff --git a/src/NzbDrone.Api/Movies/MovieResource.cs b/src/NzbDrone.Api/Movies/MovieResource.cs index 3afb1d3028..7dc9f40b4e 100644 --- a/src/NzbDrone.Api/Movies/MovieResource.cs +++ b/src/NzbDrone.Api/Movies/MovieResource.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; +using NzbDrone.Api.MovieFiles; using NzbDrone.Core.MediaCover; using NzbDrone.Core.Movies; -using NzbDrone.Api.MovieFiles; +using Radarr.Http.REST; namespace NzbDrone.Api.Movies { @@ -64,6 +64,7 @@ public MovieResource() public DateTime Added { get; set; } public AddMovieOptions AddOptions { get; set; } public Ratings Ratings { get; set; } + //public List AlternativeTitles { get; set; } public MovieFileResource MovieFile { get; set; } @@ -90,15 +91,15 @@ public static class MovieResourceMapper { public static MovieResource ToResource(this Core.Movies.Movie model) { - if (model == null) return null; - + if (model == null) + { + return null; + } long size = model.MovieFile?.Size ?? 0; bool downloaded = model.MovieFile != null; MovieFileResource movieFile = model.MovieFile?.ToResource(); - - /*if(model.MovieFile != null) { model.MovieFile.LazyLoad(); @@ -112,12 +113,12 @@ public static MovieResource ToResource(this Core.Movies.Movie model) }*/ //model.AlternativeTitles.LazyLoad(); - return new MovieResource { Id = model.Id, TmdbId = model.TmdbId, Title = model.Title, + //AlternateTitles SortTitle = model.SortTitle, InCinemas = model.InCinemas, @@ -125,12 +126,14 @@ public static MovieResource ToResource(this Core.Movies.Movie model) PhysicalReleaseNote = model.PhysicalReleaseNote, HasFile = model.HasFile, Downloaded = downloaded, + //TotalEpisodeCount //EpisodeCount //EpisodeFileCount SizeOnDisk = size, Status = model.Status, Overview = model.Overview, + //NextAiring //PreviousAiring Images = model.Images, @@ -150,7 +153,6 @@ public static MovieResource ToResource(this Core.Movies.Movie model) FolderName = model.FolderName(), //SizeOnDisk = size, - Runtime = model.Runtime, LastInfoSync = model.LastInfoSync, CleanTitle = model.CleanTitle, @@ -173,7 +175,10 @@ public static MovieResource ToResource(this Core.Movies.Movie model) public static Core.Movies.Movie ToModel(this MovieResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new Core.Movies.Movie { @@ -181,16 +186,19 @@ public static Core.Movies.Movie ToModel(this MovieResource resource) TmdbId = resource.TmdbId, Title = resource.Title, + //AlternateTitles SortTitle = resource.SortTitle, InCinemas = resource.InCinemas, PhysicalRelease = resource.PhysicalRelease, PhysicalReleaseNote = resource.PhysicalReleaseNote, + //TotalEpisodeCount //EpisodeCount //EpisodeFileCount //SizeOnDisk Overview = resource.Overview, + //NextAiring //PreviousAiring Images = resource.Images, @@ -218,6 +226,7 @@ public static Core.Movies.Movie ToModel(this MovieResource resource) Tags = resource.Tags, Added = resource.Added, AddOptions = resource.AddOptions, + //AlternativeTitles = resource.AlternativeTitles, Ratings = resource.Ratings, YouTubeTrailerId = resource.YouTubeTrailerId, diff --git a/src/NzbDrone.Api/Movies/RenameMovieModule.cs b/src/NzbDrone.Api/Movies/RenameMovieModule.cs index d34f5b3a6e..44a158125c 100644 --- a/src/NzbDrone.Api/Movies/RenameMovieModule.cs +++ b/src/NzbDrone.Api/Movies/RenameMovieModule.cs @@ -1,7 +1,7 @@ -using Radarr.Http.REST; -using NzbDrone.Core.MediaFiles; using System.Collections.Generic; +using NzbDrone.Core.MediaFiles; using Radarr.Http; +using Radarr.Http.REST; namespace NzbDrone.Api.Movies { @@ -19,7 +19,7 @@ public RenameMovieModule(IRenameMovieFileService renameMovieFileService) private List GetMovies() { - if(!Request.Query.MovieId.HasValue) + if (!Request.Query.MovieId.HasValue) { throw new BadRequestException("movieId is missing"); } @@ -28,6 +28,5 @@ private List GetMovies() return _renameMovieFileService.GetRenamePreviews(movieId).ToResource(); } - } } diff --git a/src/NzbDrone.Api/Movies/RenameMovieResource.cs b/src/NzbDrone.Api/Movies/RenameMovieResource.cs index a95b58fa42..62feb1010c 100644 --- a/src/NzbDrone.Api/Movies/RenameMovieResource.cs +++ b/src/NzbDrone.Api/Movies/RenameMovieResource.cs @@ -1,6 +1,6 @@ -using Radarr.Http.REST; using System.Collections.Generic; using System.Linq; +using Radarr.Http.REST; namespace NzbDrone.Api.Movies { @@ -16,7 +16,10 @@ public static class RenameMovieResourceMapper { public static RenameMovieResource ToResource(this Core.MediaFiles.RenameMovieFilePreview model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new RenameMovieResource { diff --git a/src/NzbDrone.Api/NetImport/ImportExclusionsModule.cs b/src/NzbDrone.Api/NetImport/ImportExclusionsModule.cs index eca4696a22..7ecc04c065 100644 --- a/src/NzbDrone.Api/NetImport/ImportExclusionsModule.cs +++ b/src/NzbDrone.Api/NetImport/ImportExclusionsModule.cs @@ -9,7 +9,8 @@ public class ImportExclusionsModule : RadarrRestModule { private readonly IImportExclusionsService _exclusionService; - public ImportExclusionsModule(NetImportFactory netImportFactory, IImportExclusionsService exclusionService) : base("exclusions") + public ImportExclusionsModule(NetImportFactory netImportFactory, IImportExclusionsService exclusionService) + : base("exclusions") { _exclusionService = exclusionService; GetResourceAll = GetAll; @@ -35,7 +36,7 @@ public int AddExclusion(ImportExclusionsResource exclusionResource) return _exclusionService.AddExclusion(model).Id; } - public void RemoveExclusion (int id) + public void RemoveExclusion(int id) { _exclusionService.RemoveExclusion(new ImportExclusion { Id = id }); } diff --git a/src/NzbDrone.Api/NetImport/ImportExclusionsResource.cs b/src/NzbDrone.Api/NetImport/ImportExclusionsResource.cs index 0ced434f63..e2a3eff22d 100644 --- a/src/NzbDrone.Api/NetImport/ImportExclusionsResource.cs +++ b/src/NzbDrone.Api/NetImport/ImportExclusionsResource.cs @@ -15,7 +15,10 @@ public static class ImportExclusionsResourceMapper { public static ImportExclusionsResource ToResource(this Core.NetImport.ImportExclusions.ImportExclusion model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ImportExclusionsResource { diff --git a/src/NzbDrone.Api/NetImport/ListImportModule.cs b/src/NzbDrone.Api/NetImport/ListImportModule.cs index a8d2eca3c8..d2c7ea0d4d 100644 --- a/src/NzbDrone.Api/NetImport/ListImportModule.cs +++ b/src/NzbDrone.Api/NetImport/ListImportModule.cs @@ -2,10 +2,10 @@ using System.Linq; using Nancy; using Nancy.Extensions; -using Radarr.Http.Extensions; using NzbDrone.Api.Movies; using NzbDrone.Core.MetadataSource; using NzbDrone.Core.Movies; +using Radarr.Http.Extensions; namespace NzbDrone.Api.NetImport { @@ -19,16 +19,16 @@ public ListImportModule(IMovieService movieService, ISearchForNewMovie movieSear { _movieService = movieService; _movieSearch = movieSearch; - Put("/", Movie => SaveAll()); + Put("/", movie => SaveAll()); } private object SaveAll() { var resources = Request.Body.FromJson>(); - var Movies = resources.Select(MovieResource => _movieSearch.MapMovieToTmdbMovie(MovieResource.ToModel())).Where(m => m != null).DistinctBy(m => m.TmdbId).ToList(); + var movies = resources.Select(movieResource => _movieSearch.MapMovieToTmdbMovie(movieResource.ToModel())).Where(m => m != null).DistinctBy(m => m.TmdbId).ToList(); - return ResponseWithCode(_movieService.AddMovies(Movies).ToResource(), HttpStatusCode.Accepted); + return ResponseWithCode(_movieService.AddMovies(movies).ToResource(), HttpStatusCode.Accepted); } } } diff --git a/src/NzbDrone.Api/NetImport/NetImportModule.cs b/src/NzbDrone.Api/NetImport/NetImportModule.cs index 845ee48190..760a64ee9f 100644 --- a/src/NzbDrone.Api/NetImport/NetImportModule.cs +++ b/src/NzbDrone.Api/NetImport/NetImportModule.cs @@ -6,7 +6,8 @@ namespace NzbDrone.Api.NetImport { public class NetImportModule : ProviderModuleBase { - public NetImportModule(NetImportFactory netImportFactory) : base(netImportFactory, "netimport") + public NetImportModule(NetImportFactory netImportFactory) + : base(netImportFactory, "netimport") { PostValidator.RuleFor(c => c.RootFolderPath).IsValidPath(); PostValidator.RuleFor(c => c.MinimumAvailability).NotNull(); @@ -41,7 +42,11 @@ protected override void MapToModel(NetImportDefinition definition, NetImportReso protected override void Validate(NetImportDefinition definition, bool includeWarnings) { - if (!definition.Enable) return; + if (!definition.Enable) + { + return; + } + base.Validate(definition, includeWarnings); } } diff --git a/src/NzbDrone.Api/Notifications/NotificationModule.cs b/src/NzbDrone.Api/Notifications/NotificationModule.cs index 6403f02f46..d86855f1cc 100644 --- a/src/NzbDrone.Api/Notifications/NotificationModule.cs +++ b/src/NzbDrone.Api/Notifications/NotificationModule.cs @@ -41,7 +41,11 @@ protected override void MapToModel(NotificationDefinition definition, Notificati protected override void Validate(NotificationDefinition definition, bool includeWarnings) { - if (!definition.OnGrab && !definition.OnDownload) return; + if (!definition.OnGrab && !definition.OnDownload) + { + return; + } + base.Validate(definition, includeWarnings); } } diff --git a/src/NzbDrone.Api/Parse/ParseModule.cs b/src/NzbDrone.Api/Parse/ParseModule.cs index 6b96c9f75a..e08bb1c8f4 100644 --- a/src/NzbDrone.Api/Parse/ParseModule.cs +++ b/src/NzbDrone.Api/Parse/ParseModule.cs @@ -21,7 +21,6 @@ private ParseResource Parse() var title = Request.Query.Title.Value as string; var parsedMovieInfo = _parsingService.ParseMovieInfo(title, new List()); - if (parsedMovieInfo == null) { return null; diff --git a/src/NzbDrone.Api/Parse/ParseResource.cs b/src/NzbDrone.Api/Parse/ParseResource.cs index ec6e4854a5..451f9c95d6 100644 --- a/src/NzbDrone.Api/Parse/ParseResource.cs +++ b/src/NzbDrone.Api/Parse/ParseResource.cs @@ -1,6 +1,6 @@ using NzbDrone.Api.Movies; -using Radarr.Http.REST; using NzbDrone.Core.Parser.Model; +using Radarr.Http.REST; namespace NzbDrone.Api.Parse { diff --git a/src/NzbDrone.Api/Profiles/Delay/DelayProfileModule.cs b/src/NzbDrone.Api/Profiles/Delay/DelayProfileModule.cs index a478edd940..ba8baed77f 100644 --- a/src/NzbDrone.Api/Profiles/Delay/DelayProfileModule.cs +++ b/src/NzbDrone.Api/Profiles/Delay/DelayProfileModule.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; using FluentValidation; -using Radarr.Http.REST; -using Radarr.Http.Validation; using NzbDrone.Core.Profiles.Delay; using Radarr.Http; +using Radarr.Http.REST; +using Radarr.Http.Validation; namespace NzbDrone.Api.Profiles.Delay { diff --git a/src/NzbDrone.Api/Profiles/Delay/DelayProfileResource.cs b/src/NzbDrone.Api/Profiles/Delay/DelayProfileResource.cs index a626c220a2..802b793fb4 100644 --- a/src/NzbDrone.Api/Profiles/Delay/DelayProfileResource.cs +++ b/src/NzbDrone.Api/Profiles/Delay/DelayProfileResource.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.Indexers; using NzbDrone.Core.Profiles.Delay; +using Radarr.Http.REST; namespace NzbDrone.Api.Profiles.Delay { @@ -21,7 +21,10 @@ public static class DelayProfileResourceMapper { public static DelayProfileResource ToResource(this DelayProfile model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new DelayProfileResource { @@ -39,7 +42,10 @@ public static DelayProfileResource ToResource(this DelayProfile model) public static DelayProfile ToModel(this DelayProfileResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new DelayProfile { diff --git a/src/NzbDrone.Api/Profiles/Languages/LanguageModule.cs b/src/NzbDrone.Api/Profiles/Languages/LanguageModule.cs index 11f457280f..2c340454c2 100644 --- a/src/NzbDrone.Api/Profiles/Languages/LanguageModule.cs +++ b/src/NzbDrone.Api/Profiles/Languages/LanguageModule.cs @@ -27,12 +27,12 @@ private LanguageResource GetById(int id) private List GetAll() { - return ((Language[])Enum.GetValues(typeof (Language))) + return ((Language[])Enum.GetValues(typeof(Language))) .Select(l => new LanguageResource - { - Id = (int) l, - Name = l.ToString() - }) + { + Id = (int)l, + Name = l.ToString() + }) .OrderBy(l => l.Name) .ToList(); } diff --git a/src/NzbDrone.Api/Profiles/LegacyProfileModule.cs b/src/NzbDrone.Api/Profiles/LegacyProfileModule.cs index 0e704aa434..043ee46651 100644 --- a/src/NzbDrone.Api/Profiles/LegacyProfileModule.cs +++ b/src/NzbDrone.Api/Profiles/LegacyProfileModule.cs @@ -3,7 +3,7 @@ namespace NzbDrone.Api.Profiles { - class LegacyProfileModule : NzbDroneApiModule + public class LegacyProfileModule : NzbDroneApiModule { public LegacyProfileModule() : base("qualityprofile") diff --git a/src/NzbDrone.Api/Profiles/ProfileResource.cs b/src/NzbDrone.Api/Profiles/ProfileResource.cs index 2f4df4f392..c950083b53 100644 --- a/src/NzbDrone.Api/Profiles/ProfileResource.cs +++ b/src/NzbDrone.Api/Profiles/ProfileResource.cs @@ -1,11 +1,11 @@ using System.Collections.Generic; using System.Linq; -using NzbDrone.Common.Extensions; using NzbDrone.Api.Qualities; -using Radarr.Http.REST; +using NzbDrone.Common.Extensions; using NzbDrone.Core.Languages; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; +using Radarr.Http.REST; namespace NzbDrone.Api.Profiles { @@ -36,13 +36,22 @@ public static class ProfileResourceMapper { public static ProfileResource ToResource(this Profile model) { - if (model == null) return null; + if (model == null) + { + return null; + } var cutoffItem = model.Items.First(q => { - if (q.Id == model.Cutoff) return true; + if (q.Id == model.Cutoff) + { + return true; + } - if (q.Quality == null) return false; + if (q.Quality == null) + { + return false; + } return q.Quality.Id == model.Cutoff; }); @@ -53,9 +62,15 @@ public static ProfileResource ToResource(this Profile model) var formatCutoffItem = model.FormatItems.First(q => { - if (q.Id == model.FormatCutoff) return true; + if (q.Id == model.FormatCutoff) + { + return true; + } - if (q.Format == null) return false; + if (q.Format == null) + { + return false; + } return q.Format.Id == model.FormatCutoff; }); @@ -93,7 +108,10 @@ public static ProfileResource ToResource(this Profile model) public static ProfileQualityItemResource ToResource(this ProfileQualityItem model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ProfileQualityItemResource { @@ -113,7 +131,10 @@ public static ProfileFormatItemResource ToResource(this ProfileFormatItem model) public static Profile ToModel(this ProfileResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new Profile { @@ -131,7 +152,10 @@ public static Profile ToModel(this ProfileResource resource) public static ProfileQualityItem ToModel(this ProfileQualityItemResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new ProfileQualityItem { diff --git a/src/NzbDrone.Api/Profiles/ProfileSchemaModule.cs b/src/NzbDrone.Api/Profiles/ProfileSchemaModule.cs index a1babd804e..25f8634276 100644 --- a/src/NzbDrone.Api/Profiles/ProfileSchemaModule.cs +++ b/src/NzbDrone.Api/Profiles/ProfileSchemaModule.cs @@ -31,7 +31,8 @@ private List GetAll() var formatItems = _formatService.All().Select(v => new ProfileFormatItem { - Format = v, Allowed = true + Format = v, + Allowed = true }).ToList(); formatItems.Insert(0, new ProfileFormatItem diff --git a/src/NzbDrone.Api/Profiles/ProfileValidation.cs b/src/NzbDrone.Api/Profiles/ProfileValidation.cs index 003c96f39b..d70d716ba0 100644 --- a/src/NzbDrone.Api/Profiles/ProfileValidation.cs +++ b/src/NzbDrone.Api/Profiles/ProfileValidation.cs @@ -20,7 +20,6 @@ public class AllowedValidator : PropertyValidator public AllowedValidator() : base("Must contain at least one allowed quality") { - } protected override bool IsValid(PropertyValidatorContext context) diff --git a/src/NzbDrone.Api/ProviderModuleBase.cs b/src/NzbDrone.Api/ProviderModuleBase.cs index 96cc568ca8..b842d832ef 100644 --- a/src/NzbDrone.Api/ProviderModuleBase.cs +++ b/src/NzbDrone.Api/ProviderModuleBase.cs @@ -3,10 +3,10 @@ using FluentValidation; using FluentValidation.Results; using Nancy; +using Newtonsoft.Json; using NzbDrone.Common.Reflection; using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Validation; -using Newtonsoft.Json; using Radarr.Http; using Radarr.Http.ClientSchema; @@ -24,9 +24,9 @@ protected ProviderModuleBase(IProviderFactory pr { _providerFactory = providerFactory; - Get("schema", x => GetTemplates()); - Post("test", x => Test(ReadResourceFromRequest(true))); - Post("action/{action}", x => RequestAction(x.action, ReadResourceFromRequest(true))); + Get("schema", x => GetTemplates()); + Post("test", x => Test(ReadResourceFromRequest(true))); + Post("action/{action}", x => RequestAction(x.action, ReadResourceFromRequest(true))); GetResourceAll = GetAll; GetResourceById = GetProviderById; @@ -35,7 +35,7 @@ protected ProviderModuleBase(IProviderFactory pr DeleteResource = DeleteProvider; SharedValidator.RuleFor(c => c.Name).NotEmpty(); - SharedValidator.RuleFor(c => c.Name).Must((v,c) => !_providerFactory.All().Any(p => p.Name == c && p.Id != v.Id)).WithMessage("Should be unique"); + SharedValidator.RuleFor(c => c.Name).Must((v, c) => !_providerFactory.All().Any(p => p.Name == c && p.Id != v.Id)).WithMessage("Should be unique"); SharedValidator.RuleFor(c => c.Implementation).NotEmpty(); SharedValidator.RuleFor(c => c.ConfigContract).NotEmpty(); @@ -181,7 +181,6 @@ private object Test(TProviderResource providerResource) return "{}"; } - private object RequestAction(string action, TProviderResource providerResource) { var providerDefinition = GetDefinition(providerResource, true, false); diff --git a/src/NzbDrone.Api/ProviderResource.cs b/src/NzbDrone.Api/ProviderResource.cs index cfa016b55d..9107097064 100644 --- a/src/NzbDrone.Api/ProviderResource.cs +++ b/src/NzbDrone.Api/ProviderResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; +using NzbDrone.Core.ThingiProvider; using Radarr.Http.ClientSchema; using Radarr.Http.REST; -using NzbDrone.Core.ThingiProvider; namespace NzbDrone.Api { diff --git a/src/NzbDrone.Api/Qualities/CustomFormatModule.cs b/src/NzbDrone.Api/Qualities/CustomFormatModule.cs index 6791f9077f..c14bfa4a20 100644 --- a/src/NzbDrone.Api/Qualities/CustomFormatModule.cs +++ b/src/NzbDrone.Api/Qualities/CustomFormatModule.cs @@ -31,7 +31,7 @@ public CustomFormatModule(ICustomFormatService formatService, IParsingService pa var allNewTags = c.Select(t => t.ToLower()); var enumerable = allTags.ToList(); var newTags = allNewTags.ToList(); - return (enumerable.All(newTags.Contains) && f.Id != v.Id && enumerable.Count() == newTags.Count()); + return enumerable.All(newTags.Contains) && f.Id != v.Id && enumerable.Count() == newTags.Count(); }); }) .WithMessage("Should be unique."); @@ -46,11 +46,11 @@ public CustomFormatModule(ICustomFormatService formatService, IParsingService pa DeleteResource = DeleteFormat; - Get("/test", x => Test()); + Get("/test", x => Test()); - Post("/test", x => TestWithNewModel()); + Post("/test", x => TestWithNewModel()); - Get("schema", x => GetTemplates()); + Get("schema", x => GetTemplates()); } private int Create(CustomFormatResource customFormatResource) @@ -95,11 +95,12 @@ private object GetTemplates() private CustomFormatTestResource Test() { - var parsed = _parsingService.ParseMovieInfo((string) Request.Query.title, new List()); + var parsed = _parsingService.ParseMovieInfo((string)Request.Query.title, new List()); if (parsed == null) { return null; } + return new CustomFormatTestResource { Matches = _parsingService.MatchFormatTags(parsed).ToResource(), @@ -109,18 +110,19 @@ private CustomFormatTestResource Test() private CustomFormatTestResource TestWithNewModel() { - var queryTitle = (string) Request.Query.title; + var queryTitle = (string)Request.Query.title; var resource = ReadResourceFromRequest(); var model = resource.ToModel(); model.Name = model.Name += " (New)"; - var parsed = _parsingService.ParseMovieInfo(queryTitle, new List{model}); + var parsed = _parsingService.ParseMovieInfo(queryTitle, new List { model }); if (parsed == null) { return null; } + return new CustomFormatTestResource { Matches = _parsingService.MatchFormatTags(parsed).ToResource(), diff --git a/src/NzbDrone.Api/Qualities/CustomFormatResource.cs b/src/NzbDrone.Api/Qualities/CustomFormatResource.cs index 1d0511d471..b4c658723d 100644 --- a/src/NzbDrone.Api/Qualities/CustomFormatResource.cs +++ b/src/NzbDrone.Api/Qualities/CustomFormatResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.CustomFormats; +using Radarr.Http.REST; namespace NzbDrone.Api.Qualities { diff --git a/src/NzbDrone.Api/Qualities/FormatTagMatchResultResource.cs b/src/NzbDrone.Api/Qualities/FormatTagMatchResultResource.cs index b6f5d671a7..c8209c2b37 100644 --- a/src/NzbDrone.Api/Qualities/FormatTagMatchResultResource.cs +++ b/src/NzbDrone.Api/Qualities/FormatTagMatchResultResource.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Common.Extensions; using NzbDrone.Core.CustomFormats; +using Radarr.Http.REST; namespace NzbDrone.Api.Qualities { @@ -29,7 +29,10 @@ public static class QualityTagMatchResultResourceMapper { public static FormatTagMatchResultResource ToResource(this FormatTagMatchResult model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new FormatTagMatchResultResource { diff --git a/src/NzbDrone.Api/Qualities/FormatTagValidator.cs b/src/NzbDrone.Api/Qualities/FormatTagValidator.cs index 53efbea21b..7f1eee36a0 100644 --- a/src/NzbDrone.Api/Qualities/FormatTagValidator.cs +++ b/src/NzbDrone.Api/Qualities/FormatTagValidator.cs @@ -7,7 +7,8 @@ namespace NzbDrone.Api.Qualities { public class FormatTagValidator : PropertyValidator { - public FormatTagValidator() : base("{ValidationMessage}") + public FormatTagValidator() + : base("{ValidationMessage}") { } @@ -19,11 +20,14 @@ protected override bool IsValid(PropertyValidatorContext context) return false; } - var tags = (IEnumerable) context.PropertyValue; + var tags = (IEnumerable)context.PropertyValue; var invalidTags = tags.Where(t => !FormatTag.QualityTagRegex.IsMatch(t)); - if (invalidTags.Count() == 0) return true; + if (invalidTags.Count() == 0) + { + return true; + } var formatMessage = $"Format Tags ({string.Join(", ", invalidTags)}) are in an invalid format! Check the Wiki to learn how they should look."; diff --git a/src/NzbDrone.Api/Qualities/QualityDefinitionModule.cs b/src/NzbDrone.Api/Qualities/QualityDefinitionModule.cs index 9a402f895f..67af695a64 100644 --- a/src/NzbDrone.Api/Qualities/QualityDefinitionModule.cs +++ b/src/NzbDrone.Api/Qualities/QualityDefinitionModule.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; -using Radarr.Http.REST; using NzbDrone.Core.Parser; using NzbDrone.Core.Qualities; using Radarr.Http; +using Radarr.Http.REST; namespace NzbDrone.Api.Qualities { diff --git a/src/NzbDrone.Api/Qualities/QualityDefinitionResource.cs b/src/NzbDrone.Api/Qualities/QualityDefinitionResource.cs index a795e7697c..6365ec58a0 100644 --- a/src/NzbDrone.Api/Qualities/QualityDefinitionResource.cs +++ b/src/NzbDrone.Api/Qualities/QualityDefinitionResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.Qualities; +using Radarr.Http.REST; namespace NzbDrone.Api.Qualities { @@ -21,7 +21,10 @@ public static class QualityDefinitionResourceMapper { public static QualityDefinitionResource ToResource(this QualityDefinition model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new QualityDefinitionResource { @@ -40,7 +43,10 @@ public static QualityDefinitionResource ToResource(this QualityDefinition model) public static QualityDefinition ToModel(this QualityDefinitionResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new QualityDefinition { diff --git a/src/NzbDrone.Api/Queue/QueueActionModule.cs b/src/NzbDrone.Api/Queue/QueueActionModule.cs index ed306dc6bd..287e5eeca1 100644 --- a/src/NzbDrone.Api/Queue/QueueActionModule.cs +++ b/src/NzbDrone.Api/Queue/QueueActionModule.cs @@ -1,12 +1,12 @@ using System; using Nancy; -using Radarr.Http.Extensions; -using Radarr.Http.REST; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Pending; using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.Queue; using Radarr.Http; +using Radarr.Http.Extensions; +using Radarr.Http.REST; namespace NzbDrone.Api.Queue { @@ -36,9 +36,9 @@ public QueueActionModule(IQueueService queueService, _pendingReleaseService = pendingReleaseService; _downloadService = downloadService; - Delete(@"/(?[\d]{1,10})", x => Remove((int)x.Id)); - Post("/import", x => Import()); - Post("/grab", x => Grab()); + Delete(@"/(?[\d]{1,10})", x => Remove((int)x.Id)); + Post("/import", x => Import()); + Post("/grab", x => Grab()); } private object Remove(int id) diff --git a/src/NzbDrone.Api/Queue/QueueResource.cs b/src/NzbDrone.Api/Queue/QueueResource.cs index eafe50794e..99640a5403 100644 --- a/src/NzbDrone.Api/Queue/QueueResource.cs +++ b/src/NzbDrone.Api/Queue/QueueResource.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; -using Radarr.Http.REST; -using NzbDrone.Core.Qualities; +using System.Linq; using NzbDrone.Api.Movies; using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.Indexers; -using System.Linq; +using NzbDrone.Core.Qualities; +using Radarr.Http.REST; namespace NzbDrone.Api.Queue { @@ -29,7 +29,10 @@ public static class QueueResourceMapper { public static QueueResource ToResource(this Core.Queue.Queue model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new QueueResource { diff --git a/src/NzbDrone.Api/RemotePathMappings/RemotePathMappingResource.cs b/src/NzbDrone.Api/RemotePathMappings/RemotePathMappingResource.cs index c52774bae7..f6a2172d33 100644 --- a/src/NzbDrone.Api/RemotePathMappings/RemotePathMappingResource.cs +++ b/src/NzbDrone.Api/RemotePathMappings/RemotePathMappingResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.RemotePathMappings; +using Radarr.Http.REST; namespace NzbDrone.Api.RemotePathMappings { @@ -16,7 +16,10 @@ public static class RemotePathMappingResourceMapper { public static RemotePathMappingResource ToResource(this RemotePathMapping model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new RemotePathMappingResource { @@ -30,7 +33,10 @@ public static RemotePathMappingResource ToResource(this RemotePathMapping model) public static RemotePathMapping ToModel(this RemotePathMappingResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new RemotePathMapping { diff --git a/src/NzbDrone.Api/Restrictions/RestrictionModule.cs b/src/NzbDrone.Api/Restrictions/RestrictionModule.cs index 92759332d3..b3ce2dd2c3 100644 --- a/src/NzbDrone.Api/Restrictions/RestrictionModule.cs +++ b/src/NzbDrone.Api/Restrictions/RestrictionModule.cs @@ -9,7 +9,6 @@ public class RestrictionModule : RadarrRestModule { private readonly IRestrictionService _restrictionService; - public RestrictionModule(IRestrictionService restrictionService) { _restrictionService = restrictionService; diff --git a/src/NzbDrone.Api/Restrictions/RestrictionResource.cs b/src/NzbDrone.Api/Restrictions/RestrictionResource.cs index a2d9d94248..2060c4cb2a 100644 --- a/src/NzbDrone.Api/Restrictions/RestrictionResource.cs +++ b/src/NzbDrone.Api/Restrictions/RestrictionResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.Restrictions; +using Radarr.Http.REST; namespace Radarr.Http.RESTrictions { @@ -22,7 +22,10 @@ public static class RestrictionResourceMapper { public static RestrictionResource ToResource(this Restriction model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new RestrictionResource { @@ -37,7 +40,10 @@ public static RestrictionResource ToResource(this Restriction model) public static Restriction ToModel(this RestrictionResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new Restriction { diff --git a/src/NzbDrone.Api/RootFolders/RootFolderModule.cs b/src/NzbDrone.Api/RootFolders/RootFolderModule.cs index 2f87df9b31..0239c4d652 100644 --- a/src/NzbDrone.Api/RootFolders/RootFolderModule.cs +++ b/src/NzbDrone.Api/RootFolders/RootFolderModule.cs @@ -18,9 +18,8 @@ public RootFolderModule(IRootFolderService rootFolderService, MappedNetworkDriveValidator mappedNetworkDriveValidator, StartupFolderValidator startupFolderValidator, SystemFolderValidator systemFolderValidator, - FolderWritableValidator folderWritableValidator - ) - : base(signalRBroadcaster) + FolderWritableValidator folderWritableValidator) + : base(signalRBroadcaster) { _rootFolderService = rootFolderService; diff --git a/src/NzbDrone.Api/RootFolders/RootFolderResource.cs b/src/NzbDrone.Api/RootFolders/RootFolderResource.cs index 4c19a23fab..0f4dc80b33 100644 --- a/src/NzbDrone.Api/RootFolders/RootFolderResource.cs +++ b/src/NzbDrone.Api/RootFolders/RootFolderResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.RootFolders; +using Radarr.Http.REST; namespace NzbDrone.Api.RootFolders { @@ -18,7 +18,10 @@ public static class RootFolderResourceMapper { public static RootFolderResource ToResource(this RootFolder model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new RootFolderResource { @@ -33,7 +36,10 @@ public static RootFolderResource ToResource(this RootFolder model) public static RootFolder ToModel(this RootFolderResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new RootFolder { diff --git a/src/NzbDrone.Api/System/Backup/BackupModule.cs b/src/NzbDrone.Api/System/Backup/BackupModule.cs index 7fb99402e0..c92e12d2ae 100644 --- a/src/NzbDrone.Api/System/Backup/BackupModule.cs +++ b/src/NzbDrone.Api/System/Backup/BackupModule.cs @@ -9,7 +9,8 @@ public class BackupModule : RadarrRestModule { private readonly IBackupService _backupService; - public BackupModule(IBackupService backupService) : base("system/backup") + public BackupModule(IBackupService backupService) + : base("system/backup") { _backupService = backupService; GetResourceAll = GetBackupFiles; @@ -20,13 +21,13 @@ public List GetBackupFiles() var backups = _backupService.GetBackups(); return backups.Select(b => new BackupResource - { - Id = b.Name.GetHashCode(), - Name = b.Name, - Path = $"/backup/{b.Type.ToString().ToLower()}/{b.Name}", - Type = b.Type, - Time = b.Time - }).ToList(); + { + Id = b.Name.GetHashCode(), + Name = b.Name, + Path = $"/backup/{b.Type.ToString().ToLower()}/{b.Name}", + Type = b.Type, + Time = b.Time + }).ToList(); } } } diff --git a/src/NzbDrone.Api/System/Backup/BackupResource.cs b/src/NzbDrone.Api/System/Backup/BackupResource.cs index f94ca56e8b..08f84a6462 100644 --- a/src/NzbDrone.Api/System/Backup/BackupResource.cs +++ b/src/NzbDrone.Api/System/Backup/BackupResource.cs @@ -1,6 +1,6 @@ using System; -using Radarr.Http.REST; using NzbDrone.Core.Backup; +using Radarr.Http.REST; namespace NzbDrone.Api.System.Backup { diff --git a/src/NzbDrone.Api/System/SystemModule.cs b/src/NzbDrone.Api/System/SystemModule.cs index 03678cb5a2..137e7aecc4 100644 --- a/src/NzbDrone.Api/System/SystemModule.cs +++ b/src/NzbDrone.Api/System/SystemModule.cs @@ -25,7 +25,8 @@ public SystemModule(IAppFolderInfo appFolderInfo, IRouteCacheProvider routeCacheProvider, IConfigFileProvider configFileProvider, IMainDatabase database, - ILifecycleService lifecycleService) : base("system") + ILifecycleService lifecycleService) + : base("system") { _appFolderInfo = appFolderInfo; _runtimeInfo = runtimeInfo; @@ -35,10 +36,10 @@ public SystemModule(IAppFolderInfo appFolderInfo, _configFileProvider = configFileProvider; _database = database; _lifecycleService = lifecycleService; - Get("/status", x => GetStatus()); - Get("/routes", x => GetRoutes()); - Post("/shutdown", x => Shutdown()); - Post("/restart", x => Restart()); + Get("/status", x => GetStatus()); + Get("/routes", x => GetRoutes()); + Post("/shutdown", x => Shutdown()); + Post("/restart", x => Restart()); } private object GetStatus() diff --git a/src/NzbDrone.Api/System/Tasks/TaskModule.cs b/src/NzbDrone.Api/System/Tasks/TaskModule.cs index 4b9667e898..af966e242e 100644 --- a/src/NzbDrone.Api/System/Tasks/TaskModule.cs +++ b/src/NzbDrone.Api/System/Tasks/TaskModule.cs @@ -32,14 +32,14 @@ private static TaskResource ConvertToResource(ScheduledTask scheduledTask) var taskName = scheduledTask.TypeName.Split('.').Last().Replace("Command", ""); return new TaskResource - { - Id = scheduledTask.Id, - Name = NameRegex.Replace(taskName, match => " " + match.Value), - TaskName = taskName, - Interval = scheduledTask.Interval, - LastExecution = scheduledTask.LastExecution, - NextExecution = scheduledTask.LastExecution.AddMinutes(scheduledTask.Interval) - }; + { + Id = scheduledTask.Id, + Name = NameRegex.Replace(taskName, match => " " + match.Value), + TaskName = taskName, + Interval = scheduledTask.Interval, + LastExecution = scheduledTask.LastExecution, + NextExecution = scheduledTask.LastExecution.AddMinutes(scheduledTask.Interval) + }; } public void Handle(CommandExecutedEvent message) diff --git a/src/NzbDrone.Api/Tags/TagResource.cs b/src/NzbDrone.Api/Tags/TagResource.cs index c22b0e38a2..bcc2c58d29 100644 --- a/src/NzbDrone.Api/Tags/TagResource.cs +++ b/src/NzbDrone.Api/Tags/TagResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.Tags; +using Radarr.Http.REST; namespace NzbDrone.Api.Tags { @@ -14,7 +14,10 @@ public static class TagResourceMapper { public static TagResource ToResource(this Tag model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new TagResource { @@ -26,7 +29,10 @@ public static TagResource ToResource(this Tag model) public static Tag ToModel(this TagResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new Tag { diff --git a/src/NzbDrone.Api/Update/UpdateResource.cs b/src/NzbDrone.Api/Update/UpdateResource.cs index f07dd1853f..dc7f606414 100644 --- a/src/NzbDrone.Api/Update/UpdateResource.cs +++ b/src/NzbDrone.Api/Update/UpdateResource.cs @@ -2,8 +2,8 @@ using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; -using Radarr.Http.REST; using NzbDrone.Core.Update; +using Radarr.Http.REST; namespace NzbDrone.Api.Update { @@ -27,7 +27,10 @@ public static class UpdateResourceMapper { public static UpdateResource ToResource(this UpdatePackage model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new UpdateResource { @@ -37,6 +40,7 @@ public static UpdateResource ToResource(this UpdatePackage model) ReleaseDate = model.ReleaseDate, FileName = model.FileName, Url = model.Url, + //Installed //Installable //Latest diff --git a/src/NzbDrone.Api/Wanted/LegacyMissingModule.cs b/src/NzbDrone.Api/Wanted/LegacyMissingModule.cs index 002ecf1796..51b7ba6242 100644 --- a/src/NzbDrone.Api/Wanted/LegacyMissingModule.cs +++ b/src/NzbDrone.Api/Wanted/LegacyMissingModule.cs @@ -3,9 +3,10 @@ namespace NzbDrone.Api.Wanted { - class LegacyMissingModule : NzbDroneApiModule + public class LegacyMissingModule : NzbDroneApiModule { - public LegacyMissingModule() : base("missing") + public LegacyMissingModule() + : base("missing") { Get("/", x => { diff --git a/src/NzbDrone.Api/Wanted/MovieCutoffModule.cs b/src/NzbDrone.Api/Wanted/MovieCutoffModule.cs index d734fb6450..c96b12f1a6 100644 --- a/src/NzbDrone.Api/Wanted/MovieCutoffModule.cs +++ b/src/NzbDrone.Api/Wanted/MovieCutoffModule.cs @@ -1,10 +1,10 @@ using System.Linq; using NzbDrone.Api.Movies; -using NzbDrone.Core.Movies; using NzbDrone.Core.Datastore; +using NzbDrone.Core.DecisionEngine.Specifications; +using NzbDrone.Core.Movies; using NzbDrone.SignalR; using Radarr.Http; -using NzbDrone.Core.DecisionEngine.Specifications; namespace NzbDrone.Api.Wanted { diff --git a/src/NzbDrone.Api/Wanted/MovieMissingModule.cs b/src/NzbDrone.Api/Wanted/MovieMissingModule.cs index 676b69da6a..3fe30f1acb 100644 --- a/src/NzbDrone.Api/Wanted/MovieMissingModule.cs +++ b/src/NzbDrone.Api/Wanted/MovieMissingModule.cs @@ -1,14 +1,14 @@ using System.Linq; using NzbDrone.Api.Movies; +using NzbDrone.Core.Datastore; using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Movies; -using NzbDrone.Core.Datastore; using NzbDrone.SignalR; using Radarr.Http; namespace NzbDrone.Api.Wanted { - class MovieMissingModule : MovieModuleWithSignalR + public class MovieMissingModule : MovieModuleWithSignalR { public MovieMissingModule(IMovieService movieService, IUpgradableSpecification qualityUpgradableSpecification, diff --git a/src/NzbDrone.Automation.Test/AutomationTest.cs b/src/NzbDrone.Automation.Test/AutomationTest.cs index f589889350..721d5eb828 100644 --- a/src/NzbDrone.Automation.Test/AutomationTest.cs +++ b/src/NzbDrone.Automation.Test/AutomationTest.cs @@ -37,8 +37,9 @@ public void SmokeTestSetup() var options = new FirefoxOptions(); options.AddArguments("--headless"); FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(); + // service.Host = "::1"; // Workaround netcore/selenium bug https://github.com/SeleniumHQ/selenium/issues/7840 - driver = new FirefoxDriver(service, options, new System.TimeSpan(0,3,0)); + driver = new FirefoxDriver(service, options, new System.TimeSpan(0, 3, 0)); _runner = new NzbDroneRunner(LogManager.GetCurrentClassLogger()); _runner.KillAll(); diff --git a/src/NzbDrone.Automation.Test/AutomationTestAttribute.cs b/src/NzbDrone.Automation.Test/AutomationTestAttribute.cs index 041c0bddd6..2ed2fac7e8 100644 --- a/src/NzbDrone.Automation.Test/AutomationTestAttribute.cs +++ b/src/NzbDrone.Automation.Test/AutomationTestAttribute.cs @@ -7,7 +7,6 @@ public class AutomationTestAttribute : CategoryAttribute public AutomationTestAttribute() : base("AutomationTest") { - } } } diff --git a/src/NzbDrone.Automation.Test/MainPagesTest.cs b/src/NzbDrone.Automation.Test/MainPagesTest.cs index c3a48415c3..acf8c2b050 100644 --- a/src/NzbDrone.Automation.Test/MainPagesTest.cs +++ b/src/NzbDrone.Automation.Test/MainPagesTest.cs @@ -8,62 +8,62 @@ namespace NzbDrone.Automation.Test [TestFixture] public class MainPagesTest : AutomationTest { - private PageBase page; + private PageBase _page; [SetUp] public void Setup() { - page = new PageBase(driver); + _page = new PageBase(driver); } [Test] public void movie_page() { - page.MovieNavIcon.Click(); - page.WaitForNoSpinner(); - page.Find(By.CssSelector("div[class*='MovieIndex']")).Should().NotBeNull(); + _page.MovieNavIcon.Click(); + _page.WaitForNoSpinner(); + _page.Find(By.CssSelector("div[class*='MovieIndex']")).Should().NotBeNull(); } [Test] public void calendar_page() { - page.CalendarNavIcon.Click(); - page.WaitForNoSpinner(); + _page.CalendarNavIcon.Click(); + _page.WaitForNoSpinner(); - page.Find(By.CssSelector("div[class*='CalendarPage']")).Should().NotBeNull(); + _page.Find(By.CssSelector("div[class*='CalendarPage']")).Should().NotBeNull(); } [Test] public void activity_page() { - page.ActivityNavIcon.Click(); - page.WaitForNoSpinner(); + _page.ActivityNavIcon.Click(); + _page.WaitForNoSpinner(); - page.Find(By.LinkText("Queue")).Should().NotBeNull(); - page.Find(By.LinkText("History")).Should().NotBeNull(); - page.Find(By.LinkText("Blacklist")).Should().NotBeNull(); + _page.Find(By.LinkText("Queue")).Should().NotBeNull(); + _page.Find(By.LinkText("History")).Should().NotBeNull(); + _page.Find(By.LinkText("Blacklist")).Should().NotBeNull(); } [Test] public void system_page() { - page.SystemNavIcon.Click(); - page.WaitForNoSpinner(); + _page.SystemNavIcon.Click(); + _page.WaitForNoSpinner(); - page.Find(By.CssSelector("div[class*='Health']")).Should().NotBeNull(); + _page.Find(By.CssSelector("div[class*='Health']")).Should().NotBeNull(); } [Test] public void add_movie_page() { - page.MovieNavIcon.Click(); - page.WaitForNoSpinner(); + _page.MovieNavIcon.Click(); + _page.WaitForNoSpinner(); - page.Find(By.LinkText("Add New")).Click(); + _page.Find(By.LinkText("Add New")).Click(); - page.WaitForNoSpinner(); + _page.WaitForNoSpinner(); - page.Find(By.CssSelector("input[class*='AddNewMovie-searchInput']")).Should().NotBeNull(); + _page.Find(By.CssSelector("input[class*='AddNewMovie-searchInput']")).Should().NotBeNull(); } } } diff --git a/src/NzbDrone.Common.Test/CacheTests/CachedFixture.cs b/src/NzbDrone.Common.Test/CacheTests/CachedFixture.cs index 082dd0f988..7c892047de 100644 --- a/src/NzbDrone.Common.Test/CacheTests/CachedFixture.cs +++ b/src/NzbDrone.Common.Test/CacheTests/CachedFixture.cs @@ -26,7 +26,6 @@ public void should_call_function_once() _cachedString.Get("Test", _worker.GetString); _worker.HitCount.Should().Be(1); - } [Test] @@ -38,7 +37,6 @@ public void multiple_calls_should_return_same_result() first.Should().Be(second); } - [Test] public void should_be_able_to_update_key() { @@ -48,7 +46,6 @@ public void should_be_able_to_update_key() _cachedString.Find("Key").Should().Be("New"); } - [Test] public void should_be_able_to_remove_key() { @@ -70,7 +67,6 @@ public void should_store_null() { int hitCount = 0; - for (int i = 0; i < 10; i++) { _cachedString.Get("key", () => @@ -92,11 +88,13 @@ public void should_honor_ttl() for (int i = 0; i < 10; i++) { - _cachedString.Get("key", () => - { - hitCount++; - return null; - }, TimeSpan.FromMilliseconds(300)); + _cachedString.Get("key", + () => + { + hitCount++; + return null; + }, + TimeSpan.FromMilliseconds(300)); Thread.Sleep(100); } diff --git a/src/NzbDrone.Common.Test/ConfigFileProviderTest.cs b/src/NzbDrone.Common.Test/ConfigFileProviderTest.cs index 4472c747db..82c2f854e4 100644 --- a/src/NzbDrone.Common.Test/ConfigFileProviderTest.cs +++ b/src/NzbDrone.Common.Test/ConfigFileProviderTest.cs @@ -62,10 +62,8 @@ public void GetInt_Success() const string key = "Port"; const int value = 7878; - var result = Subject.GetValueInt(key, value); - result.Should().Be(value); } @@ -75,20 +73,16 @@ public void GetBool_Success() const string key = "LaunchBrowser"; const bool value = true; - var result = Subject.GetValueBoolean(key, value); - result.Should().BeTrue(); } [Test] public void GetLaunchBrowser_Success() { - var result = Subject.LaunchBrowser; - result.Should().Be(true); } @@ -97,10 +91,8 @@ public void GetPort_Success() { const int value = 7878; - var result = Subject.Port; - result.Should().Be(value); } @@ -110,10 +102,8 @@ public void SetValue_bool() const string key = "LaunchBrowser"; const bool value = false; - Subject.SetValue(key, value); - var result = Subject.LaunchBrowser; result.Should().Be(value); } @@ -124,10 +114,8 @@ public void SetValue_int() const string key = "Port"; const int value = 12345; - Subject.SetValue(key, value); - var result = Subject.Port; result.Should().Be(value); } @@ -138,10 +126,8 @@ public void GetValue_New_Key() const string key = "Hello"; const string value = "World"; - var result = Subject.GetValue(key, value); - result.Should().Be(value); } @@ -178,7 +164,6 @@ public void SaveDictionary_should_only_save_specified_values() dic["SslPort"] = origSslPort; Subject.SaveConfigDictionary(dic); - dic = new Dictionary(); dic["SslPort"] = sslPort; Subject.SaveConfigDictionary(dic); diff --git a/src/NzbDrone.Common.Test/DiskTests/DiskProviderFixtureBase.cs b/src/NzbDrone.Common.Test/DiskTests/DiskProviderFixtureBase.cs index bdca59161f..73df8d8471 100644 --- a/src/NzbDrone.Common.Test/DiskTests/DiskProviderFixtureBase.cs +++ b/src/NzbDrone.Common.Test/DiskTests/DiskProviderFixtureBase.cs @@ -7,7 +7,8 @@ namespace NzbDrone.Common.Test.DiskTests { - public abstract class DiskProviderFixtureBase : TestBase where TSubject : class, IDiskProvider + public abstract class DiskProviderFixtureBase : TestBase + where TSubject : class, IDiskProvider { [Test] [Retry(5)] @@ -171,7 +172,7 @@ public void folder_should_return_correct_value_for_last_write() public void should_return_false_for_unlocked_file() { var testFile = GetTempFilePath(); - Subject.WriteAllText(testFile, new Guid().ToString()); + Subject.WriteAllText(testFile, default(Guid).ToString()); Subject.IsFileLocked(testFile).Should().BeFalse(); } @@ -180,7 +181,7 @@ public void should_return_false_for_unlocked_file() public void should_return_false_for_unlocked_and_readonly_file() { var testFile = GetTempFilePath(); - Subject.WriteAllText(testFile, new Guid().ToString()); + Subject.WriteAllText(testFile, default(Guid).ToString()); File.SetAttributes(testFile, FileAttributes.ReadOnly); @@ -191,7 +192,7 @@ public void should_return_false_for_unlocked_and_readonly_file() public void should_return_true_for_unlocked_file() { var testFile = GetTempFilePath(); - Subject.WriteAllText(testFile, new Guid().ToString()); + Subject.WriteAllText(testFile, default(Guid).ToString()); using (var file = File.OpenWrite(testFile)) { @@ -203,7 +204,7 @@ public void should_return_true_for_unlocked_file() public void should_be_able_to_set_permission_from_parrent() { var testFile = GetTempFilePath(); - Subject.WriteAllText(testFile, new Guid().ToString()); + Subject.WriteAllText(testFile, default(Guid).ToString()); Subject.InheritFolderPermissions(testFile); } @@ -212,7 +213,7 @@ public void should_be_able_to_set_permission_from_parrent() public void should_be_set_last_file_write() { var testFile = GetTempFilePath(); - Subject.WriteAllText(testFile, new Guid().ToString()); + Subject.WriteAllText(testFile, default(Guid).ToString()); var lastWriteTime = DateTime.SpecifyKind(new DateTime(2012, 1, 2), DateTimeKind.Utc); diff --git a/src/NzbDrone.Common.Test/DiskTests/DiskTransferServiceFixture.cs b/src/NzbDrone.Common.Test/DiskTests/DiskTransferServiceFixture.cs index e0e2ddf98f..8c1fab5997 100644 --- a/src/NzbDrone.Common.Test/DiskTests/DiskTransferServiceFixture.cs +++ b/src/NzbDrone.Common.Test/DiskTests/DiskTransferServiceFixture.cs @@ -535,7 +535,10 @@ public void mode_transactional_should_retry_if_partial_copy() .Callback(() => { WithExistingFile(_tempTargetPath, true, 900); - if (retry++ == 1) WithExistingFile(_tempTargetPath, true, 1000); + if (retry++ == 1) + { + WithExistingFile(_tempTargetPath, true, 1000); + } }); var result = Subject.TransferFile(_sourcePath, _targetPath, TransferMode.Copy); @@ -554,7 +557,10 @@ public void mode_transactional_should_retry_twice_if_partial_copy() .Callback(() => { WithExistingFile(_tempTargetPath, true, 900); - if (retry++ == 3) throw new Exception("Test Failed, retried too many times."); + if (retry++ == 3) + { + throw new Exception("Test Failed, retried too many times."); + } }); Assert.Throws(() => Subject.TransferFile(_sourcePath, _targetPath, TransferMode.Copy)); @@ -932,7 +938,9 @@ private void WithExistingFolder(string path, bool exists = true) { var dir = Path.GetDirectoryName(path); if (exists && dir.IsNotNullOrWhiteSpace()) + { WithExistingFolder(dir); + } Mocker.GetMock() .Setup(v => v.FolderExists(path)) @@ -943,7 +951,9 @@ private void WithExistingFile(string path, bool exists = true, int size = 1000) { var dir = Path.GetDirectoryName(path); if (exists && dir.IsNotNullOrWhiteSpace()) + { WithExistingFolder(dir); + } Mocker.GetMock() .Setup(v => v.FileExists(path)) @@ -997,7 +1007,6 @@ private void WithEmulatedDiskProvider() WithExistingFile(v, false); }); - Mocker.GetMock() .Setup(v => v.FolderExists(It.IsAny())) .Returns(false); @@ -1015,6 +1024,7 @@ private void WithEmulatedDiskProvider() { WithExistingFolder(s, false); WithExistingFolder(d); + // Note: Should also deal with the files. }); @@ -1023,6 +1033,7 @@ private void WithEmulatedDiskProvider() .Callback((f, r) => { WithExistingFolder(f, false); + // Note: Should also deal with the files. }); @@ -1053,7 +1064,7 @@ private void WithRealDiskProvider() Mocker.GetMock() .Setup(v => v.DeleteFolder(It.IsAny(), It.IsAny())) - .Callback((v,r) => Directory.Delete(v, r)); + .Callback((v, r) => Directory.Delete(v, r)); Mocker.GetMock() .Setup(v => v.DeleteFile(It.IsAny())) @@ -1081,8 +1092,13 @@ private void WithRealDiskProvider() Mocker.GetMock() .Setup(v => v.MoveFile(It.IsAny(), It.IsAny(), It.IsAny())) - .Callback((s,d,o) => { - if (File.Exists(d) && o) File.Delete(d); + .Callback((s, d, o) => + { + if (File.Exists(d) && o) + { + File.Delete(d); + } + File.Move(s, d); }); diff --git a/src/NzbDrone.Common.Test/DiskTests/FreeSpaceFixtureBase.cs b/src/NzbDrone.Common.Test/DiskTests/FreeSpaceFixtureBase.cs index efef3e1c92..63d973946a 100644 --- a/src/NzbDrone.Common.Test/DiskTests/FreeSpaceFixtureBase.cs +++ b/src/NzbDrone.Common.Test/DiskTests/FreeSpaceFixtureBase.cs @@ -7,7 +7,8 @@ namespace NzbDrone.Common.Test.DiskTests { - public abstract class FreeSpaceFixtureBase : TestBase where TSubject : class, IDiskProvider + public abstract class FreeSpaceFixtureBase : TestBase + where TSubject : class, IDiskProvider { [Ignore("Docker")] [Test] @@ -58,10 +59,12 @@ public void should_throw_if_drive_doesnt_exist() WindowsOnly(); // Find a drive that doesn't exist. - for (char driveletter = 'Z'; driveletter > 'D' ; driveletter--) + for (char driveletter = 'Z'; driveletter > 'D'; driveletter--) { if (new DriveInfo(driveletter.ToString()).IsReady) + { continue; + } Assert.Throws(() => Subject.GetAvailableSpace(driveletter + @":\NOT_A_REAL_PATH\DOES_NOT_EXIST".AsOsAgnostic())); return; diff --git a/src/NzbDrone.Common.Test/EnsureTest/PathExtensionFixture.cs b/src/NzbDrone.Common.Test/EnsureTest/PathExtensionFixture.cs index 641141358b..53c1b42f46 100644 --- a/src/NzbDrone.Common.Test/EnsureTest/PathExtensionFixture.cs +++ b/src/NzbDrone.Common.Test/EnsureTest/PathExtensionFixture.cs @@ -15,7 +15,6 @@ public void EnsureWindowsPath(string path) Ensure.That(path, () => path).IsValidPath(); } - [TestCase(@"/var/user/file with, comma.mkv")] public void EnsureLinuxPath(string path) { diff --git a/src/NzbDrone.Common.Test/EnvironmentProviderTest.cs b/src/NzbDrone.Common.Test/EnvironmentProviderTest.cs index dd7e8fcf06..1d9936a8b6 100644 --- a/src/NzbDrone.Common.Test/EnvironmentProviderTest.cs +++ b/src/NzbDrone.Common.Test/EnvironmentProviderTest.cs @@ -10,13 +10,11 @@ namespace NzbDrone.Common.Test [TestFixture] public class IAppDirectoryInfoTest : TestBase { - [Test] public void StartupPath_should_not_be_empty() { Subject.StartUpFolder.Should().NotBeNullOrWhiteSpace(); Path.IsPathRooted(Subject.StartUpFolder).Should().BeTrue("Path is not rooted"); - } [Test] diff --git a/src/NzbDrone.Common.Test/EnvironmentTests/EnvironmentProviderTest.cs b/src/NzbDrone.Common.Test/EnvironmentTests/EnvironmentProviderTest.cs index 826cf9520b..a4f0bdc6dc 100644 --- a/src/NzbDrone.Common.Test/EnvironmentTests/EnvironmentProviderTest.cs +++ b/src/NzbDrone.Common.Test/EnvironmentTests/EnvironmentProviderTest.cs @@ -9,13 +9,11 @@ namespace NzbDrone.Common.Test.EnvironmentTests [TestFixture] public class BuildInfoTest : TestBase { - [TestCase("0.0.0.0")] [TestCase("1.0.0.0")] public void Application_version_should_not_be_default(string version) { BuildInfo.Version.Should().NotBe(new Version(version)); } - } } diff --git a/src/NzbDrone.Common.Test/EnvironmentTests/StartupArgumentsFixture.cs b/src/NzbDrone.Common.Test/EnvironmentTests/StartupArgumentsFixture.cs index dd7f858f8b..07df9c79e6 100644 --- a/src/NzbDrone.Common.Test/EnvironmentTests/StartupArgumentsFixture.cs +++ b/src/NzbDrone.Common.Test/EnvironmentTests/StartupArgumentsFixture.cs @@ -26,7 +26,6 @@ public void should_parse_single_flag(string arg) args.Flags.Contains("t").Should().BeTrue(); } - [TestCase("/key=value")] [TestCase("/KEY=value")] [TestCase(" /key=\"value\"")] @@ -37,7 +36,6 @@ public void should_parse_args_with_alues(string arg) args.Args["key"].Should().Be("value"); } - [TestCase("/data=test", "/data=test")] [TestCase("/Data=/a/b/c", "/data=/a/b/c")] public void should_preserver_data(string arg, string preserved) @@ -55,7 +53,6 @@ public void should_preserver_no_browser(string arg, string preserved) args.PreservedArguments.Should().Be(preserved); } - [Test] public void should_preserver_both() { diff --git a/src/NzbDrone.Common.Test/ExtensionTests/IEnumerableExtensionTests/ExceptByFixture.cs b/src/NzbDrone.Common.Test/ExtensionTests/IEnumerableExtensionTests/ExceptByFixture.cs index 1688fd8c4b..2b7ef935b4 100644 --- a/src/NzbDrone.Common.Test/ExtensionTests/IEnumerableExtensionTests/ExceptByFixture.cs +++ b/src/NzbDrone.Common.Test/ExtensionTests/IEnumerableExtensionTests/ExceptByFixture.cs @@ -56,7 +56,7 @@ public void should_return_objects_that_do_not_have_a_match_in_the_second_list() var result = first.ExceptBy(o => o.Prop1, second, o => o.Prop1, StringComparer.InvariantCultureIgnoreCase).ToList(); result.Should().HaveCount(1); - result.First().GetType().Should().Be(typeof (Object1)); + result.First().GetType().Should().Be(typeof(Object1)); result.First().Prop1.Should().Be("two"); } } diff --git a/src/NzbDrone.Common.Test/ExtensionTests/IPAddressExtensionsFixture.cs b/src/NzbDrone.Common.Test/ExtensionTests/IPAddressExtensionsFixture.cs index 944f7417a5..ff5d7383e7 100644 --- a/src/NzbDrone.Common.Test/ExtensionTests/IPAddressExtensionsFixture.cs +++ b/src/NzbDrone.Common.Test/ExtensionTests/IPAddressExtensionsFixture.cs @@ -24,7 +24,6 @@ public void should_return_true_for_local_ip_address(string ipAddress) public void should_return_false_for_public_ip_address(string ipAddress) { IPAddress.Parse(ipAddress).IsLocalAddress().Should().BeFalse(); - } } } diff --git a/src/NzbDrone.Common.Test/Http/HttpClientFixture.cs b/src/NzbDrone.Common.Test/Http/HttpClientFixture.cs index 16c15a6f67..13b78e52d3 100644 --- a/src/NzbDrone.Common.Test/Http/HttpClientFixture.cs +++ b/src/NzbDrone.Common.Test/Http/HttpClientFixture.cs @@ -22,7 +22,8 @@ namespace NzbDrone.Common.Test.Http { [IntegrationTest] [TestFixture(typeof(ManagedHttpDispatcher))] - public class HttpClientFixture : TestBase where TDispatcher : IHttpDispatcher + public class HttpClientFixture : TestBase + where TDispatcher : IHttpDispatcher { private string[] _httpBinHosts; private int _httpBinSleep; @@ -34,6 +35,7 @@ public class HttpClientFixture : TestBase where TDispat public void FixtureSetUp() { var candidates = new[] { "eu.httpbin.org", /*"httpbin.org",*/ "www.httpbin.org" }; + // httpbin.org is broken right now, occassionally redirecting to https if it's unavailable. _httpBinHosts = candidates.Where(IsTestSiteAvailable).ToArray(); @@ -48,7 +50,10 @@ private bool IsTestSiteAvailable(string site) { var req = WebRequest.Create($"http://{site}/get") as HttpWebRequest; var res = req.GetResponse() as HttpWebResponse; - if (res.StatusCode != HttpStatusCode.OK) return false; + if (res.StatusCode != HttpStatusCode.OK) + { + return false; + } try { @@ -60,7 +65,10 @@ private bool IsTestSiteAvailable(string site) res = ex.Response as HttpWebResponse; } - if (res == null || res.StatusCode != (HttpStatusCode)429) return false; + if (res == null || res.StatusCode != (HttpStatusCode)429) + { + return false; + } return true; } @@ -617,7 +625,7 @@ public void should_throw_on_http429_too_many_requests() [Test] public void should_call_interceptor() { - Mocker.SetConstant>(new [] { Mocker.GetMock().Object }); + Mocker.SetConstant>(new[] { Mocker.GetMock().Object }); Mocker.GetMock() .Setup(v => v.PreRequest(It.IsAny())) diff --git a/src/NzbDrone.Common.Test/Http/HttpHeaderFixture.cs b/src/NzbDrone.Common.Test/Http/HttpHeaderFixture.cs index e0a22072e8..e5221e4087 100644 --- a/src/NzbDrone.Common.Test/Http/HttpHeaderFixture.cs +++ b/src/NzbDrone.Common.Test/Http/HttpHeaderFixture.cs @@ -1,11 +1,11 @@ -using NUnit.Framework; -using FluentAssertions; -using NzbDrone.Test.Common; -using System; -using System.Text; -using NzbDrone.Common.Http; +using System; using System.Collections.Specialized; using System.Linq; +using System.Text; +using FluentAssertions; +using NUnit.Framework; +using NzbDrone.Common.Http; +using NzbDrone.Test.Common; namespace NzbDrone.Common.Test.Http { diff --git a/src/NzbDrone.Common.Test/Http/HttpRequestBuilderFixture.cs b/src/NzbDrone.Common.Test/Http/HttpRequestBuilderFixture.cs index 2c2c718e69..4af9bb501e 100644 --- a/src/NzbDrone.Common.Test/Http/HttpRequestBuilderFixture.cs +++ b/src/NzbDrone.Common.Test/Http/HttpRequestBuilderFixture.cs @@ -35,7 +35,6 @@ public void should_remove_duplicated_slashes() var request = builder.Resource("/v1/").Build(); request.Url.FullUri.Should().Be("http://domain/v1/"); - } } } diff --git a/src/NzbDrone.Common.Test/InstrumentationTests/CleanseLogMessageFixture.cs b/src/NzbDrone.Common.Test/InstrumentationTests/CleanseLogMessageFixture.cs index 0dcee31655..8a61ef050f 100644 --- a/src/NzbDrone.Common.Test/InstrumentationTests/CleanseLogMessageFixture.cs +++ b/src/NzbDrone.Common.Test/InstrumentationTests/CleanseLogMessageFixture.cs @@ -1,6 +1,6 @@ -using NUnit.Framework; +using FluentAssertions; +using NUnit.Framework; using NzbDrone.Common.Instrumentation; -using FluentAssertions; namespace NzbDrone.Common.Test.InstrumentationTests { @@ -17,9 +17,11 @@ public class CleanseLogMessageFixture [TestCase(@"https://baconbits.org/feeds.php?feed=torrents_tv&user=12345&auth=2b51db35e1910123321025a12b9933d2&passkey=mySecret&authkey=2b51db35e1910123321025a12b9933d2")] [TestCase(@"http://127.0.0.1:9117/dl/indexername?jackett_apikey=flwjiefewklfjacketmySecretsdfldskjfsdlk&path=we0re9f0sdfbase64sfdkfjsdlfjk&file=The+Torrent+File+Name.torrent")] [TestCase(@"http://nzb.su/getnzb/2b51db35e1912ffc138825a12b9933d2.nzb&i=37292&r=2b51db35e1910123321025a12b9933d2")] + // NzbGet [TestCase(@"{ ""Name"" : ""ControlUsername"", ""Value"" : ""mySecret"" }, { ""Name"" : ""ControlPassword"", ""Value"" : ""mySecret"" }, ")] [TestCase(@"{ ""Name"" : ""Server1.Username"", ""Value"" : ""mySecret"" }, { ""Name"" : ""Server1.Password"", ""Value"" : ""mySecret"" }, ")] + // Sabnzbd [TestCase(@"http://127.0.0.1:1234/api/call?vv=1&apikey=mySecret")] [TestCase(@"http://127.0.0.1:1234/api/call?vv=1&ma_username=mySecret&ma_password=mySecret")] @@ -30,6 +32,7 @@ public class CleanseLogMessageFixture [TestCase(@"""misc"":{""username"":""mySecret"",""api_key"":""mySecret"",""password"":""mySecret"",""nzb_key"":""mySecret""}")] [TestCase(@"""servers"":[{""username"":""mySecret"",""password"":""mySecret""}]")] [TestCase(@"""misc"":{""email_account"":""mySecret"",""email_to"":[],""email_from"":"""",""email_pwd"":""mySecret""}")] + // uTorrent [TestCase(@"http://localhost:9091/gui/?token=wThmph5l0ZXfH-a6WOA4lqiLvyjCP0FpMrMeXmySecret_VXBO11HoKL751MAAAAA&list=1")] [TestCase(@",[""boss_key"",0,""mySecret"",{""access"":""Y""}],[""boss_key_salt"",0,""mySecret"",{""access"":""W""}]")] @@ -37,10 +40,12 @@ public class CleanseLogMessageFixture [TestCase(@",[""webui.uconnect_username"",2,""mySecret"",{""access"":""Y""}],[""webui.uconnect_password"",2,""mySecret"",{""access"":""Y""}]")] [TestCase(@",[""proxy.proxy"",2,""mySecret"",{""access"":""Y""}]")] [TestCase(@",[""proxy.username"",2,""mySecret"",{""access"":""Y""}],[""proxy.password"",2,""mySecret"",{""access"":""Y""}]")] + // Deluge [TestCase(@",{""download_location"": ""C:\Users\\mySecret mySecret\\Downloads""}")] [TestCase(@",{""download_location"": ""/home/mySecret/Downloads""}")] [TestCase(@"auth.login(""mySecret"")")] + // BroadcastheNet [TestCase(@"method: ""getTorrents"", ""params"": [ ""mySecret"",")] [TestCase(@"getTorrents(""mySecret"", [asdfasdf], 100, 0)")] diff --git a/src/NzbDrone.Common.Test/InstrumentationTests/SentryTargetFixture.cs b/src/NzbDrone.Common.Test/InstrumentationTests/SentryTargetFixture.cs index 1aec7ca884..0b8a6f15dd 100644 --- a/src/NzbDrone.Common.Test/InstrumentationTests/SentryTargetFixture.cs +++ b/src/NzbDrone.Common.Test/InstrumentationTests/SentryTargetFixture.cs @@ -1,24 +1,25 @@ -using NUnit.Framework; -using FluentAssertions; -using NzbDrone.Common.Instrumentation.Sentry; -using System; -using NLog; -using NzbDrone.Test.Common; +using System; using System.Globalization; using System.Linq; +using FluentAssertions; +using NLog; +using NUnit.Framework; +using NzbDrone.Common.Instrumentation.Sentry; +using NzbDrone.Test.Common; namespace NzbDrone.Common.Test.InstrumentationTests { [TestFixture] public class SentryTargetFixture : TestBase { - private SentryTarget Subject; + private SentryTarget _subject; private static LogLevel[] AllLevels = LogLevel.AllLevels.ToArray(); private static LogLevel[] SentryLevels = LogLevel.AllLevels.Where(x => x >= LogLevel.Error).ToArray(); private static LogLevel[] OtherLevels = AllLevels.Except(SentryLevels).ToArray(); - private static Exception[] FilteredExceptions = new Exception[] { + private static Exception[] FilteredExceptions = new Exception[] + { new UnauthorizedAccessException(), new TinyIoC.TinyIoCResolutionException(typeof(string)) }; @@ -26,7 +27,7 @@ public class SentryTargetFixture : TestBase [SetUp] public void Setup() { - Subject = new SentryTarget("https://aaaaaaaaaaaaaaaaaaaaaaaaaa@sentry.io/111111"); + _subject = new SentryTarget("https://aaaaaaaaaaaaaaaaaaaaaaaaaa@sentry.io/111111"); } private LogEventInfo GivenLogEvent(LogLevel level, Exception ex, string message) @@ -34,44 +35,50 @@ private LogEventInfo GivenLogEvent(LogLevel level, Exception ex, string message) return LogEventInfo.Create(level, "SentryTest", ex, CultureInfo.InvariantCulture, message); } - [Test, TestCaseSource("AllLevels")] + [Test] + [TestCaseSource("AllLevels")] public void log_without_error_is_not_sentry_event(LogLevel level) { - Subject.IsSentryMessage(GivenLogEvent(level, null, "test")).Should().BeFalse(); + _subject.IsSentryMessage(GivenLogEvent(level, null, "test")).Should().BeFalse(); } - [Test, TestCaseSource("SentryLevels")] + [Test] + [TestCaseSource("SentryLevels")] public void error_or_worse_with_exception_is_sentry_event(LogLevel level) { - Subject.IsSentryMessage(GivenLogEvent(level, new Exception(), "test")).Should().BeTrue(); + _subject.IsSentryMessage(GivenLogEvent(level, new Exception(), "test")).Should().BeTrue(); } - [Test, TestCaseSource("OtherLevels")] + [Test] + [TestCaseSource("OtherLevels")] public void less_than_error_with_exception_is_not_sentry_event(LogLevel level) { - Subject.IsSentryMessage(GivenLogEvent(level, new Exception(), "test")).Should().BeFalse(); + _subject.IsSentryMessage(GivenLogEvent(level, new Exception(), "test")).Should().BeFalse(); } - [Test, TestCaseSource("FilteredExceptions")] + [Test] + [TestCaseSource("FilteredExceptions")] public void should_filter_event_for_filtered_exception_types(Exception ex) { var log = GivenLogEvent(LogLevel.Error, ex, "test"); - Subject.IsSentryMessage(log).Should().BeFalse(); + _subject.IsSentryMessage(log).Should().BeFalse(); } - [Test, TestCaseSource("FilteredExceptions")] + [Test] + [TestCaseSource("FilteredExceptions")] public void should_not_filter_event_for_filtered_exception_types_if_filtering_disabled(Exception ex) { - Subject.FilterEvents = false; + _subject.FilterEvents = false; var log = GivenLogEvent(LogLevel.Error, ex, "test"); - Subject.IsSentryMessage(log).Should().BeTrue(); + _subject.IsSentryMessage(log).Should().BeTrue(); } - [Test, TestCaseSource(typeof(SentryTarget), "FilteredExceptionMessages")] + [Test] + [TestCaseSource(typeof(SentryTarget), "FilteredExceptionMessages")] public void should_filter_event_for_filtered_exception_messages(string message) { var log = GivenLogEvent(LogLevel.Error, new Exception("aaaaaaa" + message + "bbbbbbb"), "test"); - Subject.IsSentryMessage(log).Should().BeFalse(); + _subject.IsSentryMessage(log).Should().BeFalse(); } [TestCase("A message that isn't filtered")] @@ -79,7 +86,7 @@ public void should_filter_event_for_filtered_exception_messages(string message) public void should_not_filter_event_for_exception_messages_that_are_not_filtered(string message) { var log = GivenLogEvent(LogLevel.Error, new Exception(message), "test"); - Subject.IsSentryMessage(log).Should().BeTrue(); + _subject.IsSentryMessage(log).Should().BeTrue(); } } } diff --git a/src/NzbDrone.Common.Test/OsPathFixture.cs b/src/NzbDrone.Common.Test/OsPathFixture.cs index a7c20f8661..6d79e0cfcd 100644 --- a/src/NzbDrone.Common.Test/OsPathFixture.cs +++ b/src/NzbDrone.Common.Test/OsPathFixture.cs @@ -1,7 +1,7 @@ -using NUnit.Framework; +using FluentAssertions; +using NUnit.Framework; using NzbDrone.Common.Disk; using NzbDrone.Test.Common; -using FluentAssertions; namespace NzbDrone.Common.Test { diff --git a/src/NzbDrone.Common.Test/PathExtensionFixture.cs b/src/NzbDrone.Common.Test/PathExtensionFixture.cs index 9b3efc2648..e18a3d7b2f 100644 --- a/src/NzbDrone.Common.Test/PathExtensionFixture.cs +++ b/src/NzbDrone.Common.Test/PathExtensionFixture.cs @@ -110,6 +110,7 @@ public void should_return_true_when_folder_is_parent_of_a_file() _parent.IsParentPath(path).Should().BeTrue(); } + [TestCase(@"C:\Test\", @"C:\Test\mydir")] [TestCase(@"C:\Test\", @"C:\Test\mydir\")] [TestCase(@"C:\Test", @"C:\Test\30.Rock.S01E01.Pilot.avi")] @@ -163,8 +164,7 @@ public void path_should_return_parent_for_oversized_path() // This test will fail on Windows if long path support is not enabled: https://www.howtogeek.com/266621/how-to-make-windows-10-accept-file-paths-over-260-characters/ // It will also fail if the app isn't configured to use long path (such as resharper): https://blogs.msdn.microsoft.com/jeremykuhne/2016/07/30/net-4-6-2-and-long-paths-on-windows-10/ - - var path = @"C:\media\2e168617-f2ae-43fb-b88c-3663af1c8eea\downloads\sabnzbd\nzbdrone\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories".AsOsAgnostic(); + var path = @"C:\media\2e168617-f2ae-43fb-b88c-3663af1c8eea\downloads\sabnzbd\nzbdrone\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories".AsOsAgnostic(); var parentPath = @"C:\media\2e168617-f2ae-43fb-b88c-3663af1c8eea\downloads\sabnzbd\nzbdrone\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories\Some.Real.Big.Thing\With.Alot.Of.Nested.Directories\Some.Real.Big.Thing".AsOsAgnostic(); path.GetParentPath().Should().Be(parentPath); @@ -198,10 +198,9 @@ public void normalize_path_exception_null() public void get_actual_casing_for_none_existing_file_return_partially_fixed_result() { WindowsOnly(); - "C:\\WINDOWS\\invalidfile.exe".GetActualCasing().Should().Be("C:\\Windows\\invalidfile.exe"); + "C:\\WINDOWS\\invalidfile.exe".GetActualCasing().Should().Be("C:\\Windows\\invalidfile.exe"); } - [Test] public void get_actual_casing_for_none_existing_folder_return_partially_fixed_result() { @@ -218,12 +217,11 @@ public void get_actual_casing_should_return_actual_casing_for_local_file_in_wind path.ToLower().GetActualCasing().Should().Be(path); } - [Test] public void get_actual_casing_should_return_actual_casing_for_local_dir_in_windows() { WindowsOnly(); - var path = Directory.GetCurrentDirectory().Replace("c:\\","C:\\").Replace("d:\\","D:\\").Replace("system32", "System32"); + var path = Directory.GetCurrentDirectory().Replace("c:\\", "C:\\").Replace("d:\\", "D:\\").Replace("system32", "System32"); path.ToUpper().GetActualCasing().Should().Be(path); path.ToLower().GetActualCasing().Should().Be(path); diff --git a/src/NzbDrone.Common.Test/ProcessProviderFixture.cs b/src/NzbDrone.Common.Test/ProcessProviderFixture.cs index 2587d86ad0..b81bbfa19b 100644 --- a/src/NzbDrone.Common.Test/ProcessProviderFixture.cs +++ b/src/NzbDrone.Common.Test/ProcessProviderFixture.cs @@ -17,7 +17,6 @@ namespace NzbDrone.Common.Test [TestFixture] public class ProcessProviderFixture : TestBase { - [SetUp] public void Setup() { @@ -43,7 +42,6 @@ public void TearDown() { TestLogger.Warn(ex, "{0} when killing process", ex.Message); } - }); } @@ -85,7 +83,7 @@ public void should_be_able_to_start_process() } [Test] - [Platform(Exclude="MacOsX")] + [Platform(Exclude = "MacOsX")] [Retry(3)] public void exists_should_find_running_process() { @@ -153,7 +151,7 @@ public void Should_be_able_to_start_python() [Test] [Retry(3)] - [Platform(Exclude="MacOsX")] + [Platform(Exclude = "MacOsX")] public void kill_all_should_kill_all_process_with_name() { var dummy1 = StartDummyProcess(); @@ -182,12 +180,13 @@ private Process StartDummyProcess() } var path = Path.Combine(TestContext.CurrentContext.TestDirectory, DummyApp.DUMMY_PROCCESS_NAME + suffix); - var process = Subject.Start(path, onOutputDataReceived: (string data) => { - if (data.StartsWith("Dummy process. ID:")) - { - processStarted.Set(); - } - }); + var process = Subject.Start(path, onOutputDataReceived: (string data) => + { + if (data.StartsWith("Dummy process. ID:")) + { + processStarted.Set(); + } + }); if (!processStarted.Wait(5000)) { diff --git a/src/NzbDrone.Common.Test/ServiceFactoryFixture.cs b/src/NzbDrone.Common.Test/ServiceFactoryFixture.cs index c1ec37ff1f..830e2af44d 100644 --- a/src/NzbDrone.Common.Test/ServiceFactoryFixture.cs +++ b/src/NzbDrone.Common.Test/ServiceFactoryFixture.cs @@ -5,8 +5,8 @@ using NzbDrone.Core.Datastore; using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Messaging.Events; -using Radarr.Host; using NzbDrone.Test.Common; +using Radarr.Host; namespace NzbDrone.Common.Test { diff --git a/src/NzbDrone.Common.Test/ServiceProviderTests.cs b/src/NzbDrone.Common.Test/ServiceProviderTests.cs index 9b5bb7d636..99aafe6274 100644 --- a/src/NzbDrone.Common.Test/ServiceProviderTests.cs +++ b/src/NzbDrone.Common.Test/ServiceProviderTests.cs @@ -35,7 +35,6 @@ public void TearDown() } } - private void CleanupService() { if (Subject.ServiceExist(TEMP_SERVICE_NAME)) @@ -61,7 +60,6 @@ public void Exists_should_not_find_random_service() Subject.ServiceExist("random_service_name").Should().BeFalse(); } - [Test] public void Service_should_be_installed_and_then_uninstalled() { @@ -121,7 +119,6 @@ public void should_throw_if_starting_a_running_service() Subject.Start(ALWAYS_INSTALLED_SERVICE); Assert.Throws(() => Subject.Start(ALWAYS_INSTALLED_SERVICE)); - ExceptionVerification.ExpectedWarns(1); } @@ -131,15 +128,14 @@ public void Should_log_warn_if_on_stop_if_service_is_already_stopped() Subject.GetService(ALWAYS_INSTALLED_SERVICE).Status .Should().NotBe(ServiceControllerStatus.Running); - Subject.Stop(ALWAYS_INSTALLED_SERVICE); - Subject.GetService(ALWAYS_INSTALLED_SERVICE).Status .Should().Be(ServiceControllerStatus.Stopped); ExceptionVerification.ExpectedWarns(1); } + private static bool IsAnAdministrator() { var principal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); diff --git a/src/NzbDrone.Common.Test/TPLTests/DebouncerFixture.cs b/src/NzbDrone.Common.Test/TPLTests/DebouncerFixture.cs index 7f47b337b9..4b7349f4a1 100644 --- a/src/NzbDrone.Common.Test/TPLTests/DebouncerFixture.cs +++ b/src/NzbDrone.Common.Test/TPLTests/DebouncerFixture.cs @@ -20,7 +20,6 @@ public void Hit() } } - [Test] [Retry(3)] public void should_hold_the_call_for_debounce_duration() @@ -34,11 +33,9 @@ public void should_hold_the_call_for_debounce_duration() counter.Count.Should().Be(0); - Thread.Sleep(100); counter.Count.Should().Be(1); - } [Test] @@ -54,7 +51,6 @@ public void should_throttle_calls() counter.Count.Should().Be(0); - Thread.Sleep(200); debounceFunction.Execute(); @@ -64,7 +60,6 @@ public void should_throttle_calls() Thread.Sleep(200); counter.Count.Should().Be(2); - } [Test] diff --git a/src/NzbDrone.Common.Test/TPLTests/RateLimitServiceFixture.cs b/src/NzbDrone.Common.Test/TPLTests/RateLimitServiceFixture.cs index 539e3a62a4..9198684589 100644 --- a/src/NzbDrone.Common.Test/TPLTests/RateLimitServiceFixture.cs +++ b/src/NzbDrone.Common.Test/TPLTests/RateLimitServiceFixture.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Concurrent; using System.Diagnostics; +using FluentAssertions; using NUnit.Framework; using NzbDrone.Common.Cache; using NzbDrone.Common.TPL; using NzbDrone.Test.Common; -using FluentAssertions; namespace NzbDrone.Common.Test.TPLTests { diff --git a/src/NzbDrone.Common/ArchiveService.cs b/src/NzbDrone.Common/ArchiveService.cs index 2a45d7215f..57335ae7cd 100644 --- a/src/NzbDrone.Common/ArchiveService.cs +++ b/src/NzbDrone.Common/ArchiveService.cs @@ -73,11 +73,12 @@ private void ExtractZip(string compressedFile, string destination) { continue; // Ignore directories } + string entryFileName = zipEntry.Name; + // to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName); // Optionally match entrynames against a selection list here to skip as desired. // The unpacked length is available in the zipEntry.Size property. - byte[] buffer = new byte[4096]; // 4K is optimum Stream zipStream = zipFile.GetInputStream(zipEntry); @@ -85,7 +86,9 @@ private void ExtractZip(string compressedFile, string destination) string fullZipToPath = Path.Combine(destination, entryFileName); string directoryName = Path.GetDirectoryName(fullZipToPath); if (directoryName.Length > 0) + { Directory.CreateDirectory(directoryName); + } // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size // of the file, but does not waste memory. diff --git a/src/NzbDrone.Common/Cache/CacheManager.cs b/src/NzbDrone.Common/Cache/CacheManager.cs index 1b6c945e53..6c080a02ef 100644 --- a/src/NzbDrone.Common/Cache/CacheManager.cs +++ b/src/NzbDrone.Common/Cache/CacheManager.cs @@ -20,7 +20,6 @@ public class CacheManager : ICacheManager public CacheManager() { _cache = new Cached(); - } public void Clear() diff --git a/src/NzbDrone.Common/Cache/Cached.cs b/src/NzbDrone.Common/Cache/Cached.cs index d4e98be462..2285f548d7 100644 --- a/src/NzbDrone.Common/Cache/Cached.cs +++ b/src/NzbDrone.Common/Cache/Cached.cs @@ -6,7 +6,6 @@ namespace NzbDrone.Common.Cache { - public class Cached : ICached { private class CacheItem @@ -109,6 +108,5 @@ public ICollection Values return _store.Values.Select(c => c.Object).ToList(); } } - } } diff --git a/src/NzbDrone.Common/Cache/CachedDictionary.cs b/src/NzbDrone.Common/Cache/CachedDictionary.cs index 7bbda022a3..6332f50545 100644 --- a/src/NzbDrone.Common/Cache/CachedDictionary.cs +++ b/src/NzbDrone.Common/Cache/CachedDictionary.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Common.Cache { - public class CachedDictionary : ICachedDictionary { private readonly Func> _fetchFunc; @@ -34,7 +33,7 @@ public void RefreshIfExpired() } public void RefreshIfExpired(TimeSpan ttl) - { + { if (IsExpired(ttl)) { Refresh(); diff --git a/src/NzbDrone.Common/Composition/Container.cs b/src/NzbDrone.Common/Composition/Container.cs index 1b8944a8d2..d65d7d19b2 100644 --- a/src/NzbDrone.Common/Composition/Container.cs +++ b/src/NzbDrone.Common/Composition/Container.cs @@ -24,12 +24,14 @@ public void Register() _container.Register(); } - public void Register(T instance) where T : class + public void Register(T instance) + where T : class { _container.Register(instance); } - public T Resolve() where T : class + public T Resolve() + where T : class { return _container.Resolve(); } @@ -44,7 +46,8 @@ public void Register(Type serviceType, Type implementationType) _container.Register(serviceType, implementationType); } - public void Register(Func factory) where TService : class + public void Register(Func factory) + where TService : class { _container.Register((c, n) => factory(this)); } @@ -57,7 +60,8 @@ public void RegisterSingleton(Type service, Type implementation) _container.Register(service, factory, implementation.FullName); } - public IEnumerable ResolveAll() where T : class + public IEnumerable ResolveAll() + where T : class { return _container.ResolveAll(); } @@ -92,8 +96,7 @@ public IEnumerable GetImplementations(Type contractType) .Where(implementation => contractType.IsAssignableFrom(implementation) && !implementation.IsInterface && - !implementation.IsAbstract - ); + !implementation.IsAbstract); } } } diff --git a/src/NzbDrone.Common/Composition/ContainerBuilderBase.cs b/src/NzbDrone.Common/Composition/ContainerBuilderBase.cs index 6575f9236b..09f7ec8c31 100644 --- a/src/NzbDrone.Common/Composition/ContainerBuilderBase.cs +++ b/src/NzbDrone.Common/Composition/ContainerBuilderBase.cs @@ -8,8 +8,8 @@ #if NETCOREAPP using System.IO; -using System.Runtime.Loader; using System.Runtime.InteropServices; +using System.Runtime.Loader; #endif namespace NzbDrone.Common.Composition @@ -33,15 +33,15 @@ protected ContainerBuilderBase(IStartupContext args, List assemblies) _loadedTypes.AddRange(Assembly.Load(assembly).GetTypes()); } #else - var _startupPath = AppDomain.CurrentDomain.BaseDirectory; + var startupPath = AppDomain.CurrentDomain.BaseDirectory; foreach (var assemblyName in assemblies) { - _loadedTypes.AddRange(AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.Combine(_startupPath, $"{assemblyName}.dll")).GetTypes()); + _loadedTypes.AddRange(AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.Combine(startupPath, $"{assemblyName}.dll")).GetTypes()); } var toRegisterResolver = new List { "System.Data.SQLite" }; - toRegisterResolver.AddRange(assemblies.Intersect(new [] { "Radarr.Core" })); + toRegisterResolver.AddRange(assemblies.Intersect(new[] { "Radarr.Core" })); RegisterNativeResolver(toRegisterResolver); AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(ContainerResolveEventHandler); #endif @@ -54,8 +54,8 @@ protected ContainerBuilderBase(IStartupContext args, List assemblies) #if NETCOREAPP private static Assembly ContainerResolveEventHandler(object sender, ResolveEventArgs args) { - var _resolver = new AssemblyDependencyResolver(args.RequestingAssembly.Location); - var assemblyPath = _resolver.ResolveAssemblyToPath(new AssemblyName(args.Name)); + var resolver = new AssemblyDependencyResolver(args.RequestingAssembly.Location); + var assemblyPath = resolver.ResolveAssemblyToPath(new AssemblyName(args.Name)); if (assemblyPath == null) { @@ -72,8 +72,7 @@ public static void RegisterNativeResolver(IEnumerable assemblyNames) foreach (var name in assemblyNames) { var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath( - Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{name}.dll") - ); + Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{name}.dll")); try { @@ -134,6 +133,7 @@ private void AutoRegisterImplementations(Type contractType) { return; } + if (implementations.Count == 1) { var impl = implementations.Single(); diff --git a/src/NzbDrone.Common/Composition/IContainer.cs b/src/NzbDrone.Common/Composition/IContainer.cs index 1ba6c41f10..9e74020175 100644 --- a/src/NzbDrone.Common/Composition/IContainer.cs +++ b/src/NzbDrone.Common/Composition/IContainer.cs @@ -5,17 +5,21 @@ namespace NzbDrone.Common.Composition { public interface IContainer { - void Register(T instance) where T : class; + void Register(T instance) + where T : class; void Register() where TImplementation : class, TService where TService : class; - T Resolve() where T : class; + T Resolve() + where T : class; object Resolve(Type type); void Register(Type serviceType, Type implementationType); - void Register(Func factory) where TService : class; + void Register(Func factory) + where TService : class; void RegisterSingleton(Type service, Type implementation); - IEnumerable ResolveAll() where T : class; + IEnumerable ResolveAll() + where T : class; void RegisterAllAsSingleton(Type registrationType, IEnumerable implementationList); bool IsTypeRegistered(Type type); diff --git a/src/NzbDrone.Common/ConvertBase32.cs b/src/NzbDrone.Common/ConvertBase32.cs index 29cb3618e0..3ee7803d50 100644 --- a/src/NzbDrone.Common/ConvertBase32.cs +++ b/src/NzbDrone.Common/ConvertBase32.cs @@ -16,7 +16,7 @@ public static byte[] FromBase32String(string str) int bitBufferCount = 0; int index = 0; - for (int i = 0; i < str.Length;i++ ) + for (int i = 0; i < str.Length; i++) { bitBuffer = (bitBuffer << 5) | ValidChars.IndexOf(str[i]); bitBufferCount += 5; diff --git a/src/NzbDrone.Common/Disk/DestinationAlreadyExistsException.cs b/src/NzbDrone.Common/Disk/DestinationAlreadyExistsException.cs index 9864137427..ffdc36e0e3 100644 --- a/src/NzbDrone.Common/Disk/DestinationAlreadyExistsException.cs +++ b/src/NzbDrone.Common/Disk/DestinationAlreadyExistsException.cs @@ -10,19 +10,23 @@ public DestinationAlreadyExistsException() { } - public DestinationAlreadyExistsException(string message) : base(message) + public DestinationAlreadyExistsException(string message) + : base(message) { } - public DestinationAlreadyExistsException(string message, int hresult) : base(message, hresult) + public DestinationAlreadyExistsException(string message, int hresult) + : base(message, hresult) { } - public DestinationAlreadyExistsException(string message, Exception innerException) : base(message, innerException) + public DestinationAlreadyExistsException(string message, Exception innerException) + : base(message, innerException) { } - protected DestinationAlreadyExistsException(SerializationInfo info, StreamingContext context) : base(info, context) + protected DestinationAlreadyExistsException(SerializationInfo info, StreamingContext context) + : base(info, context) { } } diff --git a/src/NzbDrone.Common/Disk/DiskProviderBase.cs b/src/NzbDrone.Common/Disk/DiskProviderBase.cs index 364a258246..81dccaa1cd 100644 --- a/src/NzbDrone.Common/Disk/DiskProviderBase.cs +++ b/src/NzbDrone.Common/Disk/DiskProviderBase.cs @@ -114,10 +114,11 @@ public bool FileExists(string path, StringComparison stringComparison) { return File.Exists(path) && path == path.GetActualCasing(); } + default: - { - return File.Exists(path); - } + { + return File.Exists(path); + } } } @@ -362,9 +363,11 @@ public void SetPermissions(string filename, WellKnownSidType accountSid, FileSys return; } - var accessRule = new FileSystemAccessRule(sid, rights, + var accessRule = new FileSystemAccessRule(sid, + rights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, - PropagationFlags.InheritOnly, controlType); + PropagationFlags.InheritOnly, + controlType); bool modified; directorySecurity.ModifyAccessRule(AccessControlModification.Add, accessRule, out modified); @@ -379,7 +382,6 @@ public void SetPermissions(string filename, WellKnownSidType accountSid, FileSys Logger.Warn(e, "Couldn't set permission for {0}. account:{1} rights:{2} accessControlType:{3}", filename, accountSid, rights, controlType); throw; } - } private static void RemoveReadOnly(string path) @@ -390,7 +392,7 @@ private static void RemoveReadOnly(string path) if (attributes.HasFlag(FileAttributes.ReadOnly)) { - var newAttributes = attributes & ~(FileAttributes.ReadOnly); + var newAttributes = attributes & ~FileAttributes.ReadOnly; File.SetAttributes(path, newAttributes); } } @@ -404,7 +406,7 @@ private static void RemoveReadOnlyFolder(string path) if (dirInfo.Attributes.HasFlag(FileAttributes.ReadOnly)) { - var newAttributes = dirInfo.Attributes & ~(FileAttributes.ReadOnly); + var newAttributes = dirInfo.Attributes & ~FileAttributes.ReadOnly; dirInfo.Attributes = newAttributes; } } diff --git a/src/NzbDrone.Common/Disk/DiskTransferService.cs b/src/NzbDrone.Common/Disk/DiskTransferService.cs index fac59ceb5d..6c668e36b7 100644 --- a/src/NzbDrone.Common/Disk/DiskTransferService.cs +++ b/src/NzbDrone.Common/Disk/DiskTransferService.cs @@ -81,14 +81,20 @@ public TransferMode TransferFolder(string sourcePath, string targetPath, Transfe foreach (var subDir in _diskProvider.GetDirectoryInfos(sourcePath)) { - if (ShouldIgnore(subDir)) continue; + if (ShouldIgnore(subDir)) + { + continue; + } result &= TransferFolder(subDir.FullName, Path.Combine(targetPath, subDir.Name), mode, verificationMode); } foreach (var sourceFile in _diskProvider.GetFileInfos(sourcePath)) { - if (ShouldIgnore(sourceFile)) continue; + if (ShouldIgnore(sourceFile)) + { + continue; + } var destFile = Path.Combine(targetPath, sourceFile.Name); @@ -122,14 +128,20 @@ public int MirrorFolder(string sourcePath, string targetPath) foreach (var subDir in targetFolders.Where(v => !sourceFolders.Any(d => d.Name == v.Name))) { - if (ShouldIgnore(subDir)) continue; + if (ShouldIgnore(subDir)) + { + continue; + } _diskProvider.DeleteFolder(subDir.FullName, true); } foreach (var subDir in sourceFolders) { - if (ShouldIgnore(subDir)) continue; + if (ShouldIgnore(subDir)) + { + continue; + } filesCopied += MirrorFolder(subDir.FullName, Path.Combine(targetPath, subDir.Name)); } @@ -139,14 +151,20 @@ public int MirrorFolder(string sourcePath, string targetPath) foreach (var targetFile in targetFiles.Where(v => !sourceFiles.Any(d => d.Name == v.Name))) { - if (ShouldIgnore(targetFile)) continue; + if (ShouldIgnore(targetFile)) + { + continue; + } _diskProvider.DeleteFile(targetFile.FullName); } foreach (var sourceFile in sourceFiles) { - if (ShouldIgnore(sourceFile)) continue; + if (ShouldIgnore(sourceFile)) + { + continue; + } var targetFile = Path.Combine(targetPath, sourceFile.Name); @@ -279,6 +297,7 @@ public TransferMode TransferFile(string sourcePath, string targetPath, TransferM { return TransferMode.HardLink; } + if (!mode.HasFlag(TransferMode.Copy)) { throw new IOException("Hardlinking from '" + sourcePath + "' to '" + targetPath + "' failed."); @@ -291,7 +310,7 @@ public TransferMode TransferFile(string sourcePath, string targetPath, TransferM var sourceMount = _diskProvider.GetMount(sourcePath); var targetMount = _diskProvider.GetMount(targetPath); - var isSameMount = (sourceMount != null && targetMount != null && sourceMount.RootDirectory == targetMount.RootDirectory); + var isSameMount = sourceMount != null && targetMount != null && sourceMount.RootDirectory == targetMount.RootDirectory; var sourceDriveFormat = sourceMount?.DriveFormat ?? string.Empty; var targetDriveFormat = targetMount?.DriveFormat ?? string.Empty; @@ -532,6 +551,7 @@ private bool TryMoveFileTransactional(string sourcePath, string targetPath, long { throw new IOException(string.Format("Temporary file '{0}' still exists, aborting.", tempTargetPath)); } + _logger.Trace("Hardlink move succeeded, deleting source."); _diskProvider.DeleteFile(sourcePath); return true; diff --git a/src/NzbDrone.Common/Disk/FileSystemLookupService.cs b/src/NzbDrone.Common/Disk/FileSystemLookupService.cs index a3aa8810d4..e28a1c1cf5 100644 --- a/src/NzbDrone.Common/Disk/FileSystemLookupService.cs +++ b/src/NzbDrone.Common/Disk/FileSystemLookupService.cs @@ -124,7 +124,6 @@ private FileSystemResult GetResult(string path, bool includeFiles) result.Files = GetFiles(path); } } - catch (DirectoryNotFoundException) { return new FileSystemResult { Parent = GetParent(path) }; diff --git a/src/NzbDrone.Common/Disk/NotParentException.cs b/src/NzbDrone.Common/Disk/NotParentException.cs index 0ae3847222..4859c29be5 100644 --- a/src/NzbDrone.Common/Disk/NotParentException.cs +++ b/src/NzbDrone.Common/Disk/NotParentException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Common.Disk { public class NotParentException : NzbDroneException { - public NotParentException(string message, params object[] args) : base(message, args) + public NotParentException(string message, params object[] args) + : base(message, args) { } - public NotParentException(string message) : base(message) + public NotParentException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Common/Disk/OsPath.cs b/src/NzbDrone.Common/Disk/OsPath.cs index 89bdb50735..02aaf65616 100644 --- a/src/NzbDrone.Common/Disk/OsPath.cs +++ b/src/NzbDrone.Common/Disk/OsPath.cs @@ -44,22 +44,36 @@ private static OsPathKind DetectPathKind(string path) { return OsPathKind.Unix; } + if (HasWindowsDriveLetter(path) || path.Contains('\\')) { return OsPathKind.Windows; } + if (path.Contains('/')) { return OsPathKind.Unix; } + return OsPathKind.Unknown; } private static bool HasWindowsDriveLetter(string path) { - if (path.Length < 2) return false; - if (!char.IsLetter(path[0]) || path[1] != ':') return false; - if (path.Length > 2 && path[2] != '\\' && path[2] != '/') return false; + if (path.Length < 2) + { + return false; + } + + if (!char.IsLetter(path[0]) || path[1] != ':') + { + return false; + } + + if (path.Length > 2 && path[2] != '\\' && path[2] != '/') + { + return false; + } return true; } @@ -93,6 +107,7 @@ public bool IsRooted { return _path.StartsWith(@"\\") || HasWindowsDriveLetter(_path); } + if (IsUnixPath) { return _path.StartsWith("/"); @@ -191,10 +206,12 @@ public override bool Equals(object obj) { return Equals((OsPath)obj); } + if (obj is string) { return Equals(new OsPath(obj as string)); } + return false; } @@ -212,6 +229,7 @@ public OsPath AsDirectory() case OsPathKind.Unix: return new OsPath(_path.TrimEnd('/') + "/", _kind); } + return this; } @@ -245,7 +263,10 @@ public bool Contains(OsPath other) public bool Equals(OsPath other) { - if (ReferenceEquals(other, null)) return false; + if (ReferenceEquals(other, null)) + { + return false; + } if (_path == other._path) { @@ -259,19 +280,26 @@ public bool Equals(OsPath other) { return string.Equals(left, right, StringComparison.InvariantCultureIgnoreCase); } + return string.Equals(left, right, StringComparison.InvariantCulture); } public static bool operator ==(OsPath left, OsPath right) { - if (ReferenceEquals(left, null)) return ReferenceEquals(right, null); + if (ReferenceEquals(left, null)) + { + return ReferenceEquals(right, null); + } return left.Equals(right); } public static bool operator !=(OsPath left, OsPath right) { - if (ReferenceEquals(left, null)) return !ReferenceEquals(right, null); + if (ReferenceEquals(left, null)) + { + return !ReferenceEquals(right, null); + } return !left.Equals(right); } @@ -297,10 +325,12 @@ public bool Equals(OsPath other) { return new OsPath(string.Join("\\", left._path.TrimEnd('\\'), right._path.TrimStart('\\')), OsPathKind.Windows); } + if (left.Kind == OsPathKind.Unix || right.Kind == OsPathKind.Unix) { return new OsPath(string.Join("/", left._path.TrimEnd('/'), right._path), OsPathKind.Unix); } + return new OsPath(string.Join("/", left._path, right._path), OsPathKind.Unknown); } @@ -356,6 +386,7 @@ public bool Equals(OsPath other) { return new OsPath(string.Join("\\", newFragments), OsPathKind.Unknown); } + return new OsPath(string.Join("/", newFragments), OsPathKind.Unknown); } } diff --git a/src/NzbDrone.Common/EnsureThat/EnsureBoolExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureBoolExtensions.cs index 9cfb14ceec..a393d556c3 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureBoolExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureBoolExtensions.cs @@ -9,7 +9,9 @@ public static class EnsureBoolExtensions public static Param IsTrue(this Param param) { if (!param.Value) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotTrue); + } return param; } @@ -18,7 +20,9 @@ public static Param IsTrue(this Param param) public static Param IsFalse(this Param param) { if (param.Value) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotFalse); + } return param; } diff --git a/src/NzbDrone.Common/EnsureThat/EnsureCollectionExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureCollectionExtensions.cs index 2e2fecdf60..cf0392487e 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureCollectionExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureCollectionExtensions.cs @@ -10,10 +10,13 @@ namespace NzbDrone.Common.EnsureThat public static class EnsureCollectionExtensions { [DebuggerStepThrough] - public static Param HasItems(this Param param) where T : class, ICollection + public static Param HasItems(this Param param) + where T : class, ICollection { if (param.Value == null || param.Value.Count < 1) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection); + } return param; } @@ -22,7 +25,9 @@ public static Param HasItems(this Param param) where T : class, ICollec public static Param> HasItems(this Param> param) { if (param.Value == null || param.Value.Count < 1) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection); + } return param; } @@ -31,7 +36,9 @@ public static Param> HasItems(this Param> param) public static Param> HasItems(this Param> param) { if (param.Value == null || !param.Value.Any()) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection); + } return param; } @@ -40,7 +47,9 @@ public static Param> HasItems(this Param> param public static Param HasItems(this Param param) { if (param.Value == null || param.Value.Length < 1) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection); + } return param; } @@ -49,17 +58,20 @@ public static Param HasItems(this Param param) public static Param> HasItems(this Param> param) { if (param.Value == null || param.Value.Count < 1) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection); + } return param; } - [DebuggerStepThrough] public static Param> HasItems(this Param> param) { if (param.Value == null || param.Value.Count < 1) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection); + } return param; } diff --git a/src/NzbDrone.Common/EnsureThat/EnsureDateTimeExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureDateTimeExtensions.cs index 5c78b23713..97d9f58ee4 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureDateTimeExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureDateTimeExtensions.cs @@ -7,14 +7,15 @@ namespace NzbDrone.Common.EnsureThat { public static class EnsureDateTimeExtensions { - private static readonly DateTime _minTime = new DateTime(1960, 1, 1); [DebuggerStepThrough] public static Param IsLt(this Param param, DateTime limit) { if (param.Value >= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit)); + } return param; } @@ -23,7 +24,9 @@ public static Param IsLt(this Param param, DateTime limit) public static Param IsLte(this Param param, DateTime limit) { if (!(param.Value <= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit)); + } return param; } @@ -32,7 +35,9 @@ public static Param IsLte(this Param param, DateTime limit) public static Param IsGt(this Param param, DateTime limit) { if (param.Value <= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit)); + } return param; } @@ -41,7 +46,9 @@ public static Param IsGt(this Param param, DateTime limit) public static Param IsGte(this Param param, DateTime limit) { if (!(param.Value >= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit)); + } return param; } @@ -50,10 +57,14 @@ public static Param IsGte(this Param param, DateTime limit) public static Param IsInRange(this Param param, DateTime min, DateTime max) { if (param.Value < min) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min)); + } if (param.Value > max) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max)); + } return param; } @@ -62,11 +73,13 @@ public static Param IsInRange(this Param param, DateTime min public static Param IsUtc(this Param param) { if (param.Value.Kind != DateTimeKind.Utc) + { throw ExceptionFactory.CreateForParamValidation(param.Name, "Excepted time to be in UTC but was [{0}]".Inject(param.Value.Kind)); + } + return param; } - [DebuggerStepThrough] public static Param IsValid(this Param param) { diff --git a/src/NzbDrone.Common/EnsureThat/EnsureDecimalExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureDecimalExtensions.cs index a36ba6697e..e1bf3ba6d9 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureDecimalExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureDecimalExtensions.cs @@ -10,7 +10,9 @@ public static class EnsureDecimalExtensions public static Param IsLt(this Param param, decimal limit) { if (param.Value >= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit)); + } return param; } @@ -19,7 +21,9 @@ public static Param IsLt(this Param param, decimal limit) public static Param IsLte(this Param param, decimal limit) { if (!(param.Value <= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit)); + } return param; } @@ -28,7 +32,9 @@ public static Param IsLte(this Param param, decimal limit) public static Param IsGt(this Param param, decimal limit) { if (param.Value <= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit)); + } return param; } @@ -37,7 +43,9 @@ public static Param IsGt(this Param param, decimal limit) public static Param IsGte(this Param param, decimal limit) { if (!(param.Value >= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit)); + } return param; } @@ -46,10 +54,14 @@ public static Param IsGte(this Param param, decimal limit) public static Param IsInRange(this Param param, decimal min, decimal max) { if (param.Value < min) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min)); + } if (param.Value > max) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max)); + } return param; } diff --git a/src/NzbDrone.Common/EnsureThat/EnsureDoubleExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureDoubleExtensions.cs index ea614f6676..d67abe5128 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureDoubleExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureDoubleExtensions.cs @@ -10,7 +10,9 @@ public static class EnsureDoubleExtensions public static Param IsLt(this Param param, double limit) { if (param.Value >= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit)); + } return param; } @@ -19,7 +21,9 @@ public static Param IsLt(this Param param, double limit) public static Param IsLte(this Param param, double limit) { if (!(param.Value <= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit)); + } return param; } @@ -28,7 +32,9 @@ public static Param IsLte(this Param param, double limit) public static Param IsGt(this Param param, double limit) { if (param.Value <= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit)); + } return param; } @@ -37,7 +43,9 @@ public static Param IsGt(this Param param, double limit) public static Param IsGte(this Param param, double limit) { if (!(param.Value >= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit)); + } return param; } @@ -46,10 +54,14 @@ public static Param IsGte(this Param param, double limit) public static Param IsInRange(this Param param, double min, double max) { if (param.Value < min) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min)); + } if (param.Value > max) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max)); + } return param; } diff --git a/src/NzbDrone.Common/EnsureThat/EnsureGuidExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureGuidExtensions.cs index 7f2b75442d..a9d6190b31 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureGuidExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureGuidExtensions.cs @@ -10,7 +10,9 @@ public static class EnsureGuidExtensions public static Param IsNotEmpty(this Param param) { if (Guid.Empty.Equals(param.Value)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyGuid); + } return param; } diff --git a/src/NzbDrone.Common/EnsureThat/EnsureIntExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureIntExtensions.cs index 5979ec040f..77ecaf6697 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureIntExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureIntExtensions.cs @@ -10,7 +10,9 @@ public static class EnsureIntExtensions public static Param IsLessThan(this Param param, int limit) { if (param.Value >= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit)); + } return param; } @@ -19,7 +21,9 @@ public static Param IsLessThan(this Param param, int limit) public static Param IsLessThanOrEqualTo(this Param param, int limit) { if (!(param.Value <= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit)); + } return param; } @@ -28,7 +32,9 @@ public static Param IsLessThanOrEqualTo(this Param param, int limit) public static Param IsGreaterThan(this Param param, int limit) { if (param.Value <= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit)); + } return param; } @@ -37,7 +43,9 @@ public static Param IsGreaterThan(this Param param, int limit) public static Param IsGreaterThanZero(this Param param) { if (param.Value <= 0) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, 0)); + } return param; } @@ -46,7 +54,9 @@ public static Param IsGreaterThanZero(this Param param) public static Param IsGreaterOrEqualTo(this Param param, int limit) { if (!(param.Value >= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit)); + } return param; } @@ -55,10 +65,14 @@ public static Param IsGreaterOrEqualTo(this Param param, int limit) public static Param IsInRange(this Param param, int min, int max) { if (param.Value < min) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min)); + } if (param.Value > max) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max)); + } return param; } diff --git a/src/NzbDrone.Common/EnsureThat/EnsureLongExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureLongExtensions.cs index ef0b401c38..568fefb5a9 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureLongExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureLongExtensions.cs @@ -10,7 +10,9 @@ public static class EnsureLongExtensions public static Param IsLt(this Param param, long limit) { if (param.Value >= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit)); + } return param; } @@ -19,7 +21,9 @@ public static Param IsLt(this Param param, long limit) public static Param IsLte(this Param param, long limit) { if (!(param.Value <= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit)); + } return param; } @@ -28,7 +32,9 @@ public static Param IsLte(this Param param, long limit) public static Param IsGt(this Param param, long limit) { if (param.Value <= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit)); + } return param; } @@ -37,7 +43,9 @@ public static Param IsGt(this Param param, long limit) public static Param IsGte(this Param param, long limit) { if (!(param.Value >= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit)); + } return param; } @@ -46,10 +54,14 @@ public static Param IsGte(this Param param, long limit) public static Param IsInRange(this Param param, long min, long max) { if (param.Value < min) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min)); + } if (param.Value > max) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max)); + } return param; } diff --git a/src/NzbDrone.Common/EnsureThat/EnsureNullableValueTypeExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureNullableValueTypeExtensions.cs index 67e4863b5c..3603da2575 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureNullableValueTypeExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureNullableValueTypeExtensions.cs @@ -6,10 +6,13 @@ namespace NzbDrone.Common.EnsureThat public static class EnsureNullableValueTypeExtensions { [DebuggerStepThrough] - public static Param IsNotNull(this Param param) where T : struct + public static Param IsNotNull(this Param param) + where T : struct { if (param.Value == null || !param.Value.HasValue) + { throw ExceptionFactory.CreateForParamNullValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNull); + } return param; } diff --git a/src/NzbDrone.Common/EnsureThat/EnsureObjectExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureObjectExtensions.cs index a676d142ae..7833d02e5a 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureObjectExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureObjectExtensions.cs @@ -6,10 +6,13 @@ namespace NzbDrone.Common.EnsureThat public static class EnsureObjectExtensions { [DebuggerStepThrough] - public static Param IsNotNull(this Param param) where T : class + public static Param IsNotNull(this Param param) + where T : class { if (param.Value == null) + { throw ExceptionFactory.CreateForParamNullValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNull); + } return param; } diff --git a/src/NzbDrone.Common/EnsureThat/EnsureShortExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureShortExtensions.cs index 629527545a..54f082b8f6 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureShortExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureShortExtensions.cs @@ -10,7 +10,9 @@ public static class EnsureShortExtensions public static Param IsLt(this Param param, short limit) { if (param.Value >= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit)); + } return param; } @@ -19,7 +21,9 @@ public static Param IsLt(this Param param, short limit) public static Param IsLte(this Param param, short limit) { if (!(param.Value <= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit)); + } return param; } @@ -28,7 +32,9 @@ public static Param IsLte(this Param param, short limit) public static Param IsGt(this Param param, short limit) { if (param.Value <= limit) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit)); + } return param; } @@ -37,7 +43,9 @@ public static Param IsGt(this Param param, short limit) public static Param IsGte(this Param param, short limit) { if (!(param.Value >= limit)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit)); + } return param; } @@ -46,10 +54,14 @@ public static Param IsGte(this Param param, short limit) public static Param IsInRange(this Param param, short min, short max) { if (param.Value < min) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min)); + } if (param.Value > max) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max)); + } return param; } diff --git a/src/NzbDrone.Common/EnsureThat/EnsureStringExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureStringExtensions.cs index 99f3486678..1c10c9f28f 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureStringExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureStringExtensions.cs @@ -13,7 +13,9 @@ public static class EnsureStringExtensions public static Param IsNotNullOrWhiteSpace(this Param param) { if (string.IsNullOrWhiteSpace(param.Value)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrWhiteSpace); + } return param; } @@ -22,7 +24,9 @@ public static Param IsNotNullOrWhiteSpace(this Param param) public static Param IsNotNullOrEmpty(this Param param) { if (string.IsNullOrEmpty(param.Value)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrEmpty); + } return param; } @@ -31,15 +35,21 @@ public static Param IsNotNullOrEmpty(this Param param) public static Param HasLengthBetween(this Param param, int minLength, int maxLength) { if (string.IsNullOrEmpty(param.Value)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrEmpty); + } var length = param.Value.Length; if (length < minLength) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToShort.Inject(minLength, maxLength, length)); + } if (length > maxLength) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLong.Inject(minLength, maxLength, length)); + } return param; } @@ -48,12 +58,16 @@ public static Param HasLengthBetween(this Param param, int minLe public static Param IsLongerThan(this Param param, int minLength) { if (string.IsNullOrEmpty(param.Value)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrEmpty); + } var length = param.Value.Length; if (length < minLength) + { throw ExceptionFactory.CreateForParamValidation(param.Name, "The string is not long enough. Must be at least '{0}' but was '{1}' characters long.".Inject(minLength, length)); + } return param; } @@ -71,6 +85,7 @@ public static Param Matches(this Param param, Regex match) { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_NoMatch.Inject(param.Value, match)); } + return param; } @@ -78,7 +93,9 @@ public static Param Matches(this Param param, Regex match) public static Param IsRelativePath(this Param param) { if (string.IsNullOrWhiteSpace(param.Value)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrWhiteSpace); + } if (!param.Value.EndsWith("\\")) { @@ -97,9 +114,14 @@ public static Param IsRelativePath(this Param param) public static Param IsValidPath(this Param param) { if (string.IsNullOrWhiteSpace(param.Value)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrWhiteSpace); + } - if (param.Value.IsPathValid()) return param; + if (param.Value.IsPathValid()) + { + return param; + } if (OsInfo.IsWindows) { diff --git a/src/NzbDrone.Common/EnsureThat/EnsureTypeExtensions.cs b/src/NzbDrone.Common/EnsureThat/EnsureTypeExtensions.cs index e84c243d96..00c1b4dc20 100644 --- a/src/NzbDrone.Common/EnsureThat/EnsureTypeExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/EnsureTypeExtensions.cs @@ -9,7 +9,7 @@ public static class EnsureTypeExtensions { private static class Types { - internal static readonly Type IntType = typeof (int); + internal static readonly Type IntType = typeof(int); internal static readonly Type ShortType = typeof(short); @@ -78,8 +78,10 @@ public static TypeParam IsString(this TypeParam param) public static TypeParam IsOfType(this TypeParam param, Type type) { if (!param.Type.Equals(type)) + { throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotOfType.Inject(param.Type.FullName)); + } return param; } diff --git a/src/NzbDrone.Common/EnsureThat/ExpressionExtensions.cs b/src/NzbDrone.Common/EnsureThat/ExpressionExtensions.cs index 838397f185..11e3598c59 100644 --- a/src/NzbDrone.Common/EnsureThat/ExpressionExtensions.cs +++ b/src/NzbDrone.Common/EnsureThat/ExpressionExtensions.cs @@ -10,7 +10,9 @@ internal static string ToPath(this MemberExpression e) var parent = e.Expression as MemberExpression; if (parent != null) + { path = parent.ToPath() + "."; + } return path + e.Member.Name; } @@ -23,17 +25,23 @@ internal static string GetPath(this Expression expression) private static MemberExpression GetRightMostMember(Expression e) { if (e is LambdaExpression) + { return GetRightMostMember(((LambdaExpression)e).Body); + } if (e is MemberExpression) + { return (MemberExpression)e; + } if (e is MethodCallExpression) { var callExpression = (MethodCallExpression)e; if (callExpression.Object is MethodCallExpression || callExpression.Object is MemberExpression) + { return GetRightMostMember(callExpression.Object); + } var member = callExpression.Arguments.Count > 0 ? callExpression.Arguments[0] : callExpression.Object; return GetRightMostMember(member); diff --git a/src/NzbDrone.Common/EnsureThat/Param.cs b/src/NzbDrone.Common/EnsureThat/Param.cs index 2149f74c2d..1eea2851da 100644 --- a/src/NzbDrone.Common/EnsureThat/Param.cs +++ b/src/NzbDrone.Common/EnsureThat/Param.cs @@ -16,7 +16,8 @@ public class Param : Param { public readonly T Value; - internal Param(string name, T value) : base(name) + internal Param(string name, T value) + : base(name) { Value = value; } diff --git a/src/NzbDrone.Common/EnsureThat/Resources/ExceptionMessages.Designer.cs b/src/NzbDrone.Common/EnsureThat/Resources/ExceptionMessages.Designer.cs index a165164783..ed59c9fbe3 100644 --- a/src/NzbDrone.Common/EnsureThat/Resources/ExceptionMessages.Designer.cs +++ b/src/NzbDrone.Common/EnsureThat/Resources/ExceptionMessages.Designer.cs @@ -8,7 +8,8 @@ // //------------------------------------------------------------------------------ -namespace NzbDrone.Common.EnsureThat.Resources { +namespace NzbDrone.Common.EnsureThat.Resources +{ /// /// A strongly-typed resource class, for looking up localized strings, etc. /// @@ -19,23 +20,28 @@ namespace NzbDrone.Common.EnsureThat.Resources { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class ExceptionMessages { + internal class ExceptionMessages + { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal ExceptionMessages() { + internal ExceptionMessages() + { } /// /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if (object.ReferenceEquals(resourceMan, null)) + { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("NzbDrone.Common.EnsureThat.Resources.ExceptionMessages", typeof(ExceptionMessages).Assembly); resourceMan = temp; } @@ -48,11 +54,14 @@ internal ExceptionMessages() { /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { + internal static global::System.Globalization.CultureInfo Culture + { + get + { return resourceCulture; } - set { + set + { resourceCulture = value; } } @@ -60,8 +69,10 @@ internal ExceptionMessages() { /// /// Looks up a localized string similar to Empty collection is not allowed.. /// - internal static string EnsureExtensions_IsEmptyCollection { - get { + internal static string EnsureExtensions_IsEmptyCollection + { + get + { return ResourceManager.GetString("EnsureExtensions_IsEmptyCollection", resourceCulture); } } @@ -69,8 +80,10 @@ internal static string EnsureExtensions_IsEmptyCollection { /// /// Looks up a localized string similar to Empty Guid is not allowed.. /// - internal static string EnsureExtensions_IsEmptyGuid { - get { + internal static string EnsureExtensions_IsEmptyGuid + { + get + { return ResourceManager.GetString("EnsureExtensions_IsEmptyGuid", resourceCulture); } } @@ -78,8 +91,10 @@ internal static string EnsureExtensions_IsEmptyGuid { /// /// Looks up a localized string similar to Expected an expression that evaluates to false.. /// - internal static string EnsureExtensions_IsNotFalse { - get { + internal static string EnsureExtensions_IsNotFalse + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotFalse", resourceCulture); } } @@ -87,8 +102,10 @@ internal static string EnsureExtensions_IsNotFalse { /// /// Looks up a localized string similar to value '{0}' is not greater than limit '{1}'.. /// - internal static string EnsureExtensions_IsNotGt { - get { + internal static string EnsureExtensions_IsNotGt + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotGt", resourceCulture); } } @@ -96,8 +113,10 @@ internal static string EnsureExtensions_IsNotGt { /// /// Looks up a localized string similar to value '{0}' is not greater than or equal to limit '{1}'.. /// - internal static string EnsureExtensions_IsNotGte { - get { + internal static string EnsureExtensions_IsNotGte + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotGte", resourceCulture); } } @@ -105,8 +124,10 @@ internal static string EnsureExtensions_IsNotGte { /// /// Looks up a localized string similar to value '{0}' is > max '{1}'.. /// - internal static string EnsureExtensions_IsNotInRange_ToHigh { - get { + internal static string EnsureExtensions_IsNotInRange_ToHigh + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotInRange_ToHigh", resourceCulture); } } @@ -114,8 +135,10 @@ internal static string EnsureExtensions_IsNotInRange_ToHigh { /// /// Looks up a localized string similar to The string is too long. Must be between '{0}' and '{1}'. Must be between '{0}' and '{1}' but was '{2}' characters long.. /// - internal static string EnsureExtensions_IsNotInRange_ToLong { - get { + internal static string EnsureExtensions_IsNotInRange_ToLong + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotInRange_ToLong", resourceCulture); } } @@ -123,8 +146,10 @@ internal static string EnsureExtensions_IsNotInRange_ToLong { /// /// Looks up a localized string similar to value '{0}' is < min '{1}'.. /// - internal static string EnsureExtensions_IsNotInRange_ToLow { - get { + internal static string EnsureExtensions_IsNotInRange_ToLow + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotInRange_ToLow", resourceCulture); } } @@ -132,8 +157,10 @@ internal static string EnsureExtensions_IsNotInRange_ToLow { /// /// Looks up a localized string similar to The string is not long enough. Must be between '{0}' and '{1}' but was '{2}' characters long.. /// - internal static string EnsureExtensions_IsNotInRange_ToShort { - get { + internal static string EnsureExtensions_IsNotInRange_ToShort + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotInRange_ToShort", resourceCulture); } } @@ -141,8 +168,10 @@ internal static string EnsureExtensions_IsNotInRange_ToShort { /// /// Looks up a localized string similar to value '{0}' is not lower than limit '{1}'.. /// - internal static string EnsureExtensions_IsNotLt { - get { + internal static string EnsureExtensions_IsNotLt + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotLt", resourceCulture); } } @@ -150,8 +179,10 @@ internal static string EnsureExtensions_IsNotLt { /// /// Looks up a localized string similar to value '{0}' is not lower than or equal to limit '{1}'.. /// - internal static string EnsureExtensions_IsNotLte { - get { + internal static string EnsureExtensions_IsNotLte + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotLte", resourceCulture); } } @@ -159,8 +190,10 @@ internal static string EnsureExtensions_IsNotLte { /// /// Looks up a localized string similar to Value can not be null.. /// - internal static string EnsureExtensions_IsNotNull { - get { + internal static string EnsureExtensions_IsNotNull + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotNull", resourceCulture); } } @@ -168,8 +201,10 @@ internal static string EnsureExtensions_IsNotNull { /// /// Looks up a localized string similar to The string can't be null or empty.. /// - internal static string EnsureExtensions_IsNotNullOrEmpty { - get { + internal static string EnsureExtensions_IsNotNullOrEmpty + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotNullOrEmpty", resourceCulture); } } @@ -177,8 +212,10 @@ internal static string EnsureExtensions_IsNotNullOrEmpty { /// /// Looks up a localized string similar to The string can't be left empty, null or consist of only whitespaces.. /// - internal static string EnsureExtensions_IsNotNullOrWhiteSpace { - get { + internal static string EnsureExtensions_IsNotNullOrWhiteSpace + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotNullOrWhiteSpace", resourceCulture); } } @@ -186,8 +223,10 @@ internal static string EnsureExtensions_IsNotNullOrWhiteSpace { /// /// Looks up a localized string similar to The param is not of expected type: '{0}'.. /// - internal static string EnsureExtensions_IsNotOfType { - get { + internal static string EnsureExtensions_IsNotOfType + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotOfType", resourceCulture); } } @@ -195,8 +234,10 @@ internal static string EnsureExtensions_IsNotOfType { /// /// Looks up a localized string similar to Expected an expression that evaluates to true.. /// - internal static string EnsureExtensions_IsNotTrue { - get { + internal static string EnsureExtensions_IsNotTrue + { + get + { return ResourceManager.GetString("EnsureExtensions_IsNotTrue", resourceCulture); } } @@ -204,8 +245,10 @@ internal static string EnsureExtensions_IsNotTrue { /// /// Looks up a localized string similar to value '{0}' does not match '{1}'. /// - internal static string EnsureExtensions_NoMatch { - get { + internal static string EnsureExtensions_NoMatch + { + get + { return ResourceManager.GetString("EnsureExtensions_NoMatch", resourceCulture); } } @@ -213,8 +256,10 @@ internal static string EnsureExtensions_NoMatch { /// /// Looks up a localized string similar to No MemberExpression found in expression: '{0}'.. /// - internal static string ExpressionUtils_GetRightMostMember_NoMemberFound { - get { + internal static string ExpressionUtils_GetRightMostMember_NoMemberFound + { + get + { return ResourceManager.GetString("ExpressionUtils_GetRightMostMember_NoMemberFound", resourceCulture); } } diff --git a/src/NzbDrone.Common/EnvironmentInfo/AppFolderFactory.cs b/src/NzbDrone.Common/EnvironmentInfo/AppFolderFactory.cs index 591d029cec..3b66c02f80 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/AppFolderFactory.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/AppFolderFactory.cs @@ -48,7 +48,6 @@ public void Register() throw new RadarrStartupException("Cannot create AppFolder, Access to the path {0} is denied", _appFolderInfo.AppDataFolder); } - if (OsInfo.IsWindows) { SetPermissions(); @@ -82,8 +81,15 @@ private void MigrateAppDataFolder() if (_startupContext.Args.ContainsKey(StartupContext.APPDATA)) { - if (_diskProvider.FileExists(_appFolderInfo.GetDatabase())) return; - if (!_diskProvider.FileExists(oldDbFile)) return; + if (_diskProvider.FileExists(_appFolderInfo.GetDatabase())) + { + return; + } + + if (!_diskProvider.FileExists(oldDbFile)) + { + return; + } _diskProvider.MoveFile(oldDbFile, _appFolderInfo.GetDatabase()); CleanupSqLiteRollbackFiles(); @@ -91,7 +97,10 @@ private void MigrateAppDataFolder() } // Exit if a radarr.db already exists - if (_diskProvider.FileExists(_appFolderInfo.GetDatabase())) return; + if (_diskProvider.FileExists(_appFolderInfo.GetDatabase())) + { + return; + } // Rename the DB file if (_diskProvider.FileExists(oldDbFile)) @@ -112,10 +121,12 @@ private void MigrateAppDataFolder() } } - private void InitializeMonoApplicationData() { - if (OsInfo.IsWindows) return; + if (OsInfo.IsWindows) + { + return; + } try { @@ -125,7 +136,7 @@ private void InitializeMonoApplicationData() var configHome = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData, Environment.SpecialFolderOption.DoNotVerify); if (configHome.IsNullOrWhiteSpace() || configHome == "/.config" || - configHome.EndsWith("/.config") && !_diskProvider.FolderExists(configHome.GetParentPath()) || + (configHome.EndsWith("/.config") && !_diskProvider.FolderExists(configHome.GetParentPath())) || !_diskProvider.FolderExists(configHome)) { // Tell mono/netcore to use appData/.config as ApplicationData folder. @@ -135,7 +146,7 @@ private void InitializeMonoApplicationData() var dataHome = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify); if (dataHome.IsNullOrWhiteSpace() || dataHome == "/.local/share" || - dataHome.EndsWith("/.local/share") && !_diskProvider.FolderExists(dataHome.GetParentPath().GetParentPath()) || + (dataHome.EndsWith("/.local/share") && !_diskProvider.FolderExists(dataHome.GetParentPath().GetParentPath())) || !_diskProvider.FolderExists(dataHome)) { // Tell mono/netcore to use appData/.config/share as LocalApplicationData folder. diff --git a/src/NzbDrone.Common/EnvironmentInfo/AppFolderInfo.cs b/src/NzbDrone.Common/EnvironmentInfo/AppFolderInfo.cs index f03aaf59d5..dbbd9e5090 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/AppFolderInfo.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/AppFolderInfo.cs @@ -15,7 +15,7 @@ public interface IAppFolderInfo public class AppFolderInfo : IAppFolderInfo { - private readonly Environment.SpecialFolder DATA_SPECIAL_FOLDER = Environment.SpecialFolder.CommonApplicationData; + private readonly Environment.SpecialFolder _dataSpecialFolder = Environment.SpecialFolder.CommonApplicationData; private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(AppFolderInfo)); @@ -23,7 +23,7 @@ public AppFolderInfo(IStartupContext startupContext) { if (OsInfo.IsNotWindows) { - DATA_SPECIAL_FOLDER = Environment.SpecialFolder.ApplicationData; + _dataSpecialFolder = Environment.SpecialFolder.ApplicationData; } if (startupContext.Args.ContainsKey(StartupContext.APPDATA)) @@ -33,7 +33,7 @@ public AppFolderInfo(IStartupContext startupContext) } else { - AppDataFolder = Path.Combine(Environment.GetFolderPath(DATA_SPECIAL_FOLDER, Environment.SpecialFolderOption.DoNotVerify), "Radarr"); + AppDataFolder = Path.Combine(Environment.GetFolderPath(_dataSpecialFolder, Environment.SpecialFolderOption.DoNotVerify), "Radarr"); } StartUpFolder = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName; diff --git a/src/NzbDrone.Common/EnvironmentInfo/BuildInfo.cs b/src/NzbDrone.Common/EnvironmentInfo/BuildInfo.cs index c9ba57bb0a..1e87ba077b 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/BuildInfo.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/BuildInfo.cs @@ -29,7 +29,7 @@ static BuildInfo() public static string AppName { get; } = "Radarr"; public static Version Version { get; } - public static String Branch { get; } + public static string Branch { get; } public static string Release { get; } public static DateTime BuildDateTime diff --git a/src/NzbDrone.Common/EnvironmentInfo/IOsVersionAdapter.cs b/src/NzbDrone.Common/EnvironmentInfo/IOsVersionAdapter.cs index 25a3cbf1fc..b844a29c2c 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/IOsVersionAdapter.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/IOsVersionAdapter.cs @@ -1,6 +1,5 @@ namespace NzbDrone.Common.EnvironmentInfo { - public interface IOsVersionAdapter { bool Enabled { get; } diff --git a/src/NzbDrone.Common/EnvironmentInfo/OsInfo.cs b/src/NzbDrone.Common/EnvironmentInfo/OsInfo.cs index f109d304c4..fddfdf00bb 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/OsInfo.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/OsInfo.cs @@ -33,14 +33,14 @@ static OsInfo() Os = Os.Windows; break; } + case PlatformID.MacOSX: case PlatformID.Unix: { // Sometimes Mac OS reports itself as Unix if (Directory.Exists("/System/Library/CoreServices/") && (File.Exists("/System/Library/CoreServices/SystemVersion.plist") || - File.Exists("/System/Library/CoreServices/ServerVersion.plist")) - ) + File.Exists("/System/Library/CoreServices/ServerVersion.plist"))) { Os = Os.Osx; } @@ -48,6 +48,7 @@ static OsInfo() { Os = Os.Linux; } + break; } } diff --git a/src/NzbDrone.Common/EnvironmentInfo/OsVersionModel.cs b/src/NzbDrone.Common/EnvironmentInfo/OsVersionModel.cs index c20865813d..f5e8074fc3 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/OsVersionModel.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/OsVersionModel.cs @@ -2,8 +2,6 @@ namespace NzbDrone.Common.EnvironmentInfo { public class OsVersionModel { - - public OsVersionModel(string name, string version, string fullName = null) { Name = Trim(name); diff --git a/src/NzbDrone.Common/EnvironmentInfo/PlatformInfo.cs b/src/NzbDrone.Common/EnvironmentInfo/PlatformInfo.cs index f13d6bbc30..0a0ac17c96 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/PlatformInfo.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/PlatformInfo.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Common.EnvironmentInfo { - public enum PlatformType { DotNet = 0, @@ -122,38 +121,47 @@ private static Version GetDotNetVersion() { return new Version(4, 8, 0); } + if (releaseKey >= 461808) { return new Version(4, 7, 2); } + if (releaseKey >= 461308) { return new Version(4, 7, 1); } + if (releaseKey >= 460798) { return new Version(4, 7); } + if (releaseKey >= 394802) { return new Version(4, 6, 2); } + if (releaseKey >= 394254) { return new Version(4, 6, 1); } + if (releaseKey >= 393295) { return new Version(4, 6); } + if (releaseKey >= 379893) { return new Version(4, 5, 2); } + if (releaseKey >= 378675) { return new Version(4, 5, 1); } + if (releaseKey >= 378389) { return new Version(4, 5); diff --git a/src/NzbDrone.Common/EnvironmentInfo/RuntimeInfo.cs b/src/NzbDrone.Common/EnvironmentInfo/RuntimeInfo.cs index 91b62da302..51141ddec3 100644 --- a/src/NzbDrone.Common/EnvironmentInfo/RuntimeInfo.cs +++ b/src/NzbDrone.Common/EnvironmentInfo/RuntimeInfo.cs @@ -131,46 +131,83 @@ public RuntimeMode Mode public static bool IsProduction { get; } public static bool IsDevelopment { get; } - private static bool InternalIsTesting() { try { var lowerProcessName = Process.GetCurrentProcess().ProcessName.ToLower(); - if (lowerProcessName.Contains("vshost")) return true; - if (lowerProcessName.Contains("nunit")) return true; - if (lowerProcessName.Contains("jetbrain")) return true; - if (lowerProcessName.Contains("resharper")) return true; + if (lowerProcessName.Contains("vshost")) + { + return true; + } + + if (lowerProcessName.Contains("nunit")) + { + return true; + } + + if (lowerProcessName.Contains("jetbrain")) + { + return true; + } + + if (lowerProcessName.Contains("resharper")) + { + return true; + } } catch { - } try { var currentAssemblyLocation = typeof(RuntimeInfo).Assembly.Location; - if (currentAssemblyLocation.ToLower().Contains("_output")) return true; - if (currentAssemblyLocation.ToLower().Contains("_tests")) return true; + if (currentAssemblyLocation.ToLower().Contains("_output")) + { + return true; + } + + if (currentAssemblyLocation.ToLower().Contains("_tests")) + { + return true; + } } catch { - } var lowerCurrentDir = Directory.GetCurrentDirectory().ToLower(); - if (lowerCurrentDir.Contains("vsts")) return true; - if (lowerCurrentDir.Contains("buildagent")) return true; - if (lowerCurrentDir.Contains("_output")) return true; - if (lowerCurrentDir.Contains("_tests")) return true; + if (lowerCurrentDir.Contains("vsts")) + { + return true; + } + + if (lowerCurrentDir.Contains("buildagent")) + { + return true; + } + + if (lowerCurrentDir.Contains("_output")) + { + return true; + } + + if (lowerCurrentDir.Contains("_tests")) + { + return true; + } return false; } private static bool InternalIsDebug() { - if (BuildInfo.IsDebug || Debugger.IsAttached) return true; + if (BuildInfo.IsDebug || Debugger.IsAttached) + { + return true; + } return false; } @@ -178,7 +215,10 @@ private static bool InternalIsDebug() private static bool InternalIsOfficialBuild() { //Official builds will never have such a high revision - if (BuildInfo.Version.Major >= 10 || BuildInfo.Version.Revision > 10000) return false; + if (BuildInfo.Version.Major >= 10 || BuildInfo.Version.Revision > 10000) + { + return false; + } return true; } diff --git a/src/NzbDrone.Common/Exceptions/NotParentException.cs b/src/NzbDrone.Common/Exceptions/NotParentException.cs index d9b78247e0..59c4d1ea44 100644 --- a/src/NzbDrone.Common/Exceptions/NotParentException.cs +++ b/src/NzbDrone.Common/Exceptions/NotParentException.cs @@ -2,11 +2,13 @@ { public class NotParentException : NzbDroneException { - public NotParentException(string message, params object[] args) : base(message, args) + public NotParentException(string message, params object[] args) + : base(message, args) { } - public NotParentException(string message) : base(message) + public NotParentException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Common/Exceptions/NzbDroneException.cs b/src/NzbDrone.Common/Exceptions/NzbDroneException.cs index 7e0be7312d..015ffc0b56 100644 --- a/src/NzbDrone.Common/Exceptions/NzbDroneException.cs +++ b/src/NzbDrone.Common/Exceptions/NzbDroneException.cs @@ -7,19 +7,16 @@ public abstract class NzbDroneException : ApplicationException protected NzbDroneException(string message, params object[] args) : base(string.Format(message, args)) { - } protected NzbDroneException(string message) : base(message) { - } protected NzbDroneException(string message, Exception innerException, params object[] args) : base(string.Format(message, args), innerException) { - } protected NzbDroneException(string message, Exception innerException) diff --git a/src/NzbDrone.Common/Expansive/Expansive.cs b/src/NzbDrone.Common/Expansive/Expansive.cs index 8aad9545ea..f6a2ff3c5a 100644 --- a/src/NzbDrone.Common/Expansive/Expansive.cs +++ b/src/NzbDrone.Common/Expansive/Expansive.cs @@ -11,7 +11,6 @@ public static class Expansive { private static PatternStyle _patternStyle; - public static bool RequireAllExpansions { get; set; } public static Func DefaultExpansionFactory { get; set; } @@ -26,7 +25,6 @@ public static string Expand(this string source) return source.Expand(DefaultExpansionFactory); } - public static string Expand(this string source, params string[] args) { var output = source; @@ -50,9 +48,11 @@ public static string Expand(this string source, params string[] args) { tokenIndex = tokens.IndexOf(token); } + output = Regex.Replace(output, _patternStyle.OutputFilter(match.Value), "{" + tokenIndex + "}"); } } + var newArgs = new List(); foreach (var arg in args) { @@ -63,15 +63,20 @@ public static string Expand(this string source, params string[] args) foreach (Match match in tokenPattern.Matches(newArg)) { var token = _patternStyle.TokenReplaceFilter(match.Value); - if (calls.Contains(string.Format("{0}:{1}", callingToken, token))) throw new CircularReferenceException(string.Format("Circular Reference Detected for token '{0}'.", callingToken)); + if (calls.Contains(string.Format("{0}:{1}", callingToken, token))) + { + throw new CircularReferenceException(string.Format("Circular Reference Detected for token '{0}'.", callingToken)); + } + calls.Push(string.Format("{0}:{1}", callingToken, token)); callingToken = token; newArg = Regex.Replace(newArg, _patternStyle.OutputFilter(match.Value), args[tokens.IndexOf(token)]); } - } + newArgs.Add(newArg); } + return string.Format(output, newArgs.ToArray()); } @@ -80,9 +85,6 @@ public static string Expand(this string source, Func expansionFa return source.ExpandInternal(expansionFactory); } - - - public static string Expand(this string source, object model) { return source.ExpandInternal( @@ -106,17 +108,20 @@ public static string Expand(this string source, object model) private static void Initialize() { _patternStyle = new PatternStyle - { - TokenMatchPattern = @"\{[a-zA-Z]\w*\}", - TokenReplaceFilter = token => token.Replace("{", "").Replace("}", ""), - OutputFilter = output => (output.StartsWith("{") && output.EndsWith("}") ? output : @"\{" + output + @"\}"), - TokenFilter = tokens => "{(" + tokens + ")}" - }; + { + TokenMatchPattern = @"\{[a-zA-Z]\w*\}", + TokenReplaceFilter = token => token.Replace("{", "").Replace("}", ""), + OutputFilter = output => (output.StartsWith("{") && output.EndsWith("}") ? output : @"\{" + output + @"\}"), + TokenFilter = tokens => "{(" + tokens + ")}" + }; } private static string ExpandInternal(this string source, Func expansionFactory) { - if (expansionFactory == null) throw new ApplicationException("ExpansionFactory not defined.\nDefine a DefaultExpansionFactory or call Expand(source, Func expansionFactory))"); + if (expansionFactory == null) + { + throw new ApplicationException("ExpansionFactory not defined.\nDefine a DefaultExpansionFactory or call Expand(source, Func expansionFactory))"); + } var pattern = new Regex(_patternStyle.TokenMatchPattern, RegexOptions.IgnoreCase); @@ -139,9 +144,12 @@ private static string Explode(this string source, Regex pattern, PatternStyle pa // if we have already encountered this token in this call tree, we have a circular reference if (thisNode.CallTree.Contains(token)) + { throw new CircularReferenceException(string.Format("Circular Reference Detected for token '{0}'. Call Tree: {1}->{2}", token, - string.Join("->", thisNode.CallTree.ToArray().Reverse()), token)); + string.Join("->", thisNode.CallTree.ToArray().Reverse()), + token)); + } // expand this match var expandedValue = expansionFactory(token); @@ -156,6 +164,7 @@ private static string Explode(this string source, Regex pattern, PatternStyle pa output = Regex.Replace(output, patternStyle.OutputFilter(match.Value), child); } } + return output; } @@ -171,7 +180,11 @@ private static dynamic ToExpando(this object o) { var result = new ExpandoObject(); var d = result as IDictionary; //work with the Expando as a Dictionary - if (o is ExpandoObject) return o; //shouldn't have to... but just in case + if (o is ExpandoObject) + { + return o; //shouldn't have to... but just in case + } + if (o is NameValueCollection || o.GetType().IsSubclassOf(typeof(NameValueCollection))) { var nv = (NameValueCollection)o; @@ -185,8 +198,10 @@ private static dynamic ToExpando(this object o) d.Add(item.Name, item.GetValue(o, null)); } } + return result; } + /// /// Turns the object into a Dictionary /// diff --git a/src/NzbDrone.Common/Expansive/TreeNode.cs b/src/NzbDrone.Common/Expansive/TreeNode.cs index 206836db53..4a61fa08e0 100644 --- a/src/NzbDrone.Common/Expansive/TreeNode.cs +++ b/src/NzbDrone.Common/Expansive/TreeNode.cs @@ -7,25 +7,29 @@ internal class TreeNode private List _CallTree; private TreeNode _Parent; - public TreeNode(T Value) + public TreeNode(T value) { - this.Value = Value; + Value = value; Parent = null; Children = new TreeNodeList(this); _CallTree = new List(); } - public TreeNode(T Value, TreeNode Parent) + public TreeNode(T value, TreeNode parent) { - this.Value = Value; - this.Parent = Parent; + Value = value; + Parent = parent; Children = new TreeNodeList(this); _CallTree = new List(); } public TreeNode Parent { - get { return _Parent; } + get + { + return _Parent; + } + set { if (value == _Parent) @@ -52,12 +56,12 @@ public TreeNode Root get { //return (Parent == null) ? this : Parent.Root; - TreeNode node = this; while (node.Parent != null) { node = node.Parent; } + return node; } } @@ -75,9 +79,10 @@ public List CallTree node = node.Parent; _CallTree.Add(node.Value); } + return _CallTree; } - private set { _CallTree = value; } + private set => _CallTree = value; } public T Value { get; set; } diff --git a/src/NzbDrone.Common/Expansive/TreeNodeList.cs b/src/NzbDrone.Common/Expansive/TreeNodeList.cs index 74bfd189ff..a239a3b157 100644 --- a/src/NzbDrone.Common/Expansive/TreeNodeList.cs +++ b/src/NzbDrone.Common/Expansive/TreeNodeList.cs @@ -6,24 +6,23 @@ internal class TreeNodeList : List> { public TreeNode Parent; - public TreeNodeList(TreeNode Parent) + public TreeNodeList(TreeNode parent) { - this.Parent = Parent; + Parent = parent; } - public new TreeNode Add(TreeNode Node) + public new TreeNode Add(TreeNode node) { - base.Add(Node); - Node.Parent = Parent; - return Node; + base.Add(node); + node.Parent = Parent; + return node; } - public TreeNode Add(T Value) + public TreeNode Add(T value) { - return Add(new TreeNode(Value)); + return Add(new TreeNode(value)); } - public override string ToString() { return "Count=" + Count.ToString(); diff --git a/src/NzbDrone.Common/Extensions/DictionaryExtensions.cs b/src/NzbDrone.Common/Extensions/DictionaryExtensions.cs index 59933243d3..aa29245e3d 100644 --- a/src/NzbDrone.Common/Extensions/DictionaryExtensions.cs +++ b/src/NzbDrone.Common/Extensions/DictionaryExtensions.cs @@ -16,8 +16,15 @@ public static class DictionaryExtensions public static Dictionary Merge(this Dictionary first, Dictionary second) { - if (first == null) throw new ArgumentNullException("first"); - if (second == null) throw new ArgumentNullException("second"); + if (first == null) + { + throw new ArgumentNullException("first"); + } + + if (second == null) + { + throw new ArgumentNullException("second"); + } var merged = new Dictionary(); first.ToList().ForEach(kv => merged[kv.Key] = kv.Value); diff --git a/src/NzbDrone.Common/Extensions/ExceptionExtensions.cs b/src/NzbDrone.Common/Extensions/ExceptionExtensions.cs index 8bcaea4e83..eb1bd3e216 100644 --- a/src/NzbDrone.Common/Extensions/ExceptionExtensions.cs +++ b/src/NzbDrone.Common/Extensions/ExceptionExtensions.cs @@ -4,30 +4,37 @@ namespace NzbDrone.Common.Extensions { public static class ExceptionExtensions { - public static T WithData(this T ex, string key, string value) where T : Exception + public static T WithData(this T ex, string key, string value) + where T : Exception { ex.AddData(key, value); return ex; } - public static T WithData(this T ex, string key, int value) where T : Exception + + public static T WithData(this T ex, string key, int value) + where T : Exception { ex.AddData(key, value.ToString()); return ex; } - public static T WithData(this T ex, string key, Http.HttpUri value) where T : Exception + public static T WithData(this T ex, string key, Http.HttpUri value) + where T : Exception { ex.AddData(key, value.ToString()); return ex; } - - public static T WithData(this T ex, Http.HttpResponse response, int maxSampleLength = 512) where T : Exception + public static T WithData(this T ex, Http.HttpResponse response, int maxSampleLength = 512) + where T : Exception { - if (response == null || response.Content == null) return ex; + if (response == null || response.Content == null) + { + return ex; + } var contentSample = response.Content.Substring(0, Math.Min(response.Content.Length, maxSampleLength)); @@ -47,16 +54,19 @@ public static T WithData(this T ex, Http.HttpResponse response, int maxSample { ex.AddData("ContentType", response.Headers.ContentType ?? string.Empty); } + ex.AddData("ContentLength", response.Content.Length.ToString()); ex.AddData("ContentSample", contentSample); return ex; } - private static void AddData(this Exception ex, string key, string value) { - if (value.IsNullOrWhiteSpace()) return; + if (value.IsNullOrWhiteSpace()) + { + return; + } ex.Data[key] = value; } diff --git a/src/NzbDrone.Common/Extensions/IEnumerableExtensions.cs b/src/NzbDrone.Common/Extensions/IEnumerableExtensions.cs index b06b6d736f..627bfd583a 100644 --- a/src/NzbDrone.Common/Extensions/IEnumerableExtensions.cs +++ b/src/NzbDrone.Common/Extensions/IEnumerableExtensions.cs @@ -13,8 +13,10 @@ public static IEnumerable DistinctBy(this IEnumerable knownKeys.Add(keySelector(element))); } - public static IEnumerable IntersectBy(this IEnumerable first, Func firstKeySelector, - IEnumerable second, Func secondKeySelector, + public static IEnumerable IntersectBy(this IEnumerable first, + Func firstKeySelector, + IEnumerable second, + Func secondKeySelector, IEqualityComparer keyComparer) { var keys = new HashSet(second.Select(secondKeySelector), keyComparer); @@ -31,9 +33,11 @@ public static IEnumerable IntersectBy(this IEnume } } - public static IEnumerable ExceptBy(this IEnumerable first, Func firstKeySelector, - IEnumerable second, Func secondKeySelector, - IEqualityComparer keyComparer) + public static IEnumerable ExceptBy(this IEnumerable first, + Func firstKeySelector, + IEnumerable second, + Func secondKeySelector, + IEqualityComparer keyComparer) { var keys = new HashSet(second.Select(secondKeySelector), keyComparer); var matchedKeys = new HashSet(); @@ -62,6 +66,7 @@ public static Dictionary ToDictionaryIgnoreDuplicates( result[key] = item; } } + return result; } @@ -76,6 +81,7 @@ public static Dictionary ToDictionaryIgnoreDuplicates SelectList(this IEnumerable DropLast(this IEnumerable source, int n) { if (source == null) + { throw new ArgumentNullException("source"); + } if (n < 0) + { throw new ArgumentOutOfRangeException("n", "Argument n should be non-negative."); + } return InternalDropLast(source, n); } @@ -130,9 +140,12 @@ private static IEnumerable InternalDropLast(IEnumerable source, int n) buffer.Enqueue(x); if (buffer.Count == n + 1) + { yield return buffer.Dequeue(); + } } } + public static bool In(this T source, List list) { return list.Contains(source); diff --git a/src/NzbDrone.Common/Extensions/Int64Extensions.cs b/src/NzbDrone.Common/Extensions/Int64Extensions.cs index 911e3b2965..bfca7f66cf 100644 --- a/src/NzbDrone.Common/Extensions/Int64Extensions.cs +++ b/src/NzbDrone.Common/Extensions/Int64Extensions.cs @@ -11,8 +11,15 @@ public static string SizeSuffix(this long bytes) { const int bytesInKb = 1024; - if (bytes < 0) return "-" + SizeSuffix(-bytes); - if (bytes == 0) return "0 B"; + if (bytes < 0) + { + return "-" + SizeSuffix(-bytes); + } + + if (bytes == 0) + { + return "0 B"; + } var mag = (int)Math.Log(bytes, bytesInKb); var adjustedSize = bytes / (decimal)Math.Pow(bytesInKb, mag); diff --git a/src/NzbDrone.Common/Extensions/LevenstheinExtensions.cs b/src/NzbDrone.Common/Extensions/LevenstheinExtensions.cs index 9c3ba16536..8255254571 100644 --- a/src/NzbDrone.Common/Extensions/LevenstheinExtensions.cs +++ b/src/NzbDrone.Common/Extensions/LevenstheinExtensions.cs @@ -6,9 +6,20 @@ public static class LevenstheinExtensions { public static int LevenshteinDistance(this string text, string other, int costInsert = 1, int costDelete = 1, int costSubstitute = 1) { - if (text == other) return 0; - if (text.Length == 0) return other.Length * costInsert; - if (other.Length == 0) return text.Length * costDelete; + if (text == other) + { + return 0; + } + + if (text.Length == 0) + { + return other.Length * costInsert; + } + + if (other.Length == 0) + { + return text.Length * costDelete; + } int[] matrix = new int[other.Length + 1]; diff --git a/src/NzbDrone.Common/Extensions/ObjectExtensions.cs b/src/NzbDrone.Common/Extensions/ObjectExtensions.cs index 3937cf7333..5182465e57 100644 --- a/src/NzbDrone.Common/Extensions/ObjectExtensions.cs +++ b/src/NzbDrone.Common/Extensions/ObjectExtensions.cs @@ -4,7 +4,8 @@ namespace NzbDrone.Common.Extensions { public static class ObjectExtensions { - public static T JsonClone(this T source) where T : new() + public static T JsonClone(this T source) + where T : new() { var json = source.ToJson(); return Json.Deserialize(json); diff --git a/src/NzbDrone.Common/Extensions/PathExtensions.cs b/src/NzbDrone.Common/Extensions/PathExtensions.cs index 9f8c7cf773..4820f5dc81 100644 --- a/src/NzbDrone.Common/Extensions/PathExtensions.cs +++ b/src/NzbDrone.Common/Extensions/PathExtensions.cs @@ -33,7 +33,8 @@ public static string CleanFilePath(this string path) var info = new FileInfo(path.Trim()); - if (OsInfo.IsWindows && info.FullName.StartsWith(@"\\")) //UNC + //UNC + if (OsInfo.IsWindows && info.FullName.StartsWith(@"\\")) { return info.FullName.TrimEnd('/', '\\', ' '); } @@ -53,7 +54,11 @@ public static bool PathEquals(this string firstPath, string secondPath, StringCo comparison = DiskProviderBase.PathStringComparison; } - if (firstPath.Equals(secondPath, comparison.Value)) return true; + if (firstPath.Equals(secondPath, comparison.Value)) + { + return true; + } + return string.Equals(firstPath.CleanFilePath(), secondPath.CleanFilePath(), comparison.Value); } @@ -96,6 +101,7 @@ public static bool IsParentPath(this string parentPath, string childPath) { parentPath = parentPath.TrimEnd(Path.DirectorySeparatorChar); } + if (childPath != "/" && !parentPath.EndsWith(":\\")) { childPath = childPath.TrimEnd(Path.DirectorySeparatorChar); diff --git a/src/NzbDrone.Common/Extensions/StreamExtensions.cs b/src/NzbDrone.Common/Extensions/StreamExtensions.cs index 6283f5fc09..8f6036baa1 100644 --- a/src/NzbDrone.Common/Extensions/StreamExtensions.cs +++ b/src/NzbDrone.Common/Extensions/StreamExtensions.cs @@ -14,6 +14,7 @@ public static byte[] ToBytes(this Stream input) { ms.Write(buffer, 0, read); } + return ms.ToArray(); } } diff --git a/src/NzbDrone.Common/Extensions/StringExtensions.cs b/src/NzbDrone.Common/Extensions/StringExtensions.cs index b7d0586570..246dc05618 100644 --- a/src/NzbDrone.Common/Extensions/StringExtensions.cs +++ b/src/NzbDrone.Common/Extensions/StringExtensions.cs @@ -18,7 +18,11 @@ public static string NullSafe(this string target) public static object NullSafe(this object target) { - if (target != null) return target; + if (target != null) + { + return target; + } + return "[NULL]"; } @@ -76,7 +80,9 @@ public static string RemoveAccent(this string text) public static string TrimEnd(this string text, string postfix) { if (text.EndsWith(postfix)) + { text = text.Substring(0, text.Length - postfix.Length); + } return text; } @@ -134,7 +140,7 @@ public static string WrapInQuotes(this string text) public static byte[] HexToByteArray(this string input) { return Enumerable.Range(0, input.Length) - .Where(x => x%2 == 0) + .Where(x => x % 2 == 0) .Select(x => Convert.ToByte(input.Substring(x, 2), 16)) .ToArray(); } @@ -151,9 +157,9 @@ public static string FromOctalString(this string octalValue) var first = int.Parse(octalValue.Substring(0, 1)); var second = int.Parse(octalValue.Substring(1, 1)); var third = int.Parse(octalValue.Substring(2, 1)); - var byteResult = (byte)((first << 6) | (second << 3) | (third)); + var byteResult = (byte)((first << 6) | (second << 3) | third); - return Encoding.ASCII.GetString(new [] { byteResult }); + return Encoding.ASCII.GetString(new[] { byteResult }); } public static string SplitCamelCase(this string input) diff --git a/src/NzbDrone.Common/Extensions/UrlExtensions.cs b/src/NzbDrone.Common/Extensions/UrlExtensions.cs index 50e0b9856e..e44843838d 100644 --- a/src/NzbDrone.Common/Extensions/UrlExtensions.cs +++ b/src/NzbDrone.Common/Extensions/UrlExtensions.cs @@ -28,7 +28,6 @@ public static bool IsValidUrl(this string path) } return true; - } } } diff --git a/src/NzbDrone.Common/HashUtil.cs b/src/NzbDrone.Common/HashUtil.cs index d43c7280c6..a60349271f 100644 --- a/src/NzbDrone.Common/HashUtil.cs +++ b/src/NzbDrone.Common/HashUtil.cs @@ -11,7 +11,7 @@ public static string CalculateCrc(string input) byte[] bytes = Encoding.UTF8.GetBytes(input); foreach (byte myByte in bytes) { - mCrc ^= ((uint)(myByte) << 24); + mCrc ^= (uint)myByte << 24; for (var i = 0; i < 8; i++) { if ((Convert.ToUInt32(mCrc) & 0x80000000) == 0x80000000) @@ -24,6 +24,7 @@ public static string CalculateCrc(string input) } } } + return $"{mCrc:x8}"; } diff --git a/src/NzbDrone.Common/Http/Dispatchers/ManagedHttpDispatcher.cs b/src/NzbDrone.Common/Http/Dispatchers/ManagedHttpDispatcher.cs index 4548d3df0e..96762f120c 100644 --- a/src/NzbDrone.Common/Http/Dispatchers/ManagedHttpDispatcher.cs +++ b/src/NzbDrone.Common/Http/Dispatchers/ManagedHttpDispatcher.cs @@ -218,6 +218,7 @@ private void AbortWebRequest(HttpWebRequest webRequest) { var responseStreamInfo = currentOperation.GetType().GetField("responseStream", BindingFlags.NonPublic | BindingFlags.Instance); var responseStream = responseStreamInfo.GetValue(currentOperation) as Stream; + // Note that responseStream will likely be null once mono fixes it. responseStream?.Dispose(); } diff --git a/src/NzbDrone.Common/Http/HttpClient.cs b/src/NzbDrone.Common/Http/HttpClient.cs index 84cf6751df..8df5d23b93 100644 --- a/src/NzbDrone.Common/Http/HttpClient.cs +++ b/src/NzbDrone.Common/Http/HttpClient.cs @@ -18,10 +18,12 @@ public interface IHttpClient HttpResponse Execute(HttpRequest request); void DownloadFile(string url, string fileName); HttpResponse Get(HttpRequest request); - HttpResponse Get(HttpRequest request) where T : new(); + HttpResponse Get(HttpRequest request) + where T : new(); HttpResponse Head(HttpRequest request); HttpResponse Post(HttpRequest request); - HttpResponse Post(HttpRequest request) where T : new(); + HttpResponse Post(HttpRequest request) + where T : new(); } public class HttpClient : IHttpClient @@ -266,7 +268,8 @@ public HttpResponse Get(HttpRequest request) return Execute(request); } - public HttpResponse Get(HttpRequest request) where T : new() + public HttpResponse Get(HttpRequest request) + where T : new() { var response = Get(request); CheckResponseContentType(response); @@ -285,7 +288,8 @@ public HttpResponse Post(HttpRequest request) return Execute(request); } - public HttpResponse Post(HttpRequest request) where T : new() + public HttpResponse Post(HttpRequest request) + where T : new() { var response = Post(request); CheckResponseContentType(response); diff --git a/src/NzbDrone.Common/Http/HttpException.cs b/src/NzbDrone.Common/Http/HttpException.cs index 005fab57ae..d78dd5b3e4 100644 --- a/src/NzbDrone.Common/Http/HttpException.cs +++ b/src/NzbDrone.Common/Http/HttpException.cs @@ -17,13 +17,11 @@ public HttpException(HttpRequest request, HttpResponse response, string message) public HttpException(HttpRequest request, HttpResponse response) : this(request, response, string.Format("HTTP request failed: [{0}:{1}] [{2}] at [{3}]", (int)response.StatusCode, response.StatusCode, request.Method, request.Url)) { - } public HttpException(HttpResponse response) : this(response.Request, response) { - } public override string ToString() diff --git a/src/NzbDrone.Common/Http/HttpHeader.cs b/src/NzbDrone.Common/Http/HttpHeader.cs index 8cf25489a1..2794f6dc43 100644 --- a/src/NzbDrone.Common/Http/HttpHeader.cs +++ b/src/NzbDrone.Common/Http/HttpHeader.cs @@ -1,11 +1,11 @@ using System; -using System.Linq; +using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; +using System.Globalization; +using System.Linq; using System.Text; using NzbDrone.Common.Extensions; -using System.Collections; -using System.Globalization; namespace NzbDrone.Common.Http { @@ -14,12 +14,10 @@ public class HttpHeader : NameValueCollection, IEnumerable 1) { throw new ApplicationException($"Expected {key} to occur only once, but was {values.Join("|")}."); @@ -43,7 +42,8 @@ public string GetSingleValue(string key) return values[0]; } - protected T? GetSingleValue(string key, Func converter) where T : struct + protected T? GetSingleValue(string key, Func converter) + where T : struct { var value = GetSingleValue(key); if (value == null) @@ -53,6 +53,7 @@ public string GetSingleValue(string key) return converter(value); } + protected void SetSingleValue(string key, string value) { if (value == null) @@ -65,7 +66,8 @@ protected void SetSingleValue(string key, string value) } } - protected void SetSingleValue(string key, T? value, Func converter = null) where T : struct + protected void SetSingleValue(string key, T? value, Func converter = null) + where T : struct { if (!value.HasValue) { diff --git a/src/NzbDrone.Common/Http/HttpRequest.cs b/src/NzbDrone.Common/Http/HttpRequest.cs index 0c11ba275e..3674d61d56 100644 --- a/src/NzbDrone.Common/Http/HttpRequest.cs +++ b/src/NzbDrone.Common/Http/HttpRequest.cs @@ -17,7 +17,6 @@ public HttpRequest(string url, HttpAccept httpAccept = null) IgnorePersistentCookies = false; Cookies = new Dictionary(); - if (!RuntimeInfo.IsProduction) { AllowAutoRedirect = false; diff --git a/src/NzbDrone.Common/Http/HttpRequestBuilder.cs b/src/NzbDrone.Common/Http/HttpRequestBuilder.cs index d4ccc26d31..2e9bf1a5bb 100644 --- a/src/NzbDrone.Common/Http/HttpRequestBuilder.cs +++ b/src/NzbDrone.Common/Http/HttpRequestBuilder.cs @@ -46,7 +46,6 @@ public HttpRequestBuilder(string baseUrl) public HttpRequestBuilder(bool useHttps, string host, int port, string urlBase = null) : this(BuildBaseUrl(useHttps, host, port, urlBase)) { - } public static string BuildBaseUrl(bool useHttps, string host, int port, string urlBase = null) @@ -148,7 +147,10 @@ public IHttpRequestBuilderFactory CreateFactory() protected virtual void ApplyFormData(HttpRequest request) { - if (FormData.Empty()) return; + if (FormData.Empty()) + { + return; + } if (request.ContentData != null) { @@ -173,11 +175,22 @@ protected virtual void ApplyFormData(HttpRequest request) writer.Write(partBoundary); writer.Write("Content-Disposition: form-data"); - if (formData.Name.IsNotNullOrWhiteSpace()) writer.Write("; name=\"{0}\"", formData.Name); - if (formData.FileName.IsNotNullOrWhiteSpace()) writer.Write("; filename=\"{0}\"", formData.FileName); + if (formData.Name.IsNotNullOrWhiteSpace()) + { + writer.Write("; name=\"{0}\"", formData.Name); + } + + if (formData.FileName.IsNotNullOrWhiteSpace()) + { + writer.Write("; filename=\"{0}\"", formData.FileName); + } + writer.Write("\r\n"); - if (formData.ContentType.IsNotNullOrWhiteSpace()) writer.Write("Content-Type: {0}\r\n", formData.ContentType); + if (formData.ContentType.IsNotNullOrWhiteSpace()) + { + writer.Write("Content-Type: {0}\r\n", formData.ContentType); + } writer.Write("\r\n"); writer.Flush(); @@ -201,7 +214,6 @@ protected virtual void ApplyFormData(HttpRequest request) var body = bodyStream.ToArray(); // TODO: Scan through body to see if we have a boundary collision? - request.Headers.ContentType = "multipart/form-data; boundary=" + boundary; request.SetContent(body); @@ -379,5 +391,4 @@ public virtual HttpRequestBuilder AddFormUpload(string name, string fileName, by return this; } } - } diff --git a/src/NzbDrone.Common/Http/HttpRequestBuilderFactory.cs b/src/NzbDrone.Common/Http/HttpRequestBuilderFactory.cs index 18ee914a7d..b7a6161438 100644 --- a/src/NzbDrone.Common/Http/HttpRequestBuilderFactory.cs +++ b/src/NzbDrone.Common/Http/HttpRequestBuilderFactory.cs @@ -16,7 +16,6 @@ public HttpRequestBuilderFactory(HttpRequestBuilder rootBuilder) protected HttpRequestBuilderFactory() { - } protected void SetRootBuilder(HttpRequestBuilder rootBuilder) diff --git a/src/NzbDrone.Common/Http/HttpResponse.cs b/src/NzbDrone.Common/Http/HttpResponse.cs index e0b11b51c7..eab34c6a0c 100644 --- a/src/NzbDrone.Common/Http/HttpResponse.cs +++ b/src/NzbDrone.Common/Http/HttpResponse.cs @@ -48,7 +48,6 @@ public string Content } } - public bool HasHttpError => (int)StatusCode >= 400; public bool HasHttpRedirect => StatusCode == HttpStatusCode.Moved || @@ -90,8 +89,8 @@ public override string ToString() } } - - public class HttpResponse : HttpResponse where T : new() + public class HttpResponse : HttpResponse + where T : new() { public HttpResponse(HttpResponse response) : base(response.Request, response.Headers, response.ResponseData, response.StatusCode) diff --git a/src/NzbDrone.Common/Http/HttpUri.cs b/src/NzbDrone.Common/Http/HttpUri.cs index 756283eb5f..9dfd384ad6 100644 --- a/src/NzbDrone.Common/Http/HttpUri.cs +++ b/src/NzbDrone.Common/Http/HttpUri.cs @@ -47,6 +47,7 @@ public HttpUri(string scheme, string host, int? port, string path, string query, { builder.Append('/'); } + builder.Append(path.TrimStart('/')); } @@ -78,7 +79,7 @@ private void Parse() var query = match.Groups["query"]; var fragment = match.Groups["fragment"]; - if (!match.Success || scheme.Success && !host.Success && path.Success) + if (!match.Success || (scheme.Success && !host.Success && path.Success)) { throw new ArgumentException("Uri didn't match expected pattern: " + _uri); } @@ -126,6 +127,7 @@ private IList> QueryParams _queryParams = dict.AsReadOnly(); } + return _queryParams; } } @@ -200,6 +202,7 @@ public HttpUri AddQueryParams(IEnumerable> queryPar { builder.Append("&"); } + builder.Append(Uri.EscapeDataString(pair.Key)); builder.Append("="); builder.Append(Uri.EscapeDataString(pair.Value)); @@ -208,7 +211,6 @@ public HttpUri AddQueryParams(IEnumerable> queryPar return SetQuery(builder.ToString()); } - public override int GetHashCode() { return _uri.GetHashCode(); @@ -237,7 +239,10 @@ public override bool Equals(object obj) public bool Equals(HttpUri other) { - if (object.ReferenceEquals(other, null)) return false; + if (object.ReferenceEquals(other, null)) + { + return false; + } return _uri.Equals(other._uri); } diff --git a/src/NzbDrone.Common/Http/JsonRpcRequestBuilder.cs b/src/NzbDrone.Common/Http/JsonRpcRequestBuilder.cs index 3722fd9ceb..ae987a23db 100644 --- a/src/NzbDrone.Common/Http/JsonRpcRequestBuilder.cs +++ b/src/NzbDrone.Common/Http/JsonRpcRequestBuilder.cs @@ -22,7 +22,7 @@ public JsonRpcRequestBuilder(string baseUrl) } public JsonRpcRequestBuilder(string baseUrl, string method, IEnumerable parameters) - : base (baseUrl) + : base(baseUrl) { Method = HttpMethod.POST; JsonMethod = method; diff --git a/src/NzbDrone.Common/Http/Proxy/HttpProxySettings.cs b/src/NzbDrone.Common/Http/Proxy/HttpProxySettings.cs index 3d22f245f5..58a7541dab 100644 --- a/src/NzbDrone.Common/Http/Proxy/HttpProxySettings.cs +++ b/src/NzbDrone.Common/Http/Proxy/HttpProxySettings.cs @@ -30,15 +30,17 @@ public string[] BypassListAsArray if (!string.IsNullOrWhiteSpace(BypassFilter)) { var hostlist = BypassFilter.Split(','); - for(int i = 0; i < hostlist.Length; i++) + for (int i = 0; i < hostlist.Length; i++) { - if(hostlist[i].StartsWith("*")) + if (hostlist[i].StartsWith("*")) { hostlist[i] = ";" + hostlist[i]; } } + return hostlist; } + return new string[] { }; } } diff --git a/src/NzbDrone.Common/Http/Proxy/ManagedWebProxyFactory.cs b/src/NzbDrone.Common/Http/Proxy/ManagedWebProxyFactory.cs index 4e0a8458b3..ca58fedeef 100644 --- a/src/NzbDrone.Common/Http/Proxy/ManagedWebProxyFactory.cs +++ b/src/NzbDrone.Common/Http/Proxy/ManagedWebProxyFactory.cs @@ -31,6 +31,7 @@ public IWebProxy GetWebProxy(HttpProxySettings proxySettings) return proxy; } + private IWebProxy CreateWebProxy(HttpProxySettings proxySettings) { switch (proxySettings.Type) @@ -44,6 +45,7 @@ private IWebProxy CreateWebProxy(HttpProxySettings proxySettings) { return new WebProxy(proxySettings.Host + ":" + proxySettings.Port, proxySettings.BypassLocalAddress, proxySettings.BypassListAsArray); } + case ProxyType.Socks4: return new SocksWebProxy(new ProxyConfig(IPAddress.Loopback, GetNextFreePort(), GetProxyIpAddress(proxySettings.Host), proxySettings.Port, ProxyConfig.SocksVersion.Four, proxySettings.Username, proxySettings.Password), false); case ProxyType.Socks5: diff --git a/src/NzbDrone.Common/Http/TlsFailureException.cs b/src/NzbDrone.Common/Http/TlsFailureException.cs index b62ff73c47..cb3743c03d 100644 --- a/src/NzbDrone.Common/Http/TlsFailureException.cs +++ b/src/NzbDrone.Common/Http/TlsFailureException.cs @@ -7,8 +7,6 @@ public class TlsFailureException : WebException public TlsFailureException(WebRequest request, WebException innerException) : base("Failed to establish secure https connection to '" + request.RequestUri + "'.", innerException, WebExceptionStatus.SecureChannelFailure, innerException.Response) { - } - } } diff --git a/src/NzbDrone.Common/Http/UnexpectedHtmlContentException.cs b/src/NzbDrone.Common/Http/UnexpectedHtmlContentException.cs index c62ff37ac7..e92aa216ef 100644 --- a/src/NzbDrone.Common/Http/UnexpectedHtmlContentException.cs +++ b/src/NzbDrone.Common/Http/UnexpectedHtmlContentException.cs @@ -5,7 +5,6 @@ public class UnexpectedHtmlContentException : HttpException public UnexpectedHtmlContentException(HttpResponse response) : base(response.Request, response, $"Site responded with browser content instead of api data. This disruption may be temporary, please try again later. [{response.Request.Url}]") { - } } } diff --git a/src/NzbDrone.Common/Instrumentation/CleansingJsonVisitor.cs b/src/NzbDrone.Common/Instrumentation/CleansingJsonVisitor.cs index eb4f28c907..1e32d399f6 100644 --- a/src/NzbDrone.Common/Instrumentation/CleansingJsonVisitor.cs +++ b/src/NzbDrone.Common/Instrumentation/CleansingJsonVisitor.cs @@ -15,6 +15,7 @@ public override void Visit(JArray json) json[i] = new JValue(CleanseLogMessage.Cleanse(text)); } } + foreach (JToken token in json) { Visit(token); diff --git a/src/NzbDrone.Common/Instrumentation/GlobalExceptionHandlers.cs b/src/NzbDrone.Common/Instrumentation/GlobalExceptionHandlers.cs index 3b99b7ad37..6f778d7de4 100644 --- a/src/NzbDrone.Common/Instrumentation/GlobalExceptionHandlers.cs +++ b/src/NzbDrone.Common/Instrumentation/GlobalExceptionHandlers.cs @@ -26,7 +26,10 @@ private static void HandleAppDomainException(object sender, UnhandledExceptionEv { var exception = e.ExceptionObject as Exception; - if (exception == null) return; + if (exception == null) + { + return; + } if (exception is NullReferenceException && exception.ToString().Contains("Microsoft.AspNet.SignalR.Transports.TransportHeartbeat.ProcessServerCommand")) @@ -37,7 +40,7 @@ private static void HandleAppDomainException(object sender, UnhandledExceptionEv if (PlatformInfo.IsMono) { - if (exception is TypeInitializationException && exception.InnerException is DllNotFoundException || + if ((exception is TypeInitializationException && exception.InnerException is DllNotFoundException) || exception is DllNotFoundException) { Logger.Debug(exception, "Minor Fail: " + exception.Message); diff --git a/src/NzbDrone.Common/Instrumentation/LogEventExtensions.cs b/src/NzbDrone.Common/Instrumentation/LogEventExtensions.cs index 65c44b87f8..2c8e7c8a0e 100644 --- a/src/NzbDrone.Common/Instrumentation/LogEventExtensions.cs +++ b/src/NzbDrone.Common/Instrumentation/LogEventExtensions.cs @@ -29,7 +29,6 @@ public static string GetFormattedMessage(this LogEventInfo logEvent) message += ": " + logEvent.Exception.Message; } } - } return message; diff --git a/src/NzbDrone.Common/Instrumentation/NzbDroneLogger.cs b/src/NzbDrone.Common/Instrumentation/NzbDroneLogger.cs index 3d02c3e769..6a83ce8c5e 100644 --- a/src/NzbDrone.Common/Instrumentation/NzbDroneLogger.cs +++ b/src/NzbDrone.Common/Instrumentation/NzbDroneLogger.cs @@ -12,6 +12,8 @@ namespace NzbDrone.Common.Instrumentation { public static class NzbDroneLogger { + private const string FILE_LOG_LAYOUT = @"${date:format=yy-M-d HH\:mm\:ss.f}|${level}|${logger}|${message}${onexception:inner=${newline}${newline}[v${assembly-version}] ${exception:format=ToString}${newline}}"; + private static bool _isConfigured; static NzbDroneLogger() @@ -19,7 +21,6 @@ static NzbDroneLogger() LogManager.Configuration = new LoggingConfiguration(); } - public static void Register(IStartupContext startupContext, bool updateApp, bool inConsole) { if (_isConfigured) @@ -61,13 +62,11 @@ public static void Register(IStartupContext startupContext, bool updateApp, bool private static void RegisterSentry(bool updateClient) { - string dsn; if (updateClient) { dsn = "https://379d628d45ba475a98d2e55675d14a02@sentry.radarr.video/5"; - } else { @@ -117,8 +116,6 @@ private static void RegisterConsole() LogManager.Configuration.LoggingRules.Add(loggingRule); } - private const string FILE_LOG_LAYOUT = @"${date:format=yy-M-d HH\:mm\:ss.f}|${level}|${logger}|${message}${onexception:inner=${newline}${newline}[v${assembly-version}] ${exception:format=ToString}${newline}}"; - private static void RegisterAppFile(IAppFolderInfo appFolderInfo) { RegisterAppFile(appFolderInfo, "appFileInfo", "radarr.txt", 5, LogLevel.Info); @@ -194,6 +191,5 @@ public static Logger GetLogger(object obj) { return GetLogger(obj.GetType()); } - } } diff --git a/src/NzbDrone.Common/Instrumentation/Sentry/SentryCleanser.cs b/src/NzbDrone.Common/Instrumentation/Sentry/SentryCleanser.cs index 7d351a55ad..76f0bcb548 100644 --- a/src/NzbDrone.Common/Instrumentation/Sentry/SentryCleanser.cs +++ b/src/NzbDrone.Common/Instrumentation/Sentry/SentryCleanser.cs @@ -36,7 +36,6 @@ public static SentryEvent CleanseEvent(SentryEvent sentryEvent) } catch (Exception) { - } return sentryEvent; @@ -50,9 +49,8 @@ public static Breadcrumb CleanseBreadcrumb(Breadcrumb b) var data = b.Data?.ToDictionary(x => x.Key, y => CleanseLogMessage.Cleanse(y.Value)); return new Breadcrumb(message, b.Type, data, b.Category, b.Level); } - catch(Exception) + catch (Exception) { - } return b; @@ -60,7 +58,6 @@ public static Breadcrumb CleanseBreadcrumb(Breadcrumb b) private static string ShortenPath(string path) { - if (string.IsNullOrWhiteSpace(path)) { return null; @@ -68,7 +65,7 @@ private static string ShortenPath(string path) // the paths in the stacktrace depend on where it was compiled, // not the current OS - var rootDirs = new [] { "\\src\\", "/src/" }; + var rootDirs = new[] { "\\src\\", "/src/" }; foreach (var rootDir in rootDirs) { var index = path.IndexOf(rootDir, StringComparison.Ordinal); diff --git a/src/NzbDrone.Common/Instrumentation/Sentry/SentryTarget.cs b/src/NzbDrone.Common/Instrumentation/Sentry/SentryTarget.cs index adacdf9068..11cd1bdf31 100644 --- a/src/NzbDrone.Common/Instrumentation/Sentry/SentryTarget.cs +++ b/src/NzbDrone.Common/Instrumentation/Sentry/SentryTarget.cs @@ -1,10 +1,10 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Data.SQLite; using System.Linq; using System.Net; using System.Threading; -using System.Data.SQLite; using NLog; using NLog.Common; using NLog.Targets; @@ -21,7 +21,8 @@ public class SentryTarget : TargetWithLayout // don't report uninformative SQLite exceptions // busy/locked are benign https://forums.sonarr.tv/t/owin-sqlite-error-5-database-is-locked/5423/11 // The others will be user configuration problems and silt up Sentry - private static readonly HashSet FilteredSQLiteErrors = new HashSet { + private static readonly HashSet FilteredSQLiteErrors = new HashSet + { SQLiteErrorCode.Busy, SQLiteErrorCode.Locked, SQLiteErrorCode.Perm, @@ -35,18 +36,23 @@ public class SentryTarget : TargetWithLayout // use string and not Type so we don't need a reference to the project // where these are defined - private static readonly HashSet FilteredExceptionTypeNames = new HashSet { + private static readonly HashSet FilteredExceptionTypeNames = new HashSet + { // UnauthorizedAccessExceptions will just be user configuration issues "UnauthorizedAccessException", + // Filter out people stuck in boot loops "CorruptDatabaseException", + // This also filters some people in boot loops "TinyIoCResolutionException" }; - public static readonly List FilteredExceptionMessages = new List { + public static readonly List FilteredExceptionMessages = new List + { // Swallow the many, many exceptions flowing through from Jackett "Jackett.Common.IndexerException", + // Fix openflixr being stupid with permissions "openflixr" }; @@ -54,35 +60,36 @@ public class SentryTarget : TargetWithLayout // exception types in this list will additionally have the exception message added to the // sentry fingerprint. Make sure that this message doesn't vary by exception // (e.g. containing a path or a url) so that the sentry grouping is sensible - private static readonly HashSet IncludeExceptionMessageTypes = new HashSet { + private static readonly HashSet IncludeExceptionMessageTypes = new HashSet + { "SQLiteException" }; private static readonly IDictionary LoggingLevelMap = new Dictionary { - {LogLevel.Debug, SentryLevel.Debug}, - {LogLevel.Error, SentryLevel.Error}, - {LogLevel.Fatal, SentryLevel.Fatal}, - {LogLevel.Info, SentryLevel.Info}, - {LogLevel.Trace, SentryLevel.Debug}, - {LogLevel.Warn, SentryLevel.Warning}, + { LogLevel.Debug, SentryLevel.Debug }, + { LogLevel.Error, SentryLevel.Error }, + { LogLevel.Fatal, SentryLevel.Fatal }, + { LogLevel.Info, SentryLevel.Info }, + { LogLevel.Trace, SentryLevel.Debug }, + { LogLevel.Warn, SentryLevel.Warning }, }; private static readonly IDictionary BreadcrumbLevelMap = new Dictionary { - {LogLevel.Debug, BreadcrumbLevel.Debug}, - {LogLevel.Error, BreadcrumbLevel.Error}, - {LogLevel.Fatal, BreadcrumbLevel.Critical}, - {LogLevel.Info, BreadcrumbLevel.Info}, - {LogLevel.Trace, BreadcrumbLevel.Debug}, - {LogLevel.Warn, BreadcrumbLevel.Warning}, + { LogLevel.Debug, BreadcrumbLevel.Debug }, + { LogLevel.Error, BreadcrumbLevel.Error }, + { LogLevel.Fatal, BreadcrumbLevel.Critical }, + { LogLevel.Info, BreadcrumbLevel.Info }, + { LogLevel.Trace, BreadcrumbLevel.Debug }, + { LogLevel.Warn, BreadcrumbLevel.Warning }, }; private readonly DateTime _startTime = DateTime.UtcNow; private readonly IDisposable _sdk; - private bool _disposed; - private readonly SentryDebounce _debounce; + + private bool _disposed; private bool _unauthorized; public bool FilterEvents { get; set; } @@ -105,6 +112,7 @@ public SentryTarget(string dsn) // TODO: Check specific version o.RequestBodyCompressionLevel = System.IO.Compression.CompressionLevel.NoCompression; } + o.BeforeSend = x => SentryCleanser.CleanseEvent(x); o.BeforeBreadcrumb = x => SentryCleanser.CleanseBreadcrumb(x); o.Environment = BuildInfo.Branch; @@ -257,7 +265,6 @@ public bool IsSentryMessage(LogEventInfo logEvent) return false; } - protected override void Write(LogEventInfo logEvent) { if (_unauthorized || !SentryEnabled) @@ -322,6 +329,7 @@ protected override void Dispose(bool disposing) { _sdk?.Dispose(); } + // Flag us as disposed. This allows us to handle multiple calls to Dispose() as well as ObjectDisposedException _disposed = true; } diff --git a/src/NzbDrone.Common/OAuth/OAuthRequest.cs b/src/NzbDrone.Common/OAuth/OAuthRequest.cs index 9c34761010..7f84d9e7fd 100644 --- a/src/NzbDrone.Common/OAuth/OAuthRequest.cs +++ b/src/NzbDrone.Common/OAuth/OAuthRequest.cs @@ -32,8 +32,6 @@ public class OAuthRequest /// public virtual string RequestUrl { get; set; } - #region Authorization Header - #if !WINRT public string GetAuthorizationHeader(NameValueCollection parameters) { @@ -121,10 +119,6 @@ private string WriteAuthorizationHeader(WebParameterCollection parameters) return authorization; } - #endregion - - #region Authorization Query - #if !WINRT public string GetAuthorizationQuery(NameValueCollection parameters) { @@ -209,8 +203,6 @@ private static string WriteAuthorizationQuery(WebParameterCollection parameters) return authorization; } - #endregion - private string GetNewSignature(WebParameterCollection parameters) { var timestamp = OAuthTools.GetTimestamp(); @@ -241,8 +233,6 @@ private string GetNewSignatureXAuth(WebParameterCollection parameters) return signature; } - #region Static Helpers - public static OAuthRequest ForRequestToken(string consumerKey, string consumerSecret) { var credentials = new OAuthRequest @@ -335,8 +325,6 @@ public static OAuthRequest ForProtectedResource(string method, string consumerKe return credentials; } - #endregion - private void ValidateRequestState() { if (IsNullOrBlank(Method)) @@ -500,9 +488,7 @@ public static string ToRequestValue(OAuthSignatureMethod signatureMethod) private static bool IsNullOrBlank(string value) { - return String.IsNullOrEmpty(value) || (!String.IsNullOrEmpty(value) && value.Trim() == String.Empty); + return string.IsNullOrEmpty(value) || (!string.IsNullOrEmpty(value) && value.Trim() == string.Empty); } } } - - diff --git a/src/NzbDrone.Common/OAuth/OAuthTools.cs b/src/NzbDrone.Common/OAuth/OAuthTools.cs index 40d936ed22..c2b14c519c 100644 --- a/src/NzbDrone.Common/OAuth/OAuthTools.cs +++ b/src/NzbDrone.Common/OAuth/OAuthTools.cs @@ -61,7 +61,7 @@ static OAuthTools() /// public static string GetNonce() { - const string chars = (Lower + Digit); + const string chars = Lower + Digit; var nonce = new char[16]; lock (_randomLock) @@ -71,6 +71,7 @@ public static string GetNonce() nonce[i] = chars[_random.Next(0, chars.Length)]; } } + return new string(nonce); } @@ -98,7 +99,7 @@ public static string GetTimestamp(DateTime dateTime) private static long ToUnixTime(DateTime dateTime) { - var timeSpan = (dateTime - new DateTime(1970, 1, 1)); + var timeSpan = dateTime - new DateTime(1970, 1, 1); var timestamp = (long)timeSpan.TotalSeconds; return timestamp; @@ -138,6 +139,7 @@ private static string PercentEncode(string s) sb.Append(string.Format("%{0:X}", b)); } } + return sb.ToString(); } @@ -155,8 +157,7 @@ public static string UrlEncodeStrict(string value) var ret = original.OfType().Where( c => !Unreserved.OfType().Contains(c) && c != '%').Aggregate( value, (current, c) => current.Replace( - c.ToString(), PercentEncode(c.ToString()) - )); + c.ToString(), PercentEncode(c.ToString()))); return ret.Replace("%%", "%25%"); // Revisit to encode actual %'s } @@ -211,7 +212,7 @@ public static WebParameterCollection SortParametersExcludingSignature(WebParamet copy.RemoveAll(exclusions); - foreach(var parameter in copy) + foreach (var parameter in copy) { parameter.Value = UrlEncodeStrict(parameter.Value); } @@ -225,7 +226,7 @@ private static bool EqualsIgnoreCase(string left, string right) #if WINRT return CultureInfo.InvariantCulture.CompareInfo.Compare(left, right, CompareOptions.IgnoreCase) == 0; #else - return String.Compare(left, right, StringComparison.InvariantCultureIgnoreCase) == 0; + return string.Compare(left, right, StringComparison.InvariantCultureIgnoreCase) == 0; #endif } @@ -353,7 +354,7 @@ public static string GetSignature(OAuthSignatureMethod signatureMethod, { if (IsNullOrBlank(tokenSecret)) { - tokenSecret = String.Empty; + tokenSecret = string.Empty; } consumerSecret = UrlEncodeRelaxed(consumerSecret); @@ -381,6 +382,7 @@ public static string GetSignature(OAuthSignatureMethod signatureMethod, break; } + default: throw new NotImplementedException("Only HMAC-SHA1 is currently supported."); } @@ -403,7 +405,7 @@ private static string HashWith(string input, HashAlgorithm algorithm) private static bool IsNullOrBlank(string value) { - return String.IsNullOrEmpty(value) || (!String.IsNullOrEmpty(value) && value.Trim() == String.Empty); + return string.IsNullOrEmpty(value) || (!string.IsNullOrEmpty(value) && value.Trim() == string.Empty); } } } diff --git a/src/NzbDrone.Common/OAuth/WebParameterCollection.cs b/src/NzbDrone.Common/OAuth/WebParameterCollection.cs index 511aec0669..a1084a0efc 100644 --- a/src/NzbDrone.Common/OAuth/WebParameterCollection.cs +++ b/src/NzbDrone.Common/OAuth/WebParameterCollection.cs @@ -1,8 +1,8 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Linq; using System.Collections.Specialized; +using System.Linq; namespace NzbDrone.Common.OAuth { @@ -16,12 +16,12 @@ public virtual WebParameter this[string name] { var parameters = this.Where(p => p.Name.Equals(name)); - if(parameters.Count() == 0) + if (parameters.Count() == 0) { return null; } - if(parameters.Count() == 1) + if (parameters.Count() == 1) { return parameters.Single(); } @@ -47,7 +47,8 @@ public WebParameterCollection(IEnumerable parameters) } #if !WINRT - public WebParameterCollection(NameValueCollection collection) : this() + public WebParameterCollection(NameValueCollection collection) + : this() { AddCollection(collection); } @@ -67,7 +68,8 @@ private void AddCollection(NameValueCollection collection) } #endif - public WebParameterCollection(IDictionary collection) : this() + public WebParameterCollection(IDictionary collection) + : this() { AddCollection(collection); } @@ -128,8 +130,6 @@ public virtual void Add(string name, string value) _parameters.Add(pair); } - #region IList Members - public virtual IEnumerator GetEnumerator() { return _parameters.GetEnumerator(); @@ -142,7 +142,6 @@ IEnumerator IEnumerable.GetEnumerator() public virtual void Add(WebParameter parameter) { - _parameters.Add(parameter); } @@ -196,7 +195,5 @@ public virtual WebParameter this[int index] get { return _parameters[index]; } set { _parameters[index] = value; } } - - #endregion } } diff --git a/src/NzbDrone.Common/PathEqualityComparer.cs b/src/NzbDrone.Common/PathEqualityComparer.cs index f015792c3c..d443a3bf0f 100644 --- a/src/NzbDrone.Common/PathEqualityComparer.cs +++ b/src/NzbDrone.Common/PathEqualityComparer.cs @@ -10,7 +10,6 @@ public class PathEqualityComparer : IEqualityComparer private PathEqualityComparer() { - } public bool Equals(string x, string y) diff --git a/src/NzbDrone.Common/Processes/ProcessProvider.cs b/src/NzbDrone.Common/Processes/ProcessProvider.cs index 19a2c9a13c..685a366798 100644 --- a/src/NzbDrone.Common/Processes/ProcessProvider.cs +++ b/src/NzbDrone.Common/Processes/ProcessProvider.cs @@ -136,7 +136,6 @@ public Process Start(string path, string args = null, StringDictionary environme { _logger.Error(e, "Unable to set environment variable '{0}', value is null", environmentVariable.Key); } - else { _logger.Error(e, "Unable to set environment variable '{0}'", environmentVariable.Key); @@ -156,7 +155,10 @@ public Process Start(string path, string args = null, StringDictionary environme process.OutputDataReceived += (sender, eventArgs) => { - if (string.IsNullOrWhiteSpace(eventArgs.Data)) return; + if (string.IsNullOrWhiteSpace(eventArgs.Data)) + { + return; + } logger.Debug(eventArgs.Data); @@ -168,7 +170,10 @@ public Process Start(string path, string args = null, StringDictionary environme process.ErrorDataReceived += (sender, eventArgs) => { - if (string.IsNullOrWhiteSpace(eventArgs.Data)) return; + if (string.IsNullOrWhiteSpace(eventArgs.Data)) + { + return; + } logger.Error(eventArgs.Data); @@ -209,8 +214,11 @@ public Process SpawnNewProcess(string path, string args = null, StringDictionary public ProcessOutput StartAndCapture(string path, string args = null, StringDictionary environmentVariables = null) { var output = new ProcessOutput(); - var process = Start(path, args, environmentVariables, s => output.Lines.Add(new ProcessOutputLine(ProcessOutputLevel.Standard, s)), - error => output.Lines.Add(new ProcessOutputLine(ProcessOutputLevel.Error, error))); + var process = Start(path, + args, + environmentVariables, + s => output.Lines.Add(new ProcessOutputLine(ProcessOutputLevel.Standard, s)), + error => output.Lines.Add(new ProcessOutputLine(ProcessOutputLevel.Error, error))); process.WaitForExit(); output.ExitCode = process.ExitCode; @@ -283,7 +291,10 @@ public void KillAll(string processName) private ProcessInfo ConvertToProcessInfo(Process process) { - if (process == null) return null; + if (process == null) + { + return null; + } process.Refresh(); @@ -291,7 +302,10 @@ private ProcessInfo ConvertToProcessInfo(Process process) try { - if (process.Id <= 0) return null; + if (process.Id <= 0) + { + return null; + } processInfo = new ProcessInfo(); processInfo.Id = process.Id; @@ -309,7 +323,6 @@ private ProcessInfo ConvertToProcessInfo(Process process) } return processInfo; - } private static string GetExeFileName(Process process) @@ -325,7 +338,6 @@ private static string GetExeFileName(Process process) private List GetProcessesByName(string name) { //TODO: move this to an OS specific class - var monoProcesses = Process.GetProcessesByName("mono") .Union(Process.GetProcessesByName("mono-sgen")) .Union(Process.GetProcessesByName("mono-sgen32")) diff --git a/src/NzbDrone.Common/Reflection/ReflectionExtensions.cs b/src/NzbDrone.Common/Reflection/ReflectionExtensions.cs index 2346b288aa..6280e1c56f 100644 --- a/src/NzbDrone.Common/Reflection/ReflectionExtensions.cs +++ b/src/NzbDrone.Common/Reflection/ReflectionExtensions.cs @@ -29,7 +29,6 @@ public static bool IsSimpleType(this Type type) type = type.GetGenericArguments()[0]; } - return type.IsPrimitive || type.IsEnum || type == typeof(string) @@ -48,7 +47,8 @@ public static bool IsWritable(this PropertyInfo propertyInfo) return propertyInfo.CanWrite && propertyInfo.GetSetMethod(false) != null; } - public static T GetAttribute(this MemberInfo member, bool isRequired = true) where T : Attribute + public static T GetAttribute(this MemberInfo member, bool isRequired = true) + where T : Attribute { var attribute = member.GetCustomAttributes(typeof(T), false).SingleOrDefault(); @@ -60,7 +60,8 @@ public static T GetAttribute(this MemberInfo member, bool isRequired = true) return (T)attribute; } - public static T[] GetAttributes(this MemberInfo member) where T : Attribute + public static T[] GetAttributes(this MemberInfo member) + where T : Attribute { return member.GetCustomAttributes(typeof(T), false).OfType().ToArray(); } diff --git a/src/NzbDrone.Common/Serializer/IntConverter.cs b/src/NzbDrone.Common/Serializer/IntConverter.cs index 63b4eb213b..e49676735f 100644 --- a/src/NzbDrone.Common/Serializer/IntConverter.cs +++ b/src/NzbDrone.Common/Serializer/IntConverter.cs @@ -23,6 +23,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist { throw new JsonSerializationException("Can't convert type " + existingValue.GetType().FullName + " to number"); } + if (objectType == typeof(long)) { return Convert.ToInt64(reader.Value); diff --git a/src/NzbDrone.Common/Serializer/Json.cs b/src/NzbDrone.Common/Serializer/Json.cs index fe05b01a44..8a23c3f86c 100644 --- a/src/NzbDrone.Common/Serializer/Json.cs +++ b/src/NzbDrone.Common/Serializer/Json.cs @@ -36,7 +36,8 @@ public static JsonSerializerSettings GetSerializerSettings() return serializerSettings; } - public static T Deserialize(string json) where T : new() + public static T Deserialize(string json) + where T : new() { try { @@ -95,7 +96,8 @@ private static JsonReaderException DetailedJsonReaderException(JsonReaderExcepti return ex; } - public static bool TryDeserialize(string json, out T result) where T : new() + public static bool TryDeserialize(string json, out T result) + where T : new() { try { diff --git a/src/NzbDrone.Common/Serializer/JsonVisitor.cs b/src/NzbDrone.Common/Serializer/JsonVisitor.cs index 4b613589d7..0e69a0ae02 100644 --- a/src/NzbDrone.Common/Serializer/JsonVisitor.cs +++ b/src/NzbDrone.Common/Serializer/JsonVisitor.cs @@ -2,7 +2,6 @@ namespace NzbDrone.Common.Serializer { - public class JsonVisitor { protected void Dispatch(JToken json) @@ -66,6 +65,7 @@ public virtual void Visit(JArray json) Visit(token); } } + public virtual void Visit(JConstructor json) { } @@ -85,7 +85,6 @@ public virtual void Visit(JProperty property) public virtual void Visit(JValue value) { - } } } diff --git a/src/NzbDrone.Common/Serializer/UnderscoreStringEnumConverter.cs b/src/NzbDrone.Common/Serializer/UnderscoreStringEnumConverter.cs index 9022c029f3..772f5640c4 100644 --- a/src/NzbDrone.Common/Serializer/UnderscoreStringEnumConverter.cs +++ b/src/NzbDrone.Common/Serializer/UnderscoreStringEnumConverter.cs @@ -48,8 +48,10 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s { builder.Append('_'); } + builder.Append(char.ToLower(enumText[i])); } + enumText = builder.ToString(); writer.WriteValue(enumText); diff --git a/src/NzbDrone.Common/ServiceFactory.cs b/src/NzbDrone.Common/ServiceFactory.cs index 061dd22a2a..4f7e4bb0ba 100644 --- a/src/NzbDrone.Common/ServiceFactory.cs +++ b/src/NzbDrone.Common/ServiceFactory.cs @@ -1,14 +1,16 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using NzbDrone.Common.Composition; namespace NzbDrone.Common { public interface IServiceFactory { - T Build() where T : class; - IEnumerable BuildAll() where T : class; + T Build() + where T : class; + IEnumerable BuildAll() + where T : class; object Build(Type contract); IEnumerable GetImplementations(Type contract); } @@ -22,12 +24,14 @@ public ServiceFactory(IContainer container) _container = container; } - public T Build() where T : class + public T Build() + where T : class { return _container.Resolve(); } - public IEnumerable BuildAll() where T : class + public IEnumerable BuildAll() + where T : class { return _container.ResolveAll().GroupBy(c => c.GetType().FullName).Select(g => g.First()); } diff --git a/src/NzbDrone.Common/ServiceProvider.cs b/src/NzbDrone.Common/ServiceProvider.cs index 75d3b415c7..349fa083af 100644 --- a/src/NzbDrone.Common/ServiceProvider.cs +++ b/src/NzbDrone.Common/ServiceProvider.cs @@ -60,7 +60,6 @@ public virtual bool IsServiceRunning(string name) public virtual void Install(string serviceName) { - _logger.Info("Installing service '{0}'", serviceName); var args = $"create {serviceName} " + @@ -151,7 +150,7 @@ public virtual void Stop(string serviceName) public ServiceControllerStatus GetStatus(string serviceName) { - return GetService(serviceName).Status; + return GetService(serviceName).Status; } public void Start(string serviceName) diff --git a/src/NzbDrone.Common/TPL/Debouncer.cs b/src/NzbDrone.Common/TPL/Debouncer.cs index 08ee3b71d8..0fa1015258 100644 --- a/src/NzbDrone.Common/TPL/Debouncer.cs +++ b/src/NzbDrone.Common/TPL/Debouncer.cs @@ -17,7 +17,7 @@ public Debouncer(Action action, TimeSpan debounceDuration) _timer.Elapsed += timer_Elapsed; } - void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) + private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if (_paused == 0) { diff --git a/src/NzbDrone.Common/TPL/LimitedConcurrencyLevelTaskScheduler.cs b/src/NzbDrone.Common/TPL/LimitedConcurrencyLevelTaskScheduler.cs index c3d0372d6f..2f1a295b57 100644 --- a/src/NzbDrone.Common/TPL/LimitedConcurrencyLevelTaskScheduler.cs +++ b/src/NzbDrone.Common/TPL/LimitedConcurrencyLevelTaskScheduler.cs @@ -11,12 +11,15 @@ public class LimitedConcurrencyLevelTaskScheduler : TaskScheduler /// Whether the current thread is processing work items. [ThreadStatic] private static bool _currentThreadIsProcessingItems; + /// The list of tasks to be executed. - private readonly LinkedList _tasks = new LinkedList(); // protected by lock(_tasks) + private readonly LinkedList _tasks = new LinkedList(); + /// The maximum concurrency level allowed by this scheduler. private readonly int _maxDegreeOfParallelism; + /// Whether the scheduler is currently processing work items. - private int _delegatesQueuedOrRunning = 0; // protected by lock(_tasks) + private int _delegatesQueuedOrRunning = 0; /// /// Initializes an instance of the LimitedConcurrencyLevelTaskScheduler class with the @@ -25,7 +28,11 @@ public class LimitedConcurrencyLevelTaskScheduler : TaskScheduler /// The maximum degree of parallelism provided by this scheduler. public LimitedConcurrencyLevelTaskScheduler(int maxDegreeOfParallelism) { - if (maxDegreeOfParallelism < 1) throw new ArgumentOutOfRangeException("maxDegreeOfParallelism"); + if (maxDegreeOfParallelism < 1) + { + throw new ArgumentOutOfRangeException("maxDegreeOfParallelism"); + } + _maxDegreeOfParallelism = maxDegreeOfParallelism; } @@ -78,11 +85,15 @@ private void NotifyThreadPoolOfPendingWork() } // Execute the task we pulled out of the queue - base.TryExecuteTask(item); + TryExecuteTask(item); } } + // We're done processing items on the current thread - finally { _currentThreadIsProcessingItems = false; } + finally + { + _currentThreadIsProcessingItems = false; + } }, null); } @@ -93,13 +104,19 @@ private void NotifyThreadPoolOfPendingWork() protected sealed override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { // If this thread isn't already processing a task, we don't support inlining - if (!_currentThreadIsProcessingItems) return false; + if (!_currentThreadIsProcessingItems) + { + return false; + } // If the task was previously queued, remove it from the queue - if (taskWasPreviouslyQueued) TryDequeue(task); + if (taskWasPreviouslyQueued) + { + TryDequeue(task); + } // Try to run the task. - return base.TryExecuteTask(task); + return TryExecuteTask(task); } /// Attempts to remove a previously scheduled task from the scheduler. @@ -107,7 +124,10 @@ protected sealed override bool TryExecuteTaskInline(Task task, bool taskWasPrevi /// Whether the task could be found and removed. protected sealed override bool TryDequeue(Task task) { - lock (_tasks) return _tasks.Remove(task); + lock (_tasks) + { + return _tasks.Remove(task); + } } /// Gets the maximum concurrency level supported by this scheduler. @@ -121,12 +141,21 @@ protected sealed override IEnumerable GetScheduledTasks() try { Monitor.TryEnter(_tasks, ref lockTaken); - if (lockTaken) return _tasks.ToArray(); - else throw new NotSupportedException(); + if (lockTaken) + { + return _tasks.ToArray(); + } + else + { + throw new NotSupportedException(); + } } finally { - if (lockTaken) Monitor.Exit(_tasks); + if (lockTaken) + { + Monitor.Exit(_tasks); + } } } } diff --git a/src/NzbDrone.Common/TPL/RateLimitService.cs b/src/NzbDrone.Common/TPL/RateLimitService.cs index 6d1b9ee17e..f0d30b4ff1 100644 --- a/src/NzbDrone.Common/TPL/RateLimitService.cs +++ b/src/NzbDrone.Common/TPL/RateLimitService.cs @@ -25,7 +25,7 @@ public void WaitAndPulse(string key, TimeSpan interval) { var waitUntil = _rateLimitStore.AddOrUpdate(key, (s) => DateTime.UtcNow + interval, - (s,i) => new DateTime(Math.Max(DateTime.UtcNow.Ticks, i.Ticks), DateTimeKind.Utc) + interval); + (s, i) => new DateTime(Math.Max(DateTime.UtcNow.Ticks, i.Ticks), DateTimeKind.Utc) + interval); waitUntil -= interval; diff --git a/src/NzbDrone.Common/TinyIoC.cs b/src/NzbDrone.Common/TinyIoC.cs index 2edfd4f949..f3ac33d59a 100644 --- a/src/NzbDrone.Common/TinyIoC.cs +++ b/src/NzbDrone.Common/TinyIoC.cs @@ -13,7 +13,10 @@ // FITNESS FOR A PARTICULAR PURPOSE. //=============================================================================== +#pragma warning disable SX1101, SA1108, SA1119, SA1124, SA1200, SA1208, SA1314, SA1403, SA1503, SA1514, SA1515, SA1519, SX1309 + #region Preprocessor Directives + // Uncomment this line if you want the container to automatically // register the TinyMessenger messenger/event aggregator //#define TINYMESSENGER @@ -21,7 +24,6 @@ // Preprocessor directives for enabling/disabling functionality // depending on platform features. If the platform has an appropriate // #DEFINE then these should be set automatically below. - #define EXPRESSIONS // Platform supports System.Linq.Expressions #define COMPILED_EXPRESSIONS // Platform supports compiling expressions #define APPDOMAIN_GETASSEMBLIES // Platform supports getting all assemblies from the AppDomain object @@ -278,7 +280,7 @@ where item is IDisposable GC.SuppressFinalize(this); } - #endregion + #endregion } #endif #endregion @@ -376,8 +378,8 @@ public static MethodInfo GetGenericMethod(this Type sourceType, BindingFlags bin return method; } - //#endif + //#endif #if NETFX_CORE private static MethodInfo GetMethod(Type sourceType, BindingFlags flags, string methodName, Type[] genericTypes, Type[] parameterTypes) { @@ -509,7 +511,6 @@ private int GenerateHashCode() } } } - } // @mbrit - 2012-05-22 - shim for ForEach call on List... @@ -1123,7 +1124,6 @@ public RegisterOptions Register(Type registerType) public RegisterOptions Register(Type registerType, string name) { return RegisterInternal(registerType, name, GetDefaultObjectFactory(registerType, registerType)); - } /// @@ -1386,10 +1386,12 @@ public MultiRegisterOptions RegisterMultiple(Type registrationType, IEnumerable< throw new ArgumentNullException("types", "types is null."); foreach (var type in implementationTypes) + //#if NETFX_CORE // if (!registrationType.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())) //#else if (!registrationType.IsAssignableFrom(type)) + //#endif throw new ArgumentException(string.Format("types: The type {0} is not assignable from {1}", registrationType.FullName, type.FullName)); @@ -1398,8 +1400,8 @@ public MultiRegisterOptions RegisterMultiple(Type registrationType, IEnumerable< var queryForDuplicatedTypes = from i in implementationTypes group i by i into j - where j.Count() > 1 - select j.Key.FullName; + where j.Count() > 1 + select j.Key.FullName; var fullNamesOfDuplicatedTypes = string.Join(",\n", queryForDuplicatedTypes.ToArray()); var multipleRegMessage = string.Format("types: The same implementation type cannot be specified multiple times for {0}\n\n{1}", registrationType.FullName, fullNamesOfDuplicatedTypes); @@ -2451,6 +2453,7 @@ public MultiInstanceFactory(Type registerType, Type registerImplementation) //#else if (registerImplementation.IsAbstract() || registerImplementation.IsInterface()) throw new TinyIoCRegistrationTypeException(registerImplementation, "MultiInstanceFactory"); + //#endif if (!IsValidAssignment(registerType, registerImplementation)) throw new TinyIoCRegistrationTypeException(registerImplementation, "MultiInstanceFactory"); @@ -2716,6 +2719,7 @@ public SingletonFactory(Type registerType, Type registerImplementation) // if (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface()) //#else if (registerImplementation.IsAbstract() || registerImplementation.IsInterface()) + //#endif throw new TinyIoCRegistrationTypeException(registerImplementation, "SingletonFactory"); @@ -2792,6 +2796,7 @@ public CustomObjectLifetimeFactory(Type registerType, Type registerImplementatio // if (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface()) //#else if (registerImplementation.IsAbstract() || registerImplementation.IsInterface()) + //#endif throw new TinyIoCRegistrationTypeException(registerImplementation, errorMessage); @@ -2915,6 +2920,7 @@ public override int GetHashCode() return _hashCode; } } + private readonly SafeDictionary _RegisteredTypes; #if USE_OBJECT_CONSTRUCTOR private delegate object ObjectConstructor(params object[] parameters); @@ -2930,7 +2936,7 @@ public TinyIoCContainer() RegisterDefaultTypes(); } - TinyIoCContainer _Parent; + private TinyIoCContainer _Parent; private TinyIoCContainer(TinyIoCContainer parent) : this() { @@ -3096,6 +3102,7 @@ private ObjectFactoryBase GetDefaultObjectFactory(Type registerType, Type regist // if (registerType.GetTypeInfo().IsInterface() || registerType.GetTypeInfo().IsAbstract()) //#else if (registerType.IsInterface() || registerType.IsAbstract()) + //#endif return new SingletonFactory(registerType, registerImplementation); @@ -3188,6 +3195,7 @@ private bool IsAutomaticLazyFactoryRequest(Type type) // if ((genericType == typeof(Func<,>) && type.GetTypeInfo().GenericTypeArguments[0] == typeof(string))) //#else if ((genericType == typeof(Func<,>) && type.GetGenericArguments()[0] == typeof(string))) + //#endif return true; @@ -3196,6 +3204,7 @@ private bool IsAutomaticLazyFactoryRequest(Type type) // if ((genericType == typeof(Func<,,>) && type.GetTypeInfo().GenericTypeArguments[0] == typeof(string) && type.GetTypeInfo().GenericTypeArguments[1] == typeof(IDictionary))) //#else if ((genericType == typeof(Func<,,>) && type.GetGenericArguments()[0] == typeof(string) && type.GetGenericArguments()[1] == typeof(IDictionary))) + //#endif return true; @@ -3330,10 +3339,12 @@ private object GetLazyAutomaticFactoryRequest(Type type) return null; Type genericType = type.GetGenericTypeDefinition(); + //#if NETFX_CORE // Type[] genericArguments = type.GetTypeInfo().GenericTypeArguments.ToArray(); //#else Type[] genericArguments = type.GetGenericArguments(); + //#endif // Just a func @@ -3345,6 +3356,7 @@ private object GetLazyAutomaticFactoryRequest(Type type) // MethodInfo resolveMethod = typeof(TinyIoCContainer).GetTypeInfo().GetDeclaredMethods("Resolve").First(mi => !mi.GetParameters().Any()); //#else MethodInfo resolveMethod = typeof(TinyIoCContainer).GetMethod("Resolve", new Type[] { }); + //#endif resolveMethod = resolveMethod.MakeGenericMethod(returnType); @@ -3364,6 +3376,7 @@ private object GetLazyAutomaticFactoryRequest(Type type) // MethodInfo resolveMethod = typeof(TinyIoCContainer).GetTypeInfo().GetDeclaredMethods("Resolve").First(mi => mi.GetParameters().Length == 1 && mi.GetParameters()[0].GetType() == typeof(String)); //#else MethodInfo resolveMethod = typeof(TinyIoCContainer).GetMethod("Resolve", new Type[] { typeof(string) }); + //#endif resolveMethod = resolveMethod.MakeGenericMethod(returnType); @@ -3380,6 +3393,7 @@ private object GetLazyAutomaticFactoryRequest(Type type) // if ((genericType == typeof(Func<,,>) && type.GenericTypeArguments[0] == typeof(string) && type.GenericTypeArguments[1] == typeof(IDictionary))) //#else if ((genericType == typeof(Func<,,>) && type.GetGenericArguments()[0] == typeof(string) && type.GetGenericArguments()[1] == typeof(IDictionary))) + //#endif { Type returnType = genericArguments[2]; @@ -3391,6 +3405,7 @@ private object GetLazyAutomaticFactoryRequest(Type type) // MethodInfo resolveMethod = typeof(TinyIoCContainer).GetTypeInfo().GetDeclaredMethods("Resolve").First(mi => mi.GetParameters().Length == 2 && mi.GetParameters()[0].GetType() == typeof(String) && mi.GetParameters()[1].GetType() == typeof(NamedParameterOverloads)); //#else MethodInfo resolveMethod = typeof(TinyIoCContainer).GetMethod("Resolve", new Type[] { typeof(string), typeof(NamedParameterOverloads) }); + //#endif resolveMethod = resolveMethod.MakeGenericMethod(returnType); @@ -3410,8 +3425,8 @@ private object GetIEnumerableRequest(Type type) // var genericResolveAllMethod = this.GetType().GetGenericMethod("ResolveAll", type.GenericTypeArguments, new[] { typeof(bool) }); //#else var genericResolveAllMethod = this.GetType().GetGenericMethod(BindingFlags.Public | BindingFlags.Instance, "ResolveAll", type.GetGenericArguments(), new[] { typeof(bool) }); - //#endif + //#endif return genericResolveAllMethod.Invoke(this, new object[] { false }); } @@ -3431,6 +3446,7 @@ private bool CanConstruct(ConstructorInfo ctor, NamedParameterOverloads paramete // if (parameter.ParameterType.GetTypeInfo().IsPrimitive && !isParameterOverload) //#else if (parameter.ParameterType.IsPrimitive() && !isParameterOverload) + //#endif return false; @@ -3450,6 +3466,7 @@ private ConstructorInfo GetBestConstructor(Type type, NamedParameterOverloads pa // if (type.GetTypeInfo().IsValueType) //#else if (type.IsValueType()) + //#endif return null; @@ -3472,6 +3489,7 @@ private IEnumerable GetTypeConstructors(Type type) // return type.GetTypeInfo().DeclaredConstructors.OrderByDescending(ctor => ctor.GetParameters().Count()); //#else return type.GetConstructors().OrderByDescending(ctor => ctor.GetParameters().Count()); + //#endif } @@ -3524,15 +3542,12 @@ private object ConstructType(Type requestedType, Type implementationType, Constr try { - if (ctorParams[parameterIndex].ParameterType == typeof(Logger)) { args[parameterIndex] = LogManager.GetLogger(implementationType.Name); } else { - - args[parameterIndex] = parameters.ContainsKey(currentParam.Name) ? parameters[currentParam.Name] : ResolveInternal( @@ -3612,8 +3627,8 @@ private void BuildUpInternal(object input, ResolveOptions resolveOptions) var properties = from property in input.GetType().GetProperties() where (property.GetGetMethod() != null) && (property.GetSetMethod() != null) && !property.PropertyType.IsValueType() select property; - //#endif + //#endif foreach (var property in properties) { if (property.GetValue(input, null) == null) @@ -3691,6 +3706,7 @@ private static bool IsValidAssignment(Type registerType, Type registerImplementa return false; } } + //#endif return true; } @@ -3698,7 +3714,7 @@ private static bool IsValidAssignment(Type registerType, Type registerImplementa #endregion #region IDisposable Members - bool disposed = false; + private bool disposed = false; public void Dispose() { if (!disposed) @@ -3713,7 +3729,6 @@ public void Dispose() #endregion } - } // reverse shim for WinRT SR changes... diff --git a/src/NzbDrone.Console/ConsoleApp.cs b/src/NzbDrone.Console/ConsoleApp.cs index ef1c750ada..47cdbe2fc4 100644 --- a/src/NzbDrone.Console/ConsoleApp.cs +++ b/src/NzbDrone.Console/ConsoleApp.cs @@ -35,6 +35,7 @@ public static void Main(string[] args) System.Console.WriteLine("NLog Exception: " + ex.ToString()); throw; } + Bootstrap.Start(startupArgs, new ConsoleAlerts()); } catch (RadarrStartupException ex) @@ -87,7 +88,10 @@ private static void Exit(ExitCodes exitCode) for (int i = 0; i < 3600; i++) { System.Threading.Thread.Sleep(1000); - if (!System.Console.IsInputRedirected && System.Console.KeyAvailable) break; + if (!System.Console.IsInputRedirected && System.Console.KeyAvailable) + { + break; + } } } diff --git a/src/NzbDrone.Core.Test/Blacklisting/BlacklistRepositoryFixture.cs b/src/NzbDrone.Core.Test/Blacklisting/BlacklistRepositoryFixture.cs index 2f87fa27ed..8894c05dfe 100644 --- a/src/NzbDrone.Core.Test/Blacklisting/BlacklistRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/Blacklisting/BlacklistRepositoryFixture.cs @@ -19,13 +19,13 @@ public class BlacklistRepositoryFixture : DbTest public void Setup() { _blacklist = new Blacklist - { - MovieId = 1234, - Quality = new QualityModel(), - Languages = new List(), - SourceTitle = "movie.title.1998", - Date = DateTime.UtcNow - }; + { + MovieId = 1234, + Quality = new QualityModel(), + Languages = new List(), + SourceTitle = "movie.title.1998", + Date = DateTime.UtcNow + }; } [Test] diff --git a/src/NzbDrone.Core.Test/Blacklisting/BlacklistServiceFixture.cs b/src/NzbDrone.Core.Test/Blacklisting/BlacklistServiceFixture.cs index 74eaeb2de3..dfe82adff0 100644 --- a/src/NzbDrone.Core.Test/Blacklisting/BlacklistServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Blacklisting/BlacklistServiceFixture.cs @@ -17,13 +17,13 @@ public class BlacklistServiceFixture : CoreTest public void Setup() { _event = new DownloadFailedEvent - { - MovieId = 69, - Quality = new QualityModel(), - SourceTitle = "series.title.s01e01", - DownloadClient = "SabnzbdClient", - DownloadId = "Sabnzbd_nzo_2dfh73k" - }; + { + MovieId = 69, + Quality = new QualityModel(), + SourceTitle = "series.title.s01e01", + DownloadClient = "SabnzbdClient", + DownloadId = "Sabnzbd_nzo_2dfh73k" + }; _event.Data.Add("publishedDate", DateTime.UtcNow.ToString("s") + "Z"); _event.Data.Add("size", "1000"); diff --git a/src/NzbDrone.Core.Test/BulkImport/AddMultiMoviesFixture.cs b/src/NzbDrone.Core.Test/BulkImport/AddMultiMoviesFixture.cs index 9efa445a38..6980224a04 100644 --- a/src/NzbDrone.Core.Test/BulkImport/AddMultiMoviesFixture.cs +++ b/src/NzbDrone.Core.Test/BulkImport/AddMultiMoviesFixture.cs @@ -1,24 +1,24 @@ -using FizzWare.NBuilder; +using System.Collections.Generic; +using FizzWare.NBuilder; using FluentAssertions; -using NUnit.Framework; using Moq; -using NzbDrone.Core.Organizer; +using NUnit.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Organizer; using NzbDrone.Core.Test.Framework; -using System.Collections.Generic; namespace NzbDrone.Core.Test.BulkImport { [TestFixture] public class AddMultiMoviesFixture : CoreTest { - private List fakeMovies; + private List _fakeMovies; [SetUp] public void Setup() { - fakeMovies = Builder.CreateListOfSize(3).BuildList(); - fakeMovies.ForEach(m => + _fakeMovies = Builder.CreateListOfSize(3).BuildList(); + _fakeMovies.ForEach(m => { m.Path = null; m.RootFolderPath = @"C:\Test\TV"; @@ -32,7 +32,7 @@ public void movies_added_event_should_have_proper_path() .Setup(s => s.GetMovieFolder(It.IsAny(), null)) .Returns((Movie m, NamingConfig n) => m.Title); - var movies = Subject.AddMovies(fakeMovies); + var movies = Subject.AddMovies(_fakeMovies); foreach (Movie movie in movies) { @@ -49,9 +49,9 @@ public void movies_added_should_ignore_already_added() .Setup(s => s.GetMovieFolder(It.IsAny(), null)) .Returns((Movie m, NamingConfig n) => m.Title); - Mocker.GetMock().Setup(s => s.All()).Returns(new List { fakeMovies[0] }); + Mocker.GetMock().Setup(s => s.All()).Returns(new List { _fakeMovies[0] }); - var movies = Subject.AddMovies(fakeMovies); + var movies = Subject.AddMovies(_fakeMovies); Mocker.GetMock().Verify(v => v.InsertMany(It.Is>(l => l.Count == 2))); } @@ -63,12 +63,11 @@ public void movies_added_should_ignore_duplicates() .Setup(s => s.GetMovieFolder(It.IsAny(), null)) .Returns((Movie m, NamingConfig n) => m.Title); - fakeMovies[2].TmdbId = fakeMovies[0].TmdbId; + _fakeMovies[2].TmdbId = _fakeMovies[0].TmdbId; - var movies = Subject.AddMovies(fakeMovies); + var movies = Subject.AddMovies(_fakeMovies); Mocker.GetMock().Verify(v => v.InsertMany(It.Is>(l => l.Count == 2))); } - } } diff --git a/src/NzbDrone.Core.Test/Configuration/ConfigCachingFixture.cs b/src/NzbDrone.Core.Test/Configuration/ConfigCachingFixture.cs index 087a854d75..c903cb8391 100644 --- a/src/NzbDrone.Core.Test/Configuration/ConfigCachingFixture.cs +++ b/src/NzbDrone.Core.Test/Configuration/ConfigCachingFixture.cs @@ -5,7 +5,6 @@ using NzbDrone.Core.Configuration; using NzbDrone.Core.Test.Framework; - namespace NzbDrone.Core.Test.Configuration { [TestFixture] @@ -16,7 +15,6 @@ public void Setup() { Mocker.GetMock().Setup(c => c.All()) .Returns(new List { new Config { Key = "key1", Value = "Value1" } }); - } [Test] @@ -28,6 +26,5 @@ public void getting_value_more_than_once_should_hit_db_once() Mocker.GetMock().Verify(c => c.All(), Times.Once()); } - } } diff --git a/src/NzbDrone.Core.Test/Configuration/ConfigServiceFixture.cs b/src/NzbDrone.Core.Test/Configuration/ConfigServiceFixture.cs index ee834d507b..2ed847f4e7 100644 --- a/src/NzbDrone.Core.Test/Configuration/ConfigServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Configuration/ConfigServiceFixture.cs @@ -28,7 +28,6 @@ public void Add_new_value_to_database() AssertUpsert(key, value); } - [Test] public void Get_value_should_return_default_when_no_value() { diff --git a/src/NzbDrone.Core.Test/CustomFormat/CustomFormatsFixture.cs b/src/NzbDrone.Core.Test/CustomFormat/CustomFormatsFixture.cs index 51493cb1e0..492150de78 100644 --- a/src/NzbDrone.Core.Test/CustomFormat/CustomFormatsFixture.cs +++ b/src/NzbDrone.Core.Test/CustomFormat/CustomFormatsFixture.cs @@ -18,7 +18,7 @@ public static void GivenCustomFormats(params CustomFormats.CustomFormat[] format public static List GetSampleFormatItems(params string[] allowed) { - return _customFormats.Select(f => new ProfileFormatItem {Format = f, Allowed = allowed.Contains(f.Name)}).ToList(); + return _customFormats.Select(f => new ProfileFormatItem { Format = f, Allowed = allowed.Contains(f.Name) }).ToList(); } public static List GetDefaultFormatItems() diff --git a/src/NzbDrone.Core.Test/CustomFormat/QualityTagFixture.cs b/src/NzbDrone.Core.Test/CustomFormat/QualityTagFixture.cs index 236e1c1e7c..828bba6893 100644 --- a/src/NzbDrone.Core.Test/CustomFormat/QualityTagFixture.cs +++ b/src/NzbDrone.Core.Test/CustomFormat/QualityTagFixture.cs @@ -21,6 +21,7 @@ public class QualityTagFixture : CoreTest [TestCase("s_Dvd", TagType.Source, Source.DVD)] [TestCase("S_WEBdL", TagType.Source, Source.WEBDL)] [TestCase("S_CAM", TagType.Source, Source.CAM)] + // [TestCase("L_English", TagType.Language, Language.English)] // [TestCase("L_Italian", TagType.Language, Language.Italian)] // [TestCase("L_iTa", TagType.Language, Language.Italian)] @@ -33,9 +34,9 @@ public class QualityTagFixture : CoreTest [TestCase("C_RQ_Surround", TagType.Custom, "surround", TagModifier.AbsolutelyRequired)] [TestCase("C_RQN_Surround", TagType.Custom, "surround", TagModifier.AbsolutelyRequired, TagModifier.Not)] [TestCase("C_RQNRX_Surround|(5|7)(\\.1)?", TagType.Custom, "surround|(5|7)(\\.1)?", TagModifier.AbsolutelyRequired, TagModifier.Not, TagModifier.Regex)] - [TestCase("G_10<>20", TagType.Size, new[] { 10737418240L, 21474836480L})] - [TestCase("G_15.55<>20", TagType.Size, new[] { 16696685363L, 21474836480L})] - [TestCase("G_15.55<>25.1908754", TagType.Size, new[] { 16696685363L, 27048496500L})] + [TestCase("G_10<>20", TagType.Size, new[] { 10737418240L, 21474836480L })] + [TestCase("G_15.55<>20", TagType.Size, new[] { 16696685363L, 21474836480L })] + [TestCase("G_15.55<>25.1908754", TagType.Size, new[] { 16696685363L, 27048496500L })] [TestCase("R__1080", TagType.Resolution, Resolution.R1080p)] public void should_parse_tag_from_string(string raw, TagType type, object value, params TagModifier[] modifiers) { @@ -45,19 +46,22 @@ public void should_parse_tag_from_string(string raw, TagType type, object value, { modifier |= m; } + parsed.TagType.Should().Be(type); if (value is long[]) { - value = (((long[]) value)[0], ((long[]) value)[1]); + value = (((long[])value)[0], ((long[])value)[1]); } + if ((parsed.Value as Regex) != null) { - (parsed.Value as Regex).ToString().Should().Be((value as string)); + (parsed.Value as Regex).ToString().Should().Be(value as string); } else { parsed.Value.Should().Be(value); } + parsed.TagModifier.Should().Be(modifier); } } diff --git a/src/NzbDrone.Core.Test/Datastore/BasicRepositoryFixture.cs b/src/NzbDrone.Core.Test/Datastore/BasicRepositoryFixture.cs index 114647d3af..68f7d9fb5e 100644 --- a/src/NzbDrone.Core.Test/Datastore/BasicRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/BasicRepositoryFixture.cs @@ -9,14 +9,12 @@ namespace NzbDrone.Core.Test.Datastore { - [TestFixture] public class BasicRepositoryFixture : DbTest, ScheduledTask> { private ScheduledTask _basicType; - [SetUp] public void Setup() { @@ -44,10 +42,8 @@ public void purge_should_delete_all() Subject.Purge(); AllStoredModels.Should().BeEmpty(); - } - [Test] public void should_be_able_to_delete_model() { @@ -64,7 +60,7 @@ public void should_be_able_to_find_by_id() Subject.Insert(_basicType); var storeObject = Subject.Get(_basicType.Id); - storeObject.Should().BeEquivalentTo(_basicType, o=>o.IncludingAllRuntimeProperties()); + storeObject.Should().BeEquivalentTo(_basicType, o => o.IncludingAllRuntimeProperties()); } [Test] @@ -86,19 +82,16 @@ public void getting_model_with_invalid_id_should_throw() Assert.Throws(() => Subject.Get(12)); } - [Test] public void get_all_with_empty_db_should_return_empty_list() { Subject.All().Should().BeEmpty(); } - [Test] public void should_be_able_to_call_ToList_on_empty_quariable() { Subject.All().ToList().Should().BeEmpty(); - } } } diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/BooleanIntConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/BooleanIntConverterFixture.cs index 649a7303e7..50e1b892b0 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/BooleanIntConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/BooleanIntConverterFixture.cs @@ -27,9 +27,9 @@ public void should_return_db_null_for_null_value_when_saving_to_db() public void should_return_bool_when_getting_int_from_db(int input, bool expected) { var context = new ConverterContext - { - DbValue = (long)input - }; + { + DbValue = (long)input + }; Subject.FromDB(context).Should().Be(expected); } @@ -38,9 +38,9 @@ public void should_return_bool_when_getting_int_from_db(int input, bool expected public void should_return_db_null_for_null_value_when_getting_from_db() { var context = new ConverterContext - { - DbValue = DBNull.Value - }; + { + DbValue = DBNull.Value + }; Subject.FromDB(context).Should().Be(DBNull.Value); } @@ -49,9 +49,9 @@ public void should_return_db_null_for_null_value_when_getting_from_db() public void should_throw_for_non_boolean_equivalent_number_value_when_getting_from_db() { var context = new ConverterContext - { - DbValue = (long)2 - }; + { + DbValue = 2L + }; Assert.Throws(() => Subject.FromDB(context)); } diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/CommandConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/CommandConverterFixture.cs index 17ce66cfbb..4921bfda29 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/CommandConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/CommandConverterFixture.cs @@ -6,8 +6,8 @@ using NUnit.Framework; using NzbDrone.Common.Serializer; using NzbDrone.Core.Datastore.Converters; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies.Commands; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Datastore.Converters { @@ -42,10 +42,10 @@ public void should_return_command_when_getting_json_from_db() dataRecordMock.Setup(s => s.GetString(0)).Returns("RefreshMovie"); var context = new ConverterContext - { - DataRecord = dataRecordMock.Object, - DbValue = new RefreshMovieCommand().ToJson() - }; + { + DataRecord = dataRecordMock.Object, + DbValue = new RefreshMovieCommand().ToJson() + }; Subject.FromDB(context).Should().BeOfType(); } @@ -54,9 +54,9 @@ public void should_return_command_when_getting_json_from_db() public void should_return_null_for_null_value_when_getting_from_db() { var context = new ConverterContext - { - DbValue = DBNull.Value - }; + { + DbValue = DBNull.Value + }; Subject.FromDB(context).Should().Be(null); } diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/DoubleConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/DoubleConverterFixture.cs index bf49741241..1b5c09c7a2 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/DoubleConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/DoubleConverterFixture.cs @@ -36,9 +36,9 @@ public void should_return_double_when_getting_double_from_db() var expected = 10.5D; var context = new ConverterContext - { - DbValue = expected - }; + { + DbValue = expected + }; Subject.FromDB(context).Should().Be(expected); } @@ -49,9 +49,9 @@ public void should_return_double_when_getting_string_from_db() var expected = 10.5D; var context = new ConverterContext - { - DbValue = $"{expected}" - }; + { + DbValue = $"{expected}" + }; Subject.FromDB(context).Should().Be(expected); } @@ -60,9 +60,9 @@ public void should_return_double_when_getting_string_from_db() public void should_return_null_for_null_value_when_getting_from_db() { var context = new ConverterContext - { - DbValue = DBNull.Value - }; + { + DbValue = DBNull.Value + }; Subject.FromDB(context).Should().Be(DBNull.Value); } diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/EnumIntConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/EnumIntConverterFixture.cs index a09b49dd3b..494bba7607 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/EnumIntConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/EnumIntConverterFixture.cs @@ -5,8 +5,8 @@ using Marr.Data.Mapping; using Moq; using NUnit.Framework; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Download.Pending; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Datastore.Converters { @@ -35,10 +35,10 @@ public void should_return_enum_when_getting_int_from_db() var expected = PendingReleaseReason.Delay; var context = new ConverterContext - { - ColumnMap = new ColumnMap(mockMemberInfo.Object) { FieldType = typeof(PendingReleaseReason) }, - DbValue = (long)expected - }; + { + ColumnMap = new ColumnMap(mockMemberInfo.Object) { FieldType = typeof(PendingReleaseReason) }, + DbValue = (long)expected + }; Subject.FromDB(context).Should().Be(expected); } @@ -47,9 +47,9 @@ public void should_return_enum_when_getting_int_from_db() public void should_return_null_for_null_value_when_getting_from_db() { var context = new ConverterContext - { - DbValue = DBNull.Value - }; + { + DbValue = DBNull.Value + }; Subject.FromDB(context).Should().Be(null); } diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/GuidConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/GuidConverterFixture.cs index 8444fa053c..2d4a8e5303 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/GuidConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/GuidConverterFixture.cs @@ -30,9 +30,9 @@ public void should_return_guid_when_getting_string_from_db() var guid = Guid.NewGuid(); var context = new ConverterContext - { - DbValue = guid.ToString() - }; + { + DbValue = guid.ToString() + }; Subject.FromDB(context).Should().Be(guid); } @@ -41,9 +41,9 @@ public void should_return_guid_when_getting_string_from_db() public void should_return_empty_guid_for_db_null_value_when_getting_from_db() { var context = new ConverterContext - { - DbValue = DBNull.Value - }; + { + DbValue = DBNull.Value + }; Subject.FromDB(context).Should().Be(Guid.Empty); } diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/Int32ConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/Int32ConverterFixture.cs index 0be50e92ac..793eb5f580 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/Int32ConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/Int32ConverterFixture.cs @@ -24,9 +24,9 @@ public void should_return_int_when_getting_int_from_db() var i = 5; var context = new ConverterContext - { - DbValue = i - }; + { + DbValue = i + }; Subject.FromDB(context).Should().Be(i); } @@ -37,9 +37,9 @@ public void should_return_int_when_getting_string_from_db() var i = 5; var context = new ConverterContext - { - DbValue = i.ToString() - }; + { + DbValue = i.ToString() + }; Subject.FromDB(context).Should().Be(i); } @@ -48,9 +48,9 @@ public void should_return_int_when_getting_string_from_db() public void should_return_db_null_for_db_null_value_when_getting_from_db() { var context = new ConverterContext - { - DbValue = DBNull.Value - }; + { + DbValue = DBNull.Value + }; Subject.FromDB(context).Should().Be(DBNull.Value); } diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/OsPathConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/OsPathConverterFixture.cs index f7f3da0d87..c0c92efd39 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/OsPathConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/OsPathConverterFixture.cs @@ -28,9 +28,9 @@ public void should_return_os_path_when_getting_string_from_db() var osPath = new OsPath(path); var context = new ConverterContext - { - DbValue = path - }; + { + DbValue = path + }; Subject.FromDB(context).Should().Be(osPath); } @@ -39,9 +39,9 @@ public void should_return_os_path_when_getting_string_from_db() public void should_return_db_null_for_db_null_value_when_getting_from_db() { var context = new ConverterContext - { - DbValue = DBNull.Value - }; + { + DbValue = DBNull.Value + }; Subject.FromDB(context).Should().Be(DBNull.Value); } diff --git a/src/NzbDrone.Core.Test/Datastore/Converters/ProviderSettingConverterFixture.cs b/src/NzbDrone.Core.Test/Datastore/Converters/ProviderSettingConverterFixture.cs index efc33bf8ac..c36758be2c 100644 --- a/src/NzbDrone.Core.Test/Datastore/Converters/ProviderSettingConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Converters/ProviderSettingConverterFixture.cs @@ -15,10 +15,9 @@ public class ProviderSettingConverterFixture : CoreTest().MovieFile.Should().BeNull(); } - [Test] public void embedded_document_as_json() { - var quality = new QualityModel { Quality = Quality.Bluray720p, Revision = new Revision(version: 2 )}; + var quality = new QualityModel { Quality = Quality.Bluray720p, Revision = new Revision(version: 2) }; var languages = new List { Language.English }; var history = Builder.CreateNew() @@ -90,10 +90,8 @@ public void embedded_list_of_document_with_json() .With(c => c.Languages = languages) .Build().ToList(); - history[0].Quality = new QualityModel { Quality = Quality.HDTV1080p, Revision = new Revision(version: 2)}; - history[1].Quality = new QualityModel { Quality = Quality.Bluray720p, Revision = new Revision(version: 2)}; - - + history[0].Quality = new QualityModel { Quality = Quality.HDTV1080p, Revision = new Revision(version: 2) }; + history[1].Quality = new QualityModel { Quality = Quality.Bluray720p, Revision = new Revision(version: 2) }; Db.InsertMany(history); diff --git a/src/NzbDrone.Core.Test/Datastore/MappingExtentionFixture.cs b/src/NzbDrone.Core.Test/Datastore/MappingExtentionFixture.cs index fee3435818..4780896f35 100644 --- a/src/NzbDrone.Core.Test/Datastore/MappingExtentionFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/MappingExtentionFixture.cs @@ -12,10 +12,8 @@ namespace NzbDrone.Core.Test.Datastore [TestFixture] public class MappingExtensionFixture { - public class EmbeddedType : IEmbeddedDocument { - } public class TypeWithAllMappableProperties @@ -42,10 +40,8 @@ public void Setup() MapRepository.Instance.RegisterTypeConverter(typeof(List), new EmbeddedDocumentConverter()); MapRepository.Instance.RegisterTypeConverter(typeof(EmbeddedType), new EmbeddedDocumentConverter()); MapRepository.Instance.RegisterTypeConverter(typeof(int), new Int32Converter()); - } - [Test] public void test_mappable_types() { diff --git a/src/NzbDrone.Core.Test/Datastore/MarrDataLazyLoadingFixture.cs b/src/NzbDrone.Core.Test/Datastore/MarrDataLazyLoadingFixture.cs index d39c8528c2..05cfd3dfba 100644 --- a/src/NzbDrone.Core.Test/Datastore/MarrDataLazyLoadingFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/MarrDataLazyLoadingFixture.cs @@ -1,14 +1,13 @@ using FizzWare.NBuilder; using NUnit.Framework; -using NzbDrone.Core.Profiles; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; -using NzbDrone.Core.Qualities; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Profiles; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Datastore { - [TestFixture] public class MarrDataLazyLoadingFixture : DbTest { @@ -16,12 +15,11 @@ public class MarrDataLazyLoadingFixture : DbTest public void Setup() { var profile = new Profile - { - Name = "Test", - Cutoff = Quality.WEBDL720p.Id, - Items = Qualities.QualityFixture.GetDefaultQualities() - }; - + { + Name = "Test", + Cutoff = Quality.WEBDL720p.Id, + Items = Qualities.QualityFixture.GetDefaultQualities() + }; profile = Db.Insert(profile); @@ -48,7 +46,5 @@ public void Setup() Db.InsertMany(episodes); } - - } } diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/070_delay_profileFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/070_delay_profileFixture.cs index be2b07b669..62ed62be31 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/070_delay_profileFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/070_delay_profileFixture.cs @@ -66,30 +66,30 @@ public void should_add_tag_to_series_that_had_a_profile_with_delay_attached() var db = WithMigrationTestDb(c => { c.Insert.IntoTable("Profiles").Row(new - { - GrabDelay = 1, - Name = "OneHour", - Cutoff = 0, - Items = "[]" - }); + { + GrabDelay = 1, + Name = "OneHour", + Cutoff = 0, + Items = "[]" + }); c.Insert.IntoTable("Series").Row(new - { - TvdbId = 0, - TvRageId = 0, - Title = "Series", - TitleSlug = "series", - CleanTitle = "series", - Status = 0, - Images = "[]", - Path = @"C:\Test\Series", - Monitored = 1, - SeasonFolder = 1, - RunTime = 0, - SeriesType = 0, - UseSceneNumbering = 0, - Tags = "[1]" - }); + { + TvdbId = 0, + TvRageId = 0, + Title = "Series", + TitleSlug = "series", + CleanTitle = "series", + Status = 0, + Images = "[]", + Path = @"C:\Test\Series", + Monitored = 1, + SeasonFolder = 1, + RunTime = 0, + SeriesType = 0, + UseSceneNumbering = 0, + Tags = "[1]" + }); }); var tag = db.Query("SELECT Id, Label FROM Tags").Single(); diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/072_history_downloadIdFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/072_history_downloadIdFixture.cs index e59c58706c..59f66b25a3 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/072_history_downloadIdFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/072_history_downloadIdFixture.cs @@ -20,16 +20,15 @@ public void should_move_grab_id_from_date_to_columns() { InsertHistory(c, new Dictionary { - {"indexer","test"}, - {"downloadClientId","123"} + { "indexer", "test" }, + { "downloadClientId", "123" } }); InsertHistory(c, new Dictionary { - {"indexer","test"}, - {"downloadClientId","abc"} + { "indexer", "test" }, + { "downloadClientId", "abc" } }); - }); var history = db.Query("SELECT DownloadId, Data FROM History"); @@ -40,7 +39,6 @@ public void should_move_grab_id_from_date_to_columns() history.Should().Contain(c => c.DownloadId == "abc"); } - [Test] public void should_leave_items_with_no_grabid() { @@ -48,15 +46,14 @@ public void should_leave_items_with_no_grabid() { InsertHistory(c, new Dictionary { - {"indexer","test"}, - {"downloadClientId","123"} + { "indexer", "test" }, + { "downloadClientId", "123" } }); InsertHistory(c, new Dictionary { - {"indexer","test"} + { "indexer", "test" } }); - }); var history = db.Query("SELECT DownloadId, Data FROM History"); @@ -74,9 +71,9 @@ public void should_leave_other_data() { InsertHistory(c, new Dictionary { - {"indexer","test"}, - {"group","test2"}, - {"downloadClientId","123"} + { "indexer", "test" }, + { "group", "test2" }, + { "downloadClientId", "123" } }); }); diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/075_force_lib_updateFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/075_force_lib_updateFixture.cs index ed94d83546..29d8d411d9 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/075_force_lib_updateFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/075_force_lib_updateFixture.cs @@ -1,8 +1,8 @@ using System.Linq; using FluentAssertions; using NUnit.Framework; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Datastore.Migration; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Datastore.Migration { @@ -18,7 +18,6 @@ public void should_not_fail_on_empty_db() db.Query("SELECT * FROM Series").Should().BeEmpty(); } - [Test] public void should_reset_job_last_execution_time() { @@ -58,17 +57,17 @@ public void should_reset_series_last_sync_time() c.Insert.IntoTable("Series").Row(new { Tvdbid = 1, - TvRageId =1, - Title ="Title1", - CleanTitle ="CleanTitle1", - Status =1, - Images ="", - Path ="c:\\test", - Monitored =1, - SeasonFolder =1, - Runtime= 0, - SeriesType=0, - UseSceneNumbering =0, + TvRageId = 1, + Title = "Title1", + CleanTitle = "CleanTitle1", + Status = 1, + Images = "", + Path = "c:\\test", + Monitored = 1, + SeasonFolder = 1, + Runtime = 0, + SeriesType = 0, + UseSceneNumbering = 0, LastInfoSync = "2000-01-01 00:00:00" }); diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/081_move_dot_prefix_to_transmission_categoryFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/081_move_dot_prefix_to_transmission_categoryFixture.cs index 7aae7010e6..afd2aab459 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/081_move_dot_prefix_to_transmission_categoryFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/081_move_dot_prefix_to_transmission_categoryFixture.cs @@ -2,8 +2,8 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Common.Serializer; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Datastore.Migration; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Datastore.Migration { diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/090_update_kickass_urlFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/090_update_kickass_urlFixture.cs index 716dedb8ba..9a73fb50cf 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/090_update_kickass_urlFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/090_update_kickass_urlFixture.cs @@ -15,6 +15,7 @@ public class update_kickass_url_migration_fixture : MigrationTest { - public void AddCustomFormat(convert_regex_required_tags c, string name, params string[] formatTags) { - var customFormat = new {Name = name, FormatTags = formatTags.ToList().ToJson()}; + var customFormat = new { Name = name, FormatTags = formatTags.ToList().ToJson() }; c.Insert.IntoTable("CustomFormats").Row(customFormat); } @@ -51,7 +50,7 @@ public void should_correctly_convert_multiple() var convertedTags = items.First().DeserializedTags; convertedTags.Should().HaveCount(3); - convertedTags.Should().BeEquivalentTo( "C_RQ_HDR", "C_RX_HDR", "E_NRXRQ_Director"); + convertedTags.Should().BeEquivalentTo("C_RQ_HDR", "C_RX_HDR", "E_NRXRQ_Director"); } [Test] @@ -68,7 +67,7 @@ public void should_correctly_convert_multiple_formats() var convertedTags = items.First().DeserializedTags; convertedTags.Should().HaveCount(3); - convertedTags.Should().BeEquivalentTo( "C_RQ_HDR", "C_RX_HDR", "E_NRXRQ_Director"); + convertedTags.Should().BeEquivalentTo("C_RQ_HDR", "C_RX_HDR", "E_NRXRQ_Director"); var convertedTags2 = items.Last().DeserializedTags; diff --git a/src/NzbDrone.Core.Test/Datastore/Migration/150_fix_format_tags_double_underscoreFixture.cs b/src/NzbDrone.Core.Test/Datastore/Migration/150_fix_format_tags_double_underscoreFixture.cs index a7f7430eb3..7afde6ef0a 100644 --- a/src/NzbDrone.Core.Test/Datastore/Migration/150_fix_format_tags_double_underscoreFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/Migration/150_fix_format_tags_double_underscoreFixture.cs @@ -1,5 +1,5 @@ -using System.Linq; -using System.Collections.Generic; +using System.Collections.Generic; +using System.Linq; using FluentAssertions; using Newtonsoft.Json; using NUnit.Framework; @@ -12,10 +12,9 @@ namespace NzbDrone.Core.Test.Datastore.Migration [TestFixture] public class fix_format_tags_double_underscoreFixture : MigrationTest { - public void AddCustomFormat(fix_format_tags_double_underscore c, string name, params string[] formatTags) { - var customFormat = new {Name = name, FormatTags = formatTags.ToList().ToJson()}; + var customFormat = new { Name = name, FormatTags = formatTags.ToList().ToJson() }; c.Insert.IntoTable("CustomFormats").Row(customFormat); } diff --git a/src/NzbDrone.Core.Test/Datastore/ObjectDatabaseFixture.cs b/src/NzbDrone.Core.Test/Datastore/ObjectDatabaseFixture.cs index 84037c0505..08577f42aa 100644 --- a/src/NzbDrone.Core.Test/Datastore/ObjectDatabaseFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/ObjectDatabaseFixture.cs @@ -22,7 +22,6 @@ public void SetUp() .CreateNew() .With(s => s.Id = 0) .Build(); - } [Test] @@ -72,13 +71,12 @@ public void new_object_should_get_new_id() _sampleType.Id.Should().Be(1); } - [Test] public void should_read_and_write_in_utc() { var storedTime = DateTime.UtcNow; - _sampleType.LastExecution =storedTime; + _sampleType.LastExecution = storedTime; Subject.Insert(_sampleType); @@ -122,15 +120,14 @@ public void should_be_able_to_find_object_by_id() item.Id.Should().Be(_sampleType.Id); } - [Test] public void set_fields_should_only_update_selected_filed() { var childModel = new ScheduledTask - { - TypeName = "Address", - Interval = 12 - }; + { + TypeName = "Address", + Interval = 12 + }; Subject.Insert(childModel); @@ -143,6 +140,4 @@ public void set_fields_should_only_update_selected_filed() Db.All().Single().Interval.Should().Be(12); } } - } - diff --git a/src/NzbDrone.Core.Test/Datastore/PagingSpecExtensionsTests/PagingOffsetFixture.cs b/src/NzbDrone.Core.Test/Datastore/PagingSpecExtensionsTests/PagingOffsetFixture.cs index ad64ff036e..8a51ab9ff4 100644 --- a/src/NzbDrone.Core.Test/Datastore/PagingSpecExtensionsTests/PagingOffsetFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/PagingSpecExtensionsTests/PagingOffsetFixture.cs @@ -15,15 +15,14 @@ public class PagingOffsetFixture public void should_calcuate_expected_offset(int page, int pageSize, int expected) { var pagingSpec = new PagingSpec - { - Page = page, - PageSize = pageSize, - SortDirection = SortDirection.Ascending, - SortKey = "AirDate" - }; + { + Page = page, + PageSize = pageSize, + SortDirection = SortDirection.Ascending, + SortKey = "AirDate" + }; pagingSpec.PagingOffset().Should().Be(expected); } - } } diff --git a/src/NzbDrone.Core.Test/Datastore/PagingSpecExtensionsTests/ToSortDirectionFixture.cs b/src/NzbDrone.Core.Test/Datastore/PagingSpecExtensionsTests/ToSortDirectionFixture.cs index 0067adb1f7..2cb9546364 100644 --- a/src/NzbDrone.Core.Test/Datastore/PagingSpecExtensionsTests/ToSortDirectionFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/PagingSpecExtensionsTests/ToSortDirectionFixture.cs @@ -26,12 +26,12 @@ public void should_convert_default_to_asc() public void should_convert_ascending_to_asc() { var pagingSpec = new PagingSpec - { - Page = 1, - PageSize = 10, - SortDirection = SortDirection.Ascending, - SortKey = "AirDate" - }; + { + Page = 1, + PageSize = 10, + SortDirection = SortDirection.Ascending, + SortKey = "AirDate" + }; pagingSpec.ToSortDirection().Should().Be(Marr.Data.QGen.SortDirection.Asc); } diff --git a/src/NzbDrone.Core.Test/Datastore/ReflectionStrategyFixture/Benchmarks.cs b/src/NzbDrone.Core.Test/Datastore/ReflectionStrategyFixture/Benchmarks.cs index de162f4de7..810ae5790d 100644 --- a/src/NzbDrone.Core.Test/Datastore/ReflectionStrategyFixture/Benchmarks.cs +++ b/src/NzbDrone.Core.Test/Datastore/ReflectionStrategyFixture/Benchmarks.cs @@ -5,36 +5,35 @@ namespace NzbDrone.Core.Test.Datastore.ReflectionStrategyFixture [TestFixture] public class Benchmarks { -/* private const int iterations = 5000000; - private object _target; - private IReflectionStrategy _simpleReflectionStrategy; + /* private const int iterations = 5000000; + private object _target; + private IReflectionStrategy _simpleReflectionStrategy; - [SetUp] - public void Setup() - { - // _simpleReflectionStrategy = new DelegateReflectionStrategy(); - } + [SetUp] + public void Setup() + { + // _simpleReflectionStrategy = new DelegateReflectionStrategy(); + } - [Test] - public void clr_reflection_test() - { - _target = new Series(); + [Test] + public void clr_reflection_test() + { + _target = new Series(); - var del = _simpleReflectionStrategy.BuildSetter(typeof(Series), "Title"); + var del = _simpleReflectionStrategy.BuildSetter(typeof(Series), "Title"); - for (int i = 0; i < iterations; i++) - { - del(_target, "TestTile"); - //_simpleReflectionStrategy.SetFieldValue(_target, "Title", "TestTile"); - } - } + for (int i = 0; i < iterations; i++) + { + del(_target, "TestTile"); + //_simpleReflectionStrategy.SetFieldValue(_target, "Title", "TestTile"); + } + } - private void SetField() - { + private void SetField() + { - }*/ - + }*/ } } diff --git a/src/NzbDrone.Core.Test/Datastore/SqliteSchemaDumperTests/SqliteSchemaDumperFixture.cs b/src/NzbDrone.Core.Test/Datastore/SqliteSchemaDumperTests/SqliteSchemaDumperFixture.cs index 43f05bd9c3..64efa19ba5 100644 --- a/src/NzbDrone.Core.Test/Datastore/SqliteSchemaDumperTests/SqliteSchemaDumperFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/SqliteSchemaDumperTests/SqliteSchemaDumperFixture.cs @@ -76,7 +76,6 @@ public void should_ignore_unknown_symbols() result.Columns.First().Type.Should().Be(DbType.Int64); result.Columns.Last().Name.Should().Be("MyCol"); result.Columns.Last().Type.Should().Be(DbType.Int64); - } } } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/AcceptableSizeSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/AcceptableSizeSpecificationFixture.cs index 84fb5fa536..c052c7b95e 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/AcceptableSizeSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/AcceptableSizeSpecificationFixture.cs @@ -4,10 +4,10 @@ using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.DecisionEngineTests @@ -16,40 +16,35 @@ namespace NzbDrone.Core.Test.DecisionEngineTests public class AcceptableSizeSpecificationFixture : CoreTest { - private Movie movie; - private RemoteMovie remoteMovie; - private QualityDefinition qualityType; + private Movie _movie; + private RemoteMovie _remoteMovie; + private QualityDefinition _qualityType; [SetUp] public void Setup() { + _movie = Builder.CreateNew().Build(); - movie = Builder.CreateNew().Build(); - - qualityType = Builder.CreateNew() + _qualityType = Builder.CreateNew() .With(q => q.MinSize = 2) .With(q => q.MaxSize = 10) .With(q => q.Quality = Quality.SDTV) .Build(); - remoteMovie = new RemoteMovie + _remoteMovie = new RemoteMovie { - Movie = movie, + Movie = _movie, Release = new ReleaseInfo(), ParsedMovieInfo = new ParsedMovieInfo { Quality = new QualityModel(Quality.SDTV, new Revision(version: 2)) }, - }; Mocker.GetMock() .Setup(v => v.Get(It.IsAny())) .Returns(v => Quality.DefaultQualityDefinitions.First(c => c.Quality == v)); - - - Mocker.GetMock().Setup(s => s.Get(Quality.SDTV)).Returns(qualityType); + Mocker.GetMock().Setup(s => s.Get(Quality.SDTV)).Returns(_qualityType); } - [TestCase(30, 50, false)] [TestCase(30, 250, true)] [TestCase(30, 500, false)] @@ -58,57 +53,57 @@ public void Setup() [TestCase(60, 1000, false)] public void single_episode(int runtime, int sizeInMegaBytes, bool expectedResult) { - movie.Runtime = runtime; - remoteMovie.Movie = movie; - remoteMovie.Release.Size = sizeInMegaBytes.Megabytes(); + _movie.Runtime = runtime; + _remoteMovie.Movie = _movie; + _remoteMovie.Release.Size = sizeInMegaBytes.Megabytes(); - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().Be(expectedResult); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().Be(expectedResult); } [Test] public void should_return_true_if_size_is_zero() { - movie.Runtime = 120; - remoteMovie.Movie = movie; - remoteMovie.Release.Size = 0; - qualityType.MinSize = 10; - qualityType.MaxSize = 20; + _movie.Runtime = 120; + _remoteMovie.Movie = _movie; + _remoteMovie.Release.Size = 0; + _qualityType.MinSize = 10; + _qualityType.MaxSize = 20; - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().BeTrue(); } [Test] public void should_return_true_if_unlimited_30_minute() { - movie.Runtime = 30; - remoteMovie.Movie = movie; - remoteMovie.Release.Size = 18457280000; - qualityType.MaxSize = null; + _movie.Runtime = 30; + _remoteMovie.Movie = _movie; + _remoteMovie.Release.Size = 18457280000; + _qualityType.MaxSize = null; - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().BeTrue(); } [Test] public void should_return_true_if_unlimited_60_minute() { - movie.Runtime = 60; - remoteMovie.Movie = movie; - remoteMovie.Release.Size = 36857280000; - qualityType.MaxSize = null; + _movie.Runtime = 60; + _remoteMovie.Movie = _movie; + _remoteMovie.Release.Size = 36857280000; + _qualityType.MaxSize = null; - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().BeTrue(); } [Test] public void should_use_110_minutes_if_runtime_is_0() { - movie.Runtime = 0; - remoteMovie.Movie = movie; - remoteMovie.Release.Size = 1095.Megabytes(); + _movie.Runtime = 0; + _remoteMovie.Movie = _movie; + _remoteMovie.Release.Size = 1095.Megabytes(); - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().Be(true); - remoteMovie.Release.Size = 1105.Megabytes(); - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().Be(false); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().Be(true); + _remoteMovie.Release.Size = 1105.Megabytes(); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().Be(false); ExceptionVerification.ExpectedWarns(1); } } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/CustomFormatAllowedByProfileSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/CustomFormatAllowedByProfileSpecificationFixture.cs index 970cd52da4..38076fdc91 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/CustomFormatAllowedByProfileSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/CustomFormatAllowedByProfileSpecificationFixture.cs @@ -4,10 +4,10 @@ using Marr.Data; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; using NzbDrone.Core.Test.CustomFormat; using NzbDrone.Core.Test.Framework; @@ -17,7 +17,7 @@ namespace NzbDrone.Core.Test.DecisionEngineTests public class CustomFormatAllowedByProfileSpecificationFixture : CoreTest { - private RemoteMovie remoteMovie; + private RemoteMovie _remoteMovie; private CustomFormats.CustomFormat _format1; private CustomFormats.CustomFormat _format2; @@ -31,12 +31,11 @@ public void Setup() _format2 = new CustomFormats.CustomFormat("Cool Format"); _format2.Id = 2; - var fakeSeries = Builder.CreateNew() .With(c => c.Profile = (LazyLoaded)new Profile { Cutoff = Quality.Bluray1080p.Id }) .Build(); - remoteMovie = new RemoteMovie + _remoteMovie = new RemoteMovie { Movie = fakeSeries, ParsedMovieInfo = new ParsedMovieInfo { Quality = new QualityModel(Quality.DVD, new Revision(version: 2)) }, @@ -48,55 +47,55 @@ public void Setup() [Test] public void should_allow_if_format_is_defined_in_profile() { - remoteMovie.ParsedMovieInfo.Quality.CustomFormats = new List {_format1}; - remoteMovie.Movie.Profile.Value.FormatItems = CustomFormatsFixture.GetSampleFormatItems(_format1.Name); + _remoteMovie.ParsedMovieInfo.Quality.CustomFormats = new List { _format1 }; + _remoteMovie.Movie.Profile.Value.FormatItems = CustomFormatsFixture.GetSampleFormatItems(_format1.Name); - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().BeTrue(); } [Test] public void should_deny_if_format_is_defined_in_profile() { - remoteMovie.ParsedMovieInfo.Quality.CustomFormats = new List {_format2}; - remoteMovie.Movie.Profile.Value.FormatItems = CustomFormatsFixture.GetSampleFormatItems(_format1.Name); + _remoteMovie.ParsedMovieInfo.Quality.CustomFormats = new List { _format2 }; + _remoteMovie.Movie.Profile.Value.FormatItems = CustomFormatsFixture.GetSampleFormatItems(_format1.Name); - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().BeFalse(); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().BeFalse(); } [Test] public void should_deny_if_one_format_is_defined_in_profile() { - remoteMovie.ParsedMovieInfo.Quality.CustomFormats = new List {_format2, _format1}; - remoteMovie.Movie.Profile.Value.FormatItems = CustomFormatsFixture.GetSampleFormatItems(_format1.Name); + _remoteMovie.ParsedMovieInfo.Quality.CustomFormats = new List { _format2, _format1 }; + _remoteMovie.Movie.Profile.Value.FormatItems = CustomFormatsFixture.GetSampleFormatItems(_format1.Name); - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().BeFalse(); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().BeFalse(); } [Test] public void should_allow_if_all_format_is_defined_in_profile() { - remoteMovie.ParsedMovieInfo.Quality.CustomFormats = new List {_format2, _format1}; - remoteMovie.Movie.Profile.Value.FormatItems = CustomFormatsFixture.GetSampleFormatItems(_format1.Name, _format2.Name); + _remoteMovie.ParsedMovieInfo.Quality.CustomFormats = new List { _format2, _format1 }; + _remoteMovie.Movie.Profile.Value.FormatItems = CustomFormatsFixture.GetSampleFormatItems(_format1.Name, _format2.Name); - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().BeTrue(); } [Test] public void should_deny_if_no_format_was_parsed_and_none_not_in_profile() { - remoteMovie.ParsedMovieInfo.Quality.CustomFormats = new List {}; - remoteMovie.Movie.Profile.Value.FormatItems = CustomFormatsFixture.GetSampleFormatItems(_format1.Name, _format2.Name); + _remoteMovie.ParsedMovieInfo.Quality.CustomFormats = new List { }; + _remoteMovie.Movie.Profile.Value.FormatItems = CustomFormatsFixture.GetSampleFormatItems(_format1.Name, _format2.Name); - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().BeFalse(); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().BeFalse(); } [Test] public void should_allow_if_no_format_was_parsed_and_none_in_profile() { - remoteMovie.ParsedMovieInfo.Quality.CustomFormats = new List {}; - remoteMovie.Movie.Profile.Value.FormatItems = CustomFormatsFixture.GetSampleFormatItems(CustomFormats.CustomFormat.None.Name, _format1.Name, _format2.Name); + _remoteMovie.ParsedMovieInfo.Quality.CustomFormats = new List { }; + _remoteMovie.Movie.Profile.Value.FormatItems = CustomFormatsFixture.GetSampleFormatItems(CustomFormats.CustomFormat.None.Name, _format1.Name, _format2.Name); - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().BeTrue(); } } } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/CutoffSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/CutoffSpecificationFixture.cs index 07b50b1b9a..31dcc4b6c4 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/CutoffSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/CutoffSpecificationFixture.cs @@ -1,29 +1,27 @@ using System.Collections.Generic; using FluentAssertions; using NUnit.Framework; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; -using NzbDrone.Core.DecisionEngine.Specifications; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Test.CustomFormat; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests { [TestFixture] public class CutoffSpecificationFixture : CoreTest { - private CustomFormats.CustomFormat _customFormat; [SetUp] public void Setup() { - } private void GivenCustomFormatHigher() { - _customFormat = new CustomFormats.CustomFormat("My Format", "L_ENGLISH") {Id = 1}; + _customFormat = new CustomFormats.CustomFormat("My Format", "L_ENGLISH") { Id = 1 }; CustomFormatsFixture.GivenCustomFormats(_customFormat, CustomFormats.CustomFormat.None); } @@ -70,9 +68,9 @@ public void should_return_false_if_custom_formats_is_met_and_quality_and_format_ { GivenCustomFormatHigher(); var old = new QualityModel(Quality.HDTV720p); - old.CustomFormats = new List {CustomFormats.CustomFormat.None}; + old.CustomFormats = new List { CustomFormats.CustomFormat.None }; var newQ = new QualityModel(Quality.Bluray1080p); - newQ.CustomFormats = new List {_customFormat}; + newQ.CustomFormats = new List { _customFormat }; Subject.CutoffNotMet( new Profile { @@ -80,20 +78,22 @@ public void should_return_false_if_custom_formats_is_met_and_quality_and_format_ Items = Qualities.QualityFixture.GetDefaultQualities(), FormatCutoff = CustomFormats.CustomFormat.None.Id, FormatItems = CustomFormatsFixture.GetSampleFormatItems("None", "My Format") - }, old, newQ).Should().BeFalse(); + }, + old, + newQ).Should().BeFalse(); } [Test] public void should_return_true_if_cutoffs_are_met_but_is_a_revision_upgrade() { - Profile _profile = new Profile + Profile profile = new Profile { Cutoff = Quality.HDTV1080p.Id, Items = Qualities.QualityFixture.GetDefaultQualities(), }; Subject.CutoffNotMet( - _profile, + profile, new QualityModel(Quality.WEBDL1080p, new Revision(version: 1)), new QualityModel(Quality.WEBDL1080p, new Revision(version: 2))).Should().BeTrue(); } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/DownloadDecisionMakerFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/DownloadDecisionMakerFixture.cs index 0885d8a84c..cd192ea14b 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/DownloadDecisionMakerFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/DownloadDecisionMakerFixture.cs @@ -4,13 +4,13 @@ using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.IndexerSearch.Definitions; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; -using NzbDrone.Core.DecisionEngine.Specifications; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -51,15 +51,15 @@ public void Setup() _fail3.Setup(c => c.IsSatisfiedBy(It.IsAny(), null)).Returns(Decision.Reject("fail3")); _reports = new List { new ReleaseInfo { Title = "Trolls.2016.720p.WEB-DL.DD5.1.H264-FGT" } }; - _remoteEpisode = new RemoteMovie { + _remoteEpisode = new RemoteMovie + { Movie = new Movie(), ParsedMovieInfo = new ParsedMovieInfo() }; - _mappingResult = new MappingResult {Movie = new Movie(), MappingResultType = MappingResultType.Success}; + _mappingResult = new MappingResult { Movie = new Movie(), MappingResultType = MappingResultType.Success }; _mappingResult.RemoteMovie = _remoteEpisode; - Mocker.GetMock() .Setup(c => c.Map(It.IsAny(), It.IsAny(), It.IsAny())).Returns(_mappingResult); } @@ -184,9 +184,9 @@ public void broken_report_shouldnt_blowup_the_process() _reports = new List { - new ReleaseInfo{Title = "Trolls.2016.720p.WEB-DL.DD5.1.H264-FGT"}, - new ReleaseInfo{Title = "Trolls.2016.720p.WEB-DL.DD5.1.H264-FGT"}, - new ReleaseInfo{Title = "Trolls.2016.720p.WEB-DL.DD5.1.H264-FGT"} + new ReleaseInfo { Title = "Trolls.2016.720p.WEB-DL.DD5.1.H264-FGT" }, + new ReleaseInfo { Title = "Trolls.2016.720p.WEB-DL.DD5.1.H264-FGT" }, + new ReleaseInfo { Title = "Trolls.2016.720p.WEB-DL.DD5.1.H264-FGT" } }; Subject.GetRssDecision(_reports); @@ -248,7 +248,7 @@ public void should_return_a_decision_when_exception_is_caught() _reports = new List { - new ReleaseInfo{Title = "Trolls.2016.720p.WEB-DL.DD5.1.H264-FGT"}, + new ReleaseInfo { Title = "Trolls.2016.720p.WEB-DL.DD5.1.H264-FGT" }, }; Subject.GetRssDecision(_reports).Should().HaveCount(1); diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/HistorySpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/HistorySpecificationFixture.cs index cfc1472eb5..128e42b76c 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/HistorySpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/HistorySpecificationFixture.cs @@ -4,29 +4,30 @@ using Moq; using NUnit.Framework; using NzbDrone.Core.Configuration; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.DecisionEngine.Specifications.RssSync; using NzbDrone.Core.History; using NzbDrone.Core.IndexerSearch.Definitions; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.DecisionEngine.Specifications; namespace NzbDrone.Core.Test.DecisionEngineTests { [TestFixture] public class HistorySpecificationFixture : CoreTest { + private const int FIRST_EPISODE_ID = 1; + private const int SECOND_EPISODE_ID = 2; + private HistorySpecification _upgradeHistory; private RemoteMovie _parseResultSingle; private QualityModel _upgradableQuality; private QualityModel _notupgradableQuality; private Movie _fakeMovie; - private const int FIRST_EPISODE_ID = 1; - private const int SECOND_EPISODE_ID = 2; [SetUp] public void Setup() @@ -85,13 +86,12 @@ public void should_return_true_if_latest_history_item_is_not_grabbed() _upgradeHistory.IsSatisfiedBy(_parseResultSingle, null).Accepted.Should().BeTrue(); } -// [Test] -// public void should_return_true_if_latest_history_has_a_download_id_and_cdh_is_enabled() -// { -// GivenMostRecentForEpisode(FIRST_EPISODE_ID, "test", _notupgradableQuality, DateTime.UtcNow, HistoryEventType.Grabbed); -// _upgradeHistory.IsSatisfiedBy(_parseResultMulti, null).Accepted.Should().BeTrue(); -// } - + // [Test] + // public void should_return_true_if_latest_history_has_a_download_id_and_cdh_is_enabled() + // { + // GivenMostRecentForEpisode(FIRST_EPISODE_ID, "test", _notupgradableQuality, DateTime.UtcNow, HistoryEventType.Grabbed); + // _upgradeHistory.IsSatisfiedBy(_parseResultMulti, null).Accepted.Should().BeTrue(); + // } [Test] public void should_return_true_if_latest_history_item_is_older_than_twelve_hours() { diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/LanguageSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/LanguageSpecificationFixture.cs index 0e98bd46c9..919fb3ecf7 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/LanguageSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/LanguageSpecificationFixture.cs @@ -3,11 +3,11 @@ using Marr.Data; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; +using NzbDrone.Core.Languages; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; -using NzbDrone.Core.Languages; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -24,26 +24,26 @@ public void Setup() { ParsedMovieInfo = new ParsedMovieInfo { - Languages = new List {Language.English} + Languages = new List { Language.English } }, Movie = new Movie - { - Profile = new LazyLoaded(new Profile - { - Language = Language.English - }) - } + { + Profile = new LazyLoaded(new Profile + { + Language = Language.English + }) + } }; } private void WithEnglishRelease() { - _remoteMovie.ParsedMovieInfo.Languages = new List {Language.English}; + _remoteMovie.ParsedMovieInfo.Languages = new List { Language.English }; } private void WithGermanRelease() { - _remoteMovie.ParsedMovieInfo.Languages = new List {Language.German}; + _remoteMovie.ParsedMovieInfo.Languages = new List { Language.German }; } [Test] diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/MonitoredMovieSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/MonitoredMovieSpecificationFixture.cs index 298984e65d..869550f6b7 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/MonitoredMovieSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/MonitoredMovieSpecificationFixture.cs @@ -4,8 +4,8 @@ using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications.RssSync; using NzbDrone.Core.IndexerSearch.Definitions; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests @@ -34,7 +34,6 @@ public void Setup() _firstEpisode = new Movie() { Monitored = true }; _secondEpisode = new Movie() { Monitored = true }; - var singleEpisodeList = new List { _firstEpisode }; var doubleEpisodeList = new List { _firstEpisode, _secondEpisode }; @@ -79,8 +78,7 @@ public void only_episode_not_monitored_should_return_false() public void should_return_true_for_single_episode_search() { _fakeSeries.Monitored = false; - _monitoredEpisodeSpecification.IsSatisfiedBy(_parseResultSingle, new MovieSearchCriteria {UserInvokedSearch = true}).Accepted.Should().BeTrue(); + _monitoredEpisodeSpecification.IsSatisfiedBy(_parseResultSingle, new MovieSearchCriteria { UserInvokedSearch = true }).Accepted.Should().BeTrue(); } - } } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/PrioritizeDownloadDecisionFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/PrioritizeDownloadDecisionFixture.cs index 7826542d3c..3cf32ce995 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/PrioritizeDownloadDecisionFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/PrioritizeDownloadDecisionFixture.cs @@ -1,24 +1,25 @@ using System; using System.Collections.Generic; using System.Linq; -using Moq; -using NzbDrone.Core.Indexers; -using NzbDrone.Core.Profiles.Delay; -using NzbDrone.Core.Movies; -using NzbDrone.Core.Profiles; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.DecisionEngine; -using NUnit.Framework; -using FluentAssertions; using FizzWare.NBuilder; +using FluentAssertions; +using Moq; +using NUnit.Framework; using NzbDrone.Common.Extensions; +using NzbDrone.Core.DecisionEngine; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Profiles; +using NzbDrone.Core.Profiles.Delay; +using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.CustomFormat; using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests { [TestFixture] + //TODO: Update for custom qualities! public class PrioritizeDownloadDecisionFixture : CoreTest { @@ -30,8 +31,8 @@ public void Setup() { GivenPreferredDownloadProtocol(DownloadProtocol.Usenet); - _customFormat1 = new CustomFormats.CustomFormat("My Format 1", "L_ENGLISH"){Id=1}; - _customFormat2 = new CustomFormats.CustomFormat("My Format 2", "L_FRENCH"){Id=2}; + _customFormat1 = new CustomFormats.CustomFormat("My Format 1", "L_ENGLISH") { Id = 1 }; + _customFormat2 = new CustomFormats.CustomFormat("My Format 2", "L_FRENCH") { Id = 2 }; CustomFormatsFixture.GivenCustomFormats(CustomFormats.CustomFormat.None, _customFormat1, _customFormat2); } @@ -44,8 +45,12 @@ private RemoteMovie GivenRemoteMovie(QualityModel quality, int age = 0, long siz remoteMovie.ParsedMovieInfo.Year = 1998; remoteMovie.ParsedMovieInfo.Quality = quality; - remoteMovie.Movie = Builder.CreateNew().With(m => m.Profile = new Profile { Items = Qualities.QualityFixture.GetDefaultQualities(), - PreferredTags = new List { "DTS-HD", "SPARKS"}, FormatItems = CustomFormatsFixture.GetSampleFormatItems() }) + remoteMovie.Movie = Builder.CreateNew().With(m => m.Profile = new Profile + { + Items = Qualities.QualityFixture.GetDefaultQualities(), + PreferredTags = new List { "DTS-HD", "SPARKS" }, + FormatItems = CustomFormatsFixture.GetSampleFormatItems() + }) .With(m => m.Title = "A Movie").Build(); remoteMovie.Release = new ReleaseInfo(); @@ -119,7 +124,6 @@ public void should_order_by_youngest() var remoteEpisode1 = GivenRemoteMovie(new QualityModel(Quality.HDTV720p), age: 10); var remoteEpisode2 = GivenRemoteMovie(new QualityModel(Quality.HDTV720p), age: 5); - var decisions = new List(); decisions.Add(new DownloadDecision(remoteEpisode1)); decisions.Add(new DownloadDecision(remoteEpisode2)); @@ -185,7 +189,7 @@ public void should_prefer_releases_with_more_seeders() decisions.Add(new DownloadDecision(remoteEpisode2)); var qualifiedReports = Subject.PrioritizeDecisionsForMovies(decisions); - ((TorrentInfo) qualifiedReports.First().RemoteMovie.Release).Seeders.Should().Be(torrentInfo2.Seeders); + ((TorrentInfo)qualifiedReports.First().RemoteMovie.Release).Seeders.Should().Be(torrentInfo2.Seeders); } [Test] @@ -201,7 +205,6 @@ public void should_prefer_releases_with_more_peers_given_equal_number_of_seeds() torrentInfo1.Seeders = 10; torrentInfo1.Peers = 10; - var torrentInfo2 = torrentInfo1.JsonClone(); torrentInfo2.Peers = 100; @@ -231,7 +234,6 @@ public void should_prefer_releases_with_more_peers_no_seeds() torrentInfo1.Seeders = 0; torrentInfo1.Peers = 10; - var torrentInfo2 = torrentInfo1.JsonClone(); torrentInfo2.Seeders = 0; torrentInfo2.Peers = 100; @@ -277,7 +279,7 @@ public void should_prefer_first_release_if_peers_and_size_are_too_similar() decisions.Add(new DownloadDecision(remoteEpisode2)); var qualifiedReports = Subject.PrioritizeDecisionsForMovies(decisions); - ((TorrentInfo) qualifiedReports.First().RemoteMovie.Release).Should().Be(torrentInfo1); + ((TorrentInfo)qualifiedReports.First().RemoteMovie.Release).Should().Be(torrentInfo1); } [Test] diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/ProtocolSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/ProtocolSpecificationFixture.cs index f1ef0ddd9d..ada976e0a1 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/ProtocolSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/ProtocolSpecificationFixture.cs @@ -4,10 +4,10 @@ using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Indexers; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Delay; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.DecisionEngineTests { diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/QualityAllowedByProfileSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/QualityAllowedByProfileSpecificationFixture.cs index 980e7363f8..ddaebf8dea 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/QualityAllowedByProfileSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/QualityAllowedByProfileSpecificationFixture.cs @@ -3,10 +3,10 @@ using Marr.Data; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests @@ -15,7 +15,7 @@ namespace NzbDrone.Core.Test.DecisionEngineTests public class QualityAllowedByProfileSpecificationFixture : CoreTest { - private RemoteMovie remoteMovie; + private RemoteMovie _remoteMovie; public static object[] AllowedTestCases = { @@ -38,29 +38,31 @@ public void Setup() .With(c => c.Profile = (LazyLoaded)new Profile { Cutoff = Quality.Bluray1080p.Id }) .Build(); - remoteMovie = new RemoteMovie + _remoteMovie = new RemoteMovie { Movie = fakeSeries, ParsedMovieInfo = new ParsedMovieInfo { Quality = new QualityModel(Quality.DVD, new Revision(version: 2)) }, }; } - [Test, TestCaseSource("AllowedTestCases")] + [Test] + [TestCaseSource("AllowedTestCases")] public void should_allow_if_quality_is_defined_in_profile(Quality qualityType) { - remoteMovie.ParsedMovieInfo.Quality.Quality = qualityType; - remoteMovie.Movie.Profile.Value.Items = Qualities.QualityFixture.GetDefaultQualities(Quality.DVD, Quality.HDTV720p, Quality.Bluray1080p); + _remoteMovie.ParsedMovieInfo.Quality.Quality = qualityType; + _remoteMovie.Movie.Profile.Value.Items = Qualities.QualityFixture.GetDefaultQualities(Quality.DVD, Quality.HDTV720p, Quality.Bluray1080p); - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().BeTrue(); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().BeTrue(); } - [Test, TestCaseSource("DeniedTestCases")] + [Test] + [TestCaseSource("DeniedTestCases")] public void should_not_allow_if_quality_is_not_defined_in_profile(Quality qualityType) { - remoteMovie.ParsedMovieInfo.Quality.Quality = qualityType; - remoteMovie.Movie.Profile.Value.Items = Qualities.QualityFixture.GetDefaultQualities(Quality.DVD, Quality.HDTV720p, Quality.Bluray1080p); + _remoteMovie.ParsedMovieInfo.Quality.Quality = qualityType; + _remoteMovie.Movie.Profile.Value.Items = Qualities.QualityFixture.GetDefaultQualities(Quality.DVD, Quality.HDTV720p, Quality.Bluray1080p); - Subject.IsSatisfiedBy(remoteMovie, null).Accepted.Should().BeFalse(); + Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().BeFalse(); } } } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/QualityUpgradeSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/QualityUpgradeSpecificationFixture.cs index f8d7985938..9075955662 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/QualityUpgradeSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/QualityUpgradeSpecificationFixture.cs @@ -1,9 +1,9 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Configuration; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; -using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests @@ -26,7 +26,6 @@ public class QualityUpgradeSpecificationFixture : CoreTest(); _movie = Builder.CreateNew() - .With(e => e.Profile = new Profile { + .With(e => e.Profile = new Profile + { Items = Qualities.QualityFixture.GetDefaultQualities(), UpgradeAllowed = true }) @@ -88,9 +89,9 @@ public void should_return_true_when_quality_in_queue_is_lower() var remoteMovie = Builder.CreateNew() .With(r => r.Movie = _movie) .With(r => r.ParsedMovieInfo = new ParsedMovieInfo - { - Quality = new QualityModel(Quality.SDTV) - }) + { + Quality = new QualityModel(Quality.SDTV) + }) .Build(); GivenQueue(new List { remoteMovie }); @@ -103,9 +104,9 @@ public void should_return_false_when_qualities_are_the_same() var remoteMovie = Builder.CreateNew() .With(r => r.Movie = _movie) .With(r => r.ParsedMovieInfo = new ParsedMovieInfo - { - Quality = new QualityModel(Quality.DVD) - }) + { + Quality = new QualityModel(Quality.DVD) + }) .Build(); GivenQueue(new List { remoteMovie }); @@ -120,9 +121,9 @@ public void should_return_false_when_quality_in_queue_is_better() var remoteMovie = Builder.CreateNew() .With(r => r.Movie = _movie) .With(r => r.ParsedMovieInfo = new ParsedMovieInfo - { - Quality = new QualityModel(Quality.HDTV720p) - }) + { + Quality = new QualityModel(Quality.HDTV720p) + }) .Build(); GivenQueue(new List { remoteMovie }); @@ -147,7 +148,6 @@ public void should_return_false_if_quality_in_queue_meets_cutoff() Subject.IsSatisfiedBy(_remoteMovie, null).Accepted.Should().BeFalse(); } - [Test] public void should_return_false_when_quality_is_better_and_upgrade_allowed_is_false_for_quality_profile() { diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/RawDiskSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/RawDiskSpecificationFixture.cs index b3f63dfdea..41a6ddbeb0 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/RawDiskSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/RawDiskSpecificationFixture.cs @@ -1,10 +1,9 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; -using NzbDrone.Core.Parser.Model; - -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Indexers; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -20,10 +19,10 @@ public void Setup() _remoteMovie = new RemoteMovie { Release = new ReleaseInfo - { - Title = "Movie.title.1998", - DownloadProtocol = DownloadProtocol.Torrent - } + { + Title = "Movie.title.1998", + DownloadProtocol = DownloadProtocol.Torrent + } }; } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/ReleaseRestrictionsSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/ReleaseRestrictionsSpecificationFixture.cs index 877c9932b5..280c1dbbd1 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/ReleaseRestrictionsSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/ReleaseRestrictionsSpecificationFixture.cs @@ -3,10 +3,10 @@ using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Restrictions; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.DecisionEngineTests { @@ -20,15 +20,15 @@ public void Setup() { _remoteMovie = new RemoteMovie { - Movie = new Movie - { - Tags = new HashSet() - }, - Release = new ReleaseInfo - { - Title = "Dexter.S08E01.EDITED.WEBRip.x264-KYR" - } - }; + Movie = new Movie + { + Tags = new HashSet() + }, + Release = new ReleaseInfo + { + Title = "Dexter.S08E01.EDITED.WEBRip.x264-KYR" + } + }; Mocker.SetConstant(Mocker.Resolve()); } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/RepackSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/RepackSpecificationFixture.cs index 75837fc946..0de0b35e64 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/RepackSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/RepackSpecificationFixture.cs @@ -1,12 +1,12 @@ using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; -using NzbDrone.Core.Qualities; using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests { diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/DelaySpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/DelaySpecificationFixture.cs index b35e6cae3f..e4f5265959 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/DelaySpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/DelaySpecificationFixture.cs @@ -11,12 +11,12 @@ using NzbDrone.Core.Indexers; using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Profiles.Delay; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.DecisionEngineTests.RssSync { @@ -58,7 +58,6 @@ public void Setup() //_remoteEpisode.Episodes = Builder.CreateListOfSize(1).Build().ToList(); //_remoteEpisode.Episodes.First().EpisodeFileId = 0; - Mocker.GetMock() .Setup(s => s.BestForTags(It.IsAny>())) .Returns(_delayProfile); @@ -76,7 +75,6 @@ private void GivenExistingFile(QualityModel quality) // { // Quality = quality // }); - _remoteEpisode.Movie.MovieFile = new LazyLoaded(new MovieFile { Quality = quality }); } diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/ProperSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/ProperSpecificationFixture.cs index 4a232435de..21e9a5affc 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/ProperSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/RssSync/ProperSpecificationFixture.cs @@ -3,15 +3,14 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Configuration; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.DecisionEngine.Specifications.RssSync; using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; -using NzbDrone.Core.DecisionEngine.Specifications; - using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests.RssSync diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/Search/MovieSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/Search/MovieSpecificationFixture.cs index ca44fe1868..6c8a656344 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/Search/MovieSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/Search/MovieSpecificationFixture.cs @@ -3,8 +3,8 @@ using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications.Search; using NzbDrone.Core.IndexerSearch.Definitions; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser.Model; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.DecisionEngineTests.Search diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/Search/TorrentSeedingSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/Search/TorrentSeedingSpecificationFixture.cs index 24172a9c7d..979f7b5384 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/Search/TorrentSeedingSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/Search/TorrentSeedingSpecificationFixture.cs @@ -6,8 +6,8 @@ using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.Indexers; using NzbDrone.Core.Indexers.TorrentRss; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser.Model; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.DecisionEngineTests.Search @@ -32,6 +32,7 @@ public void Setup() IndexerId = 1, Title = "Series.Title.S01.720p.BluRay.X264-RlsGrp", Seeders = 0, + //IndexerSettings = new TorrentRssIndexerSettings {MinimumSeeders = 5} } }; @@ -64,7 +65,6 @@ public void should_return_true_if_not_torrent() } // These tests are not needed anymore, since indexer settings are saved on the release itself! - [Test] public void should_return_true_if_indexer_not_specified() { diff --git a/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeDiskSpecificationFixture.cs b/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeDiskSpecificationFixture.cs index 6dc1d50718..4882e69b02 100644 --- a/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeDiskSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/DecisionEngineTests/UpgradeDiskSpecificationFixture.cs @@ -4,10 +4,10 @@ using NUnit.Framework; using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.DecisionEngineTests diff --git a/src/NzbDrone.Core.Test/DiskSpace/DiskSpaceServiceFixture.cs b/src/NzbDrone.Core.Test/DiskSpace/DiskSpaceServiceFixture.cs index 9b739060b5..36f15cc591 100644 --- a/src/NzbDrone.Core.Test/DiskSpace/DiskSpaceServiceFixture.cs +++ b/src/NzbDrone.Core.Test/DiskSpace/DiskSpaceServiceFixture.cs @@ -5,8 +5,8 @@ using NUnit.Framework; using NzbDrone.Common.Disk; using NzbDrone.Core.DiskSpace; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.DiskSpace diff --git a/src/NzbDrone.Core.Test/Download/CompletedDownloadServiceFixture.cs b/src/NzbDrone.Core.Test/Download/CompletedDownloadServiceFixture.cs index 1b49369cdb..1e2a56bb75 100644 --- a/src/NzbDrone.Core.Test/Download/CompletedDownloadServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Download/CompletedDownloadServiceFixture.cs @@ -11,10 +11,10 @@ using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.MovieImport; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download @@ -41,7 +41,6 @@ public void Setup() .With(c => c.RemoteMovie = remoteEpisode) .Build(); - Mocker.GetMock() .SetupGet(c => c.Definition) .Returns(new DownloadClientDefinition { Id = 1, Name = "testClient" }); @@ -57,7 +56,6 @@ public void Setup() Mocker.GetMock() .Setup(s => s.GetMovie("Drone.1998")) .Returns(remoteEpisode.Movie); - } private RemoteMovie BuildRemoteMovie() @@ -68,7 +66,6 @@ private RemoteMovie BuildRemoteMovie() }; } - private void GivenNoGrabbedHistory() { Mocker.GetMock() @@ -86,7 +83,6 @@ private void GivenSuccessfulImport() }); } - private void GivenABadlyNamedDownload() { _trackedDownload.DownloadItem.DownloadId = "1234"; @@ -152,7 +148,7 @@ public void should_process_if_matching_history_is_not_found_but_category_specifi [Test] public void should_not_process_if_output_path_is_empty() { - _trackedDownload.DownloadItem.OutputPath = new OsPath(); + _trackedDownload.DownloadItem.OutputPath = default; Subject.Process(_trackedDownload); @@ -168,11 +164,11 @@ public void should_mark_as_imported_if_all_episodes_were_imported() { new ImportResult( new ImportDecision( - new LocalMovie {Path = @"C:\TestPath\Droned.1998.mkv"})), + new LocalMovie { Path = @"C:\TestPath\Droned.1998.mkv" })), - new ImportResult( + new ImportResult( new ImportDecision( - new LocalMovie {Path = @"C:\TestPath\Droned.1998.mkv"})) + new LocalMovie { Path = @"C:\TestPath\Droned.1998.mkv" })) }); Subject.Process(_trackedDownload); @@ -189,11 +185,11 @@ public void should_not_mark_as_imported_if_all_files_were_rejected() { new ImportResult( new ImportDecision( - new LocalMovie {Path = @"C:\TestPath\Droned.1998.mkv"}, new Rejection("Rejected!")), "Test Failure"), + new LocalMovie { Path = @"C:\TestPath\Droned.1998.mkv" }, new Rejection("Rejected!")), "Test Failure"), - new ImportResult( + new ImportResult( new ImportDecision( - new LocalMovie {Path = @"C:\TestPath\Droned.1999.mkv"},new Rejection("Rejected!")), "Test Failure") + new LocalMovie { Path = @"C:\TestPath\Droned.1999.mkv" }, new Rejection("Rejected!")), "Test Failure") }); Subject.Process(_trackedDownload); @@ -213,11 +209,11 @@ public void should_not_mark_as_imported_if_no_episodes_were_parsed() { new ImportResult( new ImportDecision( - new LocalMovie {Path = @"C:\TestPath\Droned.1998.mkv"}, new Rejection("Rejected!")), "Test Failure"), + new LocalMovie { Path = @"C:\TestPath\Droned.1998.mkv" }, new Rejection("Rejected!")), "Test Failure"), - new ImportResult( + new ImportResult( new ImportDecision( - new LocalMovie {Path = @"C:\TestPath\Droned.1998.mkv"},new Rejection("Rejected!")), "Test Failure") + new LocalMovie { Path = @"C:\TestPath\Droned.1998.mkv" }, new Rejection("Rejected!")), "Test Failure") }); _trackedDownload.RemoteMovie.Movie = null; @@ -234,11 +230,10 @@ public void should_not_mark_as_imported_if_all_files_were_skipped() .Setup(v => v.ProcessPath(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new List { - new ImportResult(new ImportDecision(new LocalMovie {Path = @"C:\TestPath\Droned.1998.mkv"}),"Test Failure"), - new ImportResult(new ImportDecision(new LocalMovie {Path = @"C:\TestPath\Droned.1998.mkv"}),"Test Failure") + new ImportResult(new ImportDecision(new LocalMovie { Path = @"C:\TestPath\Droned.1998.mkv" }), "Test Failure"), + new ImportResult(new ImportDecision(new LocalMovie { Path = @"C:\TestPath\Droned.1998.mkv" }), "Test Failure") }); - Subject.Process(_trackedDownload); AssertNoCompletedDownload(); @@ -253,8 +248,8 @@ public void should_mark_as_imported_if_all_episodes_were_imported_but_extra_file .Setup(v => v.ProcessPath(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new List { - new ImportResult(new ImportDecision(new LocalMovie {Path = @"C:\TestPath\Droned.1998.mkv"})), - new ImportResult(new ImportDecision(new LocalMovie{Path = @"C:\TestPath\Droned.1998.mkv"}),"Test Failure") + new ImportResult(new ImportDecision(new LocalMovie { Path = @"C:\TestPath\Droned.1998.mkv" })), + new ImportResult(new ImportDecision(new LocalMovie { Path = @"C:\TestPath\Droned.1998.mkv" }), "Test Failure") }); Subject.Process(_trackedDownload); @@ -271,7 +266,7 @@ public void should_mark_as_imported_if_the_download_can_be_tracked_using_the_sou .Setup(v => v.ProcessPath(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new List { - new ImportResult(new ImportDecision(new LocalMovie {Path = @"C:\TestPath\Droned.1998.mkv"})) + new ImportResult(new ImportDecision(new LocalMovie { Path = @"C:\TestPath\Droned.1998.mkv" })) }); Mocker.GetMock() @@ -292,7 +287,7 @@ public void should_not_mark_as_imported_if_the_download_cannot_be_tracked_using_ .Setup(v => v.ProcessPath(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new List { - new ImportResult(new ImportDecision(new LocalMovie {Path = @"C:\TestPath\Droned.1998.mkv"})) + new ImportResult(new ImportDecision(new LocalMovie { Path = @"C:\TestPath\Droned.1998.mkv" })) }); Mocker.GetMock() @@ -318,12 +313,11 @@ public void should_not_import_when_there_is_a_title_mismatch() [Test] public void should_mark_as_import_title_mismatch_if_ignore_warnings_is_true() { - Mocker.GetMock() .Setup(v => v.ProcessPath(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new List { - new ImportResult(new ImportDecision(new LocalMovie {Path = @"C:\TestPath\Droned.1998.mkv"})) + new ImportResult(new ImportDecision(new LocalMovie { Path = @"C:\TestPath\Droned.1998.mkv" })) }); Subject.Process(_trackedDownload, true); diff --git a/src/NzbDrone.Core.Test/Download/DownloadApprovedReportsTests/DownloadApprovedFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadApprovedReportsTests/DownloadApprovedFixture.cs index 49ff2f4208..e0c5794b11 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadApprovedReportsTests/DownloadApprovedFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadApprovedReportsTests/DownloadApprovedFixture.cs @@ -6,16 +6,16 @@ using NUnit.Framework; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download; +using NzbDrone.Core.Download.Clients; using NzbDrone.Core.Download.Pending; +using NzbDrone.Core.Exceptions; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; -using NzbDrone.Core.Exceptions; -using NzbDrone.Core.Indexers; -using NzbDrone.Core.Download.Clients; namespace NzbDrone.Core.Test.Download.DownloadApprovedReportsTests { @@ -99,12 +99,10 @@ public void should_only_download_movie_once() public void should_not_download_if_any_movie_was_already_downloaded() { var remoteMovie1 = GetRemoteMovie( - new QualityModel(Quality.HDTV720p) - ); + new QualityModel(Quality.HDTV720p)); var remoteMovie2 = GetRemoteMovie( - new QualityModel(Quality.HDTV720p) - ); + new QualityModel(Quality.HDTV720p)); var decisions = new List(); decisions.Add(new DownloadDecision(remoteMovie1)); @@ -128,15 +126,9 @@ public void should_return_downloaded_reports() [Test] public void should_return_all_downloaded_reports() { - var remoteMovie1 = GetRemoteMovie( - new QualityModel(Quality.HDTV720p), - GetMovie(1) - ); + var remoteMovie1 = GetRemoteMovie(new QualityModel(Quality.HDTV720p), GetMovie(1)); - var remoteMovie2 = GetRemoteMovie( - new QualityModel(Quality.HDTV720p), - GetMovie(2) - ); + var remoteMovie2 = GetRemoteMovie(new QualityModel(Quality.HDTV720p), GetMovie(2)); var decisions = new List(); decisions.Add(new DownloadDecision(remoteMovie1)); @@ -150,18 +142,15 @@ public void should_only_return_downloaded_reports() { var remoteMovie1 = GetRemoteMovie( new QualityModel(Quality.HDTV720p), - GetMovie(1) - ); + GetMovie(1)); var remoteMovie2 = GetRemoteMovie( new QualityModel(Quality.HDTV720p), - GetMovie(2) - ); + GetMovie(2)); var remoteMovie3 = GetRemoteMovie( new QualityModel(Quality.HDTV720p), - GetMovie(2) - ); + GetMovie(2)); var decisions = new List(); decisions.Add(new DownloadDecision(remoteMovie1)); diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/Blackhole/UsenetBlackholeFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/Blackhole/UsenetBlackholeFixture.cs index 0717659761..28ecca4e1d 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/Blackhole/UsenetBlackholeFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/Blackhole/UsenetBlackholeFixture.cs @@ -1,4 +1,3 @@ - using System; using System.Collections.Generic; using System.IO; @@ -16,7 +15,6 @@ namespace NzbDrone.Core.Test.Download.DownloadClientTests.Blackhole { - [TestFixture] public class UsenetBlackholeFixture : DownloadClientFixtureBase { @@ -97,7 +95,6 @@ public void partial_download_should_have_required_properties() VerifyPostprocessing(result); } - [Test] public void should_return_category() { diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DelugeTests/DelugeFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DelugeTests/DelugeFixture.cs index 7ac27df8a4..e4d86a18b8 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DelugeTests/DelugeFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DelugeTests/DelugeFixture.cs @@ -1,13 +1,13 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Common.Http; -using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients.Deluge; +using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download.DownloadClientTests.DelugeTests @@ -31,57 +31,57 @@ public void Setup() }; _queued = new DelugeTorrent - { - Hash = "HASH", - IsFinished = false, - State = DelugeTorrentStatus.Queued, - Name = _title, - Size = 1000, - BytesDownloaded = 0, - Progress = 0.0, - DownloadPath = "somepath" - }; + { + Hash = "HASH", + IsFinished = false, + State = DelugeTorrentStatus.Queued, + Name = _title, + Size = 1000, + BytesDownloaded = 0, + Progress = 0.0, + DownloadPath = "somepath" + }; _downloading = new DelugeTorrent - { - Hash = "HASH", - IsFinished = false, - State = DelugeTorrentStatus.Downloading, - Name = _title, - Size = 1000, - BytesDownloaded = 100, - Progress = 10.0, - DownloadPath = "somepath" - }; + { + Hash = "HASH", + IsFinished = false, + State = DelugeTorrentStatus.Downloading, + Name = _title, + Size = 1000, + BytesDownloaded = 100, + Progress = 10.0, + DownloadPath = "somepath" + }; _failed = new DelugeTorrent - { - Hash = "HASH", - IsFinished = false, - State = DelugeTorrentStatus.Error, - Name = _title, - Size = 1000, - BytesDownloaded = 100, - Progress = 10.0, - Message = "Error", - DownloadPath = "somepath" - }; + { + Hash = "HASH", + IsFinished = false, + State = DelugeTorrentStatus.Error, + Name = _title, + Size = 1000, + BytesDownloaded = 100, + Progress = 10.0, + Message = "Error", + DownloadPath = "somepath" + }; _completed = new DelugeTorrent - { - Hash = "HASH", - IsFinished = true, - State = DelugeTorrentStatus.Paused, - Name = _title, - Size = 1000, - BytesDownloaded = 1000, - Progress = 100.0, - DownloadPath = "somepath", - IsAutoManaged = true, - StopAtRatio = true, - StopRatio = 1.0, - Ratio = 1.5 - }; + { + Hash = "HASH", + IsFinished = true, + State = DelugeTorrentStatus.Paused, + Name = _title, + Size = 1000, + BytesDownloaded = 1000, + Progress = 100.0, + DownloadPath = "somepath", + IsAutoManaged = true, + StopAtRatio = true, + StopRatio = 1.0, + Ratio = 1.5 + }; Mocker.GetMock() .Setup(s => s.GetHashFromTorrentFile(It.IsAny())) diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadClientFixtureBase.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadClientFixtureBase.cs index 5469d4a9f6..cae124c9a4 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadClientFixtureBase.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadClientFixtureBase.cs @@ -1,17 +1,17 @@ using System; +using FluentAssertions; using Moq; using NUnit.Framework; -using FluentAssertions; -using NzbDrone.Common.Http; -using NzbDrone.Core.IndexerSearch.Definitions; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Parser; -using NzbDrone.Core.Movies; -using NzbDrone.Core.Download; -using NzbDrone.Core.Configuration; -using NzbDrone.Core.RemotePathMappings; using NzbDrone.Common.Disk; +using NzbDrone.Common.Http; +using NzbDrone.Core.Configuration; +using NzbDrone.Core.Download; +using NzbDrone.Core.IndexerSearch.Definitions; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Download.DownloadClientTests { @@ -30,7 +30,7 @@ public void SetupBase() Mocker.GetMock() .Setup(s => s.Map(It.IsAny(), It.IsAny(), (SearchCriteriaBase)null)) - .Returns(() => new MappingResult{RemoteMovie = CreateRemoteMovie(), MappingResultType = MappingResultType.Success}); + .Returns(() => new MappingResult { RemoteMovie = CreateRemoteMovie(), MappingResultType = MappingResultType.Success }); Mocker.GetMock() .Setup(s => s.Get(It.IsAny())) @@ -67,6 +67,7 @@ protected void VerifyQueued(DownloadClientItem downloadClientItem) { VerifyIdentifiable(downloadClientItem); downloadClientItem.RemainingSize.Should().NotBe(0); + //downloadClientItem.RemainingTime.Should().NotBe(TimeSpan.Zero); //downloadClientItem.OutputPath.Should().NotBeNullOrEmpty(); downloadClientItem.Status.Should().Be(DownloadItemStatus.Queued); @@ -77,6 +78,7 @@ protected void VerifyPaused(DownloadClientItem downloadClientItem) VerifyIdentifiable(downloadClientItem); downloadClientItem.RemainingSize.Should().NotBe(0); + //downloadClientItem.RemainingTime.Should().NotBe(TimeSpan.Zero); //downloadClientItem.OutputPath.Should().NotBeNullOrEmpty(); downloadClientItem.Status.Should().Be(DownloadItemStatus.Paused); @@ -87,6 +89,7 @@ protected void VerifyDownloading(DownloadClientItem downloadClientItem) VerifyIdentifiable(downloadClientItem); downloadClientItem.RemainingSize.Should().NotBe(0); + //downloadClientItem.RemainingTime.Should().NotBe(TimeSpan.Zero); //downloadClientItem.OutputPath.Should().NotBeNullOrEmpty(); downloadClientItem.Status.Should().Be(DownloadItemStatus.Downloading); @@ -108,6 +111,7 @@ protected void VerifyCompleted(DownloadClientItem downloadClientItem) downloadClientItem.Title.Should().NotBeNullOrEmpty(); downloadClientItem.RemainingSize.Should().Be(0); downloadClientItem.RemainingTime.Should().Be(TimeSpan.Zero); + //downloadClientItem.OutputPath.Should().NotBeNullOrEmpty(); downloadClientItem.Status.Should().Be(DownloadItemStatus.Completed); } diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/TorrentDownloadStationFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/TorrentDownloadStationFixture.cs index cd9896d992..6197b1b83a 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/TorrentDownloadStationFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/TorrentDownloadStationFixture.cs @@ -67,13 +67,13 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "0"}, - { "size_uploaded", "0"}, + { "size_downloaded", "0" }, + { "size_uploaded", "0" }, { "speed_download", "0" } } } @@ -91,13 +91,13 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, - { "size_uploaded", "100"}, + { "size_downloaded", "1000" }, + { "size_uploaded", "100" }, { "speed_download", "0" } }, } @@ -115,13 +115,13 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, - { "size_uploaded", "100"}, + { "size_downloaded", "1000" }, + { "size_uploaded", "100" }, { "speed_download", "0" } } } @@ -139,13 +139,13 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "100"}, - { "size_uploaded", "10"}, + { "size_downloaded", "100" }, + { "size_uploaded", "10" }, { "speed_download", "50" } } } @@ -163,13 +163,13 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "10"}, - { "size_uploaded", "1"}, + { "size_downloaded", "10" }, + { "size_uploaded", "1" }, { "speed_download", "0" } } } @@ -187,13 +187,13 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, - { "size_uploaded", "100"}, + { "size_downloaded", "1000" }, + { "size_uploaded", "100" }, { "speed_download", "0" } } } @@ -211,13 +211,13 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, - { "size_uploaded", "100"}, + { "size_downloaded", "1000" }, + { "size_uploaded", "100" }, { "speed_download", "0" } } } @@ -235,13 +235,13 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, - { "size_uploaded", "100"}, + { "size_downloaded", "1000" }, + { "size_uploaded", "100" }, { "speed_download", "0" } } } @@ -259,13 +259,13 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", DownloadURL } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, - { "size_uploaded", "100"}, + { "size_downloaded", "1000" }, + { "size_uploaded", "100" }, { "speed_download", "0" } } } @@ -587,7 +587,7 @@ public void GetItems_should_map_outputpath_for_completed_or_failed_tasks() [TestCase(DownloadStationTaskStatus.Downloading, false, false)] [TestCase(DownloadStationTaskStatus.Finished, true, true)] - [TestCase(DownloadStationTaskStatus.Seeding, true, false)] + [TestCase(DownloadStationTaskStatus.Seeding, true, false)] [TestCase(DownloadStationTaskStatus.Waiting, false, false)] public void GetItems_should_return_canBeMoved_and_canBeDeleted_as_expected(DownloadStationTaskStatus apiStatus, bool canMoveFilesExpected, bool canBeRemovedExpected) { diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/UsenetDownloadStationFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/UsenetDownloadStationFixture.cs index 331914da93..79463f1cce 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/UsenetDownloadStationFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/DownloadStationTests/UsenetDownloadStationFixture.cs @@ -9,9 +9,9 @@ using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients.DownloadStation; using NzbDrone.Core.Download.Clients.DownloadStation.Proxies; +using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; using NzbDrone.Test.Common; -using NzbDrone.Core.Organizer; namespace NzbDrone.Core.Test.Download.DownloadClientTests.DownloadStationTests { @@ -64,12 +64,12 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", CleanFileName(_remoteEpisode.Release.Title) } }, Transfer = new Dictionary { - { "size_downloaded", "0"}, + { "size_downloaded", "0" }, { "speed_download", "0" } } } @@ -87,12 +87,12 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", CleanFileName(_remoteEpisode.Release.Title) } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, + { "size_downloaded", "1000" }, { "speed_download", "0" } }, } @@ -110,12 +110,12 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", CleanFileName(_remoteEpisode.Release.Title) } }, Transfer = new Dictionary { - { "size_downloaded", "1000"}, + { "size_downloaded", "1000" }, { "speed_download", "0" } } } @@ -133,12 +133,12 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", CleanFileName(_remoteEpisode.Release.Title) } }, Transfer = new Dictionary { - { "size_downloaded", "100"}, + { "size_downloaded", "100" }, { "speed_download", "50" } } } @@ -156,12 +156,12 @@ public void Setup() { Detail = new Dictionary { - { "destination","shared/folder" }, + { "destination", "shared/folder" }, { "uri", CleanFileName(_remoteEpisode.Release.Title) } }, Transfer = new Dictionary { - { "size_downloaded", "10"}, + { "size_downloaded", "10" }, { "speed_download", "0" } } } @@ -231,7 +231,6 @@ protected void GivenSuccessfulDownload() .Setup(s => s.Get(It.IsAny())) .Returns(r => new HttpResponse(r, new HttpHeader(), new byte[1000])); */ - Mocker.GetMock() .Setup(s => s.AddTaskFromData(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback(PrepareClientToReturnQueuedItem); @@ -246,7 +245,7 @@ protected void GivenAllKindOfTasks() .Returns(tasks); } - protected static string CleanFileName(String name) + protected static string CleanFileName(string name) { return FileNameBuilder.CleanFileName(name) + ".nzb"; } diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/HadoukenTests/HadoukenFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/HadoukenTests/HadoukenFixture.cs index d9f87a880d..daaf8aed84 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/HadoukenTests/HadoukenFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/HadoukenTests/HadoukenFixture.cs @@ -1,14 +1,14 @@ -using Moq; +using System; +using System.Collections.Generic; +using System.Linq; +using FluentAssertions; +using Moq; using NUnit.Framework; using NzbDrone.Common.Http; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients.Hadouken; using NzbDrone.Core.Download.Clients.Hadouken.Models; using NzbDrone.Core.MediaFiles.TorrentInfo; -using System; -using System.Collections.Generic; -using System.Linq; -using FluentAssertions; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download.DownloadClientTests.HadoukenTests @@ -81,7 +81,7 @@ public void Setup() }; Mocker.GetMock() - .Setup(s => s.GetHashFromTorrentFile(It.IsAny())) + .Setup(s => s.GetHashFromTorrentFile(It.IsAny())) .Returns("CBC2F069FE8BB2F544EAE707D75BCD3DE9DCF951"); Mocker.GetMock() @@ -210,7 +210,7 @@ public void Download_should_return_unique_id() [Test] public void should_return_status_with_outputdirs() { - var configItems = new Dictionary(); + var configItems = new Dictionary(); configItems.Add("bittorrent.defaultSavePath", @"C:\Downloads\Downloading\deluge".AsOsAgnostic()); diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbVortexTests/NzbVortexFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbVortexTests/NzbVortexFixture.cs index 964c5978e2..535bef92fc 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbVortexTests/NzbVortexFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbVortexTests/NzbVortexFixture.cs @@ -1,18 +1,18 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentAssertions; using Moq; using NUnit.Framework; -using NzbDrone.Core.Download; -using NzbDrone.Core.Download.Clients.Nzbget; -using NzbDrone.Test.Common; -using NzbDrone.Core.RemotePathMappings; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients; +using NzbDrone.Core.Download.Clients.Nzbget; using NzbDrone.Core.Download.Clients.NzbVortex; using NzbDrone.Core.Download.Clients.NzbVortex.Responses; +using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download.DownloadClientTests.NzbVortexTests { @@ -28,42 +28,42 @@ public void Setup() { Subject.Definition = new DownloadClientDefinition(); Subject.Definition.Settings = new NzbVortexSettings - { - Host = "127.0.0.1", - Port = 2222, - ApiKey = "1234-ABCD", - TvCategory = "tv", - RecentMoviePriority = (int)NzbgetPriority.High - }; + { + Host = "127.0.0.1", + Port = 2222, + ApiKey = "1234-ABCD", + TvCategory = "tv", + RecentMoviePriority = (int)NzbgetPriority.High + }; _queued = new NzbVortexQueueItem - { - Id = RandomNumber, - DownloadedSize = 1000, - TotalDownloadSize = 10, - GroupName = "tv", - UiTitle = "Droned.1998.1080p.WEB-DL-DRONE" - }; + { + Id = RandomNumber, + DownloadedSize = 1000, + TotalDownloadSize = 10, + GroupName = "tv", + UiTitle = "Droned.1998.1080p.WEB-DL-DRONE" + }; _failed = new NzbVortexQueueItem - { - DownloadedSize = 1000, - TotalDownloadSize = 1000, - GroupName = "tv", - UiTitle = "Droned.1998.1080p.WEB-DL-DRONE", - DestinationPath = "somedirectory", - State = NzbVortexStateType.UncompressFailed, - }; + { + DownloadedSize = 1000, + TotalDownloadSize = 1000, + GroupName = "tv", + UiTitle = "Droned.1998.1080p.WEB-DL-DRONE", + DestinationPath = "somedirectory", + State = NzbVortexStateType.UncompressFailed, + }; _completed = new NzbVortexQueueItem - { - DownloadedSize = 1000, - TotalDownloadSize = 1000, - GroupName = "tv", - UiTitle = "Droned.1998.1080p.WEB-DL-DRONE", - DestinationPath = "/remote/mount/tv/Droned.1998.1080p.WEB-DL-DRONE", - State = NzbVortexStateType.Done - }; + { + DownloadedSize = 1000, + TotalDownloadSize = 1000, + GroupName = "tv", + UiTitle = "Droned.1998.1080p.WEB-DL-DRONE", + DestinationPath = "/remote/mount/tv/Droned.1998.1080p.WEB-DL-DRONE", + State = NzbVortexStateType.Done + }; } protected void GivenFailedDownload() diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbgetTests/NzbgetFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbgetTests/NzbgetFixture.cs index 7ee2b8cbab..e7e2bc84c8 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbgetTests/NzbgetFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/NzbgetTests/NzbgetFixture.cs @@ -1,15 +1,15 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentAssertions; using Moq; using NUnit.Framework; +using NzbDrone.Common.Disk; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients.Nzbget; -using NzbDrone.Test.Common; -using NzbDrone.Core.RemotePathMappings; -using NzbDrone.Common.Disk; using NzbDrone.Core.Exceptions; +using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download.DownloadClientTests.NzbgetTests { @@ -26,53 +26,53 @@ public void Setup() { Subject.Definition = new DownloadClientDefinition(); Subject.Definition.Settings = new NzbgetSettings - { - Host = "127.0.0.1", - Port = 2222, - Username = "admin", - Password = "pass", - MovieCategory = "movie", - RecentMoviePriority = (int)NzbgetPriority.High - }; + { + Host = "127.0.0.1", + Port = 2222, + Username = "admin", + Password = "pass", + MovieCategory = "movie", + RecentMoviePriority = (int)NzbgetPriority.High + }; _queued = new NzbgetQueueItem - { - FileSizeLo = 1000, - RemainingSizeLo = 10, - Category = "movie", - NzbName = "Droned.1998.1080p.WEB-DL-DRONE", - Parameters = new List { new NzbgetParameter { Name = "drone", Value = "id" } } - }; + { + FileSizeLo = 1000, + RemainingSizeLo = 10, + Category = "movie", + NzbName = "Droned.1998.1080p.WEB-DL-DRONE", + Parameters = new List { new NzbgetParameter { Name = "drone", Value = "id" } } + }; _failed = new NzbgetHistoryItem - { - FileSizeLo = 1000, - Category = "movie", - Name = "Droned.1998.1080p.WEB-DL-DRONE", - DestDir = "somedirectory", - Parameters = new List { new NzbgetParameter { Name = "drone", Value = "id" } }, - ParStatus = "Some Error", - UnpackStatus = "NONE", - MoveStatus = "NONE", - ScriptStatus = "NONE", - DeleteStatus = "NONE", - MarkStatus = "NONE" - }; + { + FileSizeLo = 1000, + Category = "movie", + Name = "Droned.1998.1080p.WEB-DL-DRONE", + DestDir = "somedirectory", + Parameters = new List { new NzbgetParameter { Name = "drone", Value = "id" } }, + ParStatus = "Some Error", + UnpackStatus = "NONE", + MoveStatus = "NONE", + ScriptStatus = "NONE", + DeleteStatus = "NONE", + MarkStatus = "NONE" + }; _completed = new NzbgetHistoryItem - { - FileSizeLo = 1000, - Category = "movie", - Name = "Droned.1998.1080p.WEB-DL-DRONE", - DestDir = "/remote/mount/tv/Droned.1998.1080p.WEB-DL-DRONE", - Parameters = new List { new NzbgetParameter { Name = "drone", Value = "id" } }, - ParStatus = "SUCCESS", - UnpackStatus = "NONE", - MoveStatus = "SUCCESS", - ScriptStatus = "NONE", - DeleteStatus = "NONE", - MarkStatus = "NONE" - }; + { + FileSizeLo = 1000, + Category = "movie", + Name = "Droned.1998.1080p.WEB-DL-DRONE", + DestDir = "/remote/mount/tv/Droned.1998.1080p.WEB-DL-DRONE", + Parameters = new List { new NzbgetParameter { Name = "drone", Value = "id" } }, + ParStatus = "SUCCESS", + UnpackStatus = "NONE", + MoveStatus = "SUCCESS", + ScriptStatus = "NONE", + DeleteStatus = "NONE", + MarkStatus = "NONE" + }; Mocker.GetMock() .Setup(s => s.GetGlobalStatus(It.IsAny())) @@ -81,7 +81,6 @@ public void Setup() DownloadRate = 7000000 }); - Mocker.GetMock() .Setup(v => v.GetVersion(It.IsAny())) .Returns("14.0"); @@ -321,7 +320,6 @@ public void should_report_scriptstatus_failure_as_failed() { // TODO: We would love to have a way to distinguish between scripts reporting video corruption, or some internal script error. // That way we could return Warning instead of Failed to notify the user to take action. - _completed.ScriptStatus = "FAILURE"; GivenQueue(null); diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/PneumaticProviderFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/PneumaticProviderFixture.cs index 2775d03b9a..7c819e8e6f 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/PneumaticProviderFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/PneumaticProviderFixture.cs @@ -58,7 +58,6 @@ public void should_download_file_if_it_doesnt_exist() Mocker.GetMock().Verify(c => c.DownloadFile(_nzbUrl, _nzbPath), Times.Once()); } - [Test] public void should_throw_on_failed_download() { diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/QBittorrentTests/QBittorrentFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/QBittorrentTests/QBittorrentFixture.cs index 13519da25a..06f05b758e 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/QBittorrentTests/QBittorrentFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/QBittorrentTests/QBittorrentFixture.cs @@ -1,15 +1,15 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Common.Http; -using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients.QBittorrent; -using NzbDrone.Test.Common; using NzbDrone.Core.Exceptions; +using NzbDrone.Core.MediaFiles.TorrentInfo; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download.DownloadClientTests.QBittorrentTests { @@ -30,12 +30,12 @@ public void Setup() }; Mocker.GetMock() - .Setup(s => s.GetHashFromTorrentFile(It.IsAny())) + .Setup(s => s.GetHashFromTorrentFile(It.IsAny())) .Returns("CBC2F069FE8BB2F544EAE707D75BCD3DE9DCF951"); Mocker.GetMock() .Setup(s => s.Get(It.IsAny())) - .Returns(r => new HttpResponse(r, new HttpHeader(), new Byte[0])); + .Returns(r => new HttpResponse(r, new HttpHeader(), new byte[0])); Mocker.GetMock() .Setup(s => s.GetConfig(It.IsAny())) @@ -53,7 +53,7 @@ protected void GivenRedirectToMagnet() Mocker.GetMock() .Setup(s => s.Get(It.IsAny())) - .Returns(r => new HttpResponse(r, httpHeader, new Byte[0], System.Net.HttpStatusCode.SeeOther)); + .Returns(r => new HttpResponse(r, httpHeader, new byte[0], System.Net.HttpStatusCode.SeeOther)); } protected void GivenRedirectToTorrent() @@ -63,7 +63,7 @@ protected void GivenRedirectToTorrent() Mocker.GetMock() .Setup(s => s.Get(It.Is(h => h.Url.FullUri == _downloadUrl))) - .Returns(r => new HttpResponse(r, httpHeader, new Byte[0], System.Net.HttpStatusCode.Found)); + .Returns(r => new HttpResponse(r, httpHeader, new byte[0], System.Net.HttpStatusCode.Found)); } protected void GivenFailedDownload() @@ -96,8 +96,8 @@ protected void GivenSuccessfulDownload() protected void GivenHighPriority() { - Subject.Definition.Settings.As().OlderMoviePriority = (int) QBittorrentPriority.First; - Subject.Definition.Settings.As().RecentMoviePriority = (int) QBittorrentPriority.First; + Subject.Definition.Settings.As().OlderMoviePriority = (int)QBittorrentPriority.First; + Subject.Definition.Settings.As().RecentMoviePriority = (int)QBittorrentPriority.First; } protected void GivenGlobalSeedLimits(float maxRatio, int maxSeedingTime = -1, bool removeOnMaxRatio = false) @@ -117,7 +117,9 @@ protected void GivenGlobalSeedLimits(float maxRatio, int maxSeedingTime = -1, bo protected virtual void GivenTorrents(List torrents) { if (torrents == null) + { torrents = new List(); + } Mocker.GetMock() .Setup(s => s.GetTorrents(It.IsAny())) @@ -414,8 +416,10 @@ public void should_not_be_removable_and_should_not_allow_move_files_if_max_ratio protected virtual QBittorrentTorrent GivenCompletedTorrent( string state = "pausedUP", - float ratio = 0.1f, float ratioLimit = -2, - int seedingTime = 1, int seedingTimeLimit = -2) + float ratio = 0.1f, + float ratioLimit = -2, + int seedingTime = 1, + int seedingTimeLimit = -2) { var torrent = new QBittorrentTorrent { @@ -500,7 +504,6 @@ public void should_not_be_removable_if_overridden_max_ratio_not_reached_and_paus item.CanMoveFiles.Should().BeFalse(); } - [Test] public void should_not_be_removable_and_should_not_allow_move_files_if_max_seedingtime_reached_and_not_paused() { @@ -628,11 +631,9 @@ public void should_handle_eta_biginteger() // Let this stand as a lesson to never write temporary unit tests on your dev machine and claim it works. // Commit the tests and let it run with the official build on the official build agents. // (Also don't replace library versions in your build script) - var json = "{ \"eta\": 18446744073709335000 }"; var torrent = Newtonsoft.Json.JsonConvert.DeserializeObject(json); torrent.Eta.ToString().Should().Be("18446744073709335000"); - } [Test] diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/RTorrentTests/RTorrentFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/RTorrentTests/RTorrentFixture.cs index 524614ded9..af08fa8b8d 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/RTorrentTests/RTorrentFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/RTorrentTests/RTorrentFixture.cs @@ -1,11 +1,11 @@ -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentAssertions; using Moq; using NUnit.Framework; -using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients.RTorrent; +using NzbDrone.Core.MediaFiles.TorrentInfo; namespace NzbDrone.Core.Test.Download.DownloadClientTests.RTorrentTests { @@ -61,7 +61,6 @@ protected void GivenSuccessfulDownload() .Setup(s => s.AddTorrentFromFile(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback(PrepareClientToReturnCompletedItem); - Mocker.GetMock() .Setup(s => s.HasHashTorrent(It.IsAny(), It.IsAny())) .Returns(true); diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/JsonConvertersTests/SabnzbdQueueTimeConverterFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/JsonConvertersTests/SabnzbdQueueTimeConverterFixture.cs index 1b9dc4bb64..0532dbff97 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/JsonConvertersTests/SabnzbdQueueTimeConverterFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/JsonConvertersTests/SabnzbdQueueTimeConverterFixture.cs @@ -15,9 +15,9 @@ public class SabnzbdQueueTimeConverterFixture [TestCase("0:1:59", 119)] [TestCase("0:59:59", 3599)] [TestCase("1:0:0", 3600)] - [TestCase("1:0:0:1", 24 * 3600 + 1)] - [TestCase("40:12:14", 40 * 3600 + 12 * 60 + 14)] - [TestCase("1:16:12:14", 40 * 3600 + 12 * 60 + 14)] + [TestCase("1:0:0:1", (24 * 3600) + 1)] + [TestCase("40:12:14", (40 * 3600) + (12 * 60) + 14)] + [TestCase("1:16:12:14", (40 * 3600) + (12 * 60) + 14)] public void valid_time_formats_should_be_parsed_correctly(string time, int expectedSeconds) { var thing = string.Format(QUERY, time); diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/SabnzbdFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/SabnzbdFixture.cs index 6dd6b50bfd..120c2a217c 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/SabnzbdFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/SabnzbdTests/SabnzbdFixture.cs @@ -1,16 +1,16 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentAssertions; using Moq; using NUnit.Framework; +using NzbDrone.Common.Disk; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients.Sabnzbd; using NzbDrone.Core.Download.Clients.Sabnzbd.Responses; -using NzbDrone.Test.Common; using NzbDrone.Core.RemotePathMappings; -using NzbDrone.Common.Disk; using NzbDrone.Core.Validation; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download.DownloadClientTests.SabnzbdTests { @@ -28,20 +28,20 @@ public void Setup() { Subject.Definition = new DownloadClientDefinition(); Subject.Definition.Settings = new SabnzbdSettings - { - Host = "127.0.0.1", - Port = 2222, - ApiKey = "5c770e3197e4fe763423ee7c392c25d1", - Username = "admin", - Password = "pass", - MovieCategory = "movie", - RecentMoviePriority = (int)SabnzbdPriority.High - }; + { + Host = "127.0.0.1", + Port = 2222, + ApiKey = "5c770e3197e4fe763423ee7c392c25d1", + Username = "admin", + Password = "pass", + MovieCategory = "movie", + RecentMoviePriority = (int)SabnzbdPriority.High + }; _queued = new SabnzbdQueue - { - DefaultRootFolder = @"Y:\nzbget\root".AsOsAgnostic(), - Paused = false, - Items = new List() + { + DefaultRootFolder = @"Y:\nzbget\root".AsOsAgnostic(), + Paused = false, + Items = new List() { new SabnzbdQueueItem { @@ -54,11 +54,11 @@ public void Setup() Title = "Droned.1998.1080p.WEB-DL-DRONE" } } - }; + }; _failed = new SabnzbdHistory - { - Items = new List() + { + Items = new List() { new SabnzbdHistoryItem { @@ -69,11 +69,11 @@ public void Setup() Title = "Droned.1998.1080p.WEB-DL-DRONE" } } - }; + }; _completed = new SabnzbdHistory - { - Items = new List() + { + Items = new List() { new SabnzbdHistoryItem { @@ -85,19 +85,19 @@ public void Setup() Storage = "/remote/mount/vv/Droned.1998.1080p.WEB-DL-DRONE" } } - }; + }; _config = new SabnzbdConfig + { + Misc = new SabnzbdConfigMisc { - Misc = new SabnzbdConfigMisc - { - complete_dir = @"/remote/mount" - }, - Categories = new List + complete_dir = @"/remote/mount" + }, + Categories = new List { new SabnzbdCategory { Name = "movie", Dir = "vv" } } - }; + }; Mocker.GetMock() .Setup(v => v.GetVersion(It.IsAny())) @@ -108,9 +108,9 @@ public void Setup() .Returns(_config); _fullStatus = new SabnzbdFullStatus - { - CompleteDir = @"Y:\sabnzbd\root\complete".AsOsAgnostic() - }; + { + CompleteDir = @"Y:\sabnzbd\root\complete".AsOsAgnostic() + }; Mocker.GetMock() .Setup(s => s.GetFullStatus(It.IsAny())) @@ -161,7 +161,9 @@ protected virtual void GivenQueue(SabnzbdQueue queue) protected virtual void GivenHistory(SabnzbdHistory history) { if (history == null) + { history = new SabnzbdHistory() { Items = new List() }; + } Mocker.GetMock() .Setup(s => s.GetHistory(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/TransmissionTests/TransmissionFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/TransmissionTests/TransmissionFixture.cs index f16b050a9a..ee2b3adbab 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/TransmissionTests/TransmissionFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/TransmissionTests/TransmissionFixture.cs @@ -284,7 +284,6 @@ public void should_ignore_negative_eta(int eta) item.RemainingTime.Should().NotHaveValue(); } - [Test] public void should_not_be_removable_and_should_not_allow_move_files_if_max_ratio_reached_and_not_stopped() { @@ -340,7 +339,6 @@ public void should_not_be_removable_if_overridden_max_ratio_not_reached_and_paus item.CanMoveFiles.Should().BeFalse(); } - [Test] public void should_not_be_removable_and_should_not_allow_move_files_if_max_idletime_reached_and_not_paused() { @@ -389,7 +387,7 @@ public void should_be_removable_and_should_not_allow_move_files_if_overridden_ma public void should_not_be_removable_if_overridden_max_idletime_not_reached_and_paused() { GivenGlobalSeedLimits(null, 20); - PrepareClientToReturnCompletedItem(true, ratio: 2.0, seedingTime: 30, idleLimit: 40); + PrepareClientToReturnCompletedItem(true, ratio: 2.0, seedingTime: 30, idleLimit: 40); var item = Subject.GetItems().Single(); item.CanBeRemoved.Should().BeFalse(); diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/TransmissionTests/TransmissionFixtureBase.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/TransmissionTests/TransmissionFixtureBase.cs index d6d4434c2a..e2c55423b6 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/TransmissionTests/TransmissionFixtureBase.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/TransmissionTests/TransmissionFixtureBase.cs @@ -110,7 +110,6 @@ public void Setup() Mocker.GetMock() .Setup(v => v.GetConfig(It.IsAny())) .Returns(() => Json.Deserialize(_transmissionConfigItems.ToJson())); - } protected void GivenMovieCategory() @@ -184,7 +183,10 @@ protected void PrepareClientToReturnFailedItem() protected void PrepareClientToReturnCompletedItem(bool stopped = false, double ratio = 0.9, int seedingTime = 60, double? ratioLimit = null, int? idleLimit = null) { if (stopped) + { _completed.Status = TransmissionTorrentStatus.Stopped; + } + _completed.UploadedEver = (int)(_completed.DownloadedEver * ratio); _completed.SecondsSeeding = seedingTime * 60; @@ -214,7 +216,6 @@ protected void PrepareClientToReturnCompletedItem(bool stopped = false, double r } } - GivenTorrents(new List { _completed diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/UTorrentTests/UTorrentFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/UTorrentTests/UTorrentFixture.cs index 11551917c5..d9b1ebfb38 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/UTorrentTests/UTorrentFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/UTorrentTests/UTorrentFixture.cs @@ -1,13 +1,13 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Common.Http; -using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Clients.UTorrent; +using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download.DownloadClientTests.UTorrentTests @@ -25,65 +25,65 @@ public void Setup() { Subject.Definition = new DownloadClientDefinition(); Subject.Definition.Settings = new UTorrentSettings - { - Host = "127.0.0.1", - Port = 2222, - Username = "admin", - Password = "pass", - MovieCategory = "movie" - }; + { + Host = "127.0.0.1", + Port = 2222, + Username = "admin", + Password = "pass", + MovieCategory = "movie" + }; _queued = new UTorrentTorrent - { - Hash = "HASH", - Status = UTorrentTorrentStatus.Queued | UTorrentTorrentStatus.Loaded, - Name = _title, - Size = 1000, - Remaining = 1000, - Progress = 0, - Label = "movie", - DownloadUrl = _downloadUrl, - RootDownloadPath = "somepath" - }; + { + Hash = "HASH", + Status = UTorrentTorrentStatus.Queued | UTorrentTorrentStatus.Loaded, + Name = _title, + Size = 1000, + Remaining = 1000, + Progress = 0, + Label = "movie", + DownloadUrl = _downloadUrl, + RootDownloadPath = "somepath" + }; _downloading = new UTorrentTorrent - { - Hash = "HASH", - Status = UTorrentTorrentStatus.Started | UTorrentTorrentStatus.Loaded, - Name = _title, - Size = 1000, - Remaining = 100, - Progress = 0.9, - Label = "movie", - DownloadUrl = _downloadUrl, - RootDownloadPath = "somepath" - }; + { + Hash = "HASH", + Status = UTorrentTorrentStatus.Started | UTorrentTorrentStatus.Loaded, + Name = _title, + Size = 1000, + Remaining = 100, + Progress = 0.9, + Label = "movie", + DownloadUrl = _downloadUrl, + RootDownloadPath = "somepath" + }; _failed = new UTorrentTorrent - { - Hash = "HASH", - Status = UTorrentTorrentStatus.Error, - Name = _title, - Size = 1000, - Remaining = 100, - Progress = 0.9, - Label = "movie", - DownloadUrl = _downloadUrl, - RootDownloadPath = "somepath" - }; + { + Hash = "HASH", + Status = UTorrentTorrentStatus.Error, + Name = _title, + Size = 1000, + Remaining = 100, + Progress = 0.9, + Label = "movie", + DownloadUrl = _downloadUrl, + RootDownloadPath = "somepath" + }; _completed = new UTorrentTorrent - { - Hash = "HASH", - Status = UTorrentTorrentStatus.Checked | UTorrentTorrentStatus.Loaded, - Name = _title, - Size = 1000, - Remaining = 0, - Progress = 1.0, - Label = "movie", - DownloadUrl = _downloadUrl, - RootDownloadPath = "somepath" - }; + { + Hash = "HASH", + Status = UTorrentTorrentStatus.Checked | UTorrentTorrentStatus.Loaded, + Name = _title, + Size = 1000, + Remaining = 0, + Progress = 1.0, + Label = "movie", + DownloadUrl = _downloadUrl, + RootDownloadPath = "somepath" + }; Mocker.GetMock() .Setup(s => s.GetHashFromTorrentFile(It.IsAny())) diff --git a/src/NzbDrone.Core.Test/Download/DownloadClientTests/VuzeTests/VuzeFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadClientTests/VuzeTests/VuzeFixture.cs index 88359757c2..61c7ec51ff 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadClientTests/VuzeTests/VuzeFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadClientTests/VuzeTests/VuzeFixture.cs @@ -341,6 +341,5 @@ public void should_have_correct_output_directory_for_singlefile_torrents() items.Should().HaveCount(1); items.First().OutputPath.Should().Be(@"C:\Downloads\" + fileName); } - } } diff --git a/src/NzbDrone.Core.Test/Download/DownloadServiceFixture.cs b/src/NzbDrone.Core.Test/Download/DownloadServiceFixture.cs index f6157b08b0..adab7b46ad 100644 --- a/src/NzbDrone.Core.Test/Download/DownloadServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Download/DownloadServiceFixture.cs @@ -10,9 +10,9 @@ using NzbDrone.Core.Download.Clients; using NzbDrone.Core.Exceptions; using NzbDrone.Core.Indexers; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.Download { @@ -108,7 +108,8 @@ public void Download_report_should_trigger_indexer_backoff_on_indexer_error() { var mock = WithUsenetClient(); mock.Setup(s => s.Download(It.IsAny())) - .Callback(v => { + .Callback(v => + { throw new ReleaseDownloadException(v.Release, "Error", new WebException()); }); @@ -127,7 +128,8 @@ public void Download_report_should_trigger_indexer_backoff_on_http429_with_long_ var mock = WithUsenetClient(); mock.Setup(s => s.Download(It.IsAny())) - .Callback(v => { + .Callback(v => + { throw new ReleaseDownloadException(v.Release, "Error", new TooManyRequestsException(request, response)); }); @@ -176,7 +178,8 @@ public void Download_report_should_not_trigger_indexer_backoff_on_indexer_404_er { var mock = WithUsenetClient(); mock.Setup(s => s.Download(It.IsAny())) - .Callback(v => { + .Callback(v => + { throw new ReleaseUnavailableException(v.Release, "Error", new WebException()); }); diff --git a/src/NzbDrone.Core.Test/Download/FailedDownloadServiceFixture.cs b/src/NzbDrone.Core.Test/Download/FailedDownloadServiceFixture.cs index 9524efa17b..14487be509 100644 --- a/src/NzbDrone.Core.Test/Download/FailedDownloadServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Download/FailedDownloadServiceFixture.cs @@ -8,9 +8,9 @@ using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.History; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Download @@ -43,11 +43,9 @@ public void Setup() .With(c => c.RemoteMovie = remoteEpisode) .Build(); - Mocker.GetMock() .Setup(s => s.Find(_trackedDownload.DownloadItem.DownloadId, HistoryEventType.Grabbed)) .Returns(_grabHistory); - } private void GivenNoGrabbedHistory() @@ -130,7 +128,6 @@ private void AssertDownloadNotFailed() _trackedDownload.State.Should().NotBe(TrackedDownloadStage.DownloadFailed); } - private void AssertDownloadFailed() { Mocker.GetMock() diff --git a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/AddFixture.cs b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/AddFixture.cs index b0faa25c2c..f2922753d0 100644 --- a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/AddFixture.cs +++ b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/AddFixture.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using FizzWare.NBuilder; using Marr.Data; using Moq; @@ -7,12 +8,11 @@ using NzbDrone.Common.Extensions; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download.Pending; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; -using System.Linq; namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests { @@ -34,16 +34,16 @@ public void Setup() .Build(); _profile = new Profile - { - Name = "Test", - Cutoff = Quality.HDTV720p.Id, - Items = new List + { + Name = "Test", + Cutoff = Quality.HDTV720p.Id, + Items = new List { new ProfileQualityItem { Allowed = true, Quality = Quality.HDTV720p }, new ProfileQualityItem { Allowed = true, Quality = Quality.WEBDL720p }, new ProfileQualityItem { Allowed = true, Quality = Quality.Bluray720p } }, - }; + }; _movie.Profile = new LazyLoaded(_profile); @@ -84,7 +84,6 @@ private void GivenHeldRelease(string title, string indexer, DateTime publishDate release.Indexer = indexer; release.PublishDate = publishDate; - var heldReleases = Builder.CreateListOfSize(1) .All() .With(h => h.MovieId = _movie.Id) diff --git a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/PendingReleaseServiceFixture.cs b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/PendingReleaseServiceFixture.cs index 8ff0f0ea0d..cb69aa5027 100644 --- a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/PendingReleaseServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/PendingReleaseServiceFixture.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine; @@ -7,7 +8,6 @@ using NzbDrone.Core.Indexers; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using FluentAssertions; namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests { @@ -18,9 +18,10 @@ private void GivenPendingRelease() { Mocker.GetMock() .Setup(v => v.All()) - .Returns(new List { - new PendingRelease { Release = new ReleaseInfo { IndexerId = 1 } } - }); + .Returns(new List + { + new PendingRelease { Release = new ReleaseInfo { IndexerId = 1 } } + }); } [Test] diff --git a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveGrabbedFixture.cs b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveGrabbedFixture.cs index e2e8339294..0eee3f04a8 100644 --- a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveGrabbedFixture.cs +++ b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveGrabbedFixture.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Linq; using FizzWare.NBuilder; using Marr.Data; using Moq; @@ -7,12 +8,11 @@ using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Pending; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; -using System.Linq; namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests { @@ -34,16 +34,16 @@ public void Setup() .Build(); _profile = new Profile - { - Name = "Test", - Cutoff = Quality.HDTV720p.Id, - Items = new List + { + Name = "Test", + Cutoff = Quality.HDTV720p.Id, + Items = new List { new ProfileQualityItem { Allowed = true, Quality = Quality.HDTV720p }, new ProfileQualityItem { Allowed = true, Quality = Quality.WEBDL720p }, new ProfileQualityItem { Allowed = true, Quality = Quality.Bluray720p } }, - }; + }; _movie.Profile = new LazyLoaded(_profile); @@ -77,7 +77,6 @@ public void Setup() .Setup(s => s.GetMovies(It.IsAny>())) .Returns(new List { _movie }); - Mocker.GetMock() .Setup(s => s.PrioritizeDecisionsForMovies(It.IsAny>())) .Returns((List d) => d); diff --git a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemovePendingFixture.cs b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemovePendingFixture.cs index fb638f4deb..b7a626fcd3 100644 --- a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemovePendingFixture.cs +++ b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemovePendingFixture.cs @@ -5,10 +5,10 @@ using NUnit.Framework; using NzbDrone.Common.Crypto; using NzbDrone.Core.Download.Pending; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests { @@ -32,7 +32,7 @@ public void Setup() Mocker.GetMock() .Setup(s => s.All()) - .Returns( _pending); + .Returns(_pending); Mocker.GetMock() .Setup(s => s.GetMovie(It.IsAny())) @@ -50,11 +50,11 @@ public void Setup() private void AddPending(int id, string title, int year) { _pending.Add(new PendingRelease - { - Id = id, - ParsedMovieInfo = new ParsedMovieInfo { MovieTitle = title, Year = year }, - MovieId = _movie.Id - }); + { + Id = id, + ParsedMovieInfo = new ParsedMovieInfo { MovieTitle = title, Year = year }, + MovieId = _movie.Id + }); } [Test] @@ -74,5 +74,4 @@ private void AssertRemoved(params int[] ids) Mocker.GetMock().Verify(c => c.DeleteMany(It.Is>(s => s.SequenceEqual(ids)))); } } - } diff --git a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveRejectedFixture.cs b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveRejectedFixture.cs index aecfec7265..a0ee689874 100644 --- a/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveRejectedFixture.cs +++ b/src/NzbDrone.Core.Test/Download/Pending/PendingReleaseServiceTests/RemoveRejectedFixture.cs @@ -9,12 +9,12 @@ using NzbDrone.Core.Download; using NzbDrone.Core.Download.Pending; using NzbDrone.Core.Indexers; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests { @@ -34,18 +34,17 @@ public void Setup() _movie = Builder.CreateNew() .Build(); - _profile = new Profile - { - Name = "Test", - Cutoff = Quality.HDTV720p.Id, - Items = new List + { + Name = "Test", + Cutoff = Quality.HDTV720p.Id, + Items = new List { new ProfileQualityItem { Allowed = true, Quality = Quality.HDTV720p }, new ProfileQualityItem { Allowed = true, Quality = Quality.WEBDL720p }, new ProfileQualityItem { Allowed = true, Quality = Quality.Bluray720p } }, - }; + }; _movie.Profile = new LazyLoaded(_profile); @@ -55,6 +54,7 @@ public void Setup() _parsedMovieInfo.Quality = new QualityModel(Quality.HDTV720p); _remoteMovie = new RemoteMovie(); + //_remoteEpisode.Episodes = new List{ _episode }; _remoteMovie.Movie = _movie; _remoteMovie.ParsedMovieInfo = _parsedMovieInfo; @@ -89,7 +89,6 @@ private void GivenHeldRelease(string title, string indexer, DateTime publishDate release.Indexer = indexer; release.PublishDate = publishDate; - var heldReleases = Builder.CreateListOfSize(1) .All() .With(h => h.MovieId = _movie.Id) diff --git a/src/NzbDrone.Core.Test/Download/TrackedDownloads/TrackedDownloadServiceFixture.cs b/src/NzbDrone.Core.Test/Download/TrackedDownloads/TrackedDownloadServiceFixture.cs index 19f2f99e2f..857b7d8267 100644 --- a/src/NzbDrone.Core.Test/Download/TrackedDownloads/TrackedDownloadServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Download/TrackedDownloads/TrackedDownloadServiceFixture.cs @@ -5,11 +5,11 @@ using NzbDrone.Core.Download; using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.History; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; -using NzbDrone.Core.Indexers; namespace NzbDrone.Core.Test.Download.TrackedDownloads { @@ -25,12 +25,14 @@ private void GivenDownloadHistory() { Mocker.GetMock() .Setup(s => s.FindByDownloadId(It.Is(sr => sr == "35238"))) - .Returns(new List(){ - new History.History(){ - DownloadId = "35238", - SourceTitle = "TV Series S01", - MovieId = 3, - } + .Returns(new List() + { + new History.History() + { + DownloadId = "35238", + SourceTitle = "TV Series S01", + MovieId = 3, + } }); } @@ -52,7 +54,7 @@ public void should_track_downloads_using_the_source_title_if_it_cannot_be_found_ Mocker.GetMock() .Setup(s => s.Map(It.Is(i => i.MovieTitle == "A Movie"), It.IsAny(), null)) - .Returns(new MappingResult{RemoteMovie = remoteEpisode}); + .Returns(new MappingResult { RemoteMovie = remoteEpisode }); ParseMovieTitle(); @@ -75,7 +77,5 @@ public void should_track_downloads_using_the_source_title_if_it_cannot_be_found_ trackedDownload.RemoteMovie.Movie.Should().NotBeNull(); trackedDownload.RemoteMovie.Movie.Id.Should().Be(3); } - - } } diff --git a/src/NzbDrone.Core.Test/Extras/Metadata/Consumers/Roksbox/FindMetadataFileFixture.cs b/src/NzbDrone.Core.Test/Extras/Metadata/Consumers/Roksbox/FindMetadataFileFixture.cs index 0449def72d..3935fe9791 100644 --- a/src/NzbDrone.Core.Test/Extras/Metadata/Consumers/Roksbox/FindMetadataFileFixture.cs +++ b/src/NzbDrone.Core.Test/Extras/Metadata/Consumers/Roksbox/FindMetadataFileFixture.cs @@ -4,8 +4,8 @@ using NUnit.Framework; using NzbDrone.Core.Extras.Metadata; using NzbDrone.Core.Extras.Metadata.Consumers.Roksbox; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Extras.Metadata.Consumers.Roksbox diff --git a/src/NzbDrone.Core.Test/Extras/Metadata/Consumers/Wdtv/FindMetadataFileFixture.cs b/src/NzbDrone.Core.Test/Extras/Metadata/Consumers/Wdtv/FindMetadataFileFixture.cs index cd10a48d22..7662ec5a84 100644 --- a/src/NzbDrone.Core.Test/Extras/Metadata/Consumers/Wdtv/FindMetadataFileFixture.cs +++ b/src/NzbDrone.Core.Test/Extras/Metadata/Consumers/Wdtv/FindMetadataFileFixture.cs @@ -4,8 +4,8 @@ using NUnit.Framework; using NzbDrone.Core.Extras.Metadata; using NzbDrone.Core.Extras.Metadata.Consumers.Wdtv; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Extras.Metadata.Consumers.Wdtv diff --git a/src/NzbDrone.Core.Test/Extras/Metadata/Consumers/Xbmc/FindMetadataFileFixture.cs b/src/NzbDrone.Core.Test/Extras/Metadata/Consumers/Xbmc/FindMetadataFileFixture.cs index 6ea699dd04..f9b5181918 100644 --- a/src/NzbDrone.Core.Test/Extras/Metadata/Consumers/Xbmc/FindMetadataFileFixture.cs +++ b/src/NzbDrone.Core.Test/Extras/Metadata/Consumers/Xbmc/FindMetadataFileFixture.cs @@ -5,8 +5,8 @@ using NUnit.Framework; using NzbDrone.Core.Extras.Metadata; using NzbDrone.Core.Extras.Metadata.Consumers.Xbmc; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Extras.Metadata.Consumers.Xbmc diff --git a/src/NzbDrone.Core.Test/FluentTest.cs b/src/NzbDrone.Core.Test/FluentTest.cs index f9116afcbd..a17f142e3b 100644 --- a/src/NzbDrone.Core.Test/FluentTest.cs +++ b/src/NzbDrone.Core.Test/FluentTest.cs @@ -87,11 +87,7 @@ public void ToBestDateTime_Before_Yesterday() [Test] public void MaxOrDefault_should_return_zero_when_collection_is_empty() { - - - - - var result = (new List()).MaxOrDefault(); + var result = new List().MaxOrDefault(); //Resolve result.Should().Be(0); @@ -100,10 +96,8 @@ public void MaxOrDefault_should_return_zero_when_collection_is_empty() [Test] public void MaxOrDefault_should_return_max_when_collection_is_not_empty() { - var list = new List { 6, 4, 5, 3, 8, 10 }; - var result = list.MaxOrDefault(); //Resolve @@ -113,10 +107,8 @@ public void MaxOrDefault_should_return_max_when_collection_is_not_empty() [Test] public void MaxOrDefault_should_return_zero_when_collection_is_null() { - List list = null; - var result = list.MaxOrDefault(); //Resolve @@ -126,10 +118,8 @@ public void MaxOrDefault_should_return_zero_when_collection_is_null() [Test] public void Truncate_should_truncate_strings_to_max_specified_number_of_bytes() { - var str = ReadAllText("Files/LongOverview.txt"); - var resultString = str.Truncate(1000); //Resolve @@ -140,10 +130,8 @@ public void Truncate_should_truncate_strings_to_max_specified_number_of_bytes() [Test] public void Truncate_should_not_truncate_string_shorter_than_max_bytes() { - var str = "Hello World"; - var resultString = str.Truncate(1000); //Resolve @@ -154,11 +142,7 @@ public void Truncate_should_not_truncate_string_shorter_than_max_bytes() [Test] public void MinOrDefault_should_return_zero_when_collection_is_empty() { - - - - - var result = (new List()).MinOrDefault(); + var result = new List().MinOrDefault(); //Resolve result.Should().Be(0); @@ -167,10 +151,8 @@ public void MinOrDefault_should_return_zero_when_collection_is_empty() [Test] public void MinOrDefault_should_return_min_when_collection_is_not_empty() { - var list = new List { 6, 4, 5, 3, 8, 10 }; - var result = list.MinOrDefault(); //Resolve @@ -180,22 +162,19 @@ public void MinOrDefault_should_return_min_when_collection_is_not_empty() [Test] public void MinOrDefault_should_return_zero_when_collection_is_null() { - List list = null; - var result = list.MinOrDefault(); //Resolve result.Should().Be(0); } - - [TestCase(100,100,100)] - [TestCase(110,100,100)] - [TestCase(199,100,100)] - [TestCase(1000,100,1000)] - [TestCase(0,100,0)] + [TestCase(100, 100, 100)] + [TestCase(110, 100, 100)] + [TestCase(199, 100, 100)] + [TestCase(1000, 100, 1000)] + [TestCase(0, 100, 0)] public void round_to_level(long number, int level, int result) { number.Round(level).Should().Be(result); diff --git a/src/NzbDrone.Core.Test/Framework/CoreTest.cs b/src/NzbDrone.Core.Test/Framework/CoreTest.cs index c7caa959f6..ab3cb795fb 100644 --- a/src/NzbDrone.Core.Test/Framework/CoreTest.cs +++ b/src/NzbDrone.Core.Test/Framework/CoreTest.cs @@ -1,17 +1,17 @@ -using Moq; using System; +using Moq; using NUnit.Framework; using NzbDrone.Common.Cache; using NzbDrone.Common.Cloud; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Common.Http; using NzbDrone.Common.Http.Dispatchers; -using NzbDrone.Common.TPL; -using NzbDrone.Test.Common; using NzbDrone.Common.Http.Proxy; -using NzbDrone.Core.Http; +using NzbDrone.Common.TPL; using NzbDrone.Core.Configuration; +using NzbDrone.Core.Http; using NzbDrone.Core.Parser; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Framework { @@ -47,12 +47,14 @@ protected void ParseMovieTitle() { result.Quality = QualityParser.ParseQuality(title); } + return result; }); } } - public abstract class CoreTest : CoreTest where TSubject : class + public abstract class CoreTest : CoreTest + where TSubject : class { private TSubject _subject; @@ -73,7 +75,6 @@ protected TSubject Subject return _subject; } - } } } diff --git a/src/NzbDrone.Core.Test/Framework/DbTest.cs b/src/NzbDrone.Core.Test/Framework/DbTest.cs index b498950a2c..f548c2c41b 100644 --- a/src/NzbDrone.Core.Test/Framework/DbTest.cs +++ b/src/NzbDrone.Core.Test/Framework/DbTest.cs @@ -41,7 +41,6 @@ protected TSubject Subject return _subject; } - } } @@ -57,7 +56,9 @@ protected ITestDatabase Db get { if (_db == null) + { throw new InvalidOperationException("Test object database doesn't exists. Make sure you call WithRealDb() if you intend to use an actual database."); + } return _db; } @@ -78,6 +79,7 @@ protected virtual ITestDatabase WithTestDb(MigrationContext migrationContext) Mocker.SetConstant(mainDb); break; } + case MigrationType.Log: { var logDb = new LogDatabase(database); @@ -85,6 +87,7 @@ protected virtual ITestDatabase WithTestDb(MigrationContext migrationContext) Mocker.SetConstant(logDb); break; } + default: { throw new ArgumentException("Invalid MigrationType"); diff --git a/src/NzbDrone.Core.Test/Framework/DirectDataMapper.cs b/src/NzbDrone.Core.Test/Framework/DirectDataMapper.cs index d05aed7785..45f9192456 100644 --- a/src/NzbDrone.Core.Test/Framework/DirectDataMapper.cs +++ b/src/NzbDrone.Core.Test/Framework/DirectDataMapper.cs @@ -11,7 +11,8 @@ namespace NzbDrone.Core.Test.Framework public interface IDirectDataMapper { List> Query(string sql); - List Query(string sql) where T : new(); + List Query(string sql) + where T : new(); } public class DirectDataMapper : IDirectDataMapper @@ -55,7 +56,8 @@ public List> Query(string sql) return dataTable.Rows.Cast().Select(MapToDictionary).ToList(); } - public List Query(string sql) where T : new() + public List Query(string sql) + where T : new() { var dataTable = GetDataTable(sql); @@ -86,7 +88,8 @@ protected Dictionary MapToDictionary(DataRow dataRow) return item; } - protected T MapToObject(DataRow dataRow) where T : new() + protected T MapToObject(DataRow dataRow) + where T : new() { var item = new T(); diff --git a/src/NzbDrone.Core.Test/Framework/MigrationTest.cs b/src/NzbDrone.Core.Test/Framework/MigrationTest.cs index ba7433647c..c751bbf555 100644 --- a/src/NzbDrone.Core.Test/Framework/MigrationTest.cs +++ b/src/NzbDrone.Core.Test/Framework/MigrationTest.cs @@ -8,7 +8,8 @@ namespace NzbDrone.Core.Test.Framework { [Category("DbMigrationTest")] [Category("DbTest")] - public abstract class MigrationTest : DbTest where TMigration : NzbDroneMigrationBase + public abstract class MigrationTest : DbTest + where TMigration : NzbDroneMigrationBase { protected long MigrationVersion { diff --git a/src/NzbDrone.Core.Test/Framework/NBuilderExtensions.cs b/src/NzbDrone.Core.Test/Framework/NBuilderExtensions.cs index 97efa8c797..9394ba74bf 100644 --- a/src/NzbDrone.Core.Test/Framework/NBuilderExtensions.cs +++ b/src/NzbDrone.Core.Test/Framework/NBuilderExtensions.cs @@ -7,20 +7,22 @@ namespace NzbDrone.Core.Test.Framework { public static class NBuilderExtensions { - public static T BuildNew(this ISingleObjectBuilder builder) where T : ModelBase, new() + public static T BuildNew(this ISingleObjectBuilder builder) + where T : ModelBase, new() { return builder.With(c => c.Id = 0).Build(); } - public static List BuildList(this IListBuilder builder) where T : ModelBase, new() + public static List BuildList(this IListBuilder builder) + where T : ModelBase, new() { return builder.Build().ToList(); } - public static List BuildListOfNew(this IListBuilder builder) where T : ModelBase, new() + public static List BuildListOfNew(this IListBuilder builder) + where T : ModelBase, new() { return BuildList(builder.All().With(c => c.Id = 0)); } - } } diff --git a/src/NzbDrone.Core.Test/Framework/TestDatabase.cs b/src/NzbDrone.Core.Test/Framework/TestDatabase.cs index 30fb2be0c9..4215a66c6a 100644 --- a/src/NzbDrone.Core.Test/Framework/TestDatabase.cs +++ b/src/NzbDrone.Core.Test/Framework/TestDatabase.cs @@ -8,12 +8,18 @@ namespace NzbDrone.Core.Test.Framework { public interface ITestDatabase { - void InsertMany(IEnumerable items) where T : ModelBase, new(); - T Insert(T item) where T : ModelBase, new(); - List All() where T : ModelBase, new(); - T Single() where T : ModelBase, new(); - void Update(T childModel) where T : ModelBase, new(); - void Delete(T childModel) where T : ModelBase, new(); + void InsertMany(IEnumerable items) + where T : ModelBase, new(); + T Insert(T item) + where T : ModelBase, new(); + List All() + where T : ModelBase, new(); + T Single() + where T : ModelBase, new(); + void Update(T childModel) + where T : ModelBase, new(); + void Delete(T childModel) + where T : ModelBase, new(); IDirectDataMapper GetDirectDataMapper(); } @@ -28,32 +34,38 @@ public TestDatabase(IDatabase dbConnection) _dbConnection = dbConnection; } - public void InsertMany(IEnumerable items) where T : ModelBase, new() + public void InsertMany(IEnumerable items) + where T : ModelBase, new() { new BasicRepository(_dbConnection, _eventAggregator).InsertMany(items.ToList()); } - public T Insert(T item) where T : ModelBase, new() + public T Insert(T item) + where T : ModelBase, new() { return new BasicRepository(_dbConnection, _eventAggregator).Insert(item); } - public List All() where T : ModelBase, new() + public List All() + where T : ModelBase, new() { return new BasicRepository(_dbConnection, _eventAggregator).All().ToList(); } - public T Single() where T : ModelBase, new() + public T Single() + where T : ModelBase, new() { return All().SingleOrDefault(); } - public void Update(T childModel) where T : ModelBase, new() + public void Update(T childModel) + where T : ModelBase, new() { new BasicRepository(_dbConnection, _eventAggregator).Update(childModel); } - public void Delete(T childModel) where T : ModelBase, new() + public void Delete(T childModel) + where T : ModelBase, new() { new BasicRepository(_dbConnection, _eventAggregator).Delete(childModel); } diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/DeleteBadMediaCovers.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/DeleteBadMediaCovers.cs index 40a9800741..7b791e91fb 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/DeleteBadMediaCovers.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/DeleteBadMediaCovers.cs @@ -10,8 +10,8 @@ using NzbDrone.Core.Extras.Metadata; using NzbDrone.Core.Extras.Metadata.Files; using NzbDrone.Core.Housekeeping.Housekeepers; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.HealthCheck.Checks @@ -30,7 +30,6 @@ public void Setup() .With(c => c.Path = "C:\\Movie\\".AsOsAgnostic()) .Build().ToList(); - _metadata = Builder.CreateListOfSize(1) .Build().ToList(); @@ -38,16 +37,13 @@ public void Setup() .Setup(c => c.GetAllMovies()) .Returns(_movies); - Mocker.GetMock() .Setup(c => c.GetFilesByMovie(_movies.First().Id)) .Returns(_metadata); - Mocker.GetMock().SetupGet(c => c.CleanupMetadataImages).Returns(true); } - [Test] public void should_not_process_non_image_files() { @@ -57,7 +53,6 @@ public void should_not_process_non_image_files() Subject.Clean(); Mocker.GetMock().Verify(c => c.OpenReadStream(It.IsAny()), Times.Never()); - } [Test] @@ -70,8 +65,6 @@ public void should_not_process_images_before_tvdb_switch() Mocker.GetMock().Verify(c => c.OpenReadStream(It.IsAny()), Times.Never()); } - - [Test] public void should_not_run_if_flag_is_false() { @@ -85,7 +78,6 @@ public void should_not_run_if_flag_is_false() AssertImageWasNotRemoved(); } - [Test] public void should_set_clean_flag_to_false() { @@ -96,11 +88,9 @@ public void should_set_clean_flag_to_false() Mocker.GetMock().VerifySet(c => c.CleanupMetadataImages = false, Times.Once()); } - [Test] public void should_delete_html_images() { - var imagePath = "C:\\Movie\\image.jpg".AsOsAgnostic(); _metadata.First().LastUpdated = new DateTime(2014, 12, 29); _metadata.First().RelativePath = "image.jpg".AsOsAgnostic(); @@ -110,19 +100,15 @@ public void should_delete_html_images() .Setup(c => c.OpenReadStream(imagePath)) .Returns(new FileStream(GetTestPath("Files/html_image.jpg"), FileMode.Open, FileAccess.Read)); - Subject.Clean(); - Mocker.GetMock().Verify(c => c.DeleteFile(imagePath), Times.Once()); Mocker.GetMock().Verify(c => c.Delete(_metadata.First().Id), Times.Once()); } - [Test] public void should_delete_empty_images() { - var imagePath = "C:\\Movie\\image.jpg".AsOsAgnostic(); _metadata.First().LastUpdated = new DateTime(2014, 12, 29); _metadata.First().Type = MetadataType.MovieImage; @@ -132,18 +118,15 @@ public void should_delete_empty_images() .Setup(c => c.OpenReadStream(imagePath)) .Returns(new FileStream(GetTestPath("Files/emptyfile.txt"), FileMode.Open, FileAccess.Read)); - Subject.Clean(); Mocker.GetMock().Verify(c => c.DeleteFile(imagePath), Times.Once()); Mocker.GetMock().Verify(c => c.Delete(_metadata.First().Id), Times.Once()); } - [Test] public void should_not_delete_non_html_files() { - var imagePath = "C:\\Movie\\image.jpg".AsOsAgnostic(); _metadata.First().LastUpdated = new DateTime(2014, 12, 29); _metadata.First().RelativePath = "image.jpg".AsOsAgnostic(); @@ -152,7 +135,6 @@ public void should_not_delete_non_html_files() .Setup(c => c.OpenReadStream(imagePath)) .Returns(new FileStream(GetTestPath("Files/Queue.txt"), FileMode.Open, FileAccess.Read)); - Subject.Clean(); AssertImageWasNotRemoved(); } diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/DownloadClientCheckFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/DownloadClientCheckFixture.cs index dd0fc09be2..d2097304ee 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/DownloadClientCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/DownloadClientCheckFixture.cs @@ -24,7 +24,7 @@ public void should_return_warning_when_download_client_has_not_been_configured() public void should_return_error_when_download_client_throws() { var downloadClient = Mocker.GetMock(); - downloadClient.Setup(s => s.Definition).Returns(new DownloadClientDefinition{Name = "Test"}); + downloadClient.Setup(s => s.Definition).Returns(new DownloadClientDefinition { Name = "Test" }); downloadClient.Setup(s => s.GetItems()) .Throws(); diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerSearchCheckFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerSearchCheckFixture.cs index 3fb2a2a70c..cffb072079 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerSearchCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerSearchCheckFixture.cs @@ -114,7 +114,6 @@ public void should_return_warning_if_search_is_supported_but_disabled() Subject.Check().ShouldBeWarning(); } - [Test] public void should_return_filter_warning_if_search_is_enabled_but_filtered() { diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerStatusCheckFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerStatusCheckFixture.cs index 1d71d3a807..a77eecf13f 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerStatusCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/IndexerStatusCheckFixture.cs @@ -39,19 +39,18 @@ private Mock GivenIndexer(int i, double backoffHours, double failureHo if (backoffHours != 0.0) { _blockedIndexers.Add(new IndexerStatus - { - ProviderId = id, - InitialFailure = DateTime.UtcNow.AddHours(-failureHours), - MostRecentFailure = DateTime.UtcNow.AddHours(-0.1), - EscalationLevel = 5, - DisabledTill = DateTime.UtcNow.AddHours(backoffHours) - }); + { + ProviderId = id, + InitialFailure = DateTime.UtcNow.AddHours(-failureHours), + MostRecentFailure = DateTime.UtcNow.AddHours(-0.1), + EscalationLevel = 5, + DisabledTill = DateTime.UtcNow.AddHours(backoffHours) + }); } return mockIndexer; } - [Test] public void should_not_return_error_when_no_indexers() { diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/MonoVersionCheckFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/MonoVersionCheckFixture.cs index b950639285..e33402e41e 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/MonoVersionCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/MonoVersionCheckFixture.cs @@ -18,7 +18,6 @@ private void GivenOutput(string version) .Returns(new Version(version)); } - [TestCase("5.18")] [TestCase("5.20")] public void should_return_ok(string version) diff --git a/src/NzbDrone.Core.Test/HealthCheck/Checks/RootFolderCheckFixture.cs b/src/NzbDrone.Core.Test/HealthCheck/Checks/RootFolderCheckFixture.cs index bf1a06cf40..cd8f87211b 100644 --- a/src/NzbDrone.Core.Test/HealthCheck/Checks/RootFolderCheckFixture.cs +++ b/src/NzbDrone.Core.Test/HealthCheck/Checks/RootFolderCheckFixture.cs @@ -5,8 +5,8 @@ using NUnit.Framework; using NzbDrone.Common.Disk; using NzbDrone.Core.HealthCheck.Checks; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.HealthCheck.Checks { diff --git a/src/NzbDrone.Core.Test/HistoryTests/HistoryRepositoryFixture.cs b/src/NzbDrone.Core.Test/HistoryTests/HistoryRepositoryFixture.cs index bd6a581d7a..916b83a80d 100644 --- a/src/NzbDrone.Core.Test/HistoryTests/HistoryRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/HistoryTests/HistoryRepositoryFixture.cs @@ -1,11 +1,11 @@ +using System.Collections.Generic; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.History; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Languages; -using System.Collections.Generic; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.HistoryTests { @@ -33,7 +33,6 @@ public void should_read_write_dictionary() StoredModel.Data.Should().HaveCount(2); } - [Test] public void should_get_download_history() { @@ -58,6 +57,5 @@ public void should_get_download_history() downloadHistory.Should().HaveCount(1); } - } } diff --git a/src/NzbDrone.Core.Test/HistoryTests/HistoryServiceFixture.cs b/src/NzbDrone.Core.Test/HistoryTests/HistoryServiceFixture.cs index b8c58f5a6b..83a0457fbe 100644 --- a/src/NzbDrone.Core.Test/HistoryTests/HistoryServiceFixture.cs +++ b/src/NzbDrone.Core.Test/HistoryTests/HistoryServiceFixture.cs @@ -1,18 +1,18 @@ +using System.Collections.Generic; using System.IO; using FizzWare.NBuilder; +using FluentAssertions; using Moq; using NUnit.Framework; +using NzbDrone.Core.History; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.History; using NzbDrone.Core.Qualities; -using System.Collections.Generic; +using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Test.Qualities; -using FluentAssertions; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.HistoryTests { @@ -73,10 +73,10 @@ public void should_use_file_name_for_source_title_if_scene_name_is_null() .Build(); var localMovie = new LocalMovie() - { - Movie = movie, - Path = @"C:\Test\Unsorted\Movie.2011.mkv" - }; + { + Movie = movie, + Path = @"C:\Test\Unsorted\Movie.2011.mkv" + }; Subject.Handle(new MovieImportedEvent(localMovie, movieFile, true, "sab", "abcd")); diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedBlacklistFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedBlacklistFixture.cs index ba4ed976e7..b9bd4d4be4 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedBlacklistFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedBlacklistFixture.cs @@ -1,13 +1,13 @@ +using System.Collections.Generic; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Blacklisting; using NzbDrone.Core.Housekeeping.Housekeepers; +using NzbDrone.Core.Languages; +using NzbDrone.Core.Movies; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; -using System.Collections.Generic; -using NzbDrone.Core.Languages; namespace NzbDrone.Core.Test.Housekeeping.Housekeepers { @@ -18,7 +18,7 @@ public class CleanupOrphanedBlacklistFixture : DbTest.CreateNew() - .With(h => h.MovieId = new int()) + .With(h => h.MovieId = default) .With(h => h.Quality = new QualityModel()) .With(h => h.Languages = new List()) .BuildNew(); @@ -36,7 +36,7 @@ public void should_not_delete_unorphaned_blacklist_items() Db.Insert(movie); var blacklist = Builder.CreateNew() - .With(h => h.MovieId = new int()) + .With(h => h.MovieId = default) .With(h => h.Quality = new QualityModel()) .With(h => h.Languages = new List()) .With(b => b.MovieId = movie.Id) diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedHistoryItemsFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedHistoryItemsFixture.cs index d6bd721d77..cbffa879f8 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedHistoryItemsFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedHistoryItemsFixture.cs @@ -1,12 +1,12 @@ +using System.Collections.Generic; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Housekeeping.Housekeepers; +using NzbDrone.Core.Languages; +using NzbDrone.Core.Movies; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; -using NzbDrone.Core.Languages; -using System.Collections.Generic; namespace NzbDrone.Core.Test.Housekeeping.Housekeepers { @@ -30,7 +30,6 @@ private void GivenSeries() [Test] public void should_delete_orphaned_items() { - var history = Builder.CreateNew() .With(h => h.Quality = new QualityModel()) .With(h => h.Languages = new List()) diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedMetadataFilesFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedMetadataFilesFixture.cs index fa5727ea78..8c1479c35d 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedMetadataFilesFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedMetadataFilesFixture.cs @@ -1,15 +1,15 @@ +using System.Collections.Generic; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Extras.Metadata; using NzbDrone.Core.Extras.Metadata.Files; using NzbDrone.Core.Housekeeping.Housekeepers; +using NzbDrone.Core.Languages; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Movies; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; -using NzbDrone.Core.Languages; -using System.Collections.Generic; namespace NzbDrone.Core.Test.Housekeeping.Housekeepers { diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedMovieFilesFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedMovieFilesFixture.cs index c92e125491..8728afc3d4 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedMovieFilesFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedMovieFilesFixture.cs @@ -1,14 +1,14 @@ +using System.Collections.Generic; using System.Linq; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Housekeeping.Housekeepers; +using NzbDrone.Core.Languages; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Languages; -using System.Collections.Generic; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Housekeeping.Housekeepers { @@ -20,7 +20,7 @@ public void should_delete_orphaned_episode_files() { var movieFile = Builder.CreateNew() .With(h => h.Quality = new QualityModel()) - .With(h => h.Languages = new List { Language.English}) + .With(h => h.Languages = new List { Language.English }) .BuildNew(); Db.Insert(movieFile); diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedPendingReleasesFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedPendingReleasesFixture.cs index 503d7f6f2c..5d05b7ae6a 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedPendingReleasesFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupOrphanedPendingReleasesFixture.cs @@ -3,9 +3,9 @@ using NUnit.Framework; using NzbDrone.Core.Download.Pending; using NzbDrone.Core.Housekeeping.Housekeepers; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.Housekeeping.Housekeepers { diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupUnusedTagsFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupUnusedTagsFixture.cs index fa7401ef54..b69727d04f 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupUnusedTagsFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/CleanupUnusedTagsFixture.cs @@ -2,9 +2,9 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Housekeeping.Housekeepers; -using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Tags; using NzbDrone.Core.Restrictions; +using NzbDrone.Core.Tags; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Housekeeping.Housekeepers { diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureDownloadClientStatusTimesFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureDownloadClientStatusTimesFixture.cs index 7ba5dbf22a..396bc9dcd1 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureDownloadClientStatusTimesFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureDownloadClientStatusTimesFixture.cs @@ -35,9 +35,7 @@ public void should_set_disabled_till_when_its_too_far_in_the_future() Mocker.GetMock() .Verify(v => v.UpdateMany( It.Is>(i => i.All( - s => s.DisabledTill.Value <= DateTime.UtcNow.AddMinutes(disabledTillTime))) - ) - ); + s => s.DisabledTill.Value <= DateTime.UtcNow.AddMinutes(disabledTillTime))))); } [Test] @@ -60,9 +58,7 @@ public void should_set_initial_failure_when_its_in_the_future() Mocker.GetMock() .Verify(v => v.UpdateMany( It.Is>(i => i.All( - s => s.InitialFailure.Value <= DateTime.UtcNow)) - ) - ); + s => s.InitialFailure.Value <= DateTime.UtcNow)))); } [Test] @@ -85,9 +81,7 @@ public void should_set_most_recent_failure_when_its_in_the_future() Mocker.GetMock() .Verify(v => v.UpdateMany( It.Is>(i => i.All( - s => s.MostRecentFailure.Value <= DateTime.UtcNow)) - ) - ); + s => s.MostRecentFailure.Value <= DateTime.UtcNow)))); } [Test] @@ -109,11 +103,7 @@ public void should_not_change_statuses_when_times_are_in_the_past() Mocker.GetMock() .Verify(v => v.UpdateMany( - It.Is>(i => i.Count == 0) - ) - ); + It.Is>(i => i.Count == 0))); } - - } } diff --git a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureIndexerStatusTimesFixture.cs b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureIndexerStatusTimesFixture.cs index 694dcff7a7..3034f49812 100644 --- a/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureIndexerStatusTimesFixture.cs +++ b/src/NzbDrone.Core.Test/Housekeeping/Housekeepers/FixFutureIndexerStatusTimesFixture.cs @@ -35,9 +35,7 @@ public void should_set_disabled_till_when_its_too_far_in_the_future() Mocker.GetMock() .Verify(v => v.UpdateMany( It.Is>(i => i.All( - s => s.DisabledTill.Value <= DateTime.UtcNow.AddMinutes(disabledTillTime))) - ) - ); + s => s.DisabledTill.Value <= DateTime.UtcNow.AddMinutes(disabledTillTime))))); } [Test] @@ -60,9 +58,7 @@ public void should_set_initial_failure_when_its_in_the_future() Mocker.GetMock() .Verify(v => v.UpdateMany( It.Is>(i => i.All( - s => s.InitialFailure.Value <= DateTime.UtcNow)) - ) - ); + s => s.InitialFailure.Value <= DateTime.UtcNow)))); } [Test] @@ -85,9 +81,7 @@ public void should_set_most_recent_failure_when_its_in_the_future() Mocker.GetMock() .Verify(v => v.UpdateMany( It.Is>(i => i.All( - s => s.MostRecentFailure.Value <= DateTime.UtcNow)) - ) - ); + s => s.MostRecentFailure.Value <= DateTime.UtcNow)))); } [Test] @@ -109,11 +103,7 @@ public void should_not_change_statuses_when_times_are_in_the_past() Mocker.GetMock() .Verify(v => v.UpdateMany( - It.Is>(i => i.Count == 0) - ) - ); + It.Is>(i => i.Count == 0))); } - - } } diff --git a/src/NzbDrone.Core.Test/Http/HttpProxySettingsProviderFixture.cs b/src/NzbDrone.Core.Test/Http/HttpProxySettingsProviderFixture.cs index 2e77593974..067149904a 100644 --- a/src/NzbDrone.Core.Test/Http/HttpProxySettingsProviderFixture.cs +++ b/src/NzbDrone.Core.Test/Http/HttpProxySettingsProviderFixture.cs @@ -1,9 +1,9 @@ -using NzbDrone.Core.Http; +using FluentAssertions; using NUnit.Framework; -using FluentAssertions; -using NzbDrone.Test.Common; -using NzbDrone.Common.Http.Proxy; using NzbDrone.Common.Http; +using NzbDrone.Common.Http.Proxy; +using NzbDrone.Core.Http; +using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.Http { diff --git a/src/NzbDrone.Core.Test/Http/TorCacheHttpRequestInterceptorFixture.cs b/src/NzbDrone.Core.Test/Http/TorCacheHttpRequestInterceptorFixture.cs index 6273c7ef8c..f92d8728ab 100644 --- a/src/NzbDrone.Core.Test/Http/TorCacheHttpRequestInterceptorFixture.cs +++ b/src/NzbDrone.Core.Test/Http/TorCacheHttpRequestInterceptorFixture.cs @@ -1,8 +1,8 @@ -using NUnit.Framework; +using FluentAssertions; +using NUnit.Framework; using NzbDrone.Common.Http; using NzbDrone.Core.Http; using NzbDrone.Test.Common; -using FluentAssertions; namespace NzbDrone.Core.Test.Http { diff --git a/src/NzbDrone.Core.Test/IndexerTests/BasicRssParserFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/BasicRssParserFixture.cs index edfa3ff163..82120f8881 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/BasicRssParserFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/BasicRssParserFixture.cs @@ -45,7 +45,6 @@ private IndexerResponse CreateResponse(string url, string content) return new IndexerResponse(new IndexerRequest(httpRequest), httpResponse); } - [Test] public void should_handle_relative_url() { diff --git a/src/NzbDrone.Core.Test/IndexerTests/HDBitsTests/HDBitsFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/HDBitsTests/HDBitsFixture.cs index df81688fda..99c716cb8b 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/HDBitsTests/HDBitsFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/HDBitsTests/HDBitsFixture.cs @@ -64,8 +64,7 @@ public void should_warn_on_wrong_passkey() Mocker.GetMock() .Setup(v => v.Execute(It.IsAny())) - .Returns(r => new HttpResponse(r, new HttpHeader(), - Encoding.UTF8.GetBytes(responseJson))); + .Returns(r => new HttpResponse(r, new HttpHeader(), Encoding.UTF8.GetBytes(responseJson))); var torrents = Subject.FetchRecent(); diff --git a/src/NzbDrone.Core.Test/IndexerTests/IPTorrentsTests/IPTorrentsFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/IPTorrentsTests/IPTorrentsFixture.cs index 08204e6a74..cabc820401 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/IPTorrentsTests/IPTorrentsFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/IPTorrentsTests/IPTorrentsFixture.cs @@ -1,3 +1,6 @@ +using System; +using System.Linq; +using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Common.Http; @@ -5,9 +8,6 @@ using NzbDrone.Core.Indexers.IPTorrents; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using System; -using System.Linq; -using FluentAssertions; namespace NzbDrone.Core.Test.IndexerTests.IPTorrentsTests { @@ -18,10 +18,10 @@ public class IPTorrentsFixture : CoreTest public void Setup() { Subject.Definition = new IndexerDefinition() - { - Name = "IPTorrents", - Settings = new IPTorrentsSettings() { BaseUrl = "http://fake.com/" } - }; + { + Name = "IPTorrents", + Settings = new IPTorrentsSettings() { BaseUrl = "http://fake.com/" } + }; } private void GivenOldFeedFormat() @@ -29,7 +29,7 @@ private void GivenOldFeedFormat() Subject.Definition = new IndexerDefinition() { Name = "IPTorrents", - Settings = new IPTorrentsSettings() { BaseUrl = "https://iptorrents.com/torrents/rss?u=snip;tp=snip;3;80;93;37;download" } + Settings = new IPTorrentsSettings() { BaseUrl = "https://iptorrents.com/torrents/rss?u=snip;tp=snip;3;80;93;37;download" } }; } @@ -38,7 +38,7 @@ private void GivenNewFeedFormat() Subject.Definition = new IndexerDefinition() { Name = "IPTorrents", - Settings = new IPTorrentsSettings() { BaseUrl = "https://iptorrents.com/t.rss?u=USERID;tp=APIKEY;3;80;93;37;download" } + Settings = new IPTorrentsSettings() { BaseUrl = "https://iptorrents.com/t.rss?u=USERID;tp=APIKEY;3;80;93;37;download" } }; } @@ -47,7 +47,7 @@ private void GivenFeedNoDownloadFormat() Subject.Definition = new IndexerDefinition() { Name = "IPTorrents", - Settings = new IPTorrentsSettings() { BaseUrl = "https://iptorrents.com/t.rss?u=USERID;tp=APIKEY;3;80;93;37" } + Settings = new IPTorrentsSettings() { BaseUrl = "https://iptorrents.com/t.rss?u=USERID;tp=APIKEY;3;80;93;37" } }; } diff --git a/src/NzbDrone.Core.Test/IndexerTests/IndexerServiceFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/IndexerServiceFixture.cs index 7d4509d8fd..4cc12f77b3 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/IndexerServiceFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/IndexerServiceFixture.cs @@ -33,7 +33,7 @@ public void should_remove_missing_indexers_on_startup() Mocker.SetConstant(repo); var existingIndexers = Builder.CreateNew().BuildNew(); - existingIndexers.ConfigContract = typeof (NewznabSettings).Name; + existingIndexers.ConfigContract = typeof(NewznabSettings).Name; repo.Insert(existingIndexers); diff --git a/src/NzbDrone.Core.Test/IndexerTests/IntegrationTests/IndexerIntegrationTests.cs b/src/NzbDrone.Core.Test/IndexerTests/IntegrationTests/IndexerIntegrationTests.cs index 39d382bbd3..c79bb8df77 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/IntegrationTests/IndexerIntegrationTests.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/IntegrationTests/IndexerIntegrationTests.cs @@ -23,9 +23,9 @@ public void SetUp() UseRealHttp(); _singleSearchCriteria = new MovieSearchCriteria() - { - SceneTitles = new List { "Person of Interest" }, - }; + { + SceneTitles = new List { "Person of Interest" }, + }; } private void ValidateTorrentResult(IList reports, bool hasSize = false, bool hasInfoUrl = false, bool hasMagnet = false) @@ -60,6 +60,5 @@ private void ValidateResult(IList reports, bool hasSize = false, bo reports.Should().OnlyContain(c => c.Size > 0); } } - } } diff --git a/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabFixture.cs index 64c0d1051a..e31bfc35bd 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabFixture.cs @@ -19,15 +19,15 @@ public class NewznabFixture : CoreTest public void Setup() { Subject.Definition = new IndexerDefinition() + { + Id = 5, + Name = "Newznab", + Settings = new NewznabSettings() { - Id = 5, - Name = "Newznab", - Settings = new NewznabSettings() - { - BaseUrl = "http://indexer.local/", - Categories = new int[] { 1 } - } - }; + BaseUrl = "http://indexer.local/", + Categories = new int[] { 1 } + } + }; _caps = new NewznabCapabilities(); Mocker.GetMock() diff --git a/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabRequestGeneratorFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabRequestGeneratorFixture.cs index 379fa0ebc0..49e26fe55a 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabRequestGeneratorFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabRequestGeneratorFixture.cs @@ -18,10 +18,10 @@ public void SetUp() { Subject.Settings = new NewznabSettings() { - BaseUrl = "http://127.0.0.1:1234/", - Categories = new [] { 1, 2 }, - AnimeCategories = new [] { 3, 4 }, - ApiKey = "abcd", + BaseUrl = "http://127.0.0.1:1234/", + Categories = new[] { 1, 2 }, + AnimeCategories = new[] { 3, 4 }, + ApiKey = "abcd", }; _movieSearchCriteria = new MovieSearchCriteria @@ -115,6 +115,5 @@ public void should_search_by_imdbid_if_supported() page.Url.Query.Should().Contain("imdbid=0076759"); } - } } diff --git a/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabSettingFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabSettingFixture.cs index 547e84b67c..51e2227d4a 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabSettingFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/NewznabTests/NewznabSettingFixture.cs @@ -7,7 +7,6 @@ namespace NzbDrone.Core.Test.IndexerTests.NewznabTests { public class NewznabSettingFixture : CoreTest { - [TestCase("http://nzbs.org")] [TestCase("http:///www.nzbplanet.net")] public void requires_apikey(string url) @@ -18,10 +17,8 @@ public void requires_apikey(string url) BaseUrl = url }; - setting.Validate().IsValid.Should().BeFalse(); setting.Validate().Errors.Should().Contain(c => c.PropertyName == "ApiKey"); - } [TestCase("")] @@ -35,14 +32,11 @@ public void invalid_url_should_not_apikey(string url) BaseUrl = url }; - setting.Validate().IsValid.Should().BeFalse(); setting.Validate().Errors.Should().NotContain(c => c.PropertyName == "ApiKey"); setting.Validate().Errors.Should().Contain(c => c.PropertyName == "BaseUrl"); - } - [TestCase("http://nzbs2.org")] public void doesnt_requires_apikey(string url) { @@ -52,7 +46,6 @@ public void doesnt_requires_apikey(string url) BaseUrl = url }; - setting.Validate().IsValid.Should().BeTrue(); } } diff --git a/src/NzbDrone.Core.Test/IndexerTests/NyaaTests/NyaaFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/NyaaTests/NyaaFixture.cs index ba670d632f..0ca24bc759 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/NyaaTests/NyaaFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/NyaaTests/NyaaFixture.cs @@ -18,10 +18,10 @@ public class NyaaFixture : CoreTest public void Setup() { Subject.Definition = new IndexerDefinition() - { - Name = "Nyaa", - Settings = new NyaaSettings() - }; + { + Name = "Nyaa", + Settings = new NyaaSettings() + }; } [Test] @@ -50,7 +50,7 @@ public void should_parse_recent_feed_from_Nyaa() torrentInfo.Size.Should().Be(2523293286); //2.35 GiB torrentInfo.InfoHash.Should().Be(null); torrentInfo.MagnetUrl.Should().Be(null); - torrentInfo.Peers.Should().Be(2+1); + torrentInfo.Peers.Should().Be(2 + 1); torrentInfo.Seeders.Should().Be(1); } } diff --git a/src/NzbDrone.Core.Test/IndexerTests/OmgwtfnzbsTests/OmgwtfnzbsFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/OmgwtfnzbsTests/OmgwtfnzbsFixture.cs index 82cd7da3ba..2e6ff1f834 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/OmgwtfnzbsTests/OmgwtfnzbsFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/OmgwtfnzbsTests/OmgwtfnzbsFixture.cs @@ -17,14 +17,14 @@ public class OmgwtfnzbsFixture : CoreTest public void Setup() { Subject.Definition = new IndexerDefinition() + { + Name = "Omgwtfnzbs", + Settings = new OmgwtfnzbsSettings() { - Name = "Omgwtfnzbs", - Settings = new OmgwtfnzbsSettings() - { - ApiKey = "xxx", - Username = "me@my.domain" - } - }; + ApiKey = "xxx", + Username = "me@my.domain" + } + }; } [Test] diff --git a/src/NzbDrone.Core.Test/IndexerTests/PTPTests/PTPFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/PTPTests/PTPFixture.cs index 2e3768a089..707f0f2a74 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/PTPTests/PTPFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/PTPTests/PTPFixture.cs @@ -35,11 +35,11 @@ public void should_parse_feed_from_PTP(string fileName) Mocker.GetMock() .Setup(o => o.Execute(It.Is(v => v.Method == HttpMethod.POST))) - .Returns(r => new HttpResponse(r,new HttpHeader(), authStream.ToString())); + .Returns(r => new HttpResponse(r, new HttpHeader(), authStream.ToString())); Mocker.GetMock() .Setup(o => o.Execute(It.Is(v => v.Method == HttpMethod.GET))) - .Returns(r => new HttpResponse(r, new HttpHeader {ContentType = HttpAccept.Json.Value}, responseJson)); + .Returns(r => new HttpResponse(r, new HttpHeader { ContentType = HttpAccept.Json.Value }, responseJson)); var torrents = Subject.FetchRecent(); @@ -53,6 +53,7 @@ public void should_parse_feed_from_PTP(string fileName) first.DownloadProtocol.Should().Be(DownloadProtocol.Torrent); first.DownloadUrl.Should().Be("https://passthepopcorn.me/torrents.php?action=download&id=452135&authkey=00000000000000000000000000000000&torrent_pass=00000000000000000000000000000000"); first.InfoUrl.Should().Be("https://passthepopcorn.me/torrents.php?id=148131&torrentid=452135"); + //first.PublishDate.Should().Be(DateTime.Parse("2017-04-17T12:13:42+0000").ToUniversalTime()); stupid timezones first.Size.Should().Be(2466170624L); first.InfoHash.Should().BeNullOrEmpty(); diff --git a/src/NzbDrone.Core.Test/IndexerTests/RarbgTests/RarbgFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/RarbgTests/RarbgFixture.cs index 6de8fd38dd..797aa96175 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/RarbgTests/RarbgFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/RarbgTests/RarbgFixture.cs @@ -19,10 +19,10 @@ public class RarbgFixture : CoreTest public void Setup() { Subject.Definition = new IndexerDefinition() - { - Name = "Rarbg", - Settings = new RarbgSettings() - }; + { + Name = "Rarbg", + Settings = new RarbgSettings() + }; Mocker.GetMock() .Setup(v => v.GetToken(It.IsAny())) diff --git a/src/NzbDrone.Core.Test/IndexerTests/TestIndexer.cs b/src/NzbDrone.Core.Test/IndexerTests/TestIndexer.cs index a4c3a05d4e..2b73b3b73e 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/TestIndexer.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/TestIndexer.cs @@ -18,7 +18,6 @@ public class TestIndexer : HttpIndexerBase public TestIndexer(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) { - } public IIndexerRequestGenerator _requestGenerator; diff --git a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TestTorrentRssIndexer.cs b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TestTorrentRssIndexer.cs index 7a0c2989e9..110db4ec2d 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TestTorrentRssIndexer.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TestTorrentRssIndexer.cs @@ -1,13 +1,13 @@ using System.Collections.Generic; using FluentValidation.Results; using NLog; +using NLog.Config; +using NLog.Targets; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.Indexers; using NzbDrone.Core.Indexers.TorrentRss; using NzbDrone.Core.Parser; -using NLog.Config; -using NLog.Targets; namespace NzbDrone.Core.Test.IndexerTests.TorrentRssIndexerTests { @@ -21,7 +21,7 @@ public TestTorrentRssIndexer(ITorrentRssParserFactory torrentRssParserFactory, I public List TestPublic() { var result = new List(); - this.SetupNLog(); // Enable this to enable trace logging with nlog for debugging purposes + SetupNLog(); // Enable this to enable trace logging with nlog for debugging purposes Test(result); return result; } diff --git a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssIndexerFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssIndexerFixture.cs index 3833184f34..23131d2808 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssIndexerFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssIndexerFixture.cs @@ -12,7 +12,6 @@ namespace NzbDrone.Core.Test.IndexerTests.TorrentRssIndexerTests { - [TestFixture] public class TorrentRssIndexerFixture : CoreTest { @@ -219,7 +218,7 @@ public void should_parse_recent_feed_from_AnimeTosho_without_size() torrentInfo.CommentUrl.Should().Be("https://animetosho.org/view/fff-ore-monogatari-vol-01-bd-720p-aac.1009077"); torrentInfo.Indexer.Should().Be(Subject.Definition.Name); torrentInfo.PublishDate.Should().Be(DateTime.Parse("Tue, 02 Aug 2016 13:48:04 +0000").ToUniversalTime()); - torrentInfo.Size.Should().Be((long)Math.Round((double)1.366m * 1024L * 1024L * 1024L)); + torrentInfo.Size.Should().Be((long)Math.Round(1.366D * 1024L * 1024L * 1024L)); torrentInfo.InfoHash.Should().BeNull(); torrentInfo.MagnetUrl.Should().BeNull(); torrentInfo.Peers.Should().NotHaveValue(); diff --git a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssParserFactoryFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssParserFactoryFixture.cs index 0ed86b3c1b..e506c2978c 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssParserFactoryFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssParserFactoryFixture.cs @@ -1,11 +1,11 @@ -using Moq; +using FluentAssertions; +using Moq; using NUnit.Framework; using NzbDrone.Common.Cache; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.Indexers.Exceptions; using NzbDrone.Core.Indexers.TorrentRss; using NzbDrone.Core.Test.Framework; -using FluentAssertions; -using NzbDrone.Core.Indexers.Exceptions; -using NzbDrone.Core.Indexers; namespace NzbDrone.Core.Test.IndexerTests.TorrentRssIndexerTests { diff --git a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssSettingsDetectorFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssSettingsDetectorFixture.cs index 6c82df89d3..2980235131 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssSettingsDetectorFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/TorrentRssIndexerTests/TorrentRssSettingsDetectorFixture.cs @@ -37,14 +37,14 @@ public void should_detect_rss_settings_for_ezrss() var settings = Subject.Detect(_indexerSettings); settings.Should().BeEquivalentTo(new TorrentRssIndexerParserSettings - { - UseEZTVFormat = true, - UseEnclosureUrl = false, - UseEnclosureLength = false, - ParseSizeInDescription = false, - ParseSeedersInDescription = false, - SizeElementName = null - }); + { + UseEZTVFormat = true, + UseEnclosureUrl = false, + UseEnclosureLength = false, + ParseSizeInDescription = false, + ParseSeedersInDescription = false, + SizeElementName = null + }); } [Test] diff --git a/src/NzbDrone.Core.Test/IndexerTests/TorznabTests/TorznabFixture.cs b/src/NzbDrone.Core.Test/IndexerTests/TorznabTests/TorznabFixture.cs index 72982a55be..d65c926600 100644 --- a/src/NzbDrone.Core.Test/IndexerTests/TorznabTests/TorznabFixture.cs +++ b/src/NzbDrone.Core.Test/IndexerTests/TorznabTests/TorznabFixture.cs @@ -21,14 +21,14 @@ public class TorznabFixture : CoreTest public void Setup() { Subject.Definition = new IndexerDefinition() + { + Name = "Torznab", + Settings = new TorznabSettings() { - Name = "Torznab", - Settings = new TorznabSettings() - { - BaseUrl = "http://indexer.local/", - Categories = new int[] { 1 } - } - }; + BaseUrl = "http://indexer.local/", + Categories = new int[] { 1 } + } + }; _caps = new NewznabCapabilities(); Mocker.GetMock() diff --git a/src/NzbDrone.Core.Test/InstrumentationTests/DatabaseTargetFixture.cs b/src/NzbDrone.Core.Test/InstrumentationTests/DatabaseTargetFixture.cs index 6608bd42f8..f9874e0124 100644 --- a/src/NzbDrone.Core.Test/InstrumentationTests/DatabaseTargetFixture.cs +++ b/src/NzbDrone.Core.Test/InstrumentationTests/DatabaseTargetFixture.cs @@ -18,7 +18,7 @@ namespace NzbDrone.Core.Test.InstrumentationTests public class DatabaseTargetFixture : DbTest { private static string _uniqueMessage; - Logger _logger; + private Logger _logger; protected override MigrationType MigrationType => MigrationType.Log; @@ -64,7 +64,6 @@ public void write_long_log() VerifyLog(StoredModel, LogLevel.Info); } - [Test] [Explicit] [ManualTest] @@ -126,7 +125,6 @@ public void null_string_as_arg_should_not_fail() epFile.RelativePath.Should().BeNull(); } - [TearDown] public void Teardown() { @@ -136,7 +134,7 @@ public void Teardown() private void VerifyLog(Log logItem, LogLevel level) { logItem.Time.Should().BeWithin(TimeSpan.FromSeconds(2)); - logItem.Logger.Should().Be(this.GetType().Name); + logItem.Logger.Should().Be(GetType().Name); logItem.Level.Should().Be(level.Name); _logger.Name.Should().EndWith(logItem.Logger); } diff --git a/src/NzbDrone.Core.Test/Languages/LanguageFixture.cs b/src/NzbDrone.Core.Test/Languages/LanguageFixture.cs index df12a77b9c..29e36acc20 100644 --- a/src/NzbDrone.Core.Test/Languages/LanguageFixture.cs +++ b/src/NzbDrone.Core.Test/Languages/LanguageFixture.cs @@ -1,7 +1,7 @@ using FluentAssertions; using NUnit.Framework; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Languages; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Languages { @@ -10,64 +10,66 @@ public class LanguageFixture : CoreTest { public static object[] FromIntCases = { - new object[] {1, Language.English}, - new object[] {2, Language.French}, - new object[] {3, Language.Spanish}, - new object[] {4, Language.German}, - new object[] {5, Language.Italian}, - new object[] {6, Language.Danish}, - new object[] {7, Language.Dutch}, - new object[] {8, Language.Japanese}, - new object[] {9, Language.Icelandic}, - new object[] {10, Language.Chinese}, - new object[] {11, Language.Russian}, - new object[] {12, Language.Polish}, - new object[] {13, Language.Vietnamese}, - new object[] {14, Language.Swedish}, - new object[] {15, Language.Norwegian}, - new object[] {16, Language.Finnish}, - new object[] {17, Language.Turkish}, - new object[] {18, Language.Portuguese}, - new object[] {19, Language.Flemish}, - new object[] {20, Language.Greek}, - new object[] {21, Language.Korean}, - new object[] {22, Language.Hungarian} + new object[] { 1, Language.English }, + new object[] { 2, Language.French }, + new object[] { 3, Language.Spanish }, + new object[] { 4, Language.German }, + new object[] { 5, Language.Italian }, + new object[] { 6, Language.Danish }, + new object[] { 7, Language.Dutch }, + new object[] { 8, Language.Japanese }, + new object[] { 9, Language.Icelandic }, + new object[] { 10, Language.Chinese }, + new object[] { 11, Language.Russian }, + new object[] { 12, Language.Polish }, + new object[] { 13, Language.Vietnamese }, + new object[] { 14, Language.Swedish }, + new object[] { 15, Language.Norwegian }, + new object[] { 16, Language.Finnish }, + new object[] { 17, Language.Turkish }, + new object[] { 18, Language.Portuguese }, + new object[] { 19, Language.Flemish }, + new object[] { 20, Language.Greek }, + new object[] { 21, Language.Korean }, + new object[] { 22, Language.Hungarian } }; public static object[] ToIntCases = { - new object[] {Language.English, 1}, - new object[] {Language.French, 2}, - new object[] {Language.Spanish, 3}, - new object[] {Language.German, 4}, - new object[] {Language.Italian, 5}, - new object[] {Language.Danish, 6}, - new object[] {Language.Dutch, 7}, - new object[] {Language.Japanese, 8}, - new object[] {Language.Icelandic, 9}, - new object[] {Language.Chinese, 10}, - new object[] {Language.Russian, 11}, - new object[] {Language.Polish, 12}, - new object[] {Language.Vietnamese, 13}, - new object[] {Language.Swedish, 14}, - new object[] {Language.Norwegian, 15}, - new object[] {Language.Finnish, 16}, - new object[] {Language.Turkish, 17}, - new object[] {Language.Portuguese, 18}, - new object[] {Language.Flemish, 19}, - new object[] {Language.Greek, 20}, - new object[] {Language.Korean, 21}, - new object[] {Language.Hungarian, 22} + new object[] { Language.English, 1 }, + new object[] { Language.French, 2 }, + new object[] { Language.Spanish, 3 }, + new object[] { Language.German, 4 }, + new object[] { Language.Italian, 5 }, + new object[] { Language.Danish, 6 }, + new object[] { Language.Dutch, 7 }, + new object[] { Language.Japanese, 8 }, + new object[] { Language.Icelandic, 9 }, + new object[] { Language.Chinese, 10 }, + new object[] { Language.Russian, 11 }, + new object[] { Language.Polish, 12 }, + new object[] { Language.Vietnamese, 13 }, + new object[] { Language.Swedish, 14 }, + new object[] { Language.Norwegian, 15 }, + new object[] { Language.Finnish, 16 }, + new object[] { Language.Turkish, 17 }, + new object[] { Language.Portuguese, 18 }, + new object[] { Language.Flemish, 19 }, + new object[] { Language.Greek, 20 }, + new object[] { Language.Korean, 21 }, + new object[] { Language.Hungarian, 22 } }; - [Test, TestCaseSource("FromIntCases")] + [Test] + [TestCaseSource("FromIntCases")] public void should_be_able_to_convert_int_to_languageTypes(int source, Language expected) { var language = (Language)source; language.Should().Be(expected); } - [Test, TestCaseSource("ToIntCases")] + [Test] + [TestCaseSource("ToIntCases")] public void should_be_able_to_convert_languageTypes_to_int(Language source, int expected) { var i = (int)source; diff --git a/src/NzbDrone.Core.Test/MediaCoverTests/CoverExistsSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaCoverTests/CoverExistsSpecificationFixture.cs index 40b7e8d8a9..ff34a9efe4 100644 --- a/src/NzbDrone.Core.Test/MediaCoverTests/CoverExistsSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaCoverTests/CoverExistsSpecificationFixture.cs @@ -20,21 +20,17 @@ public void Setup() _httpResponse = new HttpResponse(null, new HttpHeader(), "", HttpStatusCode.OK); Mocker.GetMock().Setup(c => c.GetFileSize(It.IsAny())).Returns(100); Mocker.GetMock().Setup(c => c.Head(It.IsAny())).Returns(_httpResponse); - } - private void GivenFileExistsOnDisk() { Mocker.GetMock().Setup(c => c.FileExists(It.IsAny())).Returns(true); } - private void GivenExistingFileSize(long bytes) { GivenFileExistsOnDisk(); Mocker.GetMock().Setup(c => c.GetFileSize(It.IsAny())).Returns(bytes); - } [Test] @@ -52,7 +48,6 @@ public void should_return_false_if_file_exists_but_diffrent_size() Subject.AlreadyExists("http://url", "c:\\file.exe").Should().BeFalse(); } - [Test] public void should_return_true_if_file_exists_and_same_size_and_not_corrupt() { diff --git a/src/NzbDrone.Core.Test/MediaCoverTests/MediaCoverServiceFixture.cs b/src/NzbDrone.Core.Test/MediaCoverTests/MediaCoverServiceFixture.cs index a09614d08d..602c5448fa 100644 --- a/src/NzbDrone.Core.Test/MediaCoverTests/MediaCoverServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaCoverTests/MediaCoverServiceFixture.cs @@ -9,16 +9,16 @@ using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Core.MediaCover; using NzbDrone.Core.Messaging.Commands; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; using NzbDrone.Core.Movies.Events; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.MediaCoverTests { [TestFixture] public class MediaCoverServiceFixture : CoreTest { - Movie _movie; + private Movie _movie; [SetUp] public void Setup() @@ -48,7 +48,7 @@ public void should_convert_cover_urls_to_local() { var covers = new List { - new MediaCover.MediaCover {CoverType = MediaCoverTypes.Banner} + new MediaCover.MediaCover { CoverType = MediaCoverTypes.Banner } }; Mocker.GetMock().Setup(c => c.FileGetLastWrite(It.IsAny())) @@ -59,7 +59,6 @@ public void should_convert_cover_urls_to_local() Subject.ConvertToLocalUrls(12, covers); - covers.Single().Url.Should().Be("/MediaCover/12/banner.jpg"); } @@ -68,13 +67,11 @@ public void should_convert_media_urls_to_local_without_time_if_file_doesnt_exist { var covers = new List { - new MediaCover.MediaCover {CoverType = MediaCoverTypes.Banner} + new MediaCover.MediaCover { CoverType = MediaCoverTypes.Banner } }; - Subject.ConvertToLocalUrls(12, covers); - covers.Single().Url.Should().Be("/MediaCover/12/banner.jpg"); } diff --git a/src/NzbDrone.Core.Test/MediaFiles/DiskScanServiceTests/ScanFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/DiskScanServiceTests/ScanFixture.cs index eb93bfc29b..795f5587e7 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/DiskScanServiceTests/ScanFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/DiskScanServiceTests/ScanFixture.cs @@ -7,8 +7,8 @@ using NzbDrone.Common.Disk; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.MovieImport; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles.DiskScanServiceTests diff --git a/src/NzbDrone.Core.Test/MediaFiles/DownloadedMoviesCommandServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/DownloadedMoviesCommandServiceFixture.cs index 411246fec6..943ce4f2fd 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/DownloadedMoviesCommandServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/DownloadedMoviesCommandServiceFixture.cs @@ -9,9 +9,9 @@ using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Commands; using NzbDrone.Core.MediaFiles.MovieImport; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles diff --git a/src/NzbDrone.Core.Test/MediaFiles/DownloadedMoviesImportServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/DownloadedMoviesImportServiceFixture.cs index e09821b385..ae746b3473 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/DownloadedMoviesImportServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/DownloadedMoviesImportServiceFixture.cs @@ -9,10 +9,10 @@ using NzbDrone.Core.Download; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.MovieImport; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles @@ -28,8 +28,8 @@ public class DownloadedMoviesImportServiceFixture : CoreTest().Setup(c => c.GetVideoFiles(It.IsAny(), It.IsAny())) .Returns(_videoFiles); @@ -45,7 +45,6 @@ public void Setup() Mocker.GetMock() .Setup(s => s.Import(It.IsAny>(), true, null, ImportMode.Auto)) .Returns(new List()); - } private void GivenValidMovie() @@ -279,7 +278,6 @@ public void should_use_folder_if_folder_import() var imported = new List(); imported.Add(new ImportDecision(localMovie)); - Subject.ProcessPath(fileName); Mocker.GetMock() diff --git a/src/NzbDrone.Core.Test/MediaFiles/ImportApprovedMoviesFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/ImportApprovedMoviesFixture.cs index b1367f334c..19377d08f5 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/ImportApprovedMoviesFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/ImportApprovedMoviesFixture.cs @@ -8,19 +8,20 @@ using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.MediaFiles.MovieImport; using NzbDrone.Core.MediaFiles.Events; +using NzbDrone.Core.MediaFiles.MovieImport; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles { [TestFixture] + //TODO: Update all of this for movies. public class ImportApprovedMoviesFixture : CoreTest { @@ -44,8 +45,7 @@ public void Setup() _rejectedDecisions.Add(new ImportDecision(new LocalMovie(), new Rejection("Rejected!"))); _rejectedDecisions.Add(new ImportDecision(new LocalMovie(), new Rejection("Rejected!"))); - _approvedDecisions.Add(new ImportDecision - ( + _approvedDecisions.Add(new ImportDecision( new LocalMovie { Movie = movie, @@ -54,7 +54,6 @@ public void Setup() ReleaseGroup = "DRONE" })); - Mocker.GetMock() .Setup(s => s.UpgradeMovieFile(It.IsAny(), It.IsAny(), It.IsAny())) .Returns(new MovieFileMoveResult()); @@ -193,8 +192,8 @@ public void should_import_larger_files_first() var fileDecision = _approvedDecisions.First(); fileDecision.LocalMovie.Size = 1.Gigabytes(); - var sampleDecision = new ImportDecision - (new LocalMovie + var sampleDecision = new ImportDecision( + new LocalMovie { Movie = fileDecision.LocalMovie.Movie, Path = @"C:\Test\TV\30 Rock\30 Rock - 2017 - Pilot.avi".AsOsAgnostic(), @@ -202,7 +201,6 @@ public void should_import_larger_files_first() Size = 80.Megabytes() }); - var all = new List(); all.Add(fileDecision); all.Add(sampleDecision); @@ -217,7 +215,7 @@ public void should_import_larger_files_first() [Test] public void should_copy_when_cannot_move_files_downloads() { - Subject.Import(new List { _approvedDecisions.First() }, true, new DownloadClientItem { Title = "30.Rock.S01E01", CanMoveFiles = false}); + Subject.Import(new List { _approvedDecisions.First() }, true, new DownloadClientItem { Title = "30.Rock.S01E01", CanMoveFiles = false }); Mocker.GetMock() .Verify(v => v.UpgradeMovieFile(It.IsAny(), _approvedDecisions.First().LocalMovie, true), Times.Once()); diff --git a/src/NzbDrone.Core.Test/MediaFiles/MediaFileRepositoryFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MediaFileRepositoryFixture.cs index 85b57989f3..db8430559d 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MediaFileRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MediaFileRepositoryFixture.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; @@ -5,7 +6,6 @@ using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using System.Collections.Generic; namespace NzbDrone.Core.Test.MediaFiles { @@ -29,14 +29,12 @@ public void get_files_by_movie() .With(s => s.MovieId = 12) .BuildListOfNew(); - Db.InsertMany(files); var movieFiles = Subject.GetFilesByMovie(12); movieFiles.Should().HaveCount(4); movieFiles.Should().OnlyContain(c => c.MovieId == 12); - } } } diff --git a/src/NzbDrone.Core.Test/MediaFiles/MediaFileServiceTests/FilterFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MediaFileServiceTests/FilterFixture.cs index e6e50a81fe..2f8fc3ab8b 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MediaFileServiceTests/FilterFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MediaFileServiceTests/FilterFixture.cs @@ -5,8 +5,8 @@ using Moq; using NUnit.Framework; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles.MediaFileServiceTests @@ -20,10 +20,10 @@ public class FilterFixture : CoreTest public void Setup() { _series = new Movie - { - Id = 10, - Path = @"C:\".AsOsAgnostic() - }; + { + Id = 10, + Path = @"C:\".AsOsAgnostic() + }; } [Test] @@ -40,7 +40,6 @@ public void filter_should_return_all_files_if_no_existing_files() .Setup(c => c.GetFilesByMovie(It.IsAny())) .Returns(new List()); - Subject.FilterExistingFiles(files, _series).Should().BeEquivalentTo(files); } @@ -58,7 +57,6 @@ public void filter_should_return_none_if_all_files_exist() .Setup(c => c.GetFilesByMovie(It.IsAny())) .Returns(files.Select(f => new MovieFile { RelativePath = Path.GetFileName(f) }).ToList()); - Subject.FilterExistingFiles(files, _series).Should().BeEmpty(); } @@ -76,10 +74,9 @@ public void filter_should_return_none_existing_files() .Setup(c => c.GetFilesByMovie(It.IsAny())) .Returns(new List { - new MovieFile{ RelativePath = "file2.avi".AsOsAgnostic()} + new MovieFile { RelativePath = "file2.avi".AsOsAgnostic() } }); - Subject.FilterExistingFiles(files, _series).Should().HaveCount(2); Subject.FilterExistingFiles(files, _series).Should().NotContain("C:\\file2.avi".AsOsAgnostic()); } @@ -100,10 +97,9 @@ public void filter_should_return_none_existing_files_ignoring_case() .Setup(c => c.GetFilesByMovie(It.IsAny())) .Returns(new List { - new MovieFile{ RelativePath = "file2.avi".AsOsAgnostic()} + new MovieFile { RelativePath = "file2.avi".AsOsAgnostic() } }); - Subject.FilterExistingFiles(files, _series).Should().HaveCount(2); Subject.FilterExistingFiles(files, _series).Should().NotContain("C:\\file2.avi".AsOsAgnostic()); } @@ -124,7 +120,7 @@ public void filter_should_return_none_existing_files_not_ignoring_case() .Setup(c => c.GetFilesByMovie(It.IsAny())) .Returns(new List { - new MovieFile{ RelativePath = "file2.avi".AsOsAgnostic()} + new MovieFile { RelativePath = "file2.avi".AsOsAgnostic() } }); Subject.FilterExistingFiles(files, _series).Should().HaveCount(3); diff --git a/src/NzbDrone.Core.Test/MediaFiles/MediaFileTableCleanupServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MediaFileTableCleanupServiceFixture.cs index 8800b123f0..71a399de7a 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MediaFileTableCleanupServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MediaFileTableCleanupServiceFixture.cs @@ -1,13 +1,13 @@ using System.Collections.Generic; -using System.Linq; using System.IO; +using System.Linq; using FizzWare.NBuilder; using Moq; using NUnit.Framework; using NzbDrone.Common.Disk; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles @@ -27,7 +27,6 @@ public void SetUp() Mocker.GetMock() .Setup(e => e.FileExists(It.Is(c => !c.Contains(DELETED_PATH)))) .Returns(true); - } private void GivenMovieFiles(IEnumerable movieFiles) diff --git a/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/MediaInfoFormatterTests/FormatAudioChannelsFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/MediaInfoFormatterTests/FormatAudioChannelsFixture.cs index cc9e068643..68c2031074 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/MediaInfoFormatterTests/FormatAudioChannelsFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/MediaInfoFormatterTests/FormatAudioChannelsFixture.cs @@ -150,11 +150,11 @@ public void should_sum_dual_mono_representation_AudioChannelPositions() public void should_use_AudioChannelPositionText_when_AudioChannelChannelPosition_is_invalid() { var mediaInfoModel = new MediaInfoModel - { + { AudioChannels = 6, AudioChannelPositions = "15 objects", AudioChannelPositionsText = "15 objects / Front: L C R, Side: L R, LFE", - SchemaRevision = 3 + SchemaRevision = 3 }; MediaInfoFormatter.FormatAudioChannels(mediaInfoModel).Should().Be(5.1m); diff --git a/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/UpdateMediaInfoServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/UpdateMediaInfoServiceFixture.cs index 32e012b193..d6b083350f 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/UpdateMediaInfoServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/UpdateMediaInfoServiceFixture.cs @@ -4,13 +4,13 @@ using Moq; using NUnit.Framework; using NzbDrone.Common.Disk; +using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.MediaFiles.MediaInfo; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; -using NzbDrone.Core.Configuration; namespace NzbDrone.Core.Test.MediaFiles.MediaInfo { @@ -23,10 +23,10 @@ public class UpdateMediaInfoServiceFixture : CoreTest public void Setup() { _movie = new Movie - { - Id = 1, - Path = @"C:\movie".AsOsAgnostic() - }; + { + Id = 1, + Path = @"C:\movie".AsOsAgnostic() + }; Mocker.GetMock() .SetupGet(s => s.EnableMediaInfo) @@ -240,7 +240,7 @@ public void should_update_media_info() { var movieFile = Builder.CreateNew() .With(v => v.RelativePath = "media.mkv") - .With(e => e.MediaInfo = new MediaInfoModel{SchemaRevision = 3}) + .With(e => e.MediaInfo = new MediaInfoModel { SchemaRevision = 3 }) .Build(); GivenFileExists(); @@ -260,7 +260,7 @@ public void should_not_update_media_info_if_new_info_is_null() { var movieFile = Builder.CreateNew() .With(v => v.RelativePath = "media.mkv") - .With(e => e.MediaInfo = new MediaInfoModel{SchemaRevision = 3}) + .With(e => e.MediaInfo = new MediaInfoModel { SchemaRevision = 3 }) .Build(); GivenFileExists(); @@ -276,7 +276,7 @@ public void should_not_save_movie_file_if_new_info_is_null() { var movieFile = Builder.CreateNew() .With(v => v.RelativePath = "media.mkv") - .With(e => e.MediaInfo = new MediaInfoModel{SchemaRevision = 3}) + .With(e => e.MediaInfo = new MediaInfoModel { SchemaRevision = 3 }) .Build(); GivenFileExists(); diff --git a/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/VideoFileInfoReaderFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/VideoFileInfoReaderFixture.cs index c4642733e0..5884c73dfb 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/VideoFileInfoReaderFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MediaInfo/VideoFileInfoReaderFixture.cs @@ -62,7 +62,6 @@ public void get_info() info.VideoColourPrimaries.Should().Be("BT.601 NTSC"); info.VideoTransferCharacteristics.Should().Be("BT.709"); info.AudioAdditionalFeatures.Should().BeOneOf("", "LC"); - } [Test] diff --git a/src/NzbDrone.Core.Test/MediaFiles/MovieFileMovingServiceTests/MoveMovieFileFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MovieFileMovingServiceTests/MoveMovieFileFixture.cs index 11c76a3af6..63b5dc8105 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MovieFileMovingServiceTests/MoveMovieFileFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MovieFileMovingServiceTests/MoveMovieFileFixture.cs @@ -7,10 +7,10 @@ using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Movies; using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles.MovieFileMovingServiceTests diff --git a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Aggregation/Aggregators/AggregateLanguageFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Aggregation/Aggregators/AggregateLanguageFixture.cs index 2ca1557342..ca14001c48 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Aggregation/Aggregators/AggregateLanguageFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Aggregation/Aggregators/AggregateLanguageFixture.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; @@ -5,7 +6,6 @@ using NzbDrone.Core.MediaFiles.MovieImport.Aggregation.Aggregators; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using System.Collections.Generic; namespace NzbDrone.Core.Test.MediaFiles.MovieImport.Aggregation.Aggregators { @@ -57,7 +57,6 @@ public void should_return_download_client_item_language_when_download_client_ite _localMovie.FileMovieInfo = GetParsedMovieInfo(Language.English); Subject.Aggregate(_localMovie, false).Languages.Should().Contain(_localMovie.DownloadClientMovieInfo.Languages); - } [Test] diff --git a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Aggregation/Aggregators/Augmenters/Quality/AugmentQualityFromMediaInfoFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Aggregation/Aggregators/Augmenters/Quality/AugmentQualityFromMediaInfoFixture.cs index f4e358ab0c..c52ebf6762 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Aggregation/Aggregators/Augmenters/Quality/AugmentQualityFromMediaInfoFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Aggregation/Aggregators/Augmenters/Quality/AugmentQualityFromMediaInfoFixture.cs @@ -1,11 +1,11 @@ using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; -using NzbDrone.Core.MediaFiles.MovieImport.Aggregation.Aggregators.Augmenters.Quality; using NzbDrone.Core.MediaFiles.MediaInfo; +using NzbDrone.Core.MediaFiles.MovieImport.Aggregation.Aggregators.Augmenters.Quality; +using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Parser; namespace NzbDrone.Core.Test.MediaFiles.MovieImport.Aggregation.Aggregators.Augmenters.Quality { diff --git a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/DetectSampleFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/DetectSampleFixture.cs index 7eb1c481c9..8a34f95a74 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/DetectSampleFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/DetectSampleFixture.cs @@ -3,12 +3,12 @@ using FluentAssertions; using Moq; using NUnit.Framework; -using NzbDrone.Core.MediaFiles.MovieImport; using NzbDrone.Core.MediaFiles.MediaInfo; +using NzbDrone.Core.MediaFiles.MovieImport; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles.MovieImport @@ -26,7 +26,6 @@ public void Setup() .With(s => s.Runtime = 30) .Build(); - _localMovie = new LocalMovie { Path = @"C:\Test\30 Rock\30.rock.s01e01.avi", diff --git a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/ImportDecisionMakerFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/ImportDecisionMakerFixture.cs index 13090bd134..d4b9abb496 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/ImportDecisionMakerFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/ImportDecisionMakerFixture.cs @@ -1,25 +1,26 @@ using System.Collections.Generic; using System.Linq; +using FizzWare.NBuilder; using FluentAssertions; using Moq; using NUnit.Framework; using NzbDrone.Core.DecisionEngine; +using NzbDrone.Core.Download; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.MovieImport; +using NzbDrone.Core.MediaFiles.MovieImport.Aggregation; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; -using FizzWare.NBuilder; -using NzbDrone.Core.Download; -using NzbDrone.Core.MediaFiles.MovieImport.Aggregation; namespace NzbDrone.Core.Test.MediaFiles.MovieImport { [TestFixture] + //TODO: Add tests to ensure helpers for augmenters are correctly passed. public class ImportDecisionMakerFixture : CoreTest { @@ -201,7 +202,7 @@ public void should_call_parsing_service_with_filename_as_simpletitle() .Setup(c => c.ParseMinimalPathMovieInfo(It.IsAny())) .Returns(null); - var folderInfo = new ParsedMovieInfo {SimpleReleaseTitle = "A Movie Folder 2018", Quality = _quality}; + var folderInfo = new ParsedMovieInfo { SimpleReleaseTitle = "A Movie Folder 2018", Quality = _quality }; var result = Subject.GetImportDecisions(_videoFiles, _movie, null, folderInfo, true); diff --git a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/FreeSpaceSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/FreeSpaceSpecificationFixture.cs index e601a7e3a9..2cc5da2583 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/FreeSpaceSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/FreeSpaceSpecificationFixture.cs @@ -6,9 +6,9 @@ using NzbDrone.Common.Disk; using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles.MovieImport.Specifications; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles.MovieImport.Specifications @@ -23,17 +23,17 @@ public class FreeSpaceSpecificationFixture : CoreTest [SetUp] public void Setup() { - _rootFolder = @"C:\Test\TV".AsOsAgnostic(); + _rootFolder = @"C:\Test\TV".AsOsAgnostic(); _movie = Builder.CreateNew() .With(s => s.Path = Path.Combine(_rootFolder, "30 Rock")) .Build(); _localMovie = new LocalMovie() - { - Path = @"C:\Test\Unsorted\30 Rock\30.rock.s01e01.avi".AsOsAgnostic(), - Movie = _movie - }; + { + Path = @"C:\Test\Unsorted\30 Rock\30.rock.s01e01.avi".AsOsAgnostic(), + Movie = _movie + }; } private void GivenFileSize(long size) @@ -61,7 +61,6 @@ public void should_reject_when_there_isnt_enough_disk_space() [Test] public void should_reject_when_there_isnt_enough_space_for_file_plus_min_free_space() { - Mocker.GetMock() .Setup(s => s.MinimumFreeSpaceWhenImporting) .Returns(100); diff --git a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/MatchesFolderSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/MatchesFolderSpecificationFixture.cs index 123bcf7f62..f001806cb8 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/MatchesFolderSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/MatchesFolderSpecificationFixture.cs @@ -63,6 +63,5 @@ public void should_be_rejected_if_file_and_folder_do_not_have_same_episode() _localMovie.Path = @"C:\Test\Unsorted\Series.Title.S01E01.720p.HDTV-Sonarr\S01E05.mkv".AsOsAgnostic(); Subject.IsSatisfiedBy(_localMovie, null).Accepted.Should().BeFalse(); }*/ - } } diff --git a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/NotSampleSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/NotSampleSpecificationFixture.cs index bcb9faf30e..112d837df1 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/NotSampleSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/NotSampleSpecificationFixture.cs @@ -2,9 +2,9 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.MediaFiles.MovieImport.Specifications; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.MediaFiles.MovieImport.Specifications { @@ -21,10 +21,10 @@ public void Setup() .Build(); _localEpisode = new LocalMovie - { - Path = @"C:\Test\30 Rock\30.rock.s01e01.avi", - Movie = _movie, - }; + { + Path = @"C:\Test\30 Rock\30.rock.s01e01.avi", + Movie = _movie, + }; } [Test] diff --git a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/NotUnpackingSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/NotUnpackingSpecificationFixture.cs index f7fca70a4f..1b482582bf 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/NotUnpackingSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/NotUnpackingSpecificationFixture.cs @@ -6,9 +6,9 @@ using NzbDrone.Common.Disk; using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles.MovieImport.Specifications; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles.MovieImport.Specifications diff --git a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/SameFileSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/SameFileSpecificationFixture.cs index c7b483beb9..8f63ff25c1 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/SameFileSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/SameFileSpecificationFixture.cs @@ -4,9 +4,9 @@ using NUnit.Framework; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.MovieImport.Specifications; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.MediaFiles.MovieImport.Specifications { diff --git a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/UpgradeSpecificationFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/UpgradeSpecificationFixture.cs index 3c889d0914..36d8e59706 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/UpgradeSpecificationFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/MovieImport/Specifications/UpgradeSpecificationFixture.cs @@ -4,11 +4,11 @@ using NUnit.Framework; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.MovieImport.Specifications; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.MediaFiles.MovieImport.Specifications { @@ -26,11 +26,11 @@ public void Setup() .Build(); _localMovie = new LocalMovie() - { - Path = @"C:\Test\30 Rock\30.rock.s01e01.avi", - Quality = new QualityModel(Quality.HDTV720p, new Revision(version: 1)), - Movie = _movie - }; + { + Path = @"C:\Test\30 Rock\30.rock.s01e01.avi", + Quality = new QualityModel(Quality.HDTV720p, new Revision(version: 1)), + Movie = _movie + }; } [Test] @@ -45,20 +45,16 @@ public void should_return_true_if_no_existing_episodeFile() [Test] public void should_return_true_if_upgrade_for_existing_episodeFile() { - _localMovie.Movie.MovieFileId = 1; _localMovie.Movie.MovieFile = new LazyLoaded( new MovieFile { Quality = new QualityModel(Quality.SDTV, new Revision(version: 1)) - } - ); - + }); Subject.IsSatisfiedBy(_localMovie, null).Accepted.Should().BeTrue(); } - [Test] public void should_return_false_if_not_an_upgrade_for_existing_episodeFile() { @@ -67,8 +63,7 @@ public void should_return_false_if_not_an_upgrade_for_existing_episodeFile() new MovieFile { Quality = new QualityModel(Quality.Bluray720p, new Revision(version: 1)) - } - ); + }); Subject.IsSatisfiedBy(_localMovie, null).Accepted.Should().BeFalse(); } diff --git a/src/NzbDrone.Core.Test/MediaFiles/RenameMovieFileServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/RenameMovieFileServiceFixture.cs index b08954388b..1b8b133824 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/RenameMovieFileServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/RenameMovieFileServiceFixture.cs @@ -7,8 +7,8 @@ using NzbDrone.Core.MediaFiles.Commands; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.MediaFiles { @@ -59,7 +59,7 @@ public void should_not_publish_event_if_no_files_to_rename() { GivenNoMovieFiles(); - Subject.Execute(new RenameFilesCommand(_movie.Id, new List{1})); + Subject.Execute(new RenameFilesCommand(_movie.Id, new List { 1 })); Mocker.GetMock() .Verify(v => v.PublishEvent(It.IsAny()), Times.Never()); diff --git a/src/NzbDrone.Core.Test/MediaFiles/UpdateMovieFileQualityServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/UpdateMovieFileQualityServiceFixture.cs index 866e813e9d..6c69020661 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/UpdateMovieFileQualityServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/UpdateMovieFileQualityServiceFixture.cs @@ -35,7 +35,7 @@ public void Setup() _newQuality = _oldQuality.JsonClone(); var format = new CustomFormats.CustomFormat("Awesome Format"); format.Id = 1; - _newQuality.CustomFormats = new List{format}; + _newQuality.CustomFormats = new List { format }; _newInfo = new ParsedMovieInfo { @@ -43,7 +43,7 @@ public void Setup() }; Mocker.GetMock().Setup(s => s.GetMovies(It.IsAny>())) - .Returns(new List{_movieFile}); + .Returns(new List { _movieFile }); Mocker.GetMock().Setup(s => s.GetByMovieId(It.IsAny(), null)) .Returns(new List()); @@ -51,7 +51,7 @@ public void Setup() private void ExecuteCommand() { - Subject.Execute(new UpdateMovieFileQualityCommand(new List{0})); + Subject.Execute(new UpdateMovieFileQualityCommand(new List { 0 })); } [Test] @@ -83,7 +83,7 @@ public void should_use_imported_history_title() .With(h => h.SourceTitle = "My Movie 2018.mkv").Build(); Mocker.GetMock().Setup(s => s.GetByMovieId(It.IsAny(), null)) - .Returns(new List {imported}); + .Returns(new List { imported }); Mocker.GetMock().Setup(s => s.ParseMovieInfo("My Movie 2018.mkv", It.IsAny>())) .Returns(_newInfo); diff --git a/src/NzbDrone.Core.Test/MediaFiles/UpgradeMediaFileServiceFixture.cs b/src/NzbDrone.Core.Test/MediaFiles/UpgradeMediaFileServiceFixture.cs index ce7e9fc34d..f990dc4889 100644 --- a/src/NzbDrone.Core.Test/MediaFiles/UpgradeMediaFileServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MediaFiles/UpgradeMediaFileServiceFixture.cs @@ -4,9 +4,9 @@ using NUnit.Framework; using NzbDrone.Common.Disk; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MediaFiles @@ -21,15 +21,14 @@ public void Setup() { _localMovie = new LocalMovie(); _localMovie.Movie = new Movie - { - Path = @"C:\Test\TV\Series".AsOsAgnostic() - }; + { + Path = @"C:\Test\TV\Series".AsOsAgnostic() + }; _movieFile = Builder .CreateNew() .Build(); - Mocker.GetMock() .Setup(c => c.FileExists(It.IsAny())) .Returns(true); @@ -56,8 +55,6 @@ public void should_delete_single_episode_file_once() Mocker.GetMock().Verify(v => v.DeleteFile(It.IsAny(), It.IsAny()), Times.Once()); } - - [Test] public void should_delete_episode_file_from_database() { diff --git a/src/NzbDrone.Core.Test/Messaging/Commands/CommandEqualityComparerFixture.cs b/src/NzbDrone.Core.Test/Messaging/Commands/CommandEqualityComparerFixture.cs index 72d7a24316..c27c060e6e 100644 --- a/src/NzbDrone.Core.Test/Messaging/Commands/CommandEqualityComparerFixture.cs +++ b/src/NzbDrone.Core.Test/Messaging/Commands/CommandEqualityComparerFixture.cs @@ -36,7 +36,7 @@ public void should_return_true_when_there_are_no_properties() [Test] public void should_return_true_when_single_property_matches() { - var command1 = new MoviesSearchCommand { MovieIds = new List{ 1 } }; + var command1 = new MoviesSearchCommand { MovieIds = new List { 1 } }; var command2 = new MoviesSearchCommand { MovieIds = new List { 1 } }; CommandEqualityComparer.Instance.Equals(command1, command2).Should().BeTrue(); diff --git a/src/NzbDrone.Core.Test/Messaging/Commands/CommandExecutorFixture.cs b/src/NzbDrone.Core.Test/Messaging/Commands/CommandExecutorFixture.cs index 20c209eda2..7e22f6f851 100644 --- a/src/NzbDrone.Core.Test/Messaging/Commands/CommandExecutorFixture.cs +++ b/src/NzbDrone.Core.Test/Messaging/Commands/CommandExecutorFixture.cs @@ -210,13 +210,10 @@ public CommandA(int id = 0) public class CommandB : Command { - public CommandB() { - } public override string CompletionMessage => null; } - } diff --git a/src/NzbDrone.Core.Test/Messaging/Events/EventAggregatorFixture.cs b/src/NzbDrone.Core.Test/Messaging/Events/EventAggregatorFixture.cs index 76561592b9..6a716f08cb 100644 --- a/src/NzbDrone.Core.Test/Messaging/Events/EventAggregatorFixture.cs +++ b/src/NzbDrone.Core.Test/Messaging/Events/EventAggregatorFixture.cs @@ -12,33 +12,27 @@ namespace NzbDrone.Core.Test.Messaging.Events [TestFixture] public class EventAggregatorFixture : TestBase { - private Mock> HandlerA1; - private Mock> HandlerA2; - - private Mock> HandlerB1; - private Mock> HandlerB2; - - private Mock> AsyncHandlerA1; + private Mock> _handlerA1; + private Mock> _handlerA2; + private Mock> _handlerB1; + private Mock> _handlerB2; [SetUp] public void Setup() { - HandlerA1 = new Mock>(); - HandlerA2 = new Mock>(); - HandlerB1 = new Mock>(); - HandlerB2 = new Mock>(); - - AsyncHandlerA1 = new Mock>(); + _handlerA1 = new Mock>(); + _handlerA2 = new Mock>(); + _handlerB1 = new Mock>(); + _handlerB2 = new Mock>(); Mocker.GetMock() .Setup(c => c.BuildAll>()) - .Returns(new List> { HandlerA1.Object, HandlerA2.Object }); + .Returns(new List> { _handlerA1.Object, _handlerA2.Object }); Mocker.GetMock() .Setup(c => c.BuildAll>()) - .Returns(new List> { HandlerB1.Object, HandlerB2.Object }); - + .Returns(new List> { _handlerB1.Object, _handlerB2.Object }); } [Test] @@ -48,8 +42,8 @@ public void should_publish_event_to_handlers() Subject.PublishEvent(eventA); - HandlerA1.Verify(c => c.Handle(eventA), Times.Once()); - HandlerA2.Verify(c => c.Handle(eventA), Times.Once()); + _handlerA1.Verify(c => c.Handle(eventA), Times.Once()); + _handlerA2.Verify(c => c.Handle(eventA), Times.Once()); } [Test] @@ -57,88 +51,37 @@ public void should_not_publish_to_incompatible_handlers() { var eventA = new EventA(); - Subject.PublishEvent(eventA); - HandlerA1.Verify(c => c.Handle(eventA), Times.Once()); - HandlerA2.Verify(c => c.Handle(eventA), Times.Once()); + _handlerA1.Verify(c => c.Handle(eventA), Times.Once()); + _handlerA2.Verify(c => c.Handle(eventA), Times.Once()); - HandlerB1.Verify(c => c.Handle(It.IsAny()), Times.Never()); - HandlerB2.Verify(c => c.Handle(It.IsAny()), Times.Never()); + _handlerB1.Verify(c => c.Handle(It.IsAny()), Times.Never()); + _handlerB2.Verify(c => c.Handle(It.IsAny()), Times.Never()); } - [Test] public void broken_handler_should_not_effect_others_handler() { var eventA = new EventA(); - - HandlerA1.Setup(c => c.Handle(It.IsAny())) + _handlerA1.Setup(c => c.Handle(It.IsAny())) .Throws(new NotImplementedException()); Subject.PublishEvent(eventA); - HandlerA1.Verify(c => c.Handle(eventA), Times.Once()); - HandlerA2.Verify(c => c.Handle(eventA), Times.Once()); + _handlerA1.Verify(c => c.Handle(eventA), Times.Once()); + _handlerA2.Verify(c => c.Handle(eventA), Times.Once()); ExceptionVerification.ExpectedErrors(1); } - - - /* [Test] - public void should_queue_multiple_async_events() - { - var eventA = new EventA(); - - - - var handlers = new List> - { - AsyncHandlerA1.Object, - AsyncHandlerA1.Object, - AsyncHandlerA1.Object, - AsyncHandlerA1.Object, - AsyncHandlerA1.Object, - AsyncHandlerA1.Object, - AsyncHandlerA1.Object, - }; - - Mocker.GetMock() - .Setup(c => c.BuildAll>()) - .Returns(new List>()); - - Mocker.GetMock() - .Setup(c => c.BuildAll>()) - .Returns(handlers); - - var counter = new ConcurrencyCounter(handlers.Count); - - - AsyncHandlerA1.Setup(c => c.HandleAsync(It.IsAny())) - .Callback(c => - { - var id = counter.Start(); - Thread.Sleep(1000); - counter.Stop(id); - }); - - Subject.PublishEvent(eventA); - - counter.WaitForAllItems(); - - counter.MaxThreads.Should().Be(3); - }*/ } - public class EventA : IEvent { - } public class EventB : IEvent { - } } diff --git a/src/NzbDrone.Core.Test/MetadataSource/SearchMovieComparerFixture.cs b/src/NzbDrone.Core.Test/MetadataSource/SearchMovieComparerFixture.cs index 26a81f531b..568470eb9f 100644 --- a/src/NzbDrone.Core.Test/MetadataSource/SearchMovieComparerFixture.cs +++ b/src/NzbDrone.Core.Test/MetadataSource/SearchMovieComparerFixture.cs @@ -3,8 +3,8 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.MetadataSource; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.MetadataSource { diff --git a/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxyFixture.cs b/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxyFixture.cs index 1b2b9acd14..f7306cabe5 100644 --- a/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxyFixture.cs +++ b/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxyFixture.cs @@ -1,8 +1,8 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.MetadataSource.SkyHook; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common.Categories; namespace NzbDrone.Core.Test.MetadataSource.SkyHook @@ -42,6 +42,7 @@ private void ValidateMovie(Movie movie) movie.Studio.Should().NotBeNullOrWhiteSpace(); movie.Runtime.Should().BeGreaterThan(0); movie.TitleSlug.Should().NotBeNullOrWhiteSpace(); + //series.TvRageId.Should().BeGreaterThan(0); movie.TmdbId.Should().BeGreaterThan(0); } diff --git a/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxySearchFixture.cs b/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxySearchFixture.cs index 24e3fc0501..4ae0b066d7 100644 --- a/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxySearchFixture.cs +++ b/src/NzbDrone.Core.Test/MetadataSource/SkyHook/SkyHookProxySearchFixture.cs @@ -18,6 +18,7 @@ public void Setup() } [TestCase("Prometheus", "Prometheus")] + // TODO: TMDB Doesn't like when we clean periods from this // [TestCase("The Man from U.N.C.L.E.", "The Man from U.N.C.L.E.")] [TestCase("imdb:tt2527336", "Star Wars: The Last Jedi")] diff --git a/src/NzbDrone.Core.Test/MovieTests/AlternativeTitleServiceTests/AlternativeTitleServiceFixture.cs b/src/NzbDrone.Core.Test/MovieTests/AlternativeTitleServiceTests/AlternativeTitleServiceFixture.cs index bd2b49fcb1..a09a4dbb24 100644 --- a/src/NzbDrone.Core.Test/MovieTests/AlternativeTitleServiceTests/AlternativeTitleServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MovieTests/AlternativeTitleServiceTests/AlternativeTitleServiceFixture.cs @@ -39,10 +39,10 @@ private void GivenExistingTitles(params AlternativeTitle[] titles) [Test] public void should_update_insert_remove_titles() { - var titles = new List {_title2, _title3}; - var updates = new List {_title2}; - var deletes = new List {_title1}; - var inserts = new List {_title3}; + var titles = new List { _title2, _title3 }; + var updates = new List { _title2 }; + var deletes = new List { _title1 }; + var inserts = new List { _title3 }; GivenExistingTitles(_title1, _title2); Subject.UpdateTitles(titles, _movie); @@ -56,8 +56,8 @@ public void should_update_insert_remove_titles() public void should_not_insert_duplicates() { GivenExistingTitles(); - var titles = new List {_title1, _title1}; - var inserts = new List{ _title1 }; + var titles = new List { _title1, _title1 }; + var inserts = new List { _title1 }; Subject.UpdateTitles(titles, _movie); @@ -68,7 +68,7 @@ public void should_not_insert_duplicates() public void should_not_insert_main_title() { GivenExistingTitles(); - var titles = new List{_title1}; + var titles = new List { _title1 }; var movie = Builder.CreateNew().With(m => m.CleanTitle = _title1.CleanTitle).Build(); Subject.UpdateTitles(titles, movie); @@ -80,7 +80,7 @@ public void should_not_insert_main_title() public void should_update_movie_id() { GivenExistingTitles(); - var titles = new List {_title1, _title2}; + var titles = new List { _title1, _title2 }; Subject.UpdateTitles(titles, _movie); @@ -96,7 +96,7 @@ public void should_update_with_correct_id() var updateTitle = existingTitle.JsonClone(); updateTitle.Id = 0; - Subject.UpdateTitles(new List {updateTitle}, _movie); + Subject.UpdateTitles(new List { updateTitle }, _movie); Mocker.GetMock().Verify(r => r.UpdateMany(It.Is>(list => list.First().Id == existingTitle.Id)), Times.Once()); } diff --git a/src/NzbDrone.Core.Test/MovieTests/MoveMovieServiceFixture.cs b/src/NzbDrone.Core.Test/MovieTests/MoveMovieServiceFixture.cs index 573126b7be..d658d98582 100644 --- a/src/NzbDrone.Core.Test/MovieTests/MoveMovieServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MovieTests/MoveMovieServiceFixture.cs @@ -5,10 +5,10 @@ using Moq; using NUnit.Framework; using NzbDrone.Common.Disk; -using NzbDrone.Core.Organizer; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; using NzbDrone.Core.Movies.Commands; +using NzbDrone.Core.Organizer; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MovieTests @@ -121,7 +121,6 @@ public void should_skip_movie_folder_if_it_does_not_exist() .Setup(s => s.FolderExists(It.IsAny())) .Returns(false); - Subject.Execute(_command); Mocker.GetMock() diff --git a/src/NzbDrone.Core.Test/MovieTests/MovieRepositoryTests/MovieRepositoryFixture.cs b/src/NzbDrone.Core.Test/MovieTests/MovieRepositoryTests/MovieRepositoryFixture.cs index b937350539..0f0e6a6cc7 100644 --- a/src/NzbDrone.Core.Test/MovieTests/MovieRepositoryTests/MovieRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/MovieTests/MovieRepositoryTests/MovieRepositoryFixture.cs @@ -1,10 +1,10 @@ using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; +using NzbDrone.Core.Movies; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.MovieTests.MovieRepositoryTests { @@ -21,14 +21,13 @@ public void Setup() public void should_lazyload_quality_profile() { var profile = new Profile - { - Items = Qualities.QualityFixture.GetDefaultQualities(Quality.Bluray1080p, Quality.DVD, Quality.HDTV720p), - FormatItems = CustomFormat.CustomFormatsFixture.GetDefaultFormatItems(), - FormatCutoff = CustomFormats.CustomFormat.None.Id, - Cutoff = Quality.Bluray1080p.Id, - Name = "TestProfile" - }; - + { + Items = Qualities.QualityFixture.GetDefaultQualities(Quality.Bluray1080p, Quality.DVD, Quality.HDTV720p), + FormatItems = CustomFormat.CustomFormatsFixture.GetDefaultFormatItems(), + FormatCutoff = CustomFormats.CustomFormat.None.Id, + Cutoff = Quality.Bluray1080p.Id, + Name = "TestProfile" + }; Mocker.Resolve().Insert(profile); @@ -37,7 +36,6 @@ public void should_lazyload_quality_profile() Subject.Insert(movie); - StoredModel.Profile.Should().NotBeNull(); } } diff --git a/src/NzbDrone.Core.Test/MovieTests/MovieServiceTests/AddMovieFixture.cs b/src/NzbDrone.Core.Test/MovieTests/MovieServiceTests/AddMovieFixture.cs index a317561e5d..4a01f5f788 100644 --- a/src/NzbDrone.Core.Test/MovieTests/MovieServiceTests/AddMovieFixture.cs +++ b/src/NzbDrone.Core.Test/MovieTests/MovieServiceTests/AddMovieFixture.cs @@ -1,8 +1,8 @@ using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; -using NzbDrone.Core.Organizer; using NzbDrone.Core.Movies; +using NzbDrone.Core.Organizer; using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.MovieTests.MovieServiceTests @@ -10,29 +10,27 @@ namespace NzbDrone.Core.Test.MovieTests.MovieServiceTests [TestFixture] public class AddMovieFixture : CoreTest { - private Movie fakeMovie; + private Movie _fakeMovie; [SetUp] public void Setup() { - fakeMovie = Builder.CreateNew().Build(); + _fakeMovie = Builder.CreateNew().Build(); } [Test] public void movie_added_event_should_have_proper_path() { - fakeMovie.Path = null; - fakeMovie.RootFolderPath = @"C:\Test\Movies"; + _fakeMovie.Path = null; + _fakeMovie.RootFolderPath = @"C:\Test\Movies"; Mocker.GetMock() - .Setup(s => s.GetMovieFolder(fakeMovie, null)) - .Returns(fakeMovie.Title); + .Setup(s => s.GetMovieFolder(_fakeMovie, null)) + .Returns(_fakeMovie.Title); - var series = Subject.AddMovie(fakeMovie); + var series = Subject.AddMovie(_fakeMovie); series.Path.Should().NotBeNull(); - } - } } diff --git a/src/NzbDrone.Core.Test/MovieTests/RefreshMovieServiceFixture.cs b/src/NzbDrone.Core.Test/MovieTests/RefreshMovieServiceFixture.cs index 39a148eaf8..c5cc267e86 100644 --- a/src/NzbDrone.Core.Test/MovieTests/RefreshMovieServiceFixture.cs +++ b/src/NzbDrone.Core.Test/MovieTests/RefreshMovieServiceFixture.cs @@ -4,10 +4,10 @@ using NzbDrone.Common.Extensions; using NzbDrone.Core.Exceptions; using NzbDrone.Core.MetadataSource; -using NzbDrone.Core.Profiles; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; using NzbDrone.Core.Movies.Commands; +using NzbDrone.Core.Profiles; +using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.MovieTests diff --git a/src/NzbDrone.Core.Test/NetImport/CouchPotato/CouchPotatoParserFixture.cs b/src/NzbDrone.Core.Test/NetImport/CouchPotato/CouchPotatoParserFixture.cs index 8aea02a52a..25b3811dd7 100644 --- a/src/NzbDrone.Core.Test/NetImport/CouchPotato/CouchPotatoParserFixture.cs +++ b/src/NzbDrone.Core.Test/NetImport/CouchPotato/CouchPotatoParserFixture.cs @@ -19,7 +19,6 @@ private NetImportResponse CreateResponse(string url, string content) return new NetImportResponse(new NetImportRequest(httpRequest), httpResponse); } - [Test] public void should_parse_json_of_couchpotato() { diff --git a/src/NzbDrone.Core.Test/NetImport/RSSImportFixture.cs b/src/NzbDrone.Core.Test/NetImport/RSSImportFixture.cs index e46fde60e5..286805f2f3 100644 --- a/src/NzbDrone.Core.Test/NetImport/RSSImportFixture.cs +++ b/src/NzbDrone.Core.Test/NetImport/RSSImportFixture.cs @@ -11,12 +11,12 @@ namespace NzbDrone.Core.Test.NetImport [TestFixture] public class RSSImportFixture : CoreTest { - [SetUp] public void Setup() { Subject.Definition = Subject.DefaultDefinitions.First(); } + private void GivenRecentFeedResponse(string rssXmlFile) { var recentFeed = ReadAllText(@"Files/" + rssXmlFile); diff --git a/src/NzbDrone.Core.Test/NetImport/RSSImportParserFixture.cs b/src/NzbDrone.Core.Test/NetImport/RSSImportParserFixture.cs index b9ff6f4552..face0effdc 100644 --- a/src/NzbDrone.Core.Test/NetImport/RSSImportParserFixture.cs +++ b/src/NzbDrone.Core.Test/NetImport/RSSImportParserFixture.cs @@ -19,7 +19,6 @@ private NetImportResponse CreateResponse(string url, string content) return new NetImportResponse(new NetImportRequest(httpRequest), httpResponse); } - [Test] public void should_parse_xml_of_imdb() { diff --git a/src/NzbDrone.Core.Test/NotificationTests/NotificationBaseFixture.cs b/src/NzbDrone.Core.Test/NotificationTests/NotificationBaseFixture.cs index b754eae20d..f61b2350bb 100644 --- a/src/NzbDrone.Core.Test/NotificationTests/NotificationBaseFixture.cs +++ b/src/NzbDrone.Core.Test/NotificationTests/NotificationBaseFixture.cs @@ -2,9 +2,9 @@ using FluentAssertions; using FluentValidation.Results; using NUnit.Framework; +using NzbDrone.Core.Movies; using NzbDrone.Core.Notifications; using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Movies; using NzbDrone.Core.Validation; using NzbDrone.Test.Common; @@ -13,7 +13,7 @@ namespace NzbDrone.Core.Test.NotificationTests [TestFixture] public class NotificationBaseFixture : TestBase { - class TestSetting : IProviderConfig + private class TestSetting : IProviderConfig { public NzbDroneValidationResult Validate() { @@ -21,12 +21,11 @@ public NzbDroneValidationResult Validate() } } - class TestNotificationWithOnDownload : NotificationBase + private class TestNotificationWithOnDownload : NotificationBase { public override string Name => "TestNotification"; public override string Link => ""; - public override ValidationResult Test() { throw new NotImplementedException(); @@ -36,15 +35,13 @@ public override void OnDownload(DownloadMessage downloadMessage) { TestLogger.Info("OnDownload was called"); } - } - class TestNotificationWithAllEvents : NotificationBase + private class TestNotificationWithAllEvents : NotificationBase { public override string Name => "TestNotification"; public override string Link => ""; - public override ValidationResult Test() { throw new NotImplementedException(); @@ -69,21 +66,17 @@ public override void OnHealthIssue(NzbDrone.Core.HealthCheck.HealthCheck artist) { TestLogger.Info("OnHealthIssue was called"); } - } - class TestNotificationWithNoEvents : NotificationBase + private class TestNotificationWithNoEvents : NotificationBase { public override string Name => "TestNotification"; public override string Link => ""; - public override ValidationResult Test() { throw new NotImplementedException(); } - - } [Test] @@ -110,7 +103,6 @@ public void should_support_all_if_implemented() notification.SupportsOnHealthIssue.Should().BeTrue(); } - [Test] public void should_support_none_if_none_are_implemented() { @@ -123,5 +115,4 @@ public void should_support_none_if_none_are_implemented() notification.SupportsOnHealthIssue.Should().BeFalse(); } } - } diff --git a/src/NzbDrone.Core.Test/NotificationTests/SynologyIndexerFixture.cs b/src/NzbDrone.Core.Test/NotificationTests/SynologyIndexerFixture.cs index 10f4098044..072a5e3aae 100644 --- a/src/NzbDrone.Core.Test/NotificationTests/SynologyIndexerFixture.cs +++ b/src/NzbDrone.Core.Test/NotificationTests/SynologyIndexerFixture.cs @@ -2,10 +2,10 @@ using Moq; using NUnit.Framework; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Movies; using NzbDrone.Core.Notifications; using NzbDrone.Core.Notifications.Synology; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.NotificationTests @@ -50,7 +50,7 @@ public void SetUp() { Settings = new SynologyIndexerSettings { - UpdateLibrary = true + UpdateLibrary = true } }; } diff --git a/src/NzbDrone.Core.Test/NotificationTests/Xbmc/GetMoviePathFixture.cs b/src/NzbDrone.Core.Test/NotificationTests/Xbmc/GetMoviePathFixture.cs index 82f8731cab..edce144eaa 100644 --- a/src/NzbDrone.Core.Test/NotificationTests/Xbmc/GetMoviePathFixture.cs +++ b/src/NzbDrone.Core.Test/NotificationTests/Xbmc/GetMoviePathFixture.cs @@ -3,10 +3,10 @@ using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; +using NzbDrone.Core.Movies; using NzbDrone.Core.Notifications.Xbmc; using NzbDrone.Core.Notifications.Xbmc.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.NotificationTests.Xbmc { diff --git a/src/NzbDrone.Core.Test/NotificationTests/Xbmc/OnDownloadFixture.cs b/src/NzbDrone.Core.Test/NotificationTests/Xbmc/OnDownloadFixture.cs index a7fd466114..5337ad226f 100644 --- a/src/NzbDrone.Core.Test/NotificationTests/Xbmc/OnDownloadFixture.cs +++ b/src/NzbDrone.Core.Test/NotificationTests/Xbmc/OnDownloadFixture.cs @@ -4,10 +4,10 @@ using Moq; using NUnit.Framework; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Movies; using NzbDrone.Core.Notifications; using NzbDrone.Core.Notifications.Xbmc; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.NotificationTests.Xbmc { @@ -33,9 +33,9 @@ public void Setup() Subject.Definition = new NotificationDefinition(); Subject.Definition.Settings = new XbmcSettings - { - UpdateLibrary = true - }; + { + UpdateLibrary = true + }; } private void GivenOldFiles() @@ -45,10 +45,10 @@ private void GivenOldFiles() .ToList(); Subject.Definition.Settings = new XbmcSettings - { - UpdateLibrary = true, - CleanLibrary = true - }; + { + UpdateLibrary = true, + CleanLibrary = true + }; } [Test] diff --git a/src/NzbDrone.Core.Test/NotificationTests/Xbmc/UpdateMovieFixture.cs b/src/NzbDrone.Core.Test/NotificationTests/Xbmc/UpdateMovieFixture.cs index c7751f0418..0fcf16e143 100644 --- a/src/NzbDrone.Core.Test/NotificationTests/Xbmc/UpdateMovieFixture.cs +++ b/src/NzbDrone.Core.Test/NotificationTests/Xbmc/UpdateMovieFixture.cs @@ -3,10 +3,10 @@ using FizzWare.NBuilder; using Moq; using NUnit.Framework; +using NzbDrone.Core.Movies; using NzbDrone.Core.Notifications.Xbmc; using NzbDrone.Core.Notifications.Xbmc.Model; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.NotificationTests.Xbmc { @@ -61,8 +61,8 @@ public void should_update_all_paths_when_movie_path_not_found() Subject.UpdateMovie(_settings, fakeMovie); - Mocker.GetMock() - .Verify(v => v.UpdateLibrary(_settings, null), Times.Once()); + Mocker.GetMock() + .Verify(v => v.UpdateLibrary(_settings, null), Times.Once()); } } } diff --git a/src/NzbDrone.Core.Test/OrganizerTests/CleanFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/CleanFixture.cs index 0da86640b1..aed489ea31 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/CleanFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/CleanFixture.cs @@ -14,6 +14,5 @@ public void CleanFileName(string name, string expectedName) { FileNameBuilder.CleanFileName(name).Should().Be(expectedName); } - } } diff --git a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/CleanTitleFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/CleanTitleFixture.cs index a60fccd3e8..626257574a 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/CleanTitleFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/CleanTitleFixture.cs @@ -3,10 +3,10 @@ using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Movies; using NzbDrone.Core.Organizer; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests { @@ -56,6 +56,7 @@ public void Setup() [TestCase("[a] title", "a title")] [TestCase("backslash \\ backlash", "backslash backlash")] [TestCase("I'm the Boss", "Im the Boss")] + //[TestCase("", "")] public void should_get_expected_title_back(string title, string expected) { diff --git a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/FileNameBuilderFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/FileNameBuilderFixture.cs index deed981743..91bd08bc6d 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/FileNameBuilderFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/FileNameBuilderFixture.cs @@ -2,14 +2,14 @@ using System.Linq; using FizzWare.NBuilder; using FluentAssertions; +using Moq; using NUnit.Framework; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.MediaFiles.MediaInfo; +using NzbDrone.Core.Movies; using NzbDrone.Core.Organizer; using NzbDrone.Core.Qualities; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; -using NzbDrone.Core.MediaFiles.MediaInfo; -using Moq; namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests { @@ -29,11 +29,9 @@ public void Setup() .With(s => s.Title = "South Park") .Build(); - _namingConfig = NamingConfig.Default; _namingConfig.RenameEpisodes = true; - Mocker.GetMock() .Setup(c => c.GetConfig()).Returns(_namingConfig); @@ -68,7 +66,7 @@ public void should_replace_Movie_underscore_Title() { _namingConfig.StandardMovieFormat = "{Movie_Title}"; - Subject.BuildFileName( _movie, _movieFile) + Subject.BuildFileName(_movie, _movieFile) .Should().Be("South_Park"); } @@ -77,7 +75,7 @@ public void should_replace_Movie_dot_Title() { _namingConfig.StandardMovieFormat = "{Movie.Title}"; - Subject.BuildFileName( _movie, _movieFile) + Subject.BuildFileName(_movie, _movieFile) .Should().Be("South.Park"); } @@ -86,7 +84,7 @@ public void should_replace_Movie_dash_Title() { _namingConfig.StandardMovieFormat = "{Movie-Title}"; - Subject.BuildFileName( _movie, _movieFile) + Subject.BuildFileName(_movie, _movieFile) .Should().Be("South-Park"); } @@ -95,7 +93,7 @@ public void should_replace_SERIES_TITLE_with_all_caps() { _namingConfig.StandardMovieFormat = "{MOVIE TITLE}"; - Subject.BuildFileName( _movie, _movieFile) + Subject.BuildFileName(_movie, _movieFile) .Should().Be("SOUTH PARK"); } @@ -113,7 +111,7 @@ public void should_replace_series_title_with_all_lower_case() { _namingConfig.StandardMovieFormat = "{movie title}"; - Subject.BuildFileName( _movie, _movieFile) + Subject.BuildFileName(_movie, _movieFile) .Should().Be("south park"); } @@ -127,9 +125,6 @@ public void should_cleanup_Movie_Title() .Should().Be("South.Park.1997"); } - - - [Test] public void should_replace_quality_title() { @@ -200,9 +195,6 @@ public void use_file_name_when_sceneName_is_not_null() .Should().Be("30.Rock.S01E01.xvid-LOL"); } - - - [Test] public void should_should_replace_release_group() { @@ -342,12 +334,10 @@ public void should_be_able_to_use_only_original_title() .Should().Be("30.Rock.S01E01.xvid-LOL"); } - - [Test] public void should_not_include_quality_proper_when_release_is_not_a_proper() { - _namingConfig.StandardMovieFormat= "{Quality Title} {Quality Proper}"; + _namingConfig.StandardMovieFormat = "{Quality Title} {Quality Proper}"; Subject.BuildFileName(_movie, _movieFile) .Should().Be("HDTV-720p"); @@ -356,7 +346,7 @@ public void should_not_include_quality_proper_when_release_is_not_a_proper() [Test] public void should_wrap_proper_in_square_brackets() { - _namingConfig.StandardMovieFormat= "{Movie Title} [{Quality Title}] {[Quality Proper]}"; + _namingConfig.StandardMovieFormat = "{Movie Title} [{Quality Title}] {[Quality Proper]}"; GivenProper(); @@ -367,7 +357,7 @@ public void should_wrap_proper_in_square_brackets() [Test] public void should_not_wrap_proper_in_square_brackets_when_not_a_proper() { - _namingConfig.StandardMovieFormat= "{Movie Title} [{Quality Title}] {[Quality Proper]}"; + _namingConfig.StandardMovieFormat = "{Movie Title} [{Quality Title}] {[Quality Proper]}"; Subject.BuildFileName(_movie, _movieFile) .Should().Be("South Park [HDTV-720p]"); @@ -376,7 +366,7 @@ public void should_not_wrap_proper_in_square_brackets_when_not_a_proper() [Test] public void should_replace_quality_full_with_quality_title_only_when_not_a_proper() { - _namingConfig.StandardMovieFormat= "{Movie Title} [{Quality Full}]"; + _namingConfig.StandardMovieFormat = "{Movie Title} [{Quality Full}]"; Subject.BuildFileName(_movie, _movieFile) .Should().Be("South Park [HDTV-720p]"); @@ -385,7 +375,7 @@ public void should_replace_quality_full_with_quality_title_only_when_not_a_prope [Test] public void should_replace_quality_full_with_quality_title_and_proper_only_when_a_proper() { - _namingConfig.StandardMovieFormat= "{Movie Title} [{Quality Full}]"; + _namingConfig.StandardMovieFormat = "{Movie Title} [{Quality Full}]"; GivenProper(); @@ -396,7 +386,7 @@ public void should_replace_quality_full_with_quality_title_and_proper_only_when_ [Test] public void should_replace_quality_full_with_quality_title_and_real_when_a_real() { - _namingConfig.StandardMovieFormat= "{Movie Title} [{Quality Full}]"; + _namingConfig.StandardMovieFormat = "{Movie Title} [{Quality Full}]"; GivenReal(); Subject.BuildFileName(_movie, _movieFile) @@ -409,7 +399,7 @@ public void should_replace_quality_full_with_quality_title_and_real_when_a_real( [TestCase('_')] public void should_trim_extra_separators_from_end_when_quality_proper_is_not_included(char separator) { - _namingConfig.StandardMovieFormat= string.Format("{{Quality{0}Title}}{0}{{Quality{0}Proper}}", separator); + _namingConfig.StandardMovieFormat = string.Format("{{Quality{0}Title}}{0}{{Quality{0}Proper}}", separator); Subject.BuildFileName(_movie, _movieFile) .Should().Be("HDTV-720p"); @@ -421,7 +411,7 @@ public void should_trim_extra_separators_from_end_when_quality_proper_is_not_inc [TestCase('_')] public void should_trim_extra_separators_from_middle_when_quality_proper_is_not_included(char separator) { - _namingConfig.StandardMovieFormat= string.Format("{{Quality{0}Title}}{0}{{Quality{0}Proper}}{0}{{Movie{0}Title}}", separator); + _namingConfig.StandardMovieFormat = string.Format("{{Quality{0}Title}}{0}{{Quality{0}Proper}}{0}{{Movie{0}Title}}", separator); Subject.BuildFileName(_movie, _movieFile) .Should().Be(string.Format("HDTV-720p{0}South{0}Park", separator)); @@ -431,7 +421,7 @@ public void should_trim_extra_separators_from_middle_when_quality_proper_is_not_ public void should_be_able_to_use_original_filename() { _movie.Title = "30 Rock"; - _namingConfig.StandardMovieFormat= "{Movie Title} - {Original Filename}"; + _namingConfig.StandardMovieFormat = "{Movie Title} - {Original Filename}"; _movieFile.SceneName = "30.Rock.S01E01.xvid-LOL"; _movieFile.RelativePath = "30 Rock - S01E01 - Test"; @@ -444,7 +434,7 @@ public void should_be_able_to_use_original_filename() public void should_be_able_to_use_original_filename_only() { _movie.Title = "30 Rock"; - _namingConfig.StandardMovieFormat= "{Original Filename}"; + _namingConfig.StandardMovieFormat = "{Original Filename}"; _movieFile.SceneName = "30.Rock.S01E01.xvid-LOL"; _movieFile.RelativePath = "30 Rock - S01E01 - Test"; @@ -457,7 +447,7 @@ public void should_be_able_to_use_original_filename_only() public void should_use_Sonarr_as_release_group_when_not_available() { _movieFile.ReleaseGroup = null; - _namingConfig.StandardMovieFormat= "{Release Group}"; + _namingConfig.StandardMovieFormat = "{Release Group}"; Subject.BuildFileName(_movie, _movieFile) .Should().Be("Radarr"); @@ -469,7 +459,7 @@ public void should_use_Sonarr_as_release_group_when_not_available() public void should_not_use_Sonarr_as_release_group_if_pattern_has_separator(string pattern, string expectedFileName) { _movieFile.ReleaseGroup = null; - _namingConfig.StandardMovieFormat= pattern; + _namingConfig.StandardMovieFormat = pattern; Subject.BuildFileName(_movie, _movieFile) .Should().Be(expectedFileName); @@ -481,7 +471,7 @@ public void should_not_use_Sonarr_as_release_group_if_pattern_has_separator(stri public void should_use_existing_casing_for_release_group(string releaseGroup) { _movieFile.ReleaseGroup = releaseGroup; - _namingConfig.StandardMovieFormat= "{Release Group}"; + _namingConfig.StandardMovieFormat = "{Release Group}"; Subject.BuildFileName(_movie, _movieFile) .Should().Be(releaseGroup); @@ -495,11 +485,9 @@ public void should_format_audio_languages(string audioLanguages, string expected GivenMediaInfoModel(audioLanguages: audioLanguages); - _namingConfig.StandardMovieFormat = "{MediaInfo AudioLanguages}"; - - Subject.BuildFileName( _movie , _movieFile) + Subject.BuildFileName(_movie, _movieFile) .Should().Be(expected); } @@ -511,11 +499,9 @@ public void should_format_audio_languages_all(string audioLanguages, string expe GivenMediaInfoModel(audioLanguages: audioLanguages); - _namingConfig.StandardMovieFormat = "{MediaInfo AudioLanguagesAll}"; - - Subject.BuildFileName( _movie , _movieFile) + Subject.BuildFileName(_movie, _movieFile) .Should().Be(expected); } @@ -523,8 +509,10 @@ public void should_format_audio_languages_all(string audioLanguages, string expe [TestCase(10, "BT.2020", "PQ", "South.Park.HDR")] [TestCase(10, "BT.2020", "HLG", "South.Park.HDR")] [TestCase(0, null, null, "South.Park")] - public void should_include_hdr_for_mediainfo_videodynamicrange_with_valid_properties(int bitDepth, string colourPrimaries, - string transferCharacteristics, string expectedName) + public void should_include_hdr_for_mediainfo_videodynamicrange_with_valid_properties(int bitDepth, + string colourPrimaries, + string transferCharacteristics, + string expectedName) { _namingConfig.StandardMovieFormat = "{Movie.Title}.{MediaInfo VideoDynamicRange}"; @@ -543,7 +531,7 @@ public void should_update_media_info_if_token_configured_and_revision_is_old() GivenMediaInfoModel(schemaRevision: 3); - Subject.BuildFileName( _movie, _movieFile); + Subject.BuildFileName(_movie, _movieFile); Mocker.GetMock().Verify(v => v.Update(_movieFile, _movie), Times.Once()); } @@ -557,7 +545,7 @@ public void should_not_update_media_info_if_no_movie_path_available() GivenMediaInfoModel(schemaRevision: 3); _movie.Path = null; - Subject.BuildFileName( _movie, _movieFile); + Subject.BuildFileName(_movie, _movieFile); Mocker.GetMock().Verify(v => v.Update(_movieFile, _movie), Times.Never()); } @@ -570,7 +558,7 @@ public void should_not_update_media_info_if_token_not_configured_and_revision_is GivenMediaInfoModel(schemaRevision: 3); - Subject.BuildFileName( _movie, _movieFile); + Subject.BuildFileName(_movie, _movieFile); Mocker.GetMock().Verify(v => v.Update(_movieFile, _movie), Times.Never()); } @@ -583,7 +571,7 @@ public void should_not_update_media_info_if_token_configured_and_revision_is_cur GivenMediaInfoModel(schemaRevision: 5); - Subject.BuildFileName( _movie, _movieFile); + Subject.BuildFileName(_movie, _movieFile); Mocker.GetMock().Verify(v => v.Update(_movieFile, _movie), Times.Never()); } @@ -601,9 +589,15 @@ public void should_not_update_media_info_if_token_configured_and_revision_is_new Mocker.GetMock().Verify(v => v.Update(_movieFile, _movie), Times.Never()); } - private void GivenMediaInfoModel(string videoCodec = "AVC", string audioCodec = "DTS", int audioChannels = 6, int videoBitDepth = 8, - string videoColourPrimaries = "", string videoTransferCharacteristics = "", string audioLanguages = "English", - string subtitles = "English/Spanish/Italian", int schemaRevision = 5) + private void GivenMediaInfoModel(string videoCodec = "AVC", + string audioCodec = "DTS", + int audioChannels = 6, + int videoBitDepth = 8, + string videoColourPrimaries = "", + string videoTransferCharacteristics = "", + string audioLanguages = "English", + string subtitles = "English/Spanish/Italian", + int schemaRevision = 5) { _movieFile.MediaInfo = new MediaInfoModel { @@ -617,8 +611,6 @@ private void GivenMediaInfoModel(string videoCodec = "AVC", string audioCodec = VideoTransferCharacteristics = videoTransferCharacteristics, SchemaRevision = schemaRevision }; - } - } } diff --git a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/IdFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/IdFixture.cs index 33c362f60f..b8771bf9b5 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/IdFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/FileNameBuilderTests/IdFixture.cs @@ -2,9 +2,9 @@ using FluentAssertions; using NUnit.Framework; using NUnit.Framework.Internal; +using NzbDrone.Core.Movies; using NzbDrone.Core.Organizer; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.OrganizerTests.FileNameBuilderTests { @@ -48,4 +48,4 @@ public void should_add_tmdb_id() .Should().Be($"Movie Title ({_movie.TmdbId})"); } } -} \ No newline at end of file +} diff --git a/src/NzbDrone.Core.Test/OrganizerTests/GetMovieFolderFixture.cs b/src/NzbDrone.Core.Test/OrganizerTests/GetMovieFolderFixture.cs index 95df14608a..35568c868f 100644 --- a/src/NzbDrone.Core.Test/OrganizerTests/GetMovieFolderFixture.cs +++ b/src/NzbDrone.Core.Test/OrganizerTests/GetMovieFolderFixture.cs @@ -1,8 +1,8 @@ +using FluentAssertions; using NUnit.Framework; +using NzbDrone.Core.Movies; using NzbDrone.Core.Organizer; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; -using FluentAssertions; namespace NzbDrone.Core.Test.OrganizerTests { @@ -10,15 +10,15 @@ namespace NzbDrone.Core.Test.OrganizerTests public class GetMovieFolderFixture : CoreTest { - private NamingConfig namingConfig; + private NamingConfig _namingConfig; [SetUp] public void Setup() { - namingConfig = NamingConfig.Default; + _namingConfig = NamingConfig.Default; Mocker.GetMock() - .Setup(c => c.GetConfig()).Returns(namingConfig); + .Setup(c => c.GetConfig()).Returns(_namingConfig); } [TestCase("Arrival", 2016, "{Movie Title} ({Release Year})", "Arrival (2016)")] @@ -26,7 +26,7 @@ public void Setup() [TestCase("The Big Short", 2015, "{Movie Title} ({Release Year})", "The Big Short (2015)")] public void should_use_movieFolderFormat_to_build_folder_name(string movieTitle, int year, string format, string expected) { - namingConfig.MovieFolderFormat = format; + _namingConfig.MovieFolderFormat = format; var movie = new Movie { Title = movieTitle, Year = year }; diff --git a/src/NzbDrone.Core.Test/ParserTests/NormalizeTitleFixture.cs b/src/NzbDrone.Core.Test/ParserTests/NormalizeTitleFixture.cs index 89699a0b72..21d9afcac7 100644 --- a/src/NzbDrone.Core.Test/ParserTests/NormalizeTitleFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/NormalizeTitleFixture.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.Test.ParserTests { - [TestFixture] public class NormalizeTitleFixture : CoreTest { @@ -129,9 +128,8 @@ public void should_not_remove_common_words_in_the_middle_of_word(string word) foreach (var s in dirtyFormat) { var dirty = string.Format(s, word); - dirty.CleanSeriesTitle().Should().Be(("word" + word.ToLower() + "word")); + dirty.CleanSeriesTitle().Should().Be("word" + word.ToLower() + "word"); } - } [TestCase("The Office", "theoffice")] diff --git a/src/NzbDrone.Core.Test/ParserTests/ParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ParserFixture.cs index 6b7572d921..62c564b5d8 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ParserFixture.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.Test.ParserTests { - [TestFixture] public class ParserFixture : CoreTest { diff --git a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentMovieInfoFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentMovieInfoFixture.cs index 84e78ecf40..1011834633 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentMovieInfoFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentMovieInfoFixture.cs @@ -7,7 +7,8 @@ namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests.AugmentersTests { [TestFixture] - public abstract class AugmentMovieInfoFixture : CoreTest where TAugmenter : class, IAugmentParsedMovieInfo + public abstract class AugmentMovieInfoFixture : CoreTest + where TAugmenter : class, IAugmentParsedMovieInfo { protected ParsedMovieInfo MovieInfo; diff --git a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentWithHistoryFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentWithHistoryFixture.cs index ac21a5ebd2..41027c4861 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentWithHistoryFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentWithHistoryFixture.cs @@ -21,6 +21,7 @@ public class AugmentWithHistoryFixture : AugmentMovieInfoFixture().Object, new List{ Mocker.Resolve()}); + _customSubject = new AugmentWithHistory(Mocker.GetMock().Object, new List { Mocker.Resolve() }); } return _customSubject; @@ -57,8 +57,9 @@ private void GivenIndexerSettings(IIndexerSettings indexerSettings) private History.History HistoryWithData(params string[] data) { var dict = new Dictionary(StringComparer.InvariantCultureIgnoreCase); - for (var i = 0; i < data.Length; i += 2) { - dict.Add(data[i], data[i+1]); + for (var i = 0; i < data.Length; i += 2) + { + dict.Add(data[i], data[i + 1]); } return new History.History diff --git a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentWithParsedMovieInfo.cs b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentWithParsedMovieInfo.cs index fca6406dca..0f881235f5 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentWithParsedMovieInfo.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentWithParsedMovieInfo.cs @@ -50,10 +50,10 @@ public void should_combine_languages() { var folderInfo = new ParsedMovieInfo { - Languages = new List {Language.French} + Languages = new List { Language.French } }; - MovieInfo.Languages = new List{Language.English}; + MovieInfo.Languages = new List { Language.English }; var result = Subject.AugmentMovieInfo(MovieInfo, folderInfo); diff --git a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentWithReleaseInfoFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentWithReleaseInfoFixture.cs index 384a48c5fd..e4e8acd8e8 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentWithReleaseInfoFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/AugmentersTests/AugmentWithReleaseInfoFixture.cs @@ -18,7 +18,7 @@ private ReleaseInfo ReleaseInfoWithLanguages(params Language[] languages) { _indexerDefinition = new IndexerDefinition { - Settings = new RarbgSettings { MultiLanguages = languages.ToList().Select(l => (int) l) } + Settings = new RarbgSettings { MultiLanguages = languages.ToList().Select(l => (int)l) } }; Mocker.GetMock() @@ -29,8 +29,6 @@ private ReleaseInfo ReleaseInfoWithLanguages(params Language[] languages) { IndexerId = 1 }; - - } [Test] @@ -80,6 +78,5 @@ public void should_add_indexer_flags() var movieInfo = Subject.AugmentMovieInfo(MovieInfo, releaseInfo); movieInfo.ExtraInfo["IndexerFlags"].Should().BeEquivalentTo(IndexerFlags.PTP_Approved | IndexerFlags.PTP_Golden); } - } } diff --git a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetMovieFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetMovieFixture.cs index 44648d4e0d..6dac2f9d92 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetMovieFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/GetMovieFixture.cs @@ -1,8 +1,8 @@ using Moq; using NUnit.Framework; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests { @@ -28,7 +28,7 @@ public void should_use_parsed_series_title() Subject.GetMovie(title); Mocker.GetMock() - .Verify(s => s.FindByTitle(Parser.Parser.ParseMovieTitle(title,false,false).MovieTitle), Times.Once()); + .Verify(s => s.FindByTitle(Parser.Parser.ParseMovieTitle(title, false, false).MovieTitle), Times.Once()); } /*[Test] diff --git a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/MapFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/MapFixture.cs index e59666890b..9d713b5921 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/MapFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ParsingServiceTests/MapFixture.cs @@ -6,10 +6,10 @@ using NUnit.Framework; using NzbDrone.Core.Datastore; using NzbDrone.Core.IndexerSearch.Definitions; +using NzbDrone.Core.Movies; using NzbDrone.Core.Movies.AlternativeTitles; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; namespace NzbDrone.Core.Test.ParserTests.ParsingServiceTests @@ -30,19 +30,17 @@ public class MapFixture : TestBase [SetUp] public void Setup() { - _movie = Builder.CreateNew() .With(m => m.Title = "Fack Ju Göthe 2") .With(m => m.CleanTitle = "fackjugoethe2") .With(m => m.Year = 2015) - .With(m => m.AlternativeTitles = new LazyList( new List {new AlternativeTitle("Fack Ju Göthe 2: Same same")})) + .With(m => m.AlternativeTitles = new LazyList(new List { new AlternativeTitle("Fack Ju Göthe 2: Same same") })) .Build(); _parsedMovieInfo = new ParsedMovieInfo { MovieTitle = _movie.Title, Year = _movie.Year, - }; _wrongYearInfo = new ParsedMovieInfo @@ -158,6 +156,5 @@ public void should_match_umlauts() Subject.Map(_umlautInfo, "", _movieSearchCriteria).Movie.Should().Be(_movieSearchCriteria.Movie); Subject.Map(_umlautAltInfo, "", _movieSearchCriteria).Movie.Should().Be(_movieSearchCriteria.Movie); } - } } diff --git a/src/NzbDrone.Core.Test/ParserTests/QualityParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/QualityParserFixture.cs index 3c1907851b..e11e08fc87 100644 --- a/src/NzbDrone.Core.Test/ParserTests/QualityParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/QualityParserFixture.cs @@ -11,7 +11,6 @@ namespace NzbDrone.Core.Test.ParserTests public class QualityParserFixture : CoreTest { - [SetUp] public void Setup() { @@ -19,7 +18,6 @@ public void Setup() } //public static object[] SelfQualityParserCases = QualityDefinition.DefaultQualityDefinitions.ToArray(); - public static object[] OtherSourceQualityParserCases = { new object[] { "SD TV", Source.TV, Resolution.R480p, Modifier.NONE }, @@ -113,7 +111,6 @@ public void should_parse_hdtv720p_quality(string title, bool proper) ParseAndVerifyQuality(title, Source.TV, proper, Resolution.R720p); } - [TestCase("DEXTER.S07E01.ARE.YOU.1080P.HDTV.X264-QCF", false)] [TestCase("DEXTER.S07E01.ARE.YOU.1080P.HDTV.x264-QCF", false)] [TestCase("DEXTER.S07E01.ARE.YOU.1080P.HDTV.proper.X264-QCF", true)] @@ -282,7 +279,6 @@ public void should_parse_brdisk_1080p_quality(string title) //{ // ParseAndVerifyQuality(title, Quality.RAWHD, proper); //} - [TestCase("Sonny.With.a.Chance.S02E15", false)] [TestCase("Law & Order: Special Victims Unit - 11x11 - Quickie", false)] [TestCase("Series.Title.S01E01.webm", false)] @@ -306,7 +302,8 @@ public void parsing_our_own_quality_enum_name(QualityDefinition definition) }*/ - [Test, TestCaseSource("OtherSourceQualityParserCases")] + [Test] + [TestCaseSource("OtherSourceQualityParserCases")] public void should_parse_quality_from_other_source(string qualityString, Source source, Resolution resolution, Modifier modifier = Modifier.NONE) { foreach (var c in new char[] { '-', '.', ' ', '_' }) @@ -363,6 +360,7 @@ private void ParseAndVerifyQuality(string title, Source source, bool proper, Res { result.Quality.Resolution.Should().Be((int)resolution); } + result.Quality.Source.Should().Be(source); if (modifier != Modifier.NONE) { diff --git a/src/NzbDrone.Core.Test/ParserTests/ReleaseGroupParserFixture.cs b/src/NzbDrone.Core.Test/ParserTests/ReleaseGroupParserFixture.cs index ae56e308ff..ca183c37a7 100644 --- a/src/NzbDrone.Core.Test/ParserTests/ReleaseGroupParserFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/ReleaseGroupParserFixture.cs @@ -37,17 +37,17 @@ public class ReleaseGroupParserFixture : CoreTest [TestCase("NCIS.S16E04.Third.Wheel.1080p.AMZN.WEB-DL.DDP5.1.H.264-NTb-GEROV", "NTb")] [TestCase("Will.and.Grace.S10E06.Kid.n.Play.1080p.AMZN.WEB-DL.DDP5.1.H.264-NTb-Z0iDS3N", "NTb")] [TestCase("Absolute.Power.S02E06.The.House.of.Lords.DVDRip.x264-MaG-Chamele0n", "MaG")] + //[TestCase("", "")] public void should_parse_release_group(string title, string expected) { Parser.Parser.ParseReleaseGroup(title).Should().Be(expected); } - - [TestCase("Marvels.Daredevil.S02E04.720p.WEBRip.x264-SKGTV English", "SKGTV")] [TestCase("Marvels.Daredevil.S02E04.720p.WEBRip.x264-SKGTV_English", "SKGTV")] [TestCase("Marvels.Daredevil.S02E04.720p.WEBRip.x264-SKGTV.English", "SKGTV")] + //[TestCase("", "")] public void should_not_include_language_in_release_group(string title, string expected) { @@ -72,6 +72,7 @@ public void should_not_include_repost_in_release_group(string title, string expe [TestCase("[Anime-Koi] Barakamon - S01E06 - Guys From Tokyo", "Anime-Koi")] [TestCase("[Anime-Koi] Barakamon - S01E07 - A High-Grade Fish", "Anime-Koi")] [TestCase("[Anime-Koi] Kami-sama Hajimemashita 2 - 01 [h264-720p][28D54E2C]", "Anime-Koi")] + //[TestCase("Tokyo.Ghoul.02x01.013.HDTV-720p-Anime-Koi", "Anime-Koi")] //[TestCase("", "")] public void should_parse_anime_release_groups(string title, string expected) diff --git a/src/NzbDrone.Core.Test/ParserTests/RomanNumeralTests/RomanNumeralConversionFixture.cs b/src/NzbDrone.Core.Test/ParserTests/RomanNumeralTests/RomanNumeralConversionFixture.cs index 8810150646..e6166733f1 100644 --- a/src/NzbDrone.Core.Test/ParserTests/RomanNumeralTests/RomanNumeralConversionFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/RomanNumeralTests/RomanNumeralConversionFixture.cs @@ -11,7 +11,6 @@ public class RomanNumeralConversionFixture { private const string TEST_VALUES = @"Files/ArabicRomanNumeralDictionary.JSON"; - private Dictionary _arabicToRomanNumeralsMapping; [OneTimeSetUp] @@ -22,10 +21,9 @@ public void PopulateDictionaryWithProvenValues() JsonConvert.DeserializeObject>(File.ReadAllText(pathToTestValues)); } - [Test(Description = "Converts the supported range [1-3999] of Arabic to Roman numerals.")] [Order(0)] - public void should_convert_arabic_numeral_to_roman_numeral([Range(1,20)] int arabicNumeral) + public void should_convert_arabic_numeral_to_roman_numeral([Range(1, 20)] int arabicNumeral) { RomanNumeral romanNumeral = new RomanNumeral(arabicNumeral); @@ -44,8 +42,5 @@ public void should_convert_roman_numeral_to_arabic_numeral([Range(1, 20)] int ar Assert.AreEqual(romanNumeral.ToInt(), expectecdValue); } - - - } } diff --git a/src/NzbDrone.Core.Test/ParserTests/SceneCheckerFixture.cs b/src/NzbDrone.Core.Test/ParserTests/SceneCheckerFixture.cs index cd24880504..0162c3b815 100644 --- a/src/NzbDrone.Core.Test/ParserTests/SceneCheckerFixture.cs +++ b/src/NzbDrone.Core.Test/ParserTests/SceneCheckerFixture.cs @@ -17,7 +17,6 @@ public void should_return_true_for_scene_names(string title) SceneChecker.IsSceneTitle(title).Should().BeTrue(); } - [TestCase("S08E05 - Virtual In-Stanity [WEBDL-720p]")] [TestCase("S08E05 - Virtual In-Stanity.With.Dots [WEBDL-720p]")] [TestCase("Something")] @@ -30,7 +29,5 @@ public void should_return_false_for_non_scene_names(string title) { SceneChecker.IsSceneTitle(title).Should().BeFalse(); } - - } } diff --git a/src/NzbDrone.Core.Test/Profiles/Delay/DelayProfileServiceFixture.cs b/src/NzbDrone.Core.Test/Profiles/Delay/DelayProfileServiceFixture.cs index ff533103e8..c866780358 100644 --- a/src/NzbDrone.Core.Test/Profiles/Delay/DelayProfileServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Profiles/Delay/DelayProfileServiceFixture.cs @@ -75,7 +75,6 @@ public void should_reorder_delay_profiles_that_are_after_moved() { delayProfile.Order.Should().Be(int.MaxValue); } - else { delayProfile.Order.Should().Be(i + 1); diff --git a/src/NzbDrone.Core.Test/Profiles/ProfileRepositoryFixture.cs b/src/NzbDrone.Core.Test/Profiles/ProfileRepositoryFixture.cs index 2f29fe20b4..e845d70e89 100644 --- a/src/NzbDrone.Core.Test/Profiles/ProfileRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/Profiles/ProfileRepositoryFixture.cs @@ -18,13 +18,13 @@ public void Setup() public void should_be_able_to_read_and_write() { var profile = new Profile - { - Items = Qualities.QualityFixture.GetDefaultQualities(Quality.Bluray1080p, Quality.DVD, Quality.HDTV720p), - FormatCutoff = CustomFormats.CustomFormat.None.Id, - FormatItems = CustomFormat.CustomFormatsFixture.GetDefaultFormatItems(), - Cutoff = Quality.Bluray1080p.Id, - Name = "TestProfile" - }; + { + Items = Qualities.QualityFixture.GetDefaultQualities(Quality.Bluray1080p, Quality.DVD, Quality.HDTV720p), + FormatCutoff = CustomFormats.CustomFormat.None.Id, + FormatItems = CustomFormat.CustomFormatsFixture.GetDefaultFormatItems(), + Cutoff = Quality.Bluray1080p.Id, + Name = "TestProfile" + }; Subject.Insert(profile); @@ -32,8 +32,6 @@ public void should_be_able_to_read_and_write() StoredModel.Cutoff.Should().Be(profile.Cutoff); StoredModel.Items.Should().Equal(profile.Items, (a, b) => a.Quality == b.Quality && a.Allowed == b.Allowed); - - } } } diff --git a/src/NzbDrone.Core.Test/Profiles/ProfileServiceFixture.cs b/src/NzbDrone.Core.Test/Profiles/ProfileServiceFixture.cs index 96d65f781d..fa9e0e414a 100644 --- a/src/NzbDrone.Core.Test/Profiles/ProfileServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Profiles/ProfileServiceFixture.cs @@ -1,14 +1,14 @@ +using System.Collections.Generic; using System.Linq; using FizzWare.NBuilder; using Moq; using NUnit.Framework; +using NzbDrone.Core.CustomFormats; using NzbDrone.Core.Lifecycle; -using NzbDrone.Core.Profiles; -using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Movies; using NzbDrone.Core.NetImport; -using NzbDrone.Core.CustomFormats; -using System.Collections.Generic; +using NzbDrone.Core.Profiles; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.Profiles { @@ -30,6 +30,7 @@ public void init_should_add_default_profiles() } [Test] + //This confirms that new profiles are added only if no other profiles exists. //We don't want to keep adding them back if a user deleted them on purpose. public void Init_should_skip_if_any_profiles_already_exist() @@ -44,7 +45,6 @@ public void Init_should_skip_if_any_profiles_already_exist() .Verify(v => v.Insert(It.IsAny()), Times.Never()); } - [Test] public void should_not_be_able_to_delete_profile_if_assigned_to_movie() { @@ -64,7 +64,6 @@ public void should_not_be_able_to_delete_profile_if_assigned_to_movie() Assert.Throws(() => Subject.Delete(2)); Mocker.GetMock().Verify(c => c.Delete(It.IsAny()), Times.Never()); - } [Test] @@ -86,10 +85,8 @@ public void should_not_be_able_to_delete_profile_if_assigned_to_list() Assert.Throws(() => Subject.Delete(2)); Mocker.GetMock().Verify(c => c.Delete(It.IsAny()), Times.Never()); - } - [Test] public void should_delete_profile_if_not_assigned_to_movie_or_list() { diff --git a/src/NzbDrone.Core.Test/ProviderTests/DiskProviderTests/ArchiveProviderFixture.cs b/src/NzbDrone.Core.Test/ProviderTests/DiskProviderTests/ArchiveProviderFixture.cs index 5e9d6c6a8b..504fa1a3a8 100644 --- a/src/NzbDrone.Core.Test/ProviderTests/DiskProviderTests/ArchiveProviderFixture.cs +++ b/src/NzbDrone.Core.Test/ProviderTests/DiskProviderTests/ArchiveProviderFixture.cs @@ -1,7 +1,7 @@ -using FluentAssertions; +using System.IO; +using FluentAssertions; using NUnit.Framework; using NzbDrone.Common; -using System.IO; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Test.Common; diff --git a/src/NzbDrone.Core.Test/ProviderTests/DiskScanProviderTests/GetVideoFilesFixture.cs b/src/NzbDrone.Core.Test/ProviderTests/DiskScanProviderTests/GetVideoFilesFixture.cs index 071eb535bd..163eadcb7e 100644 --- a/src/NzbDrone.Core.Test/ProviderTests/DiskScanProviderTests/GetVideoFilesFixture.cs +++ b/src/NzbDrone.Core.Test/ProviderTests/DiskScanProviderTests/GetVideoFilesFixture.cs @@ -10,7 +10,6 @@ namespace NzbDrone.Core.Test.ProviderTests.DiskScanProviderTests { - public class GetVideoFilesFixture : CoreTest { private string[] _fileNames; diff --git a/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/CleanupFixture.cs b/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/CleanupFixture.cs index 7f433f3ed7..7fb282fa2c 100644 --- a/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/CleanupFixture.cs +++ b/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/CleanupFixture.cs @@ -40,10 +40,10 @@ public void Setup() Mocker.GetMock().SetupGet(s => s.RecycleBinCleanupDays).Returns(7); Mocker.GetMock().Setup(s => s.GetDirectories(RecycleBin)) - .Returns(new [] { @"C:\Test\RecycleBin\Folder1", @"C:\Test\RecycleBin\Folder2", @"C:\Test\RecycleBin\Folder3" }); + .Returns(new[] { @"C:\Test\RecycleBin\Folder1", @"C:\Test\RecycleBin\Folder2", @"C:\Test\RecycleBin\Folder3" }); Mocker.GetMock().Setup(s => s.GetFiles(RecycleBin, SearchOption.AllDirectories)) - .Returns(new [] { @"C:\Test\RecycleBin\File1.avi", @"C:\Test\RecycleBin\File2.mkv" }); + .Returns(new[] { @"C:\Test\RecycleBin\File1.avi", @"C:\Test\RecycleBin\File2.mkv" }); } [Test] diff --git a/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/DeleteFileFixture.cs b/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/DeleteFileFixture.cs index 3adb282085..bd4b8c4b02 100644 --- a/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/DeleteFileFixture.cs +++ b/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/DeleteFileFixture.cs @@ -70,7 +70,6 @@ public void should_call_fileSetLastWriteTime_for_each_file() WithRecycleBin(); var path = @"C:\Test\TV\30 Rock\S01E01.avi".AsOsAgnostic(); - Mocker.Resolve().DeleteFile(path); Mocker.GetMock().Verify(v => v.FileSetLastWriteTime(@"C:\Test\Recycle Bin\S01E01.avi".AsOsAgnostic(), It.IsAny()), Times.Once()); diff --git a/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/EmptyFixture.cs b/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/EmptyFixture.cs index 8a5b486cd1..f061c1388b 100644 --- a/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/EmptyFixture.cs +++ b/src/NzbDrone.Core.Test/ProviderTests/RecycleBinProviderTests/EmptyFixture.cs @@ -20,10 +20,10 @@ public void Setup() Mocker.GetMock().SetupGet(s => s.RecycleBin).Returns(RecycleBin); Mocker.GetMock().Setup(s => s.GetDirectories(RecycleBin)) - .Returns(new [] { @"C:\Test\RecycleBin\Folder1", @"C:\Test\RecycleBin\Folder2", @"C:\Test\RecycleBin\Folder3" }); + .Returns(new[] { @"C:\Test\RecycleBin\Folder1", @"C:\Test\RecycleBin\Folder2", @"C:\Test\RecycleBin\Folder3" }); Mocker.GetMock().Setup(s => s.GetFiles(RecycleBin, SearchOption.TopDirectoryOnly)) - .Returns(new [] { @"C:\Test\RecycleBin\File1.avi", @"C:\Test\RecycleBin\File2.mkv" }); + .Returns(new[] { @"C:\Test\RecycleBin\File1.avi", @"C:\Test\RecycleBin\File2.mkv" }); } [Test] diff --git a/src/NzbDrone.Core.Test/Qualities/QualityDefinitionServiceFixture.cs b/src/NzbDrone.Core.Test/Qualities/QualityDefinitionServiceFixture.cs index 170fffee7f..c2417fa537 100644 --- a/src/NzbDrone.Core.Test/Qualities/QualityDefinitionServiceFixture.cs +++ b/src/NzbDrone.Core.Test/Qualities/QualityDefinitionServiceFixture.cs @@ -32,7 +32,7 @@ public void init_should_insert_any_missing_definitions() Subject.Handle(new ApplicationStartedEvent()); Mocker.GetMock() - .Verify(v => v.InsertMany(It.Is>(d => d.Count == Quality.All.Count -1 )), Times.Once()); + .Verify(v => v.InsertMany(It.Is>(d => d.Count == Quality.All.Count - 1)), Times.Once()); } [Test] @@ -59,7 +59,7 @@ public void init_should_remove_old_definitions() .Setup(s => s.All()) .Returns(new List { - new QualityDefinition(new Quality{ Id = 100, Name = "Test" }) { Weight = 1, MinSize = 0, MaxSize = 100, Id = 20 } + new QualityDefinition(new Quality { Id = 100, Name = "Test" }) { Weight = 1, MinSize = 0, MaxSize = 100, Id = 20 } }); Subject.Handle(new ApplicationStartedEvent()); diff --git a/src/NzbDrone.Core.Test/Qualities/QualityFixture.cs b/src/NzbDrone.Core.Test/Qualities/QualityFixture.cs index e64216ed93..201ec4b150 100644 --- a/src/NzbDrone.Core.Test/Qualities/QualityFixture.cs +++ b/src/NzbDrone.Core.Test/Qualities/QualityFixture.cs @@ -1,6 +1,6 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentAssertions; using NUnit.Framework; using NzbDrone.Core.Profiles; @@ -14,48 +14,52 @@ public class QualityFixture : CoreTest { public static object[] FromIntCases = { - new object[] {0, Quality.Unknown}, - new object[] {1, Quality.SDTV}, - new object[] {2, Quality.DVD}, - new object[] {3, Quality.WEBDL1080p}, - new object[] {4, Quality.HDTV720p}, - new object[] {5, Quality.WEBDL720p}, - new object[] {6, Quality.Bluray720p}, - new object[] {7, Quality.Bluray1080p}, - new object[] {8, Quality.WEBDL480p}, - new object[] {9, Quality.HDTV1080p}, + new object[] { 0, Quality.Unknown }, + new object[] { 1, Quality.SDTV }, + new object[] { 2, Quality.DVD }, + new object[] { 3, Quality.WEBDL1080p }, + new object[] { 4, Quality.HDTV720p }, + new object[] { 5, Quality.WEBDL720p }, + new object[] { 6, Quality.Bluray720p }, + new object[] { 7, Quality.Bluray1080p }, + new object[] { 8, Quality.WEBDL480p }, + new object[] { 9, Quality.HDTV1080p }, + //new object[] {10, Quality.RAWHD}, - new object[] {16, Quality.HDTV2160p}, - new object[] {18, Quality.WEBDL2160p}, - new object[] {19, Quality.Bluray2160p}, + new object[] { 16, Quality.HDTV2160p }, + new object[] { 18, Quality.WEBDL2160p }, + new object[] { 19, Quality.Bluray2160p }, }; public static object[] ToIntCases = { - new object[] {Quality.Unknown, 0}, - new object[] {Quality.SDTV, 1}, - new object[] {Quality.DVD, 2}, - new object[] {Quality.WEBDL1080p, 3}, - new object[] {Quality.HDTV720p, 4}, - new object[] {Quality.WEBDL720p, 5}, - new object[] {Quality.Bluray720p, 6}, - new object[] {Quality.Bluray1080p, 7}, - new object[] {Quality.WEBDL480p, 8}, - new object[] {Quality.HDTV1080p, 9}, + new object[] { Quality.Unknown, 0 }, + new object[] { Quality.SDTV, 1 }, + new object[] { Quality.DVD, 2 }, + new object[] { Quality.WEBDL1080p, 3 }, + new object[] { Quality.HDTV720p, 4 }, + new object[] { Quality.WEBDL720p, 5 }, + new object[] { Quality.Bluray720p, 6 }, + new object[] { Quality.Bluray1080p, 7 }, + new object[] { Quality.WEBDL480p, 8 }, + new object[] { Quality.HDTV1080p, 9 }, + //new object[] {Quality.RAWHD, 10}, - new object[] {Quality.HDTV2160p, 16}, - new object[] {Quality.WEBDL2160p, 18}, - new object[] {Quality.Bluray2160p, 19}, + new object[] { Quality.HDTV2160p, 16 }, + new object[] { Quality.WEBDL2160p, 18 }, + new object[] { Quality.Bluray2160p, 19 }, }; - [Test, TestCaseSource("FromIntCases")] + [Test] + [TestCaseSource("FromIntCases")] public void should_be_able_to_convert_int_to_qualityTypes(int source, Quality expected) { var quality = (Quality)source; quality.Should().Be(expected); } - [Test, TestCaseSource("ToIntCases")] + [Test] + [TestCaseSource("ToIntCases")] public void should_be_able_to_convert_qualityTypes_to_int(Quality source, int expected) { var i = (int)source; @@ -90,7 +94,9 @@ public static List GetDefaultQualities(params Quality[] allo }; if (allowed.Length == 0) + { allowed = qualities.ToArray(); + } var items = qualities .Except(allowed) diff --git a/src/NzbDrone.Core.Test/Qualities/QualityModelComparerFixture.cs b/src/NzbDrone.Core.Test/Qualities/QualityModelComparerFixture.cs index 4c81d7f401..180580e0be 100644 --- a/src/NzbDrone.Core.Test/Qualities/QualityModelComparerFixture.cs +++ b/src/NzbDrone.Core.Test/Qualities/QualityModelComparerFixture.cs @@ -77,12 +77,12 @@ private void GivenGroupedProfile() private void GivenDefaultProfileWithFormats() { - _customFormat1 = new CustomFormats.CustomFormat("My Format 1", "L_ENGLISH"){Id=1}; - _customFormat2 = new CustomFormats.CustomFormat("My Format 2", "L_FRENCH"){Id=2}; + _customFormat1 = new CustomFormats.CustomFormat("My Format 1", "L_ENGLISH") { Id = 1 }; + _customFormat2 = new CustomFormats.CustomFormat("My Format 2", "L_FRENCH") { Id = 2 }; CustomFormatsFixture.GivenCustomFormats(CustomFormats.CustomFormat.None, _customFormat1, _customFormat2); - Subject = new QualityModelComparer(new Profile {Items = QualityFixture.GetDefaultQualities(), FormatItems = CustomFormatsFixture.GetSampleFormatItems()}); + Subject = new QualityModelComparer(new Profile { Items = QualityFixture.GetDefaultQualities(), FormatItems = CustomFormatsFixture.GetSampleFormatItems() }); } [Test] @@ -142,8 +142,8 @@ public void should_be_lesser_when_first_quality_is_worse_format() { GivenDefaultProfileWithFormats(); - var first = new QualityModel(Quality.DVD) {CustomFormats = new List{_customFormat1}}; - var second = new QualityModel(Quality.DVD) {CustomFormats = new List{_customFormat2}}; + var first = new QualityModel(Quality.DVD) { CustomFormats = new List { _customFormat1 } }; + var second = new QualityModel(Quality.DVD) { CustomFormats = new List { _customFormat2 } }; var compare = Subject.Compare(first, second); @@ -155,8 +155,8 @@ public void should_be_greater_when_first_quality_is_better_format() { GivenDefaultProfileWithFormats(); - var first = new QualityModel(Quality.DVD) {CustomFormats = new List{_customFormat2}}; - var second = new QualityModel(Quality.DVD) {CustomFormats = new List{_customFormat1}}; + var first = new QualityModel(Quality.DVD) { CustomFormats = new List { _customFormat2 } }; + var second = new QualityModel(Quality.DVD) { CustomFormats = new List { _customFormat1 } }; var compare = Subject.Compare(first, second); diff --git a/src/NzbDrone.Core.Test/Qualities/RevisionComparableFixture.cs b/src/NzbDrone.Core.Test/Qualities/RevisionComparableFixture.cs index e67640c587..5756ede701 100644 --- a/src/NzbDrone.Core.Test/Qualities/RevisionComparableFixture.cs +++ b/src/NzbDrone.Core.Test/Qualities/RevisionComparableFixture.cs @@ -134,10 +134,10 @@ public void less_than_operator_tests() [Test] public void operating_on_nulls() { - (null > new Revision()).Should().BeFalse(); - (null >= new Revision()).Should().BeFalse(); - (null < new Revision()).Should().BeTrue(); - (null <= new Revision()).Should().BeTrue(); + (new Revision() < null).Should().BeFalse(); + (new Revision() <= null).Should().BeFalse(); + (new Revision() > null).Should().BeTrue(); + (new Revision() >= null).Should().BeTrue(); (new Revision() > null).Should().BeTrue(); (new Revision() >= null).Should().BeTrue(); diff --git a/src/NzbDrone.Core.Test/QueueTests/QueueServiceFixture.cs b/src/NzbDrone.Core.Test/QueueTests/QueueServiceFixture.cs index 849e6493cc..39ef9140b4 100644 --- a/src/NzbDrone.Core.Test/QueueTests/QueueServiceFixture.cs +++ b/src/NzbDrone.Core.Test/QueueTests/QueueServiceFixture.cs @@ -1,14 +1,14 @@ using System; using System.Collections.Generic; using System.Linq; -using NUnit.Framework; -using NzbDrone.Core.Download.TrackedDownloads; -using NzbDrone.Core.Queue; -using NzbDrone.Core.Test.Framework; using FizzWare.NBuilder; using FluentAssertions; +using NUnit.Framework; +using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Queue; +using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test.QueueTests { diff --git a/src/NzbDrone.Core.Test/RemotePathMappingsTests/RemotePathMappingServiceFixture.cs b/src/NzbDrone.Core.Test/RemotePathMappingsTests/RemotePathMappingServiceFixture.cs index 7b0777d123..47f023c1bd 100644 --- a/src/NzbDrone.Core.Test/RemotePathMappingsTests/RemotePathMappingServiceFixture.cs +++ b/src/NzbDrone.Core.Test/RemotePathMappingsTests/RemotePathMappingServiceFixture.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using FizzWare.NBuilder; using FluentAssertions; using Moq; using NUnit.Framework; @@ -7,7 +8,6 @@ using NzbDrone.Core.RemotePathMappings; using NzbDrone.Core.Test.Framework; using NzbDrone.Test.Common; -using FizzWare.NBuilder; namespace NzbDrone.Core.Test.RemotePathMappingsTests { @@ -128,7 +128,7 @@ public void should_fix_wrong_slashes_on_add(string remotePath, string cleanedPat { Host = "my-server.localdomain", RemotePath = remotePath, - LocalPath = @"D:\mountedstorage\downloads\tv" .AsOsAgnostic() + LocalPath = @"D:\mountedstorage\downloads\tv".AsOsAgnostic() }; var result = Subject.Add(mapping); diff --git a/src/NzbDrone.Core.Test/RootFolderTests/RootFolderServiceFixture.cs b/src/NzbDrone.Core.Test/RootFolderTests/RootFolderServiceFixture.cs index 84cbe51421..0909b69eff 100644 --- a/src/NzbDrone.Core.Test/RootFolderTests/RootFolderServiceFixture.cs +++ b/src/NzbDrone.Core.Test/RootFolderTests/RootFolderServiceFixture.cs @@ -7,11 +7,11 @@ using Moq; using NUnit.Framework; using NzbDrone.Common.Disk; +using NzbDrone.Common.EnvironmentInfo; +using NzbDrone.Core.Movies; using NzbDrone.Core.RootFolders; using NzbDrone.Core.Test.Framework; -using NzbDrone.Core.Movies; using NzbDrone.Test.Common; -using NzbDrone.Common.EnvironmentInfo; namespace NzbDrone.Core.Test.RootFolderTests { @@ -74,8 +74,7 @@ public void should_be_able_to_remove_root_dir() public void invalid_folder_path_throws_on_add(string path) { Assert.Throws(() => - Mocker.Resolve().Add(new RootFolder { Id = 0, Path = path }) - ); + Mocker.Resolve().Add(new RootFolder { Id = 0, Path = path })); } [Test] @@ -117,7 +116,6 @@ public void should_get_root_folder_with_subfolders_excluding_special_sub_folders .Build(); } - var subFolders = new[] { "Series1", diff --git a/src/NzbDrone.Core.Test/ThingiProvider/ProviderBaseFixture.cs b/src/NzbDrone.Core.Test/ThingiProvider/ProviderBaseFixture.cs index 6d95bc4df1..6107479e4d 100644 --- a/src/NzbDrone.Core.Test/ThingiProvider/ProviderBaseFixture.cs +++ b/src/NzbDrone.Core.Test/ThingiProvider/ProviderBaseFixture.cs @@ -7,7 +7,6 @@ namespace NzbDrone.Core.Test.ThingiProvider { - public class ProviderRepositoryFixture : DbTest { [Test] @@ -24,7 +23,7 @@ public void should_read_write_download_provider() var storedSetting = (NewznabSettings)storedProvider.Settings; - storedSetting.Should().BeEquivalentTo(newznabSettings, o=>o.IncludingAllRuntimeProperties()); + storedSetting.Should().BeEquivalentTo(newznabSettings, o => o.IncludingAllRuntimeProperties()); } } } diff --git a/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderBaseFixture.cs b/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderBaseFixture.cs index 7de6c61b8e..1faf6d750e 100644 --- a/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderBaseFixture.cs +++ b/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderBaseFixture.cs @@ -23,7 +23,7 @@ public void should_read_write_download_provider() var storedSetting = (NewznabSettings)storedProvider.Settings; - storedSetting.Should().BeEquivalentTo(newznabSettings, o=>o.IncludingAllRuntimeProperties()); + storedSetting.Should().BeEquivalentTo(newznabSettings, o => o.IncludingAllRuntimeProperties()); } } } diff --git a/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderStatusServiceFixture.cs b/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderStatusServiceFixture.cs index 80d533ed20..f9c0d43252 100644 --- a/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderStatusServiceFixture.cs +++ b/src/NzbDrone.Core.Test/ThingiProviderTests/ProviderStatusServiceFixture.cs @@ -29,7 +29,6 @@ public class MockProviderStatusService : ProviderStatusServiceBase().Verify(c => c.DeleteFolder(_sandboxFolder, true), Times.Never()); } @@ -166,7 +164,6 @@ public void should_return_without_error_or_warnings_when_no_updates_are_availabl Subject.Execute(new ApplicationUpdateCommand()); - ExceptionVerification.AssertNoUnexpectedLogs(); } @@ -181,7 +178,7 @@ public void should_not_extract_if_verification_fails() } [Test] - [Platform(Exclude="Win")] + [Platform(Exclude = "Win")] public void should_run_script_if_configured() { const string scriptPath = "/tmp/nzbdrone/update.sh"; @@ -194,7 +191,7 @@ public void should_run_script_if_configured() } [Test] - [Platform(Exclude="Win")] + [Platform(Exclude = "Win")] public void should_throw_if_script_is_not_set() { const string scriptPath = "/tmp/nzbdrone/update.sh"; @@ -208,7 +205,7 @@ public void should_throw_if_script_is_not_set() } [Test] - [Platform(Exclude="Win")] + [Platform(Exclude = "Win")] public void should_throw_if_script_is_null() { const string scriptPath = "/tmp/nzbdrone/update.sh"; @@ -222,7 +219,7 @@ public void should_throw_if_script_is_null() } [Test] - [Platform(Exclude="Win")] + [Platform(Exclude = "Win")] public void should_throw_if_script_path_does_not_exist() { const string scriptPath = "/tmp/nzbdrone/update.sh"; diff --git a/src/NzbDrone.Core.Test/ValidationTests/SystemFolderValidatorFixture.cs b/src/NzbDrone.Core.Test/ValidationTests/SystemFolderValidatorFixture.cs index 94a48cc44c..f336627040 100644 --- a/src/NzbDrone.Core.Test/ValidationTests/SystemFolderValidatorFixture.cs +++ b/src/NzbDrone.Core.Test/ValidationTests/SystemFolderValidatorFixture.cs @@ -3,11 +3,11 @@ using FizzWare.NBuilder; using FluentAssertions; using NUnit.Framework; -using NzbDrone.Core.Test.Framework; +using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Core.Movies; +using NzbDrone.Core.Test.Framework; using NzbDrone.Core.Validation.Paths; using NzbDrone.Test.Common; -using NzbDrone.Common.EnvironmentInfo; namespace NzbDrone.Core.Test.ValidationTests { diff --git a/src/NzbDrone.Core/Analytics/AnalyticsService.cs b/src/NzbDrone.Core/Analytics/AnalyticsService.cs index c16bfa0a63..9e962c0a06 100644 --- a/src/NzbDrone.Core/Analytics/AnalyticsService.cs +++ b/src/NzbDrone.Core/Analytics/AnalyticsService.cs @@ -24,7 +24,7 @@ public AnalyticsService(IHistoryService historyService, IConfigFileProvider conf _historyService = historyService; } - public bool IsEnabled => _configFileProvider.AnalyticsEnabled && RuntimeInfo.IsProduction || RuntimeInfo.IsDevelopment; + public bool IsEnabled => (_configFileProvider.AnalyticsEnabled && RuntimeInfo.IsProduction) || RuntimeInfo.IsDevelopment; public bool InstallIsActive { diff --git a/src/NzbDrone.Core/Authentication/UserService.cs b/src/NzbDrone.Core/Authentication/UserService.cs index 60f77df131..0559c2133f 100644 --- a/src/NzbDrone.Core/Authentication/UserService.cs +++ b/src/NzbDrone.Core/Authentication/UserService.cs @@ -35,11 +35,11 @@ public UserService(IUserRepository repo, IAppFolderInfo appFolderInfo, IDiskProv public User Add(string username, string password) { return _repo.Insert(new User - { - Identifier = Guid.NewGuid(), - Username = username.ToLowerInvariant(), - Password = password.SHA256Hash() - }); + { + Identifier = Guid.NewGuid(), + Username = username.ToLowerInvariant(), + Password = password.SHA256Hash() + }); } public User Update(User user) diff --git a/src/NzbDrone.Core/Backup/BackupService.cs b/src/NzbDrone.Core/Backup/BackupService.cs index 31a2905b12..f19d83d33f 100644 --- a/src/NzbDrone.Core/Backup/BackupService.cs +++ b/src/NzbDrone.Core/Backup/BackupService.cs @@ -104,11 +104,11 @@ public List GetBackups() if (_diskProvider.FolderExists(folder)) { backups.AddRange(GetBackupFiles(folder).Select(b => new Backup - { - Name = Path.GetFileName(b), - Type = backupType, - Time = _diskProvider.FileGetLastWrite(b) - })); + { + Name = Path.GetFileName(b), + Type = backupType, + Time = _diskProvider.FileGetLastWrite(b) + })); } } diff --git a/src/NzbDrone.Core/Backup/MakeDatabaseBackup.cs b/src/NzbDrone.Core/Backup/MakeDatabaseBackup.cs index 1904b0bf92..961744127d 100644 --- a/src/NzbDrone.Core/Backup/MakeDatabaseBackup.cs +++ b/src/NzbDrone.Core/Backup/MakeDatabaseBackup.cs @@ -26,9 +26,11 @@ public void BackupDatabase(IDatabase database, string targetDirectory) { sourceConnectionString = db.ConnectionString; } + var backupConnectionStringBuilder = new SQLiteConnectionStringBuilder(sourceConnectionString); backupConnectionStringBuilder.DataSource = Path.Combine(targetDirectory, Path.GetFileName(backupConnectionStringBuilder.DataSource)); + // We MUST use journal mode instead of WAL coz WAL has issues when page sizes change. This should also automatically deal with the -journal and -wal files during restore. backupConnectionStringBuilder.JournalMode = SQLiteJournalModeEnum.Truncate; diff --git a/src/NzbDrone.Core/Backup/RestoreBackupFailedException.cs b/src/NzbDrone.Core/Backup/RestoreBackupFailedException.cs index 3a06b1b1b0..40c4d22160 100644 --- a/src/NzbDrone.Core/Backup/RestoreBackupFailedException.cs +++ b/src/NzbDrone.Core/Backup/RestoreBackupFailedException.cs @@ -5,11 +5,13 @@ namespace NzbDrone.Core.Backup { public class RestoreBackupFailedException : NzbDroneClientException { - public RestoreBackupFailedException(HttpStatusCode statusCode, string message, params object[] args) : base(statusCode, message, args) + public RestoreBackupFailedException(HttpStatusCode statusCode, string message, params object[] args) + : base(statusCode, message, args) { } - public RestoreBackupFailedException(HttpStatusCode statusCode, string message) : base(statusCode, message) + public RestoreBackupFailedException(HttpStatusCode statusCode, string message) + : base(statusCode, message) { } } diff --git a/src/NzbDrone.Core/Blacklisting/Blacklist.cs b/src/NzbDrone.Core/Blacklisting/Blacklist.cs index 4000d404ea..c041126cf7 100644 --- a/src/NzbDrone.Core/Blacklisting/Blacklist.cs +++ b/src/NzbDrone.Core/Blacklisting/Blacklist.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using NzbDrone.Core.Datastore; using NzbDrone.Core.Indexers; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; using NzbDrone.Core.Languages; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Blacklisting { diff --git a/src/NzbDrone.Core/Blacklisting/BlacklistRepository.cs b/src/NzbDrone.Core/Blacklisting/BlacklistRepository.cs index fc398d89bf..6c93ec5d34 100644 --- a/src/NzbDrone.Core/Blacklisting/BlacklistRepository.cs +++ b/src/NzbDrone.Core/Blacklisting/BlacklistRepository.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; +using Marr.Data.QGen; using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; -using Marr.Data.QGen; using NzbDrone.Core.Movies; namespace NzbDrone.Core.Blacklisting @@ -15,8 +15,8 @@ public interface IBlacklistRepository : IBasicRepository public class BlacklistRepository : BasicRepository, IBlacklistRepository { - public BlacklistRepository(IMainDatabase database, IEventAggregator eventAggregator) : - base(database, eventAggregator) + public BlacklistRepository(IMainDatabase database, IEventAggregator eventAggregator) + : base(database, eventAggregator) { } diff --git a/src/NzbDrone.Core/Blacklisting/BlacklistService.cs b/src/NzbDrone.Core/Blacklisting/BlacklistService.cs index 28a390f72d..fb9bd3ad64 100644 --- a/src/NzbDrone.Core/Blacklisting/BlacklistService.cs +++ b/src/NzbDrone.Core/Blacklisting/BlacklistService.cs @@ -7,8 +7,8 @@ using NzbDrone.Core.Indexers; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Movies.Events; +using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.Blacklisting { @@ -18,6 +18,7 @@ public interface IBlacklistService PagingSpec Paged(PagingSpec pagingSpec); void Delete(int id); } + public class BlacklistService : IBlacklistService, IExecute, @@ -39,7 +40,10 @@ public bool Blacklisted(int movieId, ReleaseInfo release) { var torrentInfo = release as TorrentInfo; - if (torrentInfo == null) return false; + if (torrentInfo == null) + { + return false; + } if (torrentInfo.InfoHash.IsNullOrWhiteSpace()) { @@ -105,7 +109,10 @@ private bool HasSameIndexer(Blacklist item, string indexer) private bool HasSamePublishedDate(Blacklist item, DateTime publishedDate) { - if (!item.PublishedDate.HasValue) return true; + if (!item.PublishedDate.HasValue) + { + return true; + } return item.PublishedDate.Value.AddMinutes(-2) <= publishedDate && item.PublishedDate.Value.AddMinutes(2) >= publishedDate; @@ -113,7 +120,10 @@ private bool HasSamePublishedDate(Blacklist item, DateTime publishedDate) private bool HasSameSize(Blacklist item, long size) { - if (!item.Size.HasValue) return true; + if (!item.Size.HasValue) + { + return true; + } var difference = Math.Abs(item.Size.Value - size); @@ -128,19 +138,19 @@ public void Execute(ClearBlacklistCommand message) public void Handle(DownloadFailedEvent message) { var blacklist = new Blacklist - { - MovieId = message.MovieId, - SourceTitle = message.SourceTitle, - Quality = message.Quality, - Date = DateTime.UtcNow, - PublishedDate = DateTime.Parse(message.Data.GetValueOrDefault("publishedDate")), - Size = long.Parse(message.Data.GetValueOrDefault("size", "0")), - Indexer = message.Data.GetValueOrDefault("indexer"), - Protocol = (DownloadProtocol)Convert.ToInt32(message.Data.GetValueOrDefault("protocol")), - Message = message.Message, - TorrentInfoHash = message.Data.GetValueOrDefault("torrentInfoHash"), - Languages = message.Languages - }; + { + MovieId = message.MovieId, + SourceTitle = message.SourceTitle, + Quality = message.Quality, + Date = DateTime.UtcNow, + PublishedDate = DateTime.Parse(message.Data.GetValueOrDefault("publishedDate")), + Size = long.Parse(message.Data.GetValueOrDefault("size", "0")), + Indexer = message.Data.GetValueOrDefault("indexer"), + Protocol = (DownloadProtocol)Convert.ToInt32(message.Data.GetValueOrDefault("protocol")), + Message = message.Message, + TorrentInfoHash = message.Data.GetValueOrDefault("torrentInfoHash"), + Languages = message.Languages + }; _blacklistRepository.Insert(blacklist); } diff --git a/src/NzbDrone.Core/Configuration/ConfigFileProvider.cs b/src/NzbDrone.Core/Configuration/ConfigFileProvider.cs index ab2d94dc65..e6fae63941 100644 --- a/src/NzbDrone.Core/Configuration/ConfigFileProvider.cs +++ b/src/NzbDrone.Core/Configuration/ConfigFileProvider.cs @@ -101,7 +101,10 @@ public void SaveConfigDictionary(Dictionary configValues) object currentValue; allWithDefaults.TryGetValue(configValue.Key, out currentValue); - if (currentValue == null) continue; + if (currentValue == null) + { + continue; + } var equal = configValue.Value.ToString().Equals(currentValue.ToString()); @@ -260,7 +263,6 @@ public void SetValue(string key, object value) { parentContainer.Add(new XElement(key, valueString)); } - else { parentContainer.Descendants(key).Single().Value = valueString; @@ -334,7 +336,6 @@ private XDocument LoadConfigFile() return xDoc; } } - catch (XmlException ex) { throw new InvalidConfigFileException($"{_configFile} is corrupt is invalid. Please delete the config file and Radarr will recreate it.", ex); diff --git a/src/NzbDrone.Core/Configuration/ConfigRepository.cs b/src/NzbDrone.Core/Configuration/ConfigRepository.cs index 23d3cbd7b8..c8ae80c212 100644 --- a/src/NzbDrone.Core/Configuration/ConfigRepository.cs +++ b/src/NzbDrone.Core/Configuration/ConfigRepository.cs @@ -2,7 +2,6 @@ using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; - namespace NzbDrone.Core.Configuration { public interface IConfigRepository : IBasicRepository @@ -18,7 +17,6 @@ public ConfigRepository(IMainDatabase database, IEventAggregator eventAggregator { } - public Config Get(string key) { return Query.Where(c => c.Key == key).SingleOrDefault(); @@ -30,7 +28,7 @@ public Config Upsert(string key, string value) if (dbValue == null) { - return Insert(new Config {Key = key, Value = value}); + return Insert(new Config { Key = key, Value = value }); } dbValue.Value = value; diff --git a/src/NzbDrone.Core/Configuration/ConfigService.cs b/src/NzbDrone.Core/Configuration/ConfigService.cs index 5d4b9d2cce..664978595a 100644 --- a/src/NzbDrone.Core/Configuration/ConfigService.cs +++ b/src/NzbDrone.Core/Configuration/ConfigService.cs @@ -4,12 +4,12 @@ using System.Linq; using NLog; using NzbDrone.Common.EnsureThat; +using NzbDrone.Common.Http.Proxy; using NzbDrone.Core.Configuration.Events; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Common.Http.Proxy; -using NzbDrone.Core.Security; using NzbDrone.Core.Parser; +using NzbDrone.Core.Security; namespace NzbDrone.Core.Configuration { @@ -57,7 +57,10 @@ public void SaveConfigDictionary(Dictionary configValues) { object currentValue; allWithDefaults.TryGetValue(configValue.Key, out currentValue); - if (currentValue == null || configValue.Value == null) continue; + if (currentValue == null || configValue.Value == null) + { + continue; + } var equal = configValue.Value.ToString().Equals(currentValue.ToString()); diff --git a/src/NzbDrone.Core/Configuration/IConfigService.cs b/src/NzbDrone.Core/Configuration/IConfigService.cs index 4b3cf0978b..8da36b895c 100644 --- a/src/NzbDrone.Core/Configuration/IConfigService.cs +++ b/src/NzbDrone.Core/Configuration/IConfigService.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -using NzbDrone.Core.MediaFiles; using NzbDrone.Common.Http.Proxy; +using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Parser; using NzbDrone.Core.Security; diff --git a/src/NzbDrone.Core/Configuration/InvalidConfigFileException.cs b/src/NzbDrone.Core/Configuration/InvalidConfigFileException.cs index 1251cf30ad..4bed2f2a28 100644 --- a/src/NzbDrone.Core/Configuration/InvalidConfigFileException.cs +++ b/src/NzbDrone.Core/Configuration/InvalidConfigFileException.cs @@ -5,11 +5,13 @@ namespace NzbDrone.Core.Configuration { public class InvalidConfigFileException : NzbDroneException { - public InvalidConfigFileException(string message) : base(message) + public InvalidConfigFileException(string message) + : base(message) { } - public InvalidConfigFileException(string message, Exception innerException) : base(message, innerException) + public InvalidConfigFileException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/CustomFormats/CustomFormat.cs b/src/NzbDrone.Core/CustomFormats/CustomFormat.cs index 3aa08fda7e..8e2e2e2709 100644 --- a/src/NzbDrone.Core/CustomFormats/CustomFormat.cs +++ b/src/NzbDrone.Core/CustomFormats/CustomFormat.cs @@ -9,7 +9,6 @@ public class CustomFormat : ModelBase, IEquatable { public CustomFormat() { - } public CustomFormat(string name, params string[] tags) @@ -31,17 +30,37 @@ public override string ToString() public bool Equals(CustomFormat other) { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; + if (ReferenceEquals(null, other)) + { + return false; + } + + if (ReferenceEquals(this, other)) + { + return true; + } + return int.Equals(Id, other.Id); } public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != this.GetType()) return false; - return Equals((CustomFormat) obj); + if (ReferenceEquals(null, obj)) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } + + if (obj.GetType() != GetType()) + { + return false; + } + + return Equals((CustomFormat)obj); } public override int GetHashCode() @@ -60,9 +79,12 @@ public static string ToExtendedString(this IEnumerable formats) public static List WithNone(this IEnumerable formats) { var list = formats.ToList(); - if (list.Any()) return list; + if (list.Any()) + { + return list; + } - return new List{CustomFormat.None}; + return new List { CustomFormat.None }; } } } diff --git a/src/NzbDrone.Core/CustomFormats/CustomFormatRepository.cs b/src/NzbDrone.Core/CustomFormats/CustomFormatRepository.cs index 205bdec360..0a8e868d9d 100644 --- a/src/NzbDrone.Core/CustomFormats/CustomFormatRepository.cs +++ b/src/NzbDrone.Core/CustomFormats/CustomFormatRepository.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.CustomFormats { public interface ICustomFormatRepository : IBasicRepository { - } public class CustomFormatRepository : BasicRepository, ICustomFormatRepository diff --git a/src/NzbDrone.Core/CustomFormats/CustomFormatService.cs b/src/NzbDrone.Core/CustomFormats/CustomFormatService.cs index 82bf3b3551..3846f8d512 100644 --- a/src/NzbDrone.Core/CustomFormats/CustomFormatService.cs +++ b/src/NzbDrone.Core/CustomFormats/CustomFormatService.cs @@ -23,12 +23,11 @@ public interface ICustomFormatService void Delete(int id); } - public class CustomFormatService : ICustomFormatService, IHandle { private readonly ICustomFormatRepository _formatRepository; - private IProfileService _profileService; private readonly IHistoryService _historyService; + private IProfileService _profileService; public IProfileService ProfileService { @@ -49,8 +48,10 @@ public IProfileService ProfileService public static Dictionary AllCustomFormats; - public CustomFormatService(ICustomFormatRepository formatRepository, ICacheManager cacheManager, - IContainer container, IHistoryService historyService, + public CustomFormatService(ICustomFormatRepository formatRepository, + ICacheManager cacheManager, + IContainer container, + IHistoryService historyService, Logger logger) { _formatRepository = formatRepository; @@ -79,6 +80,7 @@ public CustomFormat Insert(CustomFormat customFormat) _formatRepository.Delete(ret); throw; } + _cache.Clear(); return ret; } @@ -90,27 +92,36 @@ public void Delete(int id) { //First history: var historyRepo = _container.Resolve(); - DeleteInRepo(historyRepo, h => h.Quality.CustomFormats, (h, f) => - { - h.Quality.CustomFormats = f; - return h; - }, id); + DeleteInRepo(historyRepo, + h => h.Quality.CustomFormats, + (h, f) => + { + h.Quality.CustomFormats = f; + return h; + }, + id); //Then Blacklist: var blacklistRepo = _container.Resolve(); - DeleteInRepo(blacklistRepo, h => h.Quality.CustomFormats, (h, f) => - { - h.Quality.CustomFormats = f; - return h; - }, id); + DeleteInRepo(blacklistRepo, + h => h.Quality.CustomFormats, + (h, f) => + { + h.Quality.CustomFormats = f; + return h; + }, + id); //Then MovieFiles: var moviefileRepo = _container.Resolve(); - DeleteInRepo(moviefileRepo, h => h.Quality.CustomFormats, (h, f) => - { - h.Quality.CustomFormats = f; - return h; - }, id); + DeleteInRepo(moviefileRepo, + h => h.Quality.CustomFormats, + (h, f) => + { + h.Quality.CustomFormats = f; + return h; + }, + id); //Then Profiles ProfileService.DeleteCustomFormat(id); @@ -127,8 +138,11 @@ public void Delete(int id) _cache.Clear(); } - private void DeleteInRepo(IBasicRepository repository, Func> queryFunc, - Func, TModel> updateFunc, int customFormatId) where TModel : ModelBase, new() + private void DeleteInRepo(IBasicRepository repository, + Func> queryFunc, + Func, TModel> updateFunc, + int customFormatId) + where TModel : ModelBase, new() { var allItems = repository.All(); diff --git a/src/NzbDrone.Core/CustomFormats/FormatTag.cs b/src/NzbDrone.Core/CustomFormats/FormatTag.cs index 63d896541a..a9de543bb8 100644 --- a/src/NzbDrone.Core/CustomFormats/FormatTag.cs +++ b/src/NzbDrone.Core/CustomFormats/FormatTag.cs @@ -37,13 +37,16 @@ public FormatTag(string raw) // This function is needed for json deserialization to work. private FormatTag() { - } public bool DoesItMatch(ParsedMovieInfo movieInfo) { var match = DoesItMatchWithoutMods(movieInfo); - if (TagModifier.HasFlag(TagModifier.Not)) match = !match; + if (TagModifier.HasFlag(TagModifier.Not)) + { + match = !match; + } + return match; } @@ -62,31 +65,33 @@ private bool DoesItMatchWithoutMods(ParsedMovieInfo movieInfo) { compared = movieInfo.Edition; } + if (TagModifier.HasFlag(TagModifier.Regex)) { - Regex regexValue = (Regex) Value; + Regex regexValue = (Regex)Value; return regexValue.IsMatch(compared); } else { - string stringValue = (string) Value; + string stringValue = (string)Value; return compared.ToLower().Contains(stringValue.Replace(" ", string.Empty).ToLower()); } + case TagType.Language: return movieInfo.Languages.Contains((Language)Value); case TagType.Resolution: - return movieInfo.Quality.Quality.Resolution == (int)(Resolution) Value; + return movieInfo.Quality.Quality.Resolution == (int)(Resolution)Value; case TagType.Modifier: - return movieInfo.Quality.Quality.Modifier == (Modifier) Value; + return movieInfo.Quality.Quality.Modifier == (Modifier)Value; case TagType.Source: - return movieInfo.Quality.Quality.Source == (Source) Value; + return movieInfo.Quality.Quality.Source == (Source)Value; case TagType.Size: var size = (movieInfo.ExtraInfo.GetValueOrDefault("Size", 0.0) as long?) ?? 0; var tuple = Value as (long, long)? ?? (0, 0); return size > tuple.Item1 && size < tuple.Item2; case TagType.Indexer: #if !LIBRARY - return (movieInfo.ExtraInfo.GetValueOrDefault("IndexerFlags") as IndexerFlags?)?.HasFlag((IndexerFlags) Value) == true; + return (movieInfo.ExtraInfo.GetValueOrDefault("IndexerFlags") as IndexerFlags?)?.HasFlag((IndexerFlags)Value) == true; #endif default: return false; @@ -98,9 +103,20 @@ private void ParseRawMatch(Match match) var type = match.Groups["type"].Value.ToLower(); var value = match.Groups["value"].Value.ToLower(); - if (match.Groups["m_re"].Success) TagModifier |= TagModifier.AbsolutelyRequired; - if (match.Groups["m_r"].Success) TagModifier |= TagModifier.Regex; - if (match.Groups["m_n"].Success) TagModifier |= TagModifier.Not; + if (match.Groups["m_re"].Success) + { + TagModifier |= TagModifier.AbsolutelyRequired; + } + + if (match.Groups["m_r"].Success) + { + TagModifier |= TagModifier.Regex; + } + + if (match.Groups["m_n"].Success) + { + TagModifier |= TagModifier.Not; + } switch (type) { @@ -124,6 +140,7 @@ private void ParseRawMatch(Match match) Value = Resolution.R480p; break; } + break; case "s": TagType = TagType.Source; @@ -154,6 +171,7 @@ private void ParseRawMatch(Match match) Value = Source.BLURAY; break; } + break; case "m": TagType = TagType.Modifier; @@ -175,6 +193,7 @@ private void ParseRawMatch(Match match) Value = Modifier.REMUX; break; } + break; case "e": TagType = TagType.Edition; @@ -186,6 +205,7 @@ private void ParseRawMatch(Match match) { Value = value; } + break; case "l": TagType = TagType.Language; @@ -199,7 +219,11 @@ private void ParseRawMatch(Match match) foreach (IndexerFlags flagValue in flagValues) { var flagString = flagValue.ToString(); - if (flagString.ToLower().Replace("_", string.Empty) != value.ToLower().Replace("_", string.Empty)) continue; + if (flagString.ToLower().Replace("_", string.Empty) != value.ToLower().Replace("_", string.Empty)) + { + continue; + } + Value = flagValue; break; } @@ -223,10 +247,10 @@ private void ParseRawMatch(Match match) { Value = value; } + break; } } - } public enum TagType diff --git a/src/NzbDrone.Core/CustomFormats/FormatTagMatchResult.cs b/src/NzbDrone.Core/CustomFormats/FormatTagMatchResult.cs index d31fbd7bd5..ecb14dbd74 100644 --- a/src/NzbDrone.Core/CustomFormats/FormatTagMatchResult.cs +++ b/src/NzbDrone.Core/CustomFormats/FormatTagMatchResult.cs @@ -9,6 +9,7 @@ public FormatTagMatchResult() { GroupMatches = new List(); } + public CustomFormat CustomFormat { get; set; } public List GroupMatches { get; set; } public bool GoodMatch { get; set; } @@ -37,6 +38,7 @@ public bool DidMatch Matches.All(m => m.Value == false)); } } + public Dictionary Matches { get; set; } } } diff --git a/src/NzbDrone.Core/Datastore/BasicRepository.cs b/src/NzbDrone.Core/Datastore/BasicRepository.cs index 344ec01dae..ea70a8db24 100644 --- a/src/NzbDrone.Core/Datastore/BasicRepository.cs +++ b/src/NzbDrone.Core/Datastore/BasicRepository.cs @@ -12,7 +12,8 @@ namespace NzbDrone.Core.Datastore { - public interface IBasicRepository where TModel : ModelBase, new() + public interface IBasicRepository + where TModel : ModelBase, new() { IEnumerable All(); int Count(); @@ -35,7 +36,8 @@ namespace NzbDrone.Core.Datastore PagingSpec GetPaged(PagingSpec pagingSpec); } - public class BasicRepository : IBasicRepository where TModel : ModelBase, new() + public class BasicRepository : IBasicRepository + where TModel : ModelBase, new() { private readonly IDatabase _database; private readonly IEventAggregator _eventAggregator; @@ -183,6 +185,7 @@ public TModel Upsert(TModel model) Insert(model); return model; } + Update(model); return model; } diff --git a/src/NzbDrone.Core/Datastore/Converters/BooleanIntConverter.cs b/src/NzbDrone.Core/Datastore/Converters/BooleanIntConverter.cs index d2ee3dc6bc..bf68e751a4 100644 --- a/src/NzbDrone.Core/Datastore/Converters/BooleanIntConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/BooleanIntConverter.cs @@ -33,7 +33,7 @@ public object FromDB(ColumnMap map, object dbValue) public object ToDB(object clrValue) { - var val = (Nullable)clrValue; + var val = (bool?)clrValue; switch (val) { diff --git a/src/NzbDrone.Core/Datastore/Converters/CommandConverter.cs b/src/NzbDrone.Core/Datastore/Converters/CommandConverter.cs index 0bb97f23a6..a6c641206c 100644 --- a/src/NzbDrone.Core/Datastore/Converters/CommandConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/CommandConverter.cs @@ -25,7 +25,7 @@ public override object FromDB(ConverterContext context) var ordinal = context.DataRecord.GetOrdinal("Name"); var contract = context.DataRecord.GetString(ordinal); - var impType = typeof (Command).Assembly.FindTypeByName(contract + "Command"); + var impType = typeof(Command).Assembly.FindTypeByName(contract + "Command"); if (impType == null) { diff --git a/src/NzbDrone.Core/Datastore/Converters/CustomFormatIntConverter.cs b/src/NzbDrone.Core/Datastore/Converters/CustomFormatIntConverter.cs index 237d6bcd47..f6dfc810d1 100644 --- a/src/NzbDrone.Core/Datastore/Converters/CustomFormatIntConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/CustomFormatIntConverter.cs @@ -38,14 +38,17 @@ public object FromDB(ColumnMap map, object dbValue) public object ToDB(object clrValue) { - if(clrValue == DBNull.Value) return null; + if (clrValue == DBNull.Value) + { + return null; + } - if(!(clrValue is CustomFormat)) + if (!(clrValue is CustomFormat)) { throw new InvalidOperationException("Attempted to save a quality definition that isn't really a quality definition"); } - var quality = (CustomFormat) clrValue; + var quality = (CustomFormat)clrValue; if (CustomFormatService.AllCustomFormats?.ContainsKey(quality.Id) == false) { diff --git a/src/NzbDrone.Core/Datastore/Converters/EmbeddedDocumentConverter.cs b/src/NzbDrone.Core/Datastore/Converters/EmbeddedDocumentConverter.cs index 82d00756d0..045ba64e26 100644 --- a/src/NzbDrone.Core/Datastore/Converters/EmbeddedDocumentConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/EmbeddedDocumentConverter.cs @@ -2,18 +2,18 @@ using Marr.Data.Converters; using Marr.Data.Mapping; using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Serialization; namespace NzbDrone.Core.Datastore.Converters { public class EmbeddedDocumentConverter : IConverter { - private readonly JsonSerializerSettings SerializerSetting; + private readonly JsonSerializerSettings _serializerSetting; public EmbeddedDocumentConverter(params JsonConverter[] converters) { - SerializerSetting = new JsonSerializerSettings + _serializerSetting = new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, @@ -22,12 +22,12 @@ public EmbeddedDocumentConverter(params JsonConverter[] converters) ContractResolver = new CamelCasePropertyNamesContractResolver() }; - SerializerSetting.Converters.Add(new StringEnumConverter { NamingStrategy = new CamelCaseNamingStrategy() }); - SerializerSetting.Converters.Add(new VersionConverter()); + _serializerSetting.Converters.Add(new StringEnumConverter { NamingStrategy = new CamelCaseNamingStrategy() }); + _serializerSetting.Converters.Add(new VersionConverter()); foreach (var converter in converters) { - SerializerSetting.Converters.Add(converter); + _serializerSetting.Converters.Add(converter); } } @@ -44,7 +44,8 @@ public virtual object FromDB(ConverterContext context) { return null; } - return JsonConvert.DeserializeObject(stringValue, context.ColumnMap.FieldType, SerializerSetting); + + return JsonConvert.DeserializeObject(stringValue, context.ColumnMap.FieldType, _serializerSetting); } public object FromDB(ColumnMap map, object dbValue) @@ -54,10 +55,17 @@ public object FromDB(ColumnMap map, object dbValue) public object ToDB(object clrValue) { - if (clrValue == null) return null; - if (clrValue == DBNull.Value) return DBNull.Value; + if (clrValue == null) + { + return null; + } - return JsonConvert.SerializeObject(clrValue, SerializerSetting); + if (clrValue == DBNull.Value) + { + return DBNull.Value; + } + + return JsonConvert.SerializeObject(clrValue, _serializerSetting); } public Type DbType => typeof(string); diff --git a/src/NzbDrone.Core/Datastore/Converters/LanguageIntConverter.cs b/src/NzbDrone.Core/Datastore/Converters/LanguageIntConverter.cs index 58f26970eb..f0c4d705b1 100644 --- a/src/NzbDrone.Core/Datastore/Converters/LanguageIntConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/LanguageIntConverter.cs @@ -27,7 +27,10 @@ public object FromDB(ColumnMap map, object dbValue) public object ToDB(object clrValue) { - if (clrValue == DBNull.Value) return 0; + if (clrValue == DBNull.Value) + { + return 0; + } if (clrValue as Language == null) { diff --git a/src/NzbDrone.Core/Datastore/Converters/ProviderSettingConverter.cs b/src/NzbDrone.Core/Datastore/Converters/ProviderSettingConverter.cs index c2e2efd188..17590c4f1b 100644 --- a/src/NzbDrone.Core/Datastore/Converters/ProviderSettingConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/ProviderSettingConverter.cs @@ -25,8 +25,7 @@ public override object FromDB(ConverterContext context) var ordinal = context.DataRecord.GetOrdinal("ConfigContract"); var contract = context.DataRecord.GetString(ordinal); - - var impType = typeof (IProviderConfig).Assembly.FindTypeByName(contract); + var impType = typeof(IProviderConfig).Assembly.FindTypeByName(contract); if (impType == null) { @@ -35,6 +34,5 @@ public override object FromDB(ConverterContext context) return Json.Deserialize(stringValue, impType); } - } } diff --git a/src/NzbDrone.Core/Datastore/Converters/QualityIntConverter.cs b/src/NzbDrone.Core/Datastore/Converters/QualityIntConverter.cs index 72a3cb53a2..8487780de4 100644 --- a/src/NzbDrone.Core/Datastore/Converters/QualityIntConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/QualityIntConverter.cs @@ -1,8 +1,8 @@ using System; using Marr.Data.Converters; using Marr.Data.Mapping; -using NzbDrone.Core.Qualities; using Newtonsoft.Json; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Datastore.Converters { @@ -27,7 +27,10 @@ public object FromDB(ColumnMap map, object dbValue) public object ToDB(object clrValue) { - if (clrValue == DBNull.Value) return 0; + if (clrValue == DBNull.Value) + { + return 0; + } if (clrValue as Quality == null) { diff --git a/src/NzbDrone.Core/Datastore/Converters/QualityTagStringConverter.cs b/src/NzbDrone.Core/Datastore/Converters/QualityTagStringConverter.cs index de8df90ba7..ea2e8ea72e 100644 --- a/src/NzbDrone.Core/Datastore/Converters/QualityTagStringConverter.cs +++ b/src/NzbDrone.Core/Datastore/Converters/QualityTagStringConverter.cs @@ -27,14 +27,17 @@ public object FromDB(ColumnMap map, object dbValue) public object ToDB(object clrValue) { - if(clrValue == DBNull.Value) return 0; + if (clrValue == DBNull.Value) + { + return 0; + } - if(!(clrValue is FormatTag)) + if (!(clrValue is FormatTag)) { throw new InvalidOperationException("Attempted to save a quality tag that isn't really a quality tag"); } - var quality = (FormatTag) clrValue; + var quality = (FormatTag)clrValue; return quality.Raw; } diff --git a/src/NzbDrone.Core/Datastore/CorruptDatabaseException.cs b/src/NzbDrone.Core/Datastore/CorruptDatabaseException.cs index 4493ca1b5f..c6763a774f 100644 --- a/src/NzbDrone.Core/Datastore/CorruptDatabaseException.cs +++ b/src/NzbDrone.Core/Datastore/CorruptDatabaseException.cs @@ -5,19 +5,23 @@ namespace NzbDrone.Core.Datastore { public class CorruptDatabaseException : RadarrStartupException { - public CorruptDatabaseException(string message, params object[] args) : base(message, args) + public CorruptDatabaseException(string message, params object[] args) + : base(message, args) { } - public CorruptDatabaseException(string message) : base(message) + public CorruptDatabaseException(string message) + : base(message) { } - public CorruptDatabaseException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public CorruptDatabaseException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } - public CorruptDatabaseException(string message, Exception innerException) : base(message, innerException) + public CorruptDatabaseException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/Datastore/Database.cs b/src/NzbDrone.Core/Datastore/Database.cs index 1ff4fba495..047cac7732 100644 --- a/src/NzbDrone.Core/Datastore/Database.cs +++ b/src/NzbDrone.Core/Datastore/Database.cs @@ -62,6 +62,7 @@ public void Vacuum() { db.ExecuteNonQuery("Vacuum;"); } + _logger.Info("{0} database compressed", _databaseName); } catch (Exception e) diff --git a/src/NzbDrone.Core/Datastore/DbFactory.cs b/src/NzbDrone.Core/Datastore/DbFactory.cs index 07e406595a..1aeb21ff80 100644 --- a/src/NzbDrone.Core/Datastore/DbFactory.cs +++ b/src/NzbDrone.Core/Datastore/DbFactory.cs @@ -10,7 +10,6 @@ using NzbDrone.Common.Instrumentation; using NzbDrone.Core.Datastore.Migration.Framework; - namespace NzbDrone.Core.Datastore { public interface IDbFactory @@ -83,6 +82,7 @@ public IDatabase Create(MigrationContext migrationContext) break; } + case MigrationType.Log: { connectionString = _connectionStringFactory.LogDbConnectionString; @@ -90,6 +90,7 @@ public IDatabase Create(MigrationContext migrationContext) break; } + default: { throw new ArgumentException("Invalid MigrationType"); diff --git a/src/NzbDrone.Core/Datastore/Events/ModelEvent.cs b/src/NzbDrone.Core/Datastore/Events/ModelEvent.cs index fe87d16762..d5b02c8cb5 100644 --- a/src/NzbDrone.Core/Datastore/Events/ModelEvent.cs +++ b/src/NzbDrone.Core/Datastore/Events/ModelEvent.cs @@ -2,7 +2,7 @@ namespace NzbDrone.Core.Datastore.Events { - public class ModelEvent : IEvent + public class ModelEvent : IEvent { public TModel Model { get; set; } public ModelAction Action { get; set; } diff --git a/src/NzbDrone.Core/Datastore/Extensions/MappingExtensions.cs b/src/NzbDrone.Core/Datastore/Extensions/MappingExtensions.cs index 39a831a092..96cdd9c0dc 100644 --- a/src/NzbDrone.Core/Datastore/Extensions/MappingExtensions.cs +++ b/src/NzbDrone.Core/Datastore/Extensions/MappingExtensions.cs @@ -8,20 +8,22 @@ namespace NzbDrone.Core.Datastore.Extensions { public static class MappingExtensions { - - public static ColumnMapBuilder MapResultSet(this FluentMappings.MappingsFluentEntity mapBuilder) where T : ResultSet, new() + public static ColumnMapBuilder MapResultSet(this FluentMappings.MappingsFluentEntity mapBuilder) + where T : ResultSet, new() { return mapBuilder .Columns .AutoMapPropertiesWhere(IsMappableProperty); } - public static ColumnMapBuilder RegisterDefinition(this FluentMappings.MappingsFluentEntity mapBuilder, string tableName = null) where T : ProviderDefinition, new() + public static ColumnMapBuilder RegisterDefinition(this FluentMappings.MappingsFluentEntity mapBuilder, string tableName = null) + where T : ProviderDefinition, new() { return RegisterModel(mapBuilder, tableName).Ignore(c => c.ImplementationName); } - public static ColumnMapBuilder RegisterModel(this FluentMappings.MappingsFluentEntity mapBuilder, string tableName = null) where T : ModelBase, new() + public static ColumnMapBuilder RegisterModel(this FluentMappings.MappingsFluentEntity mapBuilder, string tableName = null) + where T : ModelBase, new() { return mapBuilder.Table.MapTable(tableName) .Columns @@ -37,15 +39,17 @@ public static RelationshipBuilder AutoMapChildModels(this ColumnMapBuilder { return mapBuilder.Relationships.AutoMapPropertiesWhere(m => m.MemberType == MemberTypes.Property && - typeof(ModelBase).IsAssignableFrom(((PropertyInfo) m).PropertyType)); + typeof(ModelBase).IsAssignableFrom(((PropertyInfo)m).PropertyType)); } public static bool IsMappableProperty(MemberInfo memberInfo) { var propertyInfo = memberInfo as PropertyInfo; - if (propertyInfo == null) return false; - + if (propertyInfo == null) + { + return false; + } if (!propertyInfo.IsReadable() || !propertyInfo.IsWritable()) { diff --git a/src/NzbDrone.Core/Datastore/Extensions/PagingSpecExtensions.cs b/src/NzbDrone.Core/Datastore/Extensions/PagingSpecExtensions.cs index f81aacad32..46d217585c 100644 --- a/src/NzbDrone.Core/Datastore/Extensions/PagingSpecExtensions.cs +++ b/src/NzbDrone.Core/Datastore/Extensions/PagingSpecExtensions.cs @@ -13,12 +13,15 @@ public static Expression> OrderByClause(this Paging public static int PagingOffset(this PagingSpec pagingSpec) { - return (pagingSpec.Page - 1)*pagingSpec.PageSize; + return (pagingSpec.Page - 1) * pagingSpec.PageSize; } public static Marr.Data.QGen.SortDirection ToSortDirection(this PagingSpec pagingSpec) { - if (pagingSpec.SortDirection == SortDirection.Descending) return Marr.Data.QGen.SortDirection.Desc; + if (pagingSpec.SortDirection == SortDirection.Descending) + { + return Marr.Data.QGen.SortDirection.Desc; + } return Marr.Data.QGen.SortDirection.Asc; } @@ -41,4 +44,3 @@ private static Expression> CreateExpression(string } } } - diff --git a/src/NzbDrone.Core/Datastore/Extensions/RelationshipExtensions.cs b/src/NzbDrone.Core/Datastore/Extensions/RelationshipExtensions.cs index 7c91fec6aa..490bb49b41 100644 --- a/src/NzbDrone.Core/Datastore/Extensions/RelationshipExtensions.cs +++ b/src/NzbDrone.Core/Datastore/Extensions/RelationshipExtensions.cs @@ -19,8 +19,7 @@ public static RelationshipBuilder HasOne(this Relation { var id = childIdSelector(parent); return db.Query().Where(c => c.Id == id).SingleOrDefault(); - } - ); + }); } public static RelationshipBuilder Relationship(this ColumnMapBuilder mapBuilder) diff --git a/src/NzbDrone.Core/Datastore/LazyList.cs b/src/NzbDrone.Core/Datastore/LazyList.cs index ebbc51b8a9..193a118123 100644 --- a/src/NzbDrone.Core/Datastore/LazyList.cs +++ b/src/NzbDrone.Core/Datastore/LazyList.cs @@ -8,13 +8,11 @@ public class LazyList : LazyLoaded> public LazyList() : this(new List()) { - } public LazyList(IEnumerable items) : base(new List(items)) { - } public static implicit operator LazyList(List val) diff --git a/src/NzbDrone.Core/Datastore/LogDatabase.cs b/src/NzbDrone.Core/Datastore/LogDatabase.cs index e1c9c3a205..6608a144fe 100644 --- a/src/NzbDrone.Core/Datastore/LogDatabase.cs +++ b/src/NzbDrone.Core/Datastore/LogDatabase.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.Datastore { public interface ILogDatabase : IDatabase { - } public class LogDatabase : ILogDatabase diff --git a/src/NzbDrone.Core/Datastore/MainDatabase.cs b/src/NzbDrone.Core/Datastore/MainDatabase.cs index 869c3a6da3..5faf4497c1 100644 --- a/src/NzbDrone.Core/Datastore/MainDatabase.cs +++ b/src/NzbDrone.Core/Datastore/MainDatabase.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.Datastore { public interface IMainDatabase : IDatabase { - } public class MainDatabase : IMainDatabase diff --git a/src/NzbDrone.Core/Datastore/Migration/001_initial_setup.cs b/src/NzbDrone.Core/Datastore/Migration/001_initial_setup.cs index 0042de0646..44f28ce929 100644 --- a/src/NzbDrone.Core/Datastore/Migration/001_initial_setup.cs +++ b/src/NzbDrone.Core/Datastore/Migration/001_initial_setup.cs @@ -66,7 +66,6 @@ protected override void MainDbUpgrade() .WithColumn("Certification").AsString().Nullable() .WithColumn("AddOptions").AsString().Nullable(); - Create.TableForModel("Seasons") .WithColumn("SeriesId").AsInt32() .WithColumn("SeasonNumber").AsInt32() @@ -143,7 +142,6 @@ protected override void MainDbUpgrade() .WithColumn("TvdbId").AsInt32() .WithColumn("SeasonNumber").AsInt32(); - Create.TableForModel("NamingConfig") .WithColumn("UseSceneName").AsBoolean() .WithColumn("Separator").AsString() diff --git a/src/NzbDrone.Core/Datastore/Migration/004_updated_history.cs b/src/NzbDrone.Core/Datastore/Migration/004_updated_history.cs index 5ebc51ac89..0eaf4da5b2 100644 --- a/src/NzbDrone.Core/Datastore/Migration/004_updated_history.cs +++ b/src/NzbDrone.Core/Datastore/Migration/004_updated_history.cs @@ -10,7 +10,6 @@ protected override void MainDbUpgrade() { Delete.Table("History"); - Create.TableForModel("History") .WithColumn("EpisodeId").AsInt32() .WithColumn("SeriesId").AsInt32() diff --git a/src/NzbDrone.Core/Datastore/Migration/018_remove_duplicates.cs b/src/NzbDrone.Core/Datastore/Migration/018_remove_duplicates.cs index d788dd7dc6..dbe11a6a95 100644 --- a/src/NzbDrone.Core/Datastore/Migration/018_remove_duplicates.cs +++ b/src/NzbDrone.Core/Datastore/Migration/018_remove_duplicates.cs @@ -1,9 +1,9 @@ -using FluentMigrator; -using NzbDrone.Core.Datastore.Migration.Framework; -using System.Linq; -using System.Data; +using System; using System.Collections.Generic; -using System; +using System.Data; +using System.Linq; +using FluentMigrator; +using NzbDrone.Core.Datastore.Migration.Framework; namespace NzbDrone.Core.Datastore.Migration { diff --git a/src/NzbDrone.Core/Datastore/Migration/019_restore_unique_constraints.cs b/src/NzbDrone.Core/Datastore/Migration/019_restore_unique_constraints.cs index bf70a9532c..776371f94a 100644 --- a/src/NzbDrone.Core/Datastore/Migration/019_restore_unique_constraints.cs +++ b/src/NzbDrone.Core/Datastore/Migration/019_restore_unique_constraints.cs @@ -17,6 +17,5 @@ protected override void MainDbUpgrade() Create.Index().OnTable("Series").OnColumn("TitleSlug").Unique(); Create.Index().OnTable("Episodes").OnColumn("TvDbEpisodeId").Unique(); } - } } diff --git a/src/NzbDrone.Core/Datastore/Migration/020_add_year_and_seasons_to_series.cs b/src/NzbDrone.Core/Datastore/Migration/020_add_year_and_seasons_to_series.cs index 0e2136141b..bfbf78a777 100644 --- a/src/NzbDrone.Core/Datastore/Migration/020_add_year_and_seasons_to_series.cs +++ b/src/NzbDrone.Core/Datastore/Migration/020_add_year_and_seasons_to_series.cs @@ -54,7 +54,7 @@ private void ConvertSeasons(IDbConnection conn, IDbTransaction tran) using (IDbCommand updateCmd = conn.CreateCommand()) { - var text = string.Format("UPDATE Series SET Seasons = '{0}' WHERE Id = {1}", seasons.ToJson() , seriesId); + var text = string.Format("UPDATE Series SET Seasons = '{0}' WHERE Id = {1}", seasons.ToJson(), seriesId); updateCmd.Transaction = tran; updateCmd.CommandText = text; diff --git a/src/NzbDrone.Core/Datastore/Migration/027_fix_omgwtfnzbs.cs b/src/NzbDrone.Core/Datastore/Migration/027_fix_omgwtfnzbs.cs index d7b8b31fc9..daa6699bcd 100644 --- a/src/NzbDrone.Core/Datastore/Migration/027_fix_omgwtfnzbs.cs +++ b/src/NzbDrone.Core/Datastore/Migration/027_fix_omgwtfnzbs.cs @@ -9,12 +9,12 @@ public class fix_omgwtfnzbs : NzbDroneMigrationBase protected override void MainDbUpgrade() { Update.Table("Indexers") - .Set(new {ConfigContract = "OmgwtfnzbsSettings"}) - .Where(new {Implementation = "Omgwtfnzbs"}); + .Set(new { ConfigContract = "OmgwtfnzbsSettings" }) + .Where(new { Implementation = "Omgwtfnzbs" }); Update.Table("Indexers") - .Set(new {Settings = "{}"}) - .Where(new {Implementation = "Omgwtfnzbs", Settings = (string) null}); + .Set(new { Settings = "{}" }) + .Where(new { Implementation = "Omgwtfnzbs", Settings = (string)null }); Update.Table("Indexers") .Set(new { Settings = "{}" }) diff --git a/src/NzbDrone.Core/Datastore/Migration/029_add_formats_to_naming_config.cs b/src/NzbDrone.Core/Datastore/Migration/029_add_formats_to_naming_config.cs index 1bce60081f..ca8c3e2c16 100644 --- a/src/NzbDrone.Core/Datastore/Migration/029_add_formats_to_naming_config.cs +++ b/src/NzbDrone.Core/Datastore/Migration/029_add_formats_to_naming_config.cs @@ -53,7 +53,6 @@ private void ConvertConfig(IDbConnection conn, IDbTransaction tran) { seriesTitlePattern = "{Series.Title}"; } - else { seriesTitlePattern = "{Series Title}"; @@ -70,20 +69,21 @@ private void ConvertConfig(IDbConnection conn, IDbTransaction tran) { episodeTitlePattern += "{Episode.Title}"; } - else { episodeTitlePattern += "{Episode Title}"; } } - var standardEpisodeFormat = string.Format("{0}{1}{2}", seriesTitlePattern, - GetNumberStyle(numberStyle).Pattern, - episodeTitlePattern); + var standardEpisodeFormat = string.Format("{0}{1}{2}", + seriesTitlePattern, + GetNumberStyle(numberStyle).Pattern, + episodeTitlePattern); - var dailyEpisodeFormat = string.Format("{0}{1}{2}", seriesTitlePattern, - dailyEpisodePattern, - episodeTitlePattern); + var dailyEpisodeFormat = string.Format("{0}{1}{2}", + seriesTitlePattern, + dailyEpisodePattern, + episodeTitlePattern); if (includeQuality) { @@ -121,7 +121,6 @@ private void ConvertConfig(IDbConnection conn, IDbTransaction tran) Name = "1x05", Pattern = "{season}x{episode:00}", EpisodeSeparator = "x" - }, new { diff --git a/src/NzbDrone.Core/Datastore/Migration/033_add_api_key_to_pushover.cs b/src/NzbDrone.Core/Datastore/Migration/033_add_api_key_to_pushover.cs index 670d1f8abe..edd93183b6 100644 --- a/src/NzbDrone.Core/Datastore/Migration/033_add_api_key_to_pushover.cs +++ b/src/NzbDrone.Core/Datastore/Migration/033_add_api_key_to_pushover.cs @@ -44,8 +44,8 @@ private void UpdatePushoverSettings(IDbConnection conn, IDbTransaction tran) var text = string.Format("UPDATE Notifications " + "SET Settings = '{0}'" + "WHERE Id = {1}", - settings.ToJson(), id - ); + settings.ToJson(), + id); updateCmd.Transaction = tran; updateCmd.CommandText = text; diff --git a/src/NzbDrone.Core/Datastore/Migration/036_update_with_quality_converters.cs b/src/NzbDrone.Core/Datastore/Migration/036_update_with_quality_converters.cs index e98e667a86..f7d3cf386b 100644 --- a/src/NzbDrone.Core/Datastore/Migration/036_update_with_quality_converters.cs +++ b/src/NzbDrone.Core/Datastore/Migration/036_update_with_quality_converters.cs @@ -1,12 +1,12 @@ -using FluentMigrator; -using NzbDrone.Core.Datastore.Migration.Framework; +using System.Collections.Generic; using System.Data; using System.Linq; +using FluentMigrator; using NzbDrone.Common.Serializer; +using NzbDrone.Core.Datastore.Converters; +using NzbDrone.Core.Datastore.Migration.Framework; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; -using System.Collections.Generic; -using NzbDrone.Core.Datastore.Converters; namespace NzbDrone.Core.Datastore.Migration { @@ -90,10 +90,10 @@ private void ConvertQualityModel(IDbConnection conn, IDbTransaction tran, string } var qualityNewJson = qualityModelConverter.ToDB(new DestinationQualityModel036 - { - Quality = sourceQuality.Quality.Id, - Proper = sourceQuality.Proper - }); + { + Quality = sourceQuality.Quality.Id, + Proper = sourceQuality.Proper + }); using (IDbCommand updateCmd = conn.CreateCommand()) { diff --git a/src/NzbDrone.Core/Datastore/Migration/037_add_configurable_qualities.cs b/src/NzbDrone.Core/Datastore/Migration/037_add_configurable_qualities.cs index 2e272db099..75f08ff349 100644 --- a/src/NzbDrone.Core/Datastore/Migration/037_add_configurable_qualities.cs +++ b/src/NzbDrone.Core/Datastore/Migration/037_add_configurable_qualities.cs @@ -1,7 +1,7 @@ -using FluentMigrator; -using NzbDrone.Core.Datastore.Migration.Framework; -using System.Data; +using System.Data; using System.Linq; +using FluentMigrator; +using NzbDrone.Core.Datastore.Migration.Framework; using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Datastore.Migration diff --git a/src/NzbDrone.Core/Datastore/Migration/043_convert_config_to_download_clients.cs b/src/NzbDrone.Core/Datastore/Migration/043_convert_config_to_download_clients.cs index 505962776d..62c3fb7c3a 100644 --- a/src/NzbDrone.Core/Datastore/Migration/043_convert_config_to_download_clients.cs +++ b/src/NzbDrone.Core/Datastore/Migration/043_convert_config_to_download_clients.cs @@ -48,21 +48,20 @@ private void ConvertToThingyProvder(IDbConnection conn, IDbTransaction tran) if (client.Equals("sabnzbd", StringComparison.InvariantCultureIgnoreCase)) { var settings = new ClientSettingsForMigration - { - Host = GetConfigValue(config, "SabHost", "localhost"), - Port = GetConfigValue(config, "SabPort", 8080), - ApiKey = GetConfigValue(config, "SabApiKey", ""), - Username = GetConfigValue(config, "SabUsername", ""), - Password = GetConfigValue(config, "SabPassword", ""), - TvCategory = GetConfigValue(config, "SabTvCategory", "tv"), - RecentTvPriority = GetSabnzbdPriority(GetConfigValue(config, "NzbgetRecentTvPriority", "Default")), - OlderTvPriority = GetSabnzbdPriority(GetConfigValue(config, "NzbgetOlderTvPriority", "Default")), - UseSsl = GetConfigValue(config, "SabUseSsl", false) - }; + { + Host = GetConfigValue(config, "SabHost", "localhost"), + Port = GetConfigValue(config, "SabPort", 8080), + ApiKey = GetConfigValue(config, "SabApiKey", ""), + Username = GetConfigValue(config, "SabUsername", ""), + Password = GetConfigValue(config, "SabPassword", ""), + TvCategory = GetConfigValue(config, "SabTvCategory", "tv"), + RecentTvPriority = GetSabnzbdPriority(GetConfigValue(config, "NzbgetRecentTvPriority", "Default")), + OlderTvPriority = GetSabnzbdPriority(GetConfigValue(config, "NzbgetOlderTvPriority", "Default")), + UseSsl = GetConfigValue(config, "SabUseSsl", false) + }; AddDownloadClient(conn, tran, "Sabnzbd", "Sabnzbd", settings.ToJson(), "SabnzbdSettings", 1); } - else if (client.Equals("nzbget", StringComparison.InvariantCultureIgnoreCase)) { var settings = new ClientSettingsForMigration @@ -78,17 +77,15 @@ private void ConvertToThingyProvder(IDbConnection conn, IDbTransaction tran) AddDownloadClient(conn, tran, "Nzbget", "Nzbget", settings.ToJson(), "NzbgetSettings", 1); } - else if (client.Equals("pneumatic", StringComparison.InvariantCultureIgnoreCase)) { var settings = new FolderSettingsForMigration - { - Folder = GetConfigValue(config, "PneumaticFolder", "") - }; + { + Folder = GetConfigValue(config, "PneumaticFolder", "") + }; AddDownloadClient(conn, tran, "Pneumatic", "Pneumatic", settings.ToJson(), "FolderSettings", 1); } - else if (client.Equals("blackhole", StringComparison.InvariantCultureIgnoreCase)) { var settings = new FolderSettingsForMigration @@ -108,14 +105,19 @@ private T GetConfigValue(Dictionary config, string key, T def if (config.ContainsKey(key)) { - return (T) Convert.ChangeType(config[key], typeof (T)); + return (T)Convert.ChangeType(config[key], typeof(T)); } return defaultValue; } - private void AddDownloadClient(IDbConnection conn, IDbTransaction tran, string name, string implementation, string settings, - string configContract, int protocol) + private void AddDownloadClient(IDbConnection conn, + IDbTransaction tran, + string name, + string implementation, + string settings, + string configContract, + int protocol) { using (IDbCommand updateCmd = conn.CreateCommand()) { diff --git a/src/NzbDrone.Core/Datastore/Migration/048_add_title_to_scenemappings.cs b/src/NzbDrone.Core/Datastore/Migration/048_add_title_to_scenemappings.cs index 4a2e94bbfc..af5c7359c9 100644 --- a/src/NzbDrone.Core/Datastore/Migration/048_add_title_to_scenemappings.cs +++ b/src/NzbDrone.Core/Datastore/Migration/048_add_title_to_scenemappings.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.Datastore.Migration.Framework; -using FluentMigrator; +using FluentMigrator; +using NzbDrone.Core.Datastore.Migration.Framework; namespace NzbDrone.Core.Datastore.Migration { diff --git a/src/NzbDrone.Core/Datastore/Migration/050_add_hash_to_metadata_files.cs b/src/NzbDrone.Core/Datastore/Migration/050_add_hash_to_metadata_files.cs index 8986a7fba3..7f97ec9937 100644 --- a/src/NzbDrone.Core/Datastore/Migration/050_add_hash_to_metadata_files.cs +++ b/src/NzbDrone.Core/Datastore/Migration/050_add_hash_to_metadata_files.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.Datastore.Migration.Framework; -using FluentMigrator; +using FluentMigrator; +using NzbDrone.Core.Datastore.Migration.Framework; namespace NzbDrone.Core.Datastore.Migration { diff --git a/src/NzbDrone.Core/Datastore/Migration/051_download_client_import.cs b/src/NzbDrone.Core/Datastore/Migration/051_download_client_import.cs index ff81b765ea..2c314bd738 100644 --- a/src/NzbDrone.Core/Datastore/Migration/051_download_client_import.cs +++ b/src/NzbDrone.Core/Datastore/Migration/051_download_client_import.cs @@ -1,13 +1,13 @@ using System; -using System.Data; -using System.Linq; using System.Collections.Generic; +using System.Data; +using System.IO; +using System.Linq; using FluentMigrator; using Newtonsoft.Json; using NzbDrone.Common.Extensions; using NzbDrone.Common.Serializer; using NzbDrone.Core.Datastore.Migration.Framework; -using System.IO; namespace NzbDrone.Core.Datastore.Migration { @@ -148,15 +148,15 @@ private void AssociateImportedHistoryItems(IDbConnection conn, IDbTransaction tr while (historyRead.Read()) { historyItems.Add(new MigrationHistoryItem - { - Id = historyRead.GetInt32(0), - EpisodeId = historyRead.GetInt32(1), - SeriesId = historyRead.GetInt32(2), - SourceTitle = historyRead.GetString(3), - Date = historyRead.GetDateTime(4), - Data = Json.Deserialize>(historyRead.GetString(5)), - EventType = (MigrationHistoryEventType)historyRead.GetInt32(6) - }); + { + Id = historyRead.GetInt32(0), + EpisodeId = historyRead.GetInt32(1), + SeriesId = historyRead.GetInt32(2), + SourceTitle = historyRead.GetString(3), + Date = historyRead.GetDateTime(4), + Data = Json.Deserialize>(historyRead.GetString(5)), + EventType = (MigrationHistoryEventType)historyRead.GetInt32(6) + }); } } } @@ -180,12 +180,19 @@ private void AssociateImportedHistoryItems(IDbConnection conn, IDbTransaction tr for (int i = 0; i < list.Count - 1; i++) { var grabbedEvent = list[i]; - if (grabbedEvent.EventType != MigrationHistoryEventType.Grabbed) continue; - if (grabbedEvent.Data.GetValueOrDefault("downloadClient") == null || grabbedEvent.Data.GetValueOrDefault("downloadClientId") == null) continue; + if (grabbedEvent.EventType != MigrationHistoryEventType.Grabbed) + { + continue; + } + + if (grabbedEvent.Data.GetValueOrDefault("downloadClient") == null || grabbedEvent.Data.GetValueOrDefault("downloadClientId") == null) + { + continue; + } // Check if it is already associated with a failed/imported event. int j; - for (j = i + 1; j < list.Count;j++) + for (j = i + 1; j < list.Count; j++) { if (list[j].EventType != MigrationHistoryEventType.DownloadFolderImported && list[j].EventType != MigrationHistoryEventType.DownloadFailed) @@ -208,7 +215,10 @@ private void AssociateImportedHistoryItems(IDbConnection conn, IDbTransaction tr } var importedEvent = list[i + 1]; - if (importedEvent.EventType != MigrationHistoryEventType.DownloadFolderImported) continue; + if (importedEvent.EventType != MigrationHistoryEventType.DownloadFolderImported) + { + continue; + } var droppedPath = importedEvent.Data.GetValueOrDefault("droppedPath"); if (droppedPath != null && new FileInfo(droppedPath).Directory.Name == grabbedEvent.SourceTitle) diff --git a/src/NzbDrone.Core/Datastore/Migration/052_add_columns_for_anime.cs b/src/NzbDrone.Core/Datastore/Migration/052_add_columns_for_anime.cs index e781ca0100..e0dba24961 100644 --- a/src/NzbDrone.Core/Datastore/Migration/052_add_columns_for_anime.cs +++ b/src/NzbDrone.Core/Datastore/Migration/052_add_columns_for_anime.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.Datastore.Migration.Framework; -using FluentMigrator; +using FluentMigrator; +using NzbDrone.Core.Datastore.Migration.Framework; namespace NzbDrone.Core.Datastore.Migration { diff --git a/src/NzbDrone.Core/Datastore/Migration/057_convert_episode_file_path_to_relative.cs b/src/NzbDrone.Core/Datastore/Migration/057_convert_episode_file_path_to_relative.cs index a1bf307fd3..7fcd9c31dc 100644 --- a/src/NzbDrone.Core/Datastore/Migration/057_convert_episode_file_path_to_relative.cs +++ b/src/NzbDrone.Core/Datastore/Migration/057_convert_episode_file_path_to_relative.cs @@ -14,7 +14,6 @@ protected override void MainDbUpgrade() //TODO: Add unique contraint for series ID and Relative Path //TODO: Warn if multiple series share the same path - Execute.WithConnection(UpdateRelativePaths); } diff --git a/src/NzbDrone.Core/Datastore/Migration/062_convert_quality_models.cs b/src/NzbDrone.Core/Datastore/Migration/062_convert_quality_models.cs index cc9cea68ae..0087345dbd 100644 --- a/src/NzbDrone.Core/Datastore/Migration/062_convert_quality_models.cs +++ b/src/NzbDrone.Core/Datastore/Migration/062_convert_quality_models.cs @@ -46,7 +46,10 @@ private void ConvertQualityModelsOnTable(IDbConnection conn, IDbTransaction tran var newQualityModel = new QualityModel062 { Quality = quality.Quality, Revision = new Revision() }; if (quality.Proper) + { newQualityModel.Revision.Version = 2; + } + var newQualityJson = newQualityModel.ToJson(); qualitiesToUpdate.Add(qualityJson, newQualityJson); diff --git a/src/NzbDrone.Core/Datastore/Migration/069_quality_proper.cs b/src/NzbDrone.Core/Datastore/Migration/069_quality_proper.cs index 9db5f2955f..6185e0fd17 100644 --- a/src/NzbDrone.Core/Datastore/Migration/069_quality_proper.cs +++ b/src/NzbDrone.Core/Datastore/Migration/069_quality_proper.cs @@ -60,7 +60,7 @@ private string GetNewFormat(string currentFormat) foreach (Match match in matches) { var tokenMatch = GetTokenMatch(match); - var qualityFullToken = string.Format("Quality{0}Full", tokenMatch.Separator); ; + var qualityFullToken = string.Format("Quality{0}Full", tokenMatch.Separator); if (tokenMatch.Token.All(t => !char.IsLetter(t) || char.IsLower(t))) { @@ -80,12 +80,12 @@ private string GetNewFormat(string currentFormat) private TokenMatch69 GetTokenMatch(Match match) { return new TokenMatch69 - { - Prefix = match.Groups["prefix"].Value, - Token = match.Groups["token"].Value, - Separator = match.Groups["separator"].Value, - Suffix = match.Groups["suffix"].Value, - }; + { + Prefix = match.Groups["prefix"].Value, + Token = match.Groups["token"].Value, + Separator = match.Groups["separator"].Value, + Suffix = match.Groups["suffix"].Value, + }; } private class TokenMatch69 diff --git a/src/NzbDrone.Core/Datastore/Migration/070_delay_profile.cs b/src/NzbDrone.Core/Datastore/Migration/070_delay_profile.cs index 11c92ce0c6..e77f5f9f7a 100644 --- a/src/NzbDrone.Core/Datastore/Migration/070_delay_profile.cs +++ b/src/NzbDrone.Core/Datastore/Migration/070_delay_profile.cs @@ -24,15 +24,15 @@ protected override void MainDbUpgrade() .WithColumn("Tags").AsString().NotNullable(); Insert.IntoTable("DelayProfiles").Row(new - { - EnableUsenet = 1, - EnableTorrent = 1, - PreferredProtocol = 1, - UsenetDelay = 0, - TorrentDelay = 0, - Order = int.MaxValue, - Tags = "[]" - }); + { + EnableUsenet = 1, + EnableTorrent = 1, + PreferredProtocol = 1, + UsenetDelay = 0, + TorrentDelay = 0, + Order = int.MaxValue, + Tags = "[]" + }); Execute.WithConnection(ConvertProfile); @@ -48,7 +48,10 @@ private void ConvertProfile(IDbConnection conn, IDbTransaction tran) foreach (var profileClosure in profiles.DistinctBy(p => p.GrabDelay)) { var profile = profileClosure; - if (profile.GrabDelay == 0) continue; + if (profile.GrabDelay == 0) + { + continue; + } var tag = string.Format("delay-{0}", profile.GrabDelay); var tagId = InsertTag(conn, tran, tag); diff --git a/src/NzbDrone.Core/Datastore/Migration/071_unknown_quality_in_profile.cs b/src/NzbDrone.Core/Datastore/Migration/071_unknown_quality_in_profile.cs index 6421f1ecb9..ab500282b6 100644 --- a/src/NzbDrone.Core/Datastore/Migration/071_unknown_quality_in_profile.cs +++ b/src/NzbDrone.Core/Datastore/Migration/071_unknown_quality_in_profile.cs @@ -24,6 +24,7 @@ private void ConvertProfile(IDbConnection conn, IDbTransaction tran) updater.Commit(); } } + public class Profile70 { public int Id { get; set; } @@ -88,7 +89,10 @@ public void PrependQuality(int quality) { foreach (var profile in _profiles) { - if (profile.Items.Any(v => v.Quality == quality)) continue; + if (profile.Items.Any(v => v.Quality == quality)) + { + continue; + } profile.Items.Insert(0, new ProfileItem70 { @@ -104,7 +108,10 @@ public void AppendQuality(int quality) { foreach (var profile in _profiles) { - if (profile.Items.Any(v => v.Quality == quality)) continue; + if (profile.Items.Any(v => v.Quality == quality)) + { + continue; + } profile.Items.Add(new ProfileItem70 { @@ -120,7 +127,10 @@ public void SplitQualityPrepend(int find, int quality) { foreach (var profile in _profiles) { - if (profile.Items.Any(v => v.Quality == quality)) continue; + if (profile.Items.Any(v => v.Quality == quality)) + { + continue; + } var findIndex = profile.Items.FindIndex(v => v.Quality == find); @@ -143,7 +153,10 @@ public void SplitQualityAppend(int find, int quality) { foreach (var profile in _profiles) { - if (profile.Items.Any(v => v.Quality == quality)) continue; + if (profile.Items.Any(v => v.Quality == quality)) + { + continue; + } var findIndex = profile.Items.FindIndex(v => v.Quality == find); @@ -171,7 +184,7 @@ public void UpdateQualityToQualityDefinition() { int id = definitionsReader.GetInt32(0); int quality = definitionsReader.GetInt32(1); - definitions.Add(new QualityDefinition70 {Id = id, Quality = quality}); + definitions.Add(new QualityDefinition70 { Id = id, Quality = quality }); } } } diff --git a/src/NzbDrone.Core/Datastore/Migration/072_history_grabid.cs b/src/NzbDrone.Core/Datastore/Migration/072_history_grabid.cs index 23523808fa..40eece1a05 100644 --- a/src/NzbDrone.Core/Datastore/Migration/072_history_grabid.cs +++ b/src/NzbDrone.Core/Datastore/Migration/072_history_grabid.cs @@ -57,7 +57,6 @@ private void UpdateHistory(IDbTransaction tran, IDbConnection conn, int id, stri updateHistoryCmd.AddParameter(id); updateHistoryCmd.ExecuteNonQuery(); - } } } diff --git a/src/NzbDrone.Core/Datastore/Migration/073_clear_ratings.cs b/src/NzbDrone.Core/Datastore/Migration/073_clear_ratings.cs index ef9c4074f4..b1b547b601 100644 --- a/src/NzbDrone.Core/Datastore/Migration/073_clear_ratings.cs +++ b/src/NzbDrone.Core/Datastore/Migration/073_clear_ratings.cs @@ -9,7 +9,7 @@ public class clear_ratings : NzbDroneMigrationBase protected override void MainDbUpgrade() { Update.Table("Series") - .Set(new {Ratings = "{}"}) + .Set(new { Ratings = "{}" }) .AllRows(); Update.Table("Episodes") diff --git a/src/NzbDrone.Core/Datastore/Migration/079_dedupe_tags.cs b/src/NzbDrone.Core/Datastore/Migration/079_dedupe_tags.cs index b786747a27..6b753635ab 100644 --- a/src/NzbDrone.Core/Datastore/Migration/079_dedupe_tags.cs +++ b/src/NzbDrone.Core/Datastore/Migration/079_dedupe_tags.cs @@ -85,10 +85,10 @@ private void UpdateTaggedModel(IDbConnection conn, IDbTransaction tran, string t var tags = tagReader.GetString(1); tagged.Add(new TaggedModel079 - { - Id = id, - Tags = Json.Deserialize>(tags) - }); + { + Id = id, + Tags = Json.Deserialize>(tags) + }); } } } diff --git a/src/NzbDrone.Core/Datastore/Migration/085_expand_transmission_urlbase.cs b/src/NzbDrone.Core/Datastore/Migration/085_expand_transmission_urlbase.cs index 4855c6a3d8..8ef73a2e42 100644 --- a/src/NzbDrone.Core/Datastore/Migration/085_expand_transmission_urlbase.cs +++ b/src/NzbDrone.Core/Datastore/Migration/085_expand_transmission_urlbase.cs @@ -7,7 +7,9 @@ namespace NzbDrone.Core.Datastore.Migration { // this is here to resolve ambiguity in GetValueOrDefault extension method in net core 3 +#pragma warning disable SA1200 using NzbDrone.Common.Extensions; +#pragma warning restore SA1200 [Migration(85)] public class expand_transmission_urlbase : NzbDroneMigrationBase diff --git a/src/NzbDrone.Core/Datastore/Migration/086_pushbullet_device_ids.cs b/src/NzbDrone.Core/Datastore/Migration/086_pushbullet_device_ids.cs index 1e7cced76c..9d1962616d 100644 --- a/src/NzbDrone.Core/Datastore/Migration/086_pushbullet_device_ids.cs +++ b/src/NzbDrone.Core/Datastore/Migration/086_pushbullet_device_ids.cs @@ -8,7 +8,9 @@ namespace NzbDrone.Core.Datastore.Migration { // this is here to resolve ambiguity in GetValueOrDefault extension method in net core 3 +#pragma warning disable SA1200 using NzbDrone.Common.Extensions; +#pragma warning restore SA1200 [Migration(86)] public class pushbullet_device_ids : NzbDroneMigrationBase diff --git a/src/NzbDrone.Core/Datastore/Migration/088_pushbullet_devices_channels_list.cs b/src/NzbDrone.Core/Datastore/Migration/088_pushbullet_devices_channels_list.cs index e4760fe793..cd55fb831b 100644 --- a/src/NzbDrone.Core/Datastore/Migration/088_pushbullet_devices_channels_list.cs +++ b/src/NzbDrone.Core/Datastore/Migration/088_pushbullet_devices_channels_list.cs @@ -8,7 +8,9 @@ namespace NzbDrone.Core.Datastore.Migration { // this is here to resolve ambiguity in GetValueOrDefault extension method in net core 3 +#pragma warning disable SA1200 using NzbDrone.Common.Extensions; +#pragma warning restore SA1200 [Migration(88)] public class pushbullet_devices_channels_list : NzbDroneMigrationBase @@ -51,7 +53,7 @@ private void UpdateTransmissionSettings(IDbConnection conn, IDbTransaction tran) if (channelTagsString.IsNotNullOrWhiteSpace()) { - var channelTags = channelTagsString.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries); + var channelTags = channelTagsString.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries); settings["channelTags"] = channelTags; } diff --git a/src/NzbDrone.Core/Datastore/Migration/090_update_kickass_url.cs b/src/NzbDrone.Core/Datastore/Migration/090_update_kickass_url.cs index ec96f48dca..bc22b32586 100644 --- a/src/NzbDrone.Core/Datastore/Migration/090_update_kickass_url.cs +++ b/src/NzbDrone.Core/Datastore/Migration/090_update_kickass_url.cs @@ -12,8 +12,7 @@ protected override void MainDbUpgrade() Execute.Sql( "UPDATE Indexers SET Settings = Replace(Settings, 'kickass.so', 'kat.cr') WHERE Implementation = 'KickassTorrents';" + "UPDATE Indexers SET Settings = Replace(Settings, 'kickass.to', 'kat.cr') WHERE Implementation = 'KickassTorrents';" + - "UPDATE Indexers SET Settings = Replace(Settings, 'http://', 'https://') WHERE Implementation = 'KickassTorrents';" - ); + "UPDATE Indexers SET Settings = Replace(Settings, 'http://', 'https://') WHERE Implementation = 'KickassTorrents';"); } } diff --git a/src/NzbDrone.Core/Datastore/Migration/104_add_moviefiles_table.cs b/src/NzbDrone.Core/Datastore/Migration/104_add_moviefiles_table.cs index f192b7709e..29c2304814 100644 --- a/src/NzbDrone.Core/Datastore/Migration/104_add_moviefiles_table.cs +++ b/src/NzbDrone.Core/Datastore/Migration/104_add_moviefiles_table.cs @@ -20,8 +20,6 @@ protected override void MainDbUpgrade() .WithColumn("RelativePath").AsString().Nullable(); Alter.Table("Movies").AddColumn("MovieFileId").AsInt32().WithDefaultValue(0); - - } } } diff --git a/src/NzbDrone.Core/Datastore/Migration/109_add_movie_formats_to_naming_config.cs b/src/NzbDrone.Core/Datastore/Migration/109_add_movie_formats_to_naming_config.cs index 786977b2ca..ca7f447a5e 100644 --- a/src/NzbDrone.Core/Datastore/Migration/109_add_movie_formats_to_naming_config.cs +++ b/src/NzbDrone.Core/Datastore/Migration/109_add_movie_formats_to_naming_config.cs @@ -1,6 +1,6 @@ -using FluentMigrator; +using System.Data; +using FluentMigrator; using NzbDrone.Core.Datastore.Migration.Framework; -using System.Data; namespace NzbDrone.Core.Datastore.Migration { @@ -17,14 +17,12 @@ protected override void MainDbUpgrade() private void ConvertConfig(IDbConnection conn, IDbTransaction tran) { - using (IDbCommand namingConfigCmd = conn.CreateCommand()) { namingConfigCmd.Transaction = tran; namingConfigCmd.CommandText = @"SELECT * FROM NamingConfig LIMIT 1"; using (IDataReader namingConfigReader = namingConfigCmd.ExecuteReader()) { - while (namingConfigReader.Read()) { // Output Settings @@ -34,13 +32,10 @@ private void ConvertConfig(IDbConnection conn, IDbTransaction tran) movieTitlePattern = "{Movie Title}"; - var standardMovieFormat = string.Format("{0} {1} {2}", movieTitlePattern, - movieYearPattern, - qualityFormat); + var standardMovieFormat = string.Format("{0} {1} {2}", movieTitlePattern, movieYearPattern, qualityFormat); var movieFolderFormat = string.Format("{0} {1}", movieTitlePattern, movieYearPattern); - using (IDbCommand updateCmd = conn.CreateCommand()) { var text = string.Format("UPDATE NamingConfig " + diff --git a/src/NzbDrone.Core/Datastore/Migration/110_add_physical_release_to_table.cs b/src/NzbDrone.Core/Datastore/Migration/110_add_physical_release_to_table.cs index b4412bb321..e1f9a7e83c 100644 --- a/src/NzbDrone.Core/Datastore/Migration/110_add_physical_release_to_table.cs +++ b/src/NzbDrone.Core/Datastore/Migration/110_add_physical_release_to_table.cs @@ -9,10 +9,6 @@ public class add_phyiscal_release : NzbDroneMigrationBase protected override void MainDbUpgrade() { Alter.Table("Movies").AddColumn("PhysicalRelease").AsDateTime().Nullable(); - } - - - } } diff --git a/src/NzbDrone.Core/Datastore/Migration/117_update_movie_file.cs b/src/NzbDrone.Core/Datastore/Migration/117_update_movie_file.cs index ba5ed3045d..6e157b9bc1 100644 --- a/src/NzbDrone.Core/Datastore/Migration/117_update_movie_file.cs +++ b/src/NzbDrone.Core/Datastore/Migration/117_update_movie_file.cs @@ -10,6 +10,7 @@ public class update_movie_file : NzbDroneMigrationBase protected override void MainDbUpgrade() { Create.Column("Edition").OnTable("MovieFiles").AsString().Nullable(); + //Execute.WithConnection(SetSortTitles); } diff --git a/src/NzbDrone.Core/Datastore/Migration/119_add_youtube_trailer_id_table .cs b/src/NzbDrone.Core/Datastore/Migration/119_add_youtube_trailer_id_table .cs index 5b1ee7f6b9..a8ea901634 100644 --- a/src/NzbDrone.Core/Datastore/Migration/119_add_youtube_trailer_id_table .cs +++ b/src/NzbDrone.Core/Datastore/Migration/119_add_youtube_trailer_id_table .cs @@ -9,8 +9,6 @@ public class add_youtube_trailer_id : NzbDroneMigrationBase protected override void MainDbUpgrade() { Alter.Table("Movies").AddColumn("YouTubeTrailerId").AsString().Nullable(); - } - } } diff --git a/src/NzbDrone.Core/Datastore/Migration/120_add_studio_to_table.cs b/src/NzbDrone.Core/Datastore/Migration/120_add_studio_to_table.cs index f5c4dc36ef..202005901e 100644 --- a/src/NzbDrone.Core/Datastore/Migration/120_add_studio_to_table.cs +++ b/src/NzbDrone.Core/Datastore/Migration/120_add_studio_to_table.cs @@ -10,6 +10,5 @@ protected override void MainDbUpgrade() { Alter.Table("Movies").AddColumn("Studio").AsString().Nullable(); } - } } diff --git a/src/NzbDrone.Core/Datastore/Migration/121_update_filedate_config.cs b/src/NzbDrone.Core/Datastore/Migration/121_update_filedate_config.cs index 0e548b7237..8478360bd3 100644 --- a/src/NzbDrone.Core/Datastore/Migration/121_update_filedate_config.cs +++ b/src/NzbDrone.Core/Datastore/Migration/121_update_filedate_config.cs @@ -1,8 +1,8 @@ using System.Data; -using FluentMigrator; -using NzbDrone.Core.Datastore.Migration.Framework; using System.Text; using System.Text.RegularExpressions; +using FluentMigrator; +using NzbDrone.Core.Datastore.Migration.Framework; namespace NzbDrone.Core.Datastore.Migration { diff --git a/src/NzbDrone.Core/Datastore/Migration/122_add_movieid_to_blacklist.cs b/src/NzbDrone.Core/Datastore/Migration/122_add_movieid_to_blacklist.cs index 8f6ebb9e25..f0002017f4 100644 --- a/src/NzbDrone.Core/Datastore/Migration/122_add_movieid_to_blacklist.cs +++ b/src/NzbDrone.Core/Datastore/Migration/122_add_movieid_to_blacklist.cs @@ -12,6 +12,5 @@ protected override void MainDbUpgrade() Alter.Table("Blacklist").AlterColumn("SeriesId").AsInt32().Nullable(); Alter.Table("Blacklist").AlterColumn("EpisodeIds").AsString().Nullable(); } - } } diff --git a/src/NzbDrone.Core/Datastore/Migration/123_create_netimport_table.cs b/src/NzbDrone.Core/Datastore/Migration/123_create_netimport_table.cs index 86a6029179..91af60e368 100644 --- a/src/NzbDrone.Core/Datastore/Migration/123_create_netimport_table.cs +++ b/src/NzbDrone.Core/Datastore/Migration/123_create_netimport_table.cs @@ -8,7 +8,7 @@ public class create_netimport_table : NzbDroneMigrationBase { protected override void MainDbUpgrade() { - if (!this.Schema.Schema("dbo").Table("NetImport").Exists()) + if (!Schema.Schema("dbo").Table("NetImport").Exists()) { Create.TableForModel("NetImport") .WithColumn("Enabled").AsBoolean() diff --git a/src/NzbDrone.Core/Datastore/Migration/124_add_preferred_tags_to_profile.cs b/src/NzbDrone.Core/Datastore/Migration/124_add_preferred_tags_to_profile.cs index 3ab1c2641d..aa7133479f 100644 --- a/src/NzbDrone.Core/Datastore/Migration/124_add_preferred_tags_to_profile.cs +++ b/src/NzbDrone.Core/Datastore/Migration/124_add_preferred_tags_to_profile.cs @@ -10,6 +10,5 @@ protected override void MainDbUpgrade() { Alter.Table("Profiles").AddColumn("PreferredTags").AsString().Nullable(); } - } } diff --git a/src/NzbDrone.Core/Datastore/Migration/125_fix_imdb_unique.cs b/src/NzbDrone.Core/Datastore/Migration/125_fix_imdb_unique.cs index 1b6f4b3f39..fdbcdcd06e 100644 --- a/src/NzbDrone.Core/Datastore/Migration/125_fix_imdb_unique.cs +++ b/src/NzbDrone.Core/Datastore/Migration/125_fix_imdb_unique.cs @@ -1,6 +1,6 @@ -using FluentMigrator; +using System.Data; +using FluentMigrator; using NzbDrone.Core.Datastore.Migration.Framework; -using System.Data; namespace NzbDrone.Core.Datastore.Migration { @@ -22,6 +22,5 @@ private void DeleteUniqueIndex(IDbConnection conn, IDbTransaction tran) getSeriesCmd.ExecuteNonQuery(); } } - } } diff --git a/src/NzbDrone.Core/Datastore/Migration/133_add_minimumavailability.cs b/src/NzbDrone.Core/Datastore/Migration/133_add_minimumavailability.cs index 84909dd6ca..b162040f8b 100644 --- a/src/NzbDrone.Core/Datastore/Migration/133_add_minimumavailability.cs +++ b/src/NzbDrone.Core/Datastore/Migration/133_add_minimumavailability.cs @@ -1,4 +1,5 @@ using FluentMigrator; + //using FluentMigrator.Expressions; using NzbDrone.Core.Datastore.Migration.Framework; using NzbDrone.Core.Movies; @@ -10,11 +11,12 @@ public class add_minimumavailability : NzbDroneMigrationBase { protected override void MainDbUpgrade() { - if (!this.Schema.Schema("dbo").Table("NetImport").Column("MinimumAvailability").Exists()) + if (!Schema.Schema("dbo").Table("NetImport").Column("MinimumAvailability").Exists()) { Alter.Table("NetImport").AddColumn("MinimumAvailability").AsInt32().WithDefaultValue(MovieStatusType.PreDB); } - if (!this.Schema.Schema("dbo").Table("Movies").Column("MinimumAvailability").Exists()) + + if (!Schema.Schema("dbo").Table("Movies").Column("MinimumAvailability").Exists()) { Alter.Table("Movies").AddColumn("MinimumAvailability").AsInt32().WithDefaultValue(MovieStatusType.PreDB); } diff --git a/src/NzbDrone.Core/Datastore/Migration/137_add_import_exclusions_table.cs b/src/NzbDrone.Core/Datastore/Migration/137_add_import_exclusions_table.cs index 2e1be0307e..25b68583a9 100644 --- a/src/NzbDrone.Core/Datastore/Migration/137_add_import_exclusions_table.cs +++ b/src/NzbDrone.Core/Datastore/Migration/137_add_import_exclusions_table.cs @@ -1,10 +1,10 @@ using System.Data; -using FluentMigrator; -using NzbDrone.Core.Datastore.Migration.Framework; +using System.Globalization; using System.Linq; using System.Text.RegularExpressions; -using System.Globalization; +using FluentMigrator; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Datastore.Migration.Framework; namespace NzbDrone.Core.Datastore.Migration { @@ -13,13 +13,14 @@ public class add_import_exclusions_table : NzbDroneMigrationBase { protected override void MainDbUpgrade() { - if (!this.Schema.Schema("dbo").Table("ImportExclusions").Exists()) + if (!Schema.Schema("dbo").Table("ImportExclusions").Exists()) { Create.TableForModel("ImportExclusions") .WithColumn("TmdbId").AsInt64().NotNullable().Unique().PrimaryKey() .WithColumn("MovieTitle").AsString().Nullable() .WithColumn("MovieYear").AsInt64().Nullable().WithDefaultValue(0); } + Execute.WithConnection(AddExisting); } @@ -34,12 +35,14 @@ private void AddExisting(IDbConnection conn, IDbTransaction tran) { while (seriesReader.Read()) { - var Key = seriesReader.GetString(0); - var Value = seriesReader.GetString(1); + var key = seriesReader.GetString(0); + var value = seriesReader.GetString(1); - var importExclusions = Value.Split(',').Select(x => { - return string.Format("(\"{0}\", \"{1}\")", Regex.Replace(x, @"^.*\-(.*)$", "$1"), - textInfo.ToTitleCase(string.Join(" ", x.Split('-').DropLast(1)))); + var importExclusions = value.Split(',').Select(x => + { + return string.Format("(\"{0}\", \"{1}\")", + Regex.Replace(x, @"^.*\-(.*)$", "$1"), + textInfo.ToTitleCase(string.Join(" ", x.Split('-').DropLast(1)))); }).ToList(); using (IDbCommand updateCmd = conn.CreateCommand()) diff --git a/src/NzbDrone.Core/Datastore/Migration/140_add_alternative_titles_table.cs b/src/NzbDrone.Core/Datastore/Migration/140_add_alternative_titles_table.cs index 64f9dd0094..55712d9bf5 100644 --- a/src/NzbDrone.Core/Datastore/Migration/140_add_alternative_titles_table.cs +++ b/src/NzbDrone.Core/Datastore/Migration/140_add_alternative_titles_table.cs @@ -8,7 +8,7 @@ public class add_alternative_titles_table : NzbDroneMigrationBase { protected override void MainDbUpgrade() { - if (!this.Schema.Schema("dbo").Table("alternative_titles").Exists()) + if (!Schema.Schema("dbo").Table("alternative_titles").Exists()) { Create.TableForModel("AlternativeTitles") .WithColumn("MovieId").AsInt64().NotNullable() diff --git a/src/NzbDrone.Core/Datastore/Migration/141_fix_duplicate_alt_titles.cs b/src/NzbDrone.Core/Datastore/Migration/141_fix_duplicate_alt_titles.cs index faaa8424ee..dd09aa4a60 100644 --- a/src/NzbDrone.Core/Datastore/Migration/141_fix_duplicate_alt_titles.cs +++ b/src/NzbDrone.Core/Datastore/Migration/141_fix_duplicate_alt_titles.cs @@ -21,7 +21,6 @@ private void RenameUrlToBaseUrl(IDbConnection conn, IDbTransaction tran) cmd.CommandText = "DELETE FROM AlternativeTitles WHERE rowid NOT IN ( SELECT MIN(rowid) FROM AlternativeTitles GROUP BY CleanTitle )"; cmd.ExecuteNonQuery(); - } } } diff --git a/src/NzbDrone.Core/Datastore/Migration/144_add_cookies_to_indexer_status.cs b/src/NzbDrone.Core/Datastore/Migration/144_add_cookies_to_indexer_status.cs index fb90202d92..71a182e769 100644 --- a/src/NzbDrone.Core/Datastore/Migration/144_add_cookies_to_indexer_status.cs +++ b/src/NzbDrone.Core/Datastore/Migration/144_add_cookies_to_indexer_status.cs @@ -10,7 +10,6 @@ protected override void MainDbUpgrade() { Alter.Table("IndexerStatus").AddColumn("Cookies").AsString().Nullable() .AddColumn("CookiesExpirationDate").AsDateTime().Nullable(); - } } } diff --git a/src/NzbDrone.Core/Datastore/Migration/147_add_custom_formats.cs b/src/NzbDrone.Core/Datastore/Migration/147_add_custom_formats.cs index af13aeefe5..d122b43d3c 100644 --- a/src/NzbDrone.Core/Datastore/Migration/147_add_custom_formats.cs +++ b/src/NzbDrone.Core/Datastore/Migration/147_add_custom_formats.cs @@ -21,7 +21,6 @@ protected override void MainDbUpgrade() private void AddCustomFormatsToProfile(IDbConnection conn, IDbTransaction tran) { - } } } diff --git a/src/NzbDrone.Core/Datastore/Migration/149_convert_regex_required_tags.cs b/src/NzbDrone.Core/Datastore/Migration/149_convert_regex_required_tags.cs index ab006cb91d..18ba368132 100644 --- a/src/NzbDrone.Core/Datastore/Migration/149_convert_regex_required_tags.cs +++ b/src/NzbDrone.Core/Datastore/Migration/149_convert_regex_required_tags.cs @@ -25,10 +25,26 @@ private void ConvertExistingFormatTags(IDbConnection conn, IDbTransaction tran) updater.ReplaceInTags(OriginalRegex, match => { var modifiers = ""; - if (match.Groups["m_n"].Success) modifiers += "N"; - if (match.Groups["m_r"].Success) modifiers += "RX"; - if (match.Groups["m_re"].Success) modifiers += "RQ"; - if (modifiers != "") modifiers = "_" + modifiers; + if (match.Groups["m_n"].Success) + { + modifiers += "N"; + } + + if (match.Groups["m_r"].Success) + { + modifiers += "RX"; + } + + if (match.Groups["m_re"].Success) + { + modifiers += "RQ"; + } + + if (modifiers != "") + { + modifiers = "_" + modifiers; + } + return $"{match.Groups["type"].Value}{modifiers}_{match.Groups["value"].Value}"; }); diff --git a/src/NzbDrone.Core/Datastore/Migration/154_add_language_to_file_history_blacklist.cs b/src/NzbDrone.Core/Datastore/Migration/154_add_language_to_file_history_blacklist.cs index 4013e3d196..a5a7d66dec 100644 --- a/src/NzbDrone.Core/Datastore/Migration/154_add_language_to_file_history_blacklist.cs +++ b/src/NzbDrone.Core/Datastore/Migration/154_add_language_to_file_history_blacklist.cs @@ -1,16 +1,18 @@ -using System.Data; -using FluentMigrator; -using NzbDrone.Core.Datastore.Migration.Framework; -using NzbDrone.Core.Datastore.Converters; -using NzbDrone.Core.Languages; using System; using System.Collections.Generic; +using System.Data; using System.Linq; +using FluentMigrator; +using NzbDrone.Core.Datastore.Converters; +using NzbDrone.Core.Datastore.Migration.Framework; +using NzbDrone.Core.Languages; namespace NzbDrone.Core.Datastore.Migration { // this is here to resolve ambiguity in GetValueOrDefault extension method in net core 3 +#pragma warning disable SA1200 using NzbDrone.Common.Extensions; +#pragma warning restore SA1200 [Migration(154)] public class add_language_to_files_history_blacklist : NzbDroneMigrationBase @@ -31,7 +33,7 @@ protected override void MainDbUpgrade() private void UpdateLanguage(IDbConnection conn, IDbTransaction tran) { - var LanguageConverter = new EmbeddedDocumentConverter(new LanguageIntConverter()); + var languageConverter = new EmbeddedDocumentConverter(new LanguageIntConverter()); var profileLanguages = new Dictionary(); using (IDbCommand getProfileCmd = conn.CreateCommand()) @@ -77,7 +79,7 @@ private void UpdateLanguage(IDbConnection conn, IDbTransaction tran) foreach (var group in movieLanguages.GroupBy(v => v.Value, v => v.Key)) { - var languageJson = LanguageConverter.ToDB(new List { Language.FindById(group.Key) }); + var languageJson = languageConverter.ToDB(new List { Language.FindById(group.Key) }); var movieIds = group.Select(v => v.ToString()).Join(","); diff --git a/src/NzbDrone.Core/Datastore/Migration/156_add_download_client_priority.cs b/src/NzbDrone.Core/Datastore/Migration/156_add_download_client_priority.cs index fd08c86311..8d7349b5dd 100644 --- a/src/NzbDrone.Core/Datastore/Migration/156_add_download_client_priority.cs +++ b/src/NzbDrone.Core/Datastore/Migration/156_add_download_client_priority.cs @@ -18,7 +18,6 @@ protected override void MainDbUpgrade() { Alter.Table("DownloadClients").AddColumn("Priority").AsInt32().WithDefaultValue(1); Execute.WithConnection(InitPriorityForBackwardCompatibility); - } private void InitPriorityForBackwardCompatibility(IDbConnection conn, IDbTransaction tran) diff --git a/src/NzbDrone.Core/Datastore/Migration/159_add_webrip_qualities.cs b/src/NzbDrone.Core/Datastore/Migration/159_add_webrip_qualities.cs index effa7b520d..fc5f120e72 100644 --- a/src/NzbDrone.Core/Datastore/Migration/159_add_webrip_qualities.cs +++ b/src/NzbDrone.Core/Datastore/Migration/159_add_webrip_qualities.cs @@ -20,10 +20,10 @@ private void ConvertProfile(IDbConnection conn, IDbTransaction tran) { var updater = new ProfileUpdater159(conn, tran); - updater.CreateGroupAt(8, "WEB 480p", new int[]{12}); // Group WEBRip480p with WEBDL480p - updater.CreateGroupAt(5, "WEB 720p", new int[]{14}); // Group WEBRip720p with WEBDL720p - updater.CreateGroupAt(3, "WEB 1080p", new int[]{15}); // Group WEBRip1080p with WEBDL1080p - updater.CreateGroupAt(18, "WEB 2160p", new int[]{17}); // Group WEBRip2160p with WEBDL2160p + updater.CreateGroupAt(8, "WEB 480p", new int[] { 12 }); // Group WEBRip480p with WEBDL480p + updater.CreateGroupAt(5, "WEB 720p", new int[] { 14 }); // Group WEBRip720p with WEBDL720p + updater.CreateGroupAt(3, "WEB 1080p", new int[] { 15 }); // Group WEBRip1080p with WEBDL1080p + updater.CreateGroupAt(18, "WEB 2160p", new int[] { 17 }); // Group WEBRip2160p with WEBDL2160p updater.Commit(); } @@ -108,7 +108,6 @@ public void CreateGroupAt(int find, string name, int[] newQualities) } } - var findIndex = profile.Items.FindIndex(v => { return v.Quality == find || (v.Items != null && v.Items.Any(b => b.Quality == find)); @@ -116,7 +115,6 @@ public void CreateGroupAt(int find, string name, int[] newQualities) var isGrouped = !profile.Items.Any(p => p.Quality == find); - if (findIndex > -1 && !isGrouped) { var findQuality = profile.Items[findIndex]; @@ -163,7 +161,6 @@ public void CreateGroupAt(int find, string name, int[] newQualities) else { // If the ID isn't found for some reason (mangled migration 71?) - var groupItems = new List(); foreach (var newQuality in newQualities) diff --git a/src/NzbDrone.Core/Datastore/Migration/Framework/MigrationController.cs b/src/NzbDrone.Core/Datastore/Migration/Framework/MigrationController.cs index b90d3de7c1..e49b7b4937 100644 --- a/src/NzbDrone.Core/Datastore/Migration/Framework/MigrationController.cs +++ b/src/NzbDrone.Core/Datastore/Migration/Framework/MigrationController.cs @@ -42,10 +42,11 @@ public void Migrate(string connectionString, MigrationContext migrationContext) .WithGlobalConnectionString(connectionString) .WithMigrationsIn(Assembly.GetExecutingAssembly())) .Configure(opt => opt.Namespace = "NzbDrone.Core.Datastore.Migration") - .Configure(opt => { - opt.PreviewOnly = false; - opt.Timeout = TimeSpan.FromSeconds(60); - }) + .Configure(opt => + { + opt.PreviewOnly = false; + opt.Timeout = TimeSpan.FromSeconds(60); + }) .BuildServiceProvider(); using (var scope = serviceProvider.CreateScope()) diff --git a/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSchemaDumper.cs b/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSchemaDumper.cs index e6ad4dd52c..57b984c5aa 100644 --- a/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSchemaDumper.cs +++ b/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSchemaDumper.cs @@ -38,7 +38,9 @@ protected virtual TableDefinition ParseCreateTableStatement(SqliteSyntaxReader r { var table = new TableDefinition(); - while (reader.Read() != SqliteSyntaxReader.TokenType.StringToken || reader.ValueToUpper != "TABLE") ; + while (reader.Read() != SqliteSyntaxReader.TokenType.StringToken || reader.ValueToUpper != "TABLE") + { + } if (reader.Read() == SqliteSyntaxReader.TokenType.StringToken && reader.ValueToUpper == "IF") { @@ -114,7 +116,10 @@ protected virtual IndexDefinition ParseCreateIndexStatement(SqliteSyntaxReader r reader.Read(); index.IsUnique = reader.ValueToUpper == "UNIQUE"; - while (reader.ValueToUpper != "INDEX") reader.Read(); + while (reader.ValueToUpper != "INDEX") + { + reader.Read(); + } if (reader.Read() == SqliteSyntaxReader.TokenType.StringToken && reader.ValueToUpper == "IF") { @@ -175,22 +180,19 @@ protected virtual string ParseIdentifier(SqliteSyntaxReader reader) return reader.Value; } - #region ISchemaDumper Members - public virtual IList ReadDbSchema() { IList tables = ReadTables(); foreach (var table in tables) { table.Indexes = ReadIndexes(table.SchemaName, table.Name); + //table.ForeignKeys = ReadForeignKeys(table.SchemaName, table.Name); } return tables; } - #endregion - protected virtual DataSet Read(string template, params object[] args) { return Processor.Read(template, args); @@ -210,6 +212,7 @@ protected virtual IList ReadTables() tableDefinitionList.Add(table); } + return tableDefinitionList; } @@ -252,6 +255,7 @@ protected virtual IList ReadIndexes(string schemaName, string t var index = ReadIndexSchema(sql); indexes.Add(index); } + return indexes; } } diff --git a/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSyntaxReader.cs b/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSyntaxReader.cs index b2556fee1c..6c76fbdc14 100644 --- a/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSyntaxReader.cs +++ b/src/NzbDrone.Core/Datastore/Migration/Framework/SqliteSyntaxReader.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.Datastore.Migration.Framework { - public class SqliteSyntaxReader { public string Buffer { get; private set; } @@ -48,18 +47,25 @@ public void TrimBuffer() public void SkipWhitespace() { - while (!IsEndOfFile && char.IsWhiteSpace(Buffer[Index])) Index++; + while (!IsEndOfFile && char.IsWhiteSpace(Buffer[Index])) + { + Index++; + } } public void SkipTillToken(TokenType tokenType) { if (IsEndOfFile) + { return; + } while (Read() != tokenType) { if (Type == TokenType.ListStart) + { SkipTillToken(TokenType.ListEnd); + } } } @@ -148,7 +154,10 @@ public TokenType Read() { var start = Index; var end = start + 1; - while (end < Buffer.Length && (char.IsLetter(Buffer[end]) || char.IsNumber(Buffer[end]) || Buffer[end] == '_' || Buffer[end] == '(')) end++; + while (end < Buffer.Length && (char.IsLetter(Buffer[end]) || char.IsNumber(Buffer[end]) || Buffer[end] == '_' || Buffer[end] == '(')) + { + end++; + } if (end >= Buffer.Length || Buffer[end] == ',' || Buffer[end] == ')' || char.IsWhiteSpace(Buffer[end])) { @@ -164,6 +173,7 @@ public TokenType Read() { throw CreateSyntaxException("Unexpected sequence."); } + Type = TokenType.StringToken; Value = Buffer.Substring(start, end - start); return Type; @@ -191,6 +201,7 @@ public List ReadList() { throw CreateSyntaxException("Expected ListEnd first"); } + if (Type == TokenType.ListStart) { SkipTillToken(TokenType.ListEnd); @@ -215,7 +226,10 @@ protected string ReadTerminatedString(char terminator) var start = Index + 1; var end = Buffer.IndexOf(terminator, Index); - if (end == -1) throw new SyntaxErrorException(); + if (end == -1) + { + throw new SyntaxErrorException(); + } Index = end + 1; return Buffer.Substring(start, end - start); @@ -230,12 +244,18 @@ protected string ReadEscapedString(char escape) var start = Index + 1; var end = Buffer.IndexOf(escape, start); - if (end == -1) throw new SyntaxErrorException(); + if (end == -1) + { + throw new SyntaxErrorException(); + } Index = end + 1; identifier.Append(Buffer.Substring(start, end - start)); - if (Buffer[Index] != escape) break; + if (Buffer[Index] != escape) + { + break; + } identifier.Append(escape); } diff --git a/src/NzbDrone.Core/Datastore/Migration/Framework/TableDefinition.cs b/src/NzbDrone.Core/Datastore/Migration/Framework/TableDefinition.cs index 1a680f0d80..0e7d78f137 100644 --- a/src/NzbDrone.Core/Datastore/Migration/Framework/TableDefinition.cs +++ b/src/NzbDrone.Core/Datastore/Migration/Framework/TableDefinition.cs @@ -1,5 +1,3 @@ -#region License -// // Copyright (c) 2007-2009, Sean Chambers // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#endregion - - using System; using System.Collections.Generic; using System.Linq; diff --git a/src/NzbDrone.Core/Datastore/ModelConflictException.cs b/src/NzbDrone.Core/Datastore/ModelConflictException.cs index b9e5687bea..f313e34442 100644 --- a/src/NzbDrone.Core/Datastore/ModelConflictException.cs +++ b/src/NzbDrone.Core/Datastore/ModelConflictException.cs @@ -8,13 +8,11 @@ public class ModelConflictException : NzbDroneException public ModelConflictException(Type modelType, int modelId) : base("{0} with ID {1} cannot be modified", modelType.Name, modelId) { - } public ModelConflictException(Type modelType, int modelId, string message) : base("{0} with ID {1} {2}", modelType.Name, modelId, message) { - } } } diff --git a/src/NzbDrone.Core/Datastore/ModelNotFoundException.cs b/src/NzbDrone.Core/Datastore/ModelNotFoundException.cs index 6f889dfd7c..b9ad28da9b 100644 --- a/src/NzbDrone.Core/Datastore/ModelNotFoundException.cs +++ b/src/NzbDrone.Core/Datastore/ModelNotFoundException.cs @@ -8,7 +8,6 @@ public class ModelNotFoundException : NzbDroneException public ModelNotFoundException(Type modelType, int modelId) : base("{0} with ID {1} does not exist", modelType.Name, modelId) { - } } } diff --git a/src/NzbDrone.Core/Datastore/TableMapping.cs b/src/NzbDrone.Core/Datastore/TableMapping.cs index 4a8afc2886..c033e6410e 100644 --- a/src/NzbDrone.Core/Datastore/TableMapping.cs +++ b/src/NzbDrone.Core/Datastore/TableMapping.cs @@ -2,42 +2,42 @@ using System.Collections.Generic; using Marr.Data; using Marr.Data.Mapping; +using NzbDrone.Common.Disk; using NzbDrone.Common.Reflection; +using NzbDrone.Core.Authentication; using NzbDrone.Core.Blacklisting; using NzbDrone.Core.Configuration; +using NzbDrone.Core.CustomFilters; +using NzbDrone.Core.CustomFormats; using NzbDrone.Core.Datastore.Converters; using NzbDrone.Core.Datastore.Extensions; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Pending; -using NzbDrone.Core.Indexers; -using NzbDrone.Core.Instrumentation; -using NzbDrone.Core.Jobs; -using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Profiles.Delay; -using NzbDrone.Core.RemotePathMappings; -using NzbDrone.Core.Notifications; -using NzbDrone.Core.Organizer; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Profiles; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Restrictions; -using NzbDrone.Core.RootFolders; -using NzbDrone.Core.Tags; -using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Movies; -using NzbDrone.Common.Disk; -using NzbDrone.Core.Authentication; -using NzbDrone.Core.CustomFilters; -using NzbDrone.Core.CustomFormats; using NzbDrone.Core.Extras.Metadata; using NzbDrone.Core.Extras.Metadata.Files; using NzbDrone.Core.Extras.Others; using NzbDrone.Core.Extras.Subtitles; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.Instrumentation; +using NzbDrone.Core.Jobs; +using NzbDrone.Core.Languages; +using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Messaging.Commands; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Movies.AlternativeTitles; using NzbDrone.Core.NetImport; using NzbDrone.Core.NetImport.ImportExclusions; -using NzbDrone.Core.Movies.AlternativeTitles; -using NzbDrone.Core.Languages; +using NzbDrone.Core.Notifications; +using NzbDrone.Core.Organizer; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.Profiles; +using NzbDrone.Core.Profiles.Delay; +using NzbDrone.Core.Qualities; +using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.Restrictions; +using NzbDrone.Core.RootFolders; +using NzbDrone.Core.Tags; +using NzbDrone.Core.ThingiProvider; namespace NzbDrone.Core.Datastore { @@ -87,28 +87,27 @@ public static void Map() Mapper.Entity().RegisterModel("History") .AutoMapChildModels(); - Mapper.Entity().RegisterModel("MovieFiles") - .Ignore(f => f.Path) - .Relationships.AutoMapICollectionOrComplexProperties() - .For("Movie") - .LazyLoad(condition: parent => parent.Id > 0, - query: (db, parent) => db.Query().Where(c => c.MovieFileId == parent.Id).ToList()) - .HasOne(file => file.Movie, file => file.MovieId); + Mapper.Entity().RegisterModel("MovieFiles") + .Ignore(f => f.Path) + .Relationships.AutoMapICollectionOrComplexProperties() + .For("Movie") + .LazyLoad(condition: parent => parent.Id > 0, + query: (db, parent) => db.Query().Where(c => c.MovieFileId == parent.Id).ToList()) + .HasOne(file => file.Movie, file => file.MovieId); Mapper.Entity().RegisterModel("Movies") .Ignore(s => s.RootFolderPath) .Ignore(m => m.Actors) .Relationship() .HasOne(s => s.Profile, s => s.ProfileId); - //.HasOne(m => m.MovieFile, m => m.MovieFileId); + //.HasOne(m => m.MovieFile, m => m.MovieFileId); Mapper.Entity().RegisterModel("AlternativeTitles") .For(t => t.Id) .SetAltName("AltTitle_Id") .Relationship() .HasOne(t => t.Movie, t => t.MovieId); - Mapper.Entity().RegisterModel("ImportExclusions"); Mapper.Entity().RegisterModel("QualityDefinitions") diff --git a/src/NzbDrone.Core/DecisionEngine/DownloadDecisionComparer.cs b/src/NzbDrone.Core/DecisionEngine/DownloadDecisionComparer.cs index a4e171dffe..b1f0213d9d 100644 --- a/src/NzbDrone.Core/DecisionEngine/DownloadDecisionComparer.cs +++ b/src/NzbDrone.Core/DecisionEngine/DownloadDecisionComparer.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; using System.Linq; +using NzbDrone.Core.Configuration; +using NzbDrone.Core.CustomFormats; using NzbDrone.Core.Indexers; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Delay; -using NzbDrone.Core.Configuration; -using NzbDrone.Core.CustomFormats; using NzbDrone.Core.Qualities; namespace NzbDrone.Core.DecisionEngine @@ -74,7 +74,7 @@ private int CompareCustomFormats(DownloadDecision x, DownloadDecision y) var right = y.RemoteMovie.ParsedMovieInfo.Quality.CustomFormats; var leftIndicies = QualityModelComparer.GetIndicies(left, x.RemoteMovie.Movie.Profile.Value); - var rightIndicies = QualityModelComparer.GetIndicies(right, y.RemoteMovie.Movie.Profile.Value); + var rightIndicies = QualityModelComparer.GetIndicies(right, y.RemoteMovie.Movie.Profile.Value); var leftTotal = leftIndicies.Sum(); var rightTotal = rightIndicies.Sum(); @@ -98,7 +98,6 @@ private int ComparePreferredWords(DownloadDecision x, DownloadDecision y) var num = preferredWords.AsEnumerable().Count(w => title.ToLower().Contains(w.ToLower())); return num; - }); } @@ -189,7 +188,6 @@ private int CompareAgeIfUsenet(DownloadDecision x, DownloadDecision y) private int CompareSize(DownloadDecision x, DownloadDecision y) { // TODO: Is smaller better? Smaller for usenet could mean no par2 files. - return CompareBy(x.RemoteMovie, y.RemoteMovie, remoteEpisode => remoteEpisode.Release.Size.Round(200.Megabytes())); } diff --git a/src/NzbDrone.Core/DecisionEngine/DownloadDecisionMaker.cs b/src/NzbDrone.Core/DecisionEngine/DownloadDecisionMaker.cs index 88ad820a98..ab4cbeead1 100644 --- a/src/NzbDrone.Core/DecisionEngine/DownloadDecisionMaker.cs +++ b/src/NzbDrone.Core/DecisionEngine/DownloadDecisionMaker.cs @@ -6,12 +6,12 @@ using NzbDrone.Common.Instrumentation.Extensions; using NzbDrone.Common.Serializer; using NzbDrone.Core.Configuration; +using NzbDrone.Core.DecisionEngine.Specifications; using NzbDrone.Core.IndexerSearch.Definitions; -using NzbDrone.Core.Parser; using NzbDrone.Core.Languages; +using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; -using NzbDrone.Core.DecisionEngine.Specifications; namespace NzbDrone.Core.DecisionEngine { @@ -30,8 +30,10 @@ public class DownloadDecisionMaker : IMakeDownloadDecision private readonly Logger _logger; public DownloadDecisionMaker(IEnumerable specifications, - IParsingService parsingService, IConfigService configService, - IQualityDefinitionService qualityDefinitionService, Logger logger) + IParsingService parsingService, + IConfigService configService, + IQualityDefinitionService qualityDefinitionService, + Logger logger) { _specifications = specifications; _parsingService = parsingService; @@ -56,7 +58,6 @@ private IEnumerable GetDecisions(List reports, Se { _logger.ProgressInfo("Processing {0} releases", reports.Count); } - else { _logger.ProgressInfo("No results found"); @@ -71,8 +72,7 @@ private IEnumerable GetDecisions(List reports, Se try { - - var parsedMovieInfo = _parsingService.ParseMovieInfo(report.Title, new List{report}); + var parsedMovieInfo = _parsingService.ParseMovieInfo(report.Title, new List { report }); MappingResult result = null; @@ -83,7 +83,7 @@ private IEnumerable GetDecisions(List reports, Se { MovieTitle = report.Title, Year = 1290, - Languages = new List{Language.Unknown}, + Languages = new List { Language.Unknown }, Quality = new QualityModel(), }; @@ -94,11 +94,10 @@ private IEnumerable GetDecisions(List reports, Se if (result == null || result.MappingResultType != MappingResultType.SuccessLenientMapping) { - result = new MappingResult {MappingResultType = MappingResultType.NotParsable}; + result = new MappingResult { MappingResultType = MappingResultType.NotParsable }; result.Movie = null; //To ensure we have a remote movie, else null exception on next line! result.RemoteMovie.ParsedMovieInfo = parsedMovieInfo; } - } else { @@ -115,7 +114,6 @@ private IEnumerable GetDecisions(List reports, Se { var rejection = result.ToRejection(); decision = new DownloadDecision(remoteMovie, rejection); - } else { @@ -146,7 +144,6 @@ private IEnumerable GetDecisions(List reports, Se remoteMovie.DownloadAllowed = remoteMovie.Movie != null; decision = GetDecisionForReport(remoteMovie, searchCriteria); } - } } catch (Exception e) @@ -165,7 +162,6 @@ private IEnumerable GetDecisions(List reports, Se { _logger.Debug("Release rejected for the following reasons: {0}", string.Join(", ", decision.Rejections)); } - else { _logger.Debug("Release accepted"); diff --git a/src/NzbDrone.Core/DecisionEngine/DownloadDecisionPriorizationService.cs b/src/NzbDrone.Core/DecisionEngine/DownloadDecisionPriorizationService.cs index 3b3acbb727..163ff7a9f7 100644 --- a/src/NzbDrone.Core/DecisionEngine/DownloadDecisionPriorizationService.cs +++ b/src/NzbDrone.Core/DecisionEngine/DownloadDecisionPriorizationService.cs @@ -1,8 +1,8 @@ -using System.Linq; using System.Collections.Generic; +using System.Linq; using NzbDrone.Core.Configuration; -using NzbDrone.Core.Profiles.Delay; using NzbDrone.Core.Parser; +using NzbDrone.Core.Profiles.Delay; namespace NzbDrone.Core.DecisionEngine { diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/AcceptableSizeSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/AcceptableSizeSpecification.cs index 98e7237f44..f7a50c41c7 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/AcceptableSizeSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/AcceptableSizeSpecification.cs @@ -56,6 +56,7 @@ public Decision IsSatisfiedBy(RemoteMovie subject, SearchCriteriaBase searchCrit return Decision.Reject("{0} is smaller than minimum allowed {1} (for {2})", subject.Release.Size.SizeSuffix(), minSize.SizeSuffix(), runtimeMessage); } } + if (!qualityDefinition.MaxSize.HasValue || qualityDefinition.MaxSize.Value == 0) { _logger.Debug("Max size is unlimited - skipping check."); @@ -69,8 +70,7 @@ public Decision IsSatisfiedBy(RemoteMovie subject, SearchCriteriaBase searchCrit //If the parsed size is greater than maxSize we don't want it if (subject.Release.Size > maxSize) - {; - + { _logger.Debug("Item: {0}, Size: {1} is greater than maximum allowed size ({2} for {3}), rejecting.", subject, subject.Release.Size, maxSize, subject.Movie.Title); return Decision.Reject("{0} is larger than maximum allowed {1} (for {2})", subject.Release.Size.SizeSuffix(), maxSize.SizeSuffix(), subject.Movie.Title); } diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/AlreadyImportedSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/AlreadyImportedSpecification.cs index 595b9fb3c4..5492ea2f47 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/AlreadyImportedSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/AlreadyImportedSpecification.cs @@ -86,9 +86,8 @@ public Decision IsSatisfiedBy(RemoteMovie subject, SearchCriteriaBase searchCrit } } - // Only based on title because a release with the same title on another indexer/released at + // Only based on title because a release with the same title on another indexer/released at // a different time very likely has the exact same content and we don't need to also try it. - if (release.Title.Equals(lastGrabbed.SourceTitle, StringComparison.InvariantCultureIgnoreCase)) { _logger.Debug("Has same release name as a grabbed and imported release"); diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/BlacklistSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/BlacklistSpecification.cs index c0138c3cb2..eb74b50232 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/BlacklistSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/BlacklistSpecification.cs @@ -21,7 +21,6 @@ public BlacklistSpecification(IBlacklistService blacklistService, Logger logger) public Decision IsSatisfiedBy(RemoteMovie subject, SearchCriteriaBase searchCriteria) { - if (_blacklistService.Blacklisted(subject.Movie.Id, subject.Release)) { _logger.Debug("{0} is blacklisted, rejecting.", subject.Release.Title); diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/MinimumAgeSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/MinimumAgeSpecification.cs index d21cb6efc4..53e228de03 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/MinimumAgeSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/MinimumAgeSpecification.cs @@ -38,7 +38,6 @@ public virtual Decision IsSatisfiedBy(RemoteMovie subject, SearchCriteriaBase se return Decision.Accept(); } - _logger.Debug("Checking if report meets minimum age requirements. {0}", ageRounded); if (age < minimumAge) diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/QueueSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/QueueSpecification.cs index 7edb8c1501..55e6b3cb54 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/QueueSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/QueueSpecification.cs @@ -26,7 +26,6 @@ public QueueSpecification(IQueueService queueService, public Decision IsSatisfiedBy(RemoteMovie subject, SearchCriteriaBase searchCriteria) { - var queue = _queueService.GetQueue(); var matchingMovies = queue.Where(q => q.RemoteMovie?.Movie != null && q.RemoteMovie.Movie.Id == subject.Movie.Id) diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/RepackSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/RepackSpecification.cs index f75c22d944..c19181eb19 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/RepackSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/RepackSpecification.cs @@ -50,10 +50,12 @@ public Decision IsSatisfiedBy(RemoteMovie subject, SearchCriteriaBase searchCrit { _logger.Debug( "Release is a repack for a different release group. Release Group: {0}. File release group: {1}", - releaseGroup, fileReleaseGroup); + releaseGroup, + fileReleaseGroup); return Decision.Reject( "Release is a repack for a different release group. Release Group: {0}. File release group: {1}", - releaseGroup, fileReleaseGroup); + releaseGroup, + fileReleaseGroup); } } } diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/RequiredIndexerFlagsSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/RequiredIndexerFlagsSpecification.cs index 34b7209305..91a682fd6f 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/RequiredIndexerFlagsSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/RequiredIndexerFlagsSpecification.cs @@ -25,9 +25,9 @@ public Decision IsSatisfiedBy(RemoteMovie subject, SearchCriteriaBase searchCrit { var torrentInfo = subject.Release; - IIndexerSettings indexerSettings = null; - try { + try + { indexerSettings = _indexerFactory.Get(subject.Release.IndexerId)?.Settings as IIndexerSettings; } catch (Exception) @@ -43,7 +43,7 @@ public Decision IsSatisfiedBy(RemoteMovie subject, SearchCriteriaBase searchCrit if (indexerSettings is ITorrentIndexerSettings torrentIndexerSettings) { var requiredFlags = torrentIndexerSettings.RequiredFlags; - var requiredFlag = (IndexerFlags) 0; + var requiredFlag = (IndexerFlags)0; if (requiredFlags == null || !requiredFlags.Any()) { @@ -56,6 +56,7 @@ public Decision IsSatisfiedBy(RemoteMovie subject, SearchCriteriaBase searchCrit { return Decision.Accept(); } + requiredFlag |= (IndexerFlags)flag; } diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/AvailabilitySpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/AvailabilitySpecification.cs index 44d1c137b4..704145dbba 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/AvailabilitySpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/AvailabilitySpecification.cs @@ -1,7 +1,7 @@ using NLog; +using NzbDrone.Core.Configuration; using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Configuration; namespace NzbDrone.Core.DecisionEngine.Specifications.RssSync { @@ -29,6 +29,7 @@ public Decision IsSatisfiedBy(RemoteMovie subject, SearchCriteriaBase searchCrit return Decision.Accept(); } } + if (!subject.Movie.IsAvailable(_settingsService.AvailabilityDelay)) { return Decision.Reject("Movie {0} will only be considered available {1} days after {2}", subject.Movie, _settingsService.AvailabilityDelay, subject.Movie.MinimumAvailability.ToString()); diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/DelaySpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/DelaySpecification.cs index 77ea89651d..acfe1c058c 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/DelaySpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/DelaySpecification.cs @@ -67,32 +67,30 @@ public virtual Decision IsSatisfiedBy(RemoteMovie subject, SearchCriteriaBase se if (isPreferredProtocol && (subject.Movie.MovieFileId != 0 && subject.Movie.MovieFile != null) && (preferredCount > 0 || preferredWords == null)) { - var upgradable = _qualityUpgradableSpecification.IsUpgradable(profile, subject.Movie.MovieFile.Quality, subject.ParsedMovieInfo.Quality); + var upgradable = _qualityUpgradableSpecification.IsUpgradable(profile, subject.Movie.MovieFile.Quality, subject.ParsedMovieInfo.Quality); - if (upgradable) + if (upgradable) + { + var revisionUpgrade = _qualityUpgradableSpecification.IsRevisionUpgrade(subject.Movie.MovieFile.Quality, subject.ParsedMovieInfo.Quality); + + if (revisionUpgrade) { - var revisionUpgrade = _qualityUpgradableSpecification.IsRevisionUpgrade(subject.Movie.MovieFile.Quality, subject.ParsedMovieInfo.Quality); - - if (revisionUpgrade) - { - _logger.Debug("New quality is a better revision for existing quality and preferred word count is {0}, skipping delay", preferredCount); - return Decision.Accept(); - } + _logger.Debug("New quality is a better revision for existing quality and preferred word count is {0}, skipping delay", preferredCount); + return Decision.Accept(); } - + } } // If quality meets or exceeds the best allowed quality in the profile accept it immediately var bestQualityInProfile = profile.LastAllowedQuality(); var isBestInProfile = comparer.Compare(subject.ParsedMovieInfo.Quality.Quality, bestQualityInProfile) >= 0; - if (isBestInProfile && isPreferredProtocol && (preferredCount > 0 || preferredWords == null)) + if (isBestInProfile && isPreferredProtocol && (preferredCount > 0 || preferredWords == null)) { _logger.Debug("Quality is highest in profile for preferred protocol and preferred word count is {0}, will not delay.", preferredCount); return Decision.Accept(); } - var oldest = _pendingReleaseService.OldestPendingRelease(subject.Movie.Id); if (oldest != null && oldest.Release.AgeMinutes > delay) diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/HistorySpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/HistorySpecification.cs index 09f4515721..eefe79c6de 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/HistorySpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/HistorySpecification.cs @@ -39,42 +39,41 @@ public virtual Decision IsSatisfiedBy(RemoteMovie subject, SearchCriteriaBase se var cdhEnabled = _configService.EnableCompletedDownloadHandling; - _logger.Debug("Performing history status check on report"); - _logger.Debug("Checking current status of movie [{0}] in history", subject.Movie.Id); - var mostRecent = _historyService.MostRecentForMovie(subject.Movie.Id); + _logger.Debug("Performing history status check on report"); + _logger.Debug("Checking current status of movie [{0}] in history", subject.Movie.Id); + var mostRecent = _historyService.MostRecentForMovie(subject.Movie.Id); - if (mostRecent != null && mostRecent.EventType == HistoryEventType.Grabbed) + if (mostRecent != null && mostRecent.EventType == HistoryEventType.Grabbed) + { + var recent = mostRecent.Date.After(DateTime.UtcNow.AddHours(-12)); + var cutoffUnmet = _qualityUpgradableSpecification.CutoffNotMet(subject.Movie.Profile, mostRecent.Quality, subject.ParsedMovieInfo.Quality); + var upgradeable = _qualityUpgradableSpecification.IsUpgradable(subject.Movie.Profile, mostRecent.Quality, subject.ParsedMovieInfo.Quality); + + if (!recent && cdhEnabled) { - var recent = mostRecent.Date.After(DateTime.UtcNow.AddHours(-12)); - var cutoffUnmet = _qualityUpgradableSpecification.CutoffNotMet(subject.Movie.Profile, mostRecent.Quality, subject.ParsedMovieInfo.Quality); - var upgradeable = _qualityUpgradableSpecification.IsUpgradable(subject.Movie.Profile, mostRecent.Quality, subject.ParsedMovieInfo.Quality); - - if (!recent && cdhEnabled) - { - return Decision.Accept(); - } - - if (!cutoffUnmet) - { - if (recent) - { - return Decision.Reject("Recent grab event in history already meets cutoff: {0}", mostRecent.Quality); - } - - return Decision.Reject("CDH is disabled and grab event in history already meets cutoff: {0}", mostRecent.Quality); - } - - if (!upgradeable) - { - if (recent) - { - return Decision.Reject("Recent grab event in history is of equal or higher quality: {0}", mostRecent.Quality); - } - - return Decision.Reject("CDH is disabled and grab event in history is of equal or higher quality: {0}", mostRecent.Quality); - } + return Decision.Accept(); } + if (!cutoffUnmet) + { + if (recent) + { + return Decision.Reject("Recent grab event in history already meets cutoff: {0}", mostRecent.Quality); + } + + return Decision.Reject("CDH is disabled and grab event in history already meets cutoff: {0}", mostRecent.Quality); + } + + if (!upgradeable) + { + if (recent) + { + return Decision.Reject("Recent grab event in history is of equal or higher quality: {0}", mostRecent.Quality); + } + + return Decision.Reject("CDH is disabled and grab event in history is of equal or higher quality: {0}", mostRecent.Quality); + } + } return Decision.Accept(); } diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/ProperSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/ProperSpecification.cs index 3cd8af9a6f..7f22ed7614 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/ProperSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/RssSync/ProperSpecification.cs @@ -36,21 +36,20 @@ public virtual Decision IsSatisfiedBy(RemoteMovie subject, SearchCriteriaBase se var file = subject.Movie.MovieFile; - if (_qualityUpgradableSpecification.IsRevisionUpgrade(file.Quality, subject.ParsedMovieInfo.Quality)) + if (_qualityUpgradableSpecification.IsRevisionUpgrade(file.Quality, subject.ParsedMovieInfo.Quality)) + { + if (file.DateAdded < DateTime.Today.AddDays(-7)) { - if (file.DateAdded < DateTime.Today.AddDays(-7)) - { - _logger.Debug("Proper for old file, rejecting: {0}", subject); - return Decision.Reject("Proper for old file"); - } - - if (!_configService.AutoDownloadPropers) - { - _logger.Debug("Auto downloading of propers is disabled"); - return Decision.Reject("Proper downloading is disabled"); - } + _logger.Debug("Proper for old file, rejecting: {0}", subject); + return Decision.Reject("Proper for old file"); } + if (!_configService.AutoDownloadPropers) + { + _logger.Debug("Auto downloading of propers is disabled"); + return Decision.Reject("Proper downloading is disabled"); + } + } return Decision.Accept(); } diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradableSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradableSpecification.cs index b91283861a..dcedb23db6 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradableSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradableSpecification.cs @@ -66,7 +66,6 @@ public bool CutoffNotMet(Profile profile, QualityModel currentQuality, QualityMo } return false; - } public bool IsRevisionUpgrade(QualityModel currentQuality, QualityModel newQuality) diff --git a/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradeDiskSpecification.cs b/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradeDiskSpecification.cs index b183f24265..8dfb6eae79 100644 --- a/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradeDiskSpecification.cs +++ b/src/NzbDrone.Core/DecisionEngine/Specifications/UpgradeDiskSpecification.cs @@ -26,13 +26,12 @@ public virtual Decision IsSatisfiedBy(RemoteMovie subject, SearchCriteriaBase se } var file = subject.Movie.MovieFile; - _logger.Debug("Comparing file quality with report. Existing file is {0}", file.Quality); - - if (!_qualityUpgradableSpecification.IsUpgradable(subject.Movie.Profile, file.Quality, subject.ParsedMovieInfo.Quality)) - { - return Decision.Reject("Quality for existing file on disk is of equal or higher preference: {0}", file.Quality); - } + _logger.Debug("Comparing file quality with report. Existing file is {0}", file.Quality); + if (!_qualityUpgradableSpecification.IsUpgradable(subject.Movie.Profile, file.Quality, subject.ParsedMovieInfo.Quality)) + { + return Decision.Reject("Quality for existing file on disk is of equal or higher preference: {0}", file.Quality); + } return Decision.Accept(); } diff --git a/src/NzbDrone.Core/DiskSpace/DiskSpaceService.cs b/src/NzbDrone.Core/DiskSpace/DiskSpaceService.cs index 63402605c1..3a6395b69c 100644 --- a/src/NzbDrone.Core/DiskSpace/DiskSpaceService.cs +++ b/src/NzbDrone.Core/DiskSpace/DiskSpaceService.cs @@ -1,6 +1,6 @@ using System; -using System.IO; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Text.RegularExpressions; using NLog; @@ -73,11 +73,11 @@ private IEnumerable GetDiskSpace(IEnumerable paths, bool supp } diskSpace = new DiskSpace - { - Path = path, - FreeSpace = freeSpace.Value, - TotalSpace = totalSpace.Value - }; + { + Path = path, + FreeSpace = freeSpace.Value, + TotalSpace = totalSpace.Value + }; diskSpace.Label = _diskProvider.GetVolumeLabel(path); } diff --git a/src/NzbDrone.Core/Download/Clients/Blackhole/ScanWatchFolder.cs b/src/NzbDrone.Core/Download/Clients/Blackhole/ScanWatchFolder.cs index fe69586d20..6fef92d305 100644 --- a/src/NzbDrone.Core/Download/Clients/Blackhole/ScanWatchFolder.cs +++ b/src/NzbDrone.Core/Download/Clients/Blackhole/ScanWatchFolder.cs @@ -24,7 +24,7 @@ public class ScanWatchFolder : IScanWatchFolder private readonly IDiskProvider _diskProvider; private readonly IDiskScanService _diskScanService; private readonly INamingConfigService _namingConfigService; - private readonly ICached> _watchFolderItemCache; + private readonly ICached> _watchFolderItemCache; public ScanWatchFolder(ICacheManager cacheManager, IDiskScanService diskScanService, INamingConfigService namingConfigService, IDiskProvider diskProvider, Logger logger) { diff --git a/src/NzbDrone.Core/Download/Clients/Blackhole/WatchFolderItem.cs b/src/NzbDrone.Core/Download/Clients/Blackhole/WatchFolderItem.cs index 554aa82b5a..bba855d0d5 100644 --- a/src/NzbDrone.Core/Download/Clients/Blackhole/WatchFolderItem.cs +++ b/src/NzbDrone.Core/Download/Clients/Blackhole/WatchFolderItem.cs @@ -1,9 +1,8 @@ -using NzbDrone.Common.Disk; -using System; +using System; +using NzbDrone.Common.Disk; namespace NzbDrone.Core.Download.Clients.Blackhole { - public class WatchFolderItem { public string DownloadId { get; set; } diff --git a/src/NzbDrone.Core/Download/Clients/Deluge/Deluge.cs b/src/NzbDrone.Core/Download/Clients/Deluge/Deluge.cs index a5df892760..a1f97e5c80 100644 --- a/src/NzbDrone.Core/Download/Clients/Deluge/Deluge.cs +++ b/src/NzbDrone.Core/Download/Clients/Deluge/Deluge.cs @@ -46,7 +46,8 @@ public override void MarkItemAsImported(DownloadClientItem downloadClientItem) catch (DownloadClientUnavailableException) { _logger.Warn("Failed to set torrent post-import label \"{0}\" for {1} in Deluge. Does the label exist?", - Settings.MovieImportedCategory, downloadClientItem.Title); + Settings.MovieImportedCategory, + downloadClientItem.Title); } } } @@ -69,8 +70,8 @@ protected override string AddFromMagnetLink(RemoteMovie remoteMovie, string hash var isRecentMovie = remoteMovie.Movie.IsRecentMovie; - if (isRecentMovie && Settings.RecentMoviePriority == (int)DelugePriority.First || - !isRecentMovie && Settings.OlderMoviePriority == (int)DelugePriority.First) + if ((isRecentMovie && Settings.RecentMoviePriority == (int)DelugePriority.First) || + (!isRecentMovie && Settings.OlderMoviePriority == (int)DelugePriority.First)) { _proxy.MoveTorrentToTopInQueue(actualHash, Settings); } @@ -96,8 +97,8 @@ protected override string AddFromTorrentFile(RemoteMovie remoteMovie, string has var isRecentMovie = remoteMovie.Movie.IsRecentMovie; - if (isRecentMovie && Settings.RecentMoviePriority == (int)DelugePriority.First || - !isRecentMovie && Settings.OlderMoviePriority == (int)DelugePriority.First) + if ((isRecentMovie && Settings.RecentMoviePriority == (int)DelugePriority.First) || + (!isRecentMovie && Settings.OlderMoviePriority == (int)DelugePriority.First)) { _proxy.MoveTorrentToTopInQueue(actualHash, Settings); } @@ -124,7 +125,10 @@ public override IEnumerable GetItems() foreach (var torrent in torrents) { - if (torrent.Hash == null) continue; + if (torrent.Hash == null) + { + continue; + } var item = new DownloadClientItem(); item.DownloadId = torrent.Hash.ToUpper(); @@ -218,7 +222,11 @@ public override DownloadClientInfo GetStatus() protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestCategory()); failures.AddIfNotNull(TestGetTorrents()); } diff --git a/src/NzbDrone.Core/Download/Clients/Deluge/DelugeException.cs b/src/NzbDrone.Core/Download/Clients/Deluge/DelugeException.cs index 7646625478..45df09c8c0 100644 --- a/src/NzbDrone.Core/Download/Clients/Deluge/DelugeException.cs +++ b/src/NzbDrone.Core/Download/Clients/Deluge/DelugeException.cs @@ -5,7 +5,7 @@ public class DelugeException : DownloadClientException public int Code { get; set; } public DelugeException(string message, int code) - :base (message + " (code " + code + ")") + : base(message + " (code " + code + ")") { Code = code; } diff --git a/src/NzbDrone.Core/Download/Clients/Deluge/DelugeProxy.cs b/src/NzbDrone.Core/Download/Clients/Deluge/DelugeProxy.cs index f3068c497b..f8a331de98 100644 --- a/src/NzbDrone.Core/Download/Clients/Deluge/DelugeProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/Deluge/DelugeProxy.cs @@ -31,7 +31,7 @@ public interface IDelugeProxy public class DelugeProxy : IDelugeProxy { - private static readonly string[] requiredProperties = new string[] { "hash", "name", "state", "progress", "eta", "message", "is_finished", "save_path", "total_size", "total_done", "time_added", "active_time", "ratio", "is_auto_managed", "stop_at_ratio", "remove_at_ratio", "stop_ratio" }; + private static readonly string[] RequiredProperties = new string[] { "hash", "name", "state", "progress", "eta", "message", "is_finished", "save_path", "total_size", "total_done", "time_added", "active_time", "ratio", "is_auto_managed", "stop_at_ratio", "remove_at_ratio", "stop_ratio" }; private readonly IHttpClient _httpClient; private readonly Logger _logger; @@ -82,7 +82,7 @@ public DelugeTorrent[] GetTorrents(DelugeSettings settings) // TODO: get_torrents_status returns the files as well, which starts to cause deluge timeouts when you get enough season packs. //var response = ProcessRequest>(settings, "core.get_torrents_status", filter, new String[0]); - var response = ProcessRequest(settings, "web.update_ui", requiredProperties, filter); + var response = ProcessRequest(settings, "web.update_ui", RequiredProperties, filter); return GetTorrents(response); } @@ -93,7 +93,7 @@ public DelugeTorrent[] GetTorrentsByLabel(string label, DelugeSettings settings) filter.Add("label", label); //var response = ProcessRequest>(settings, "core.get_torrents_status", filter, new String[0]); - var response = ProcessRequest(settings, "web.update_ui", requiredProperties, filter); + var response = ProcessRequest(settings, "web.update_ui", RequiredProperties, filter); return GetTorrents(response); } @@ -101,10 +101,10 @@ public DelugeTorrent[] GetTorrentsByLabel(string label, DelugeSettings settings) public string AddTorrentFromMagnet(string magnetLink, DelugeSettings settings) { var options = new - { - add_paused = settings.AddPaused, - remove_at_ratio = false - }; + { + add_paused = settings.AddPaused, + remove_at_ratio = false + }; var response = ProcessRequest(settings, "core.add_torrent_magnet", magnetLink, options); @@ -114,10 +114,10 @@ public string AddTorrentFromMagnet(string magnetLink, DelugeSettings settings) public string AddTorrentFromFile(string filename, byte[] fileContent, DelugeSettings settings) { var options = new - { - add_paused = settings.AddPaused, - remove_at_ratio = false - }; + { + add_paused = settings.AddPaused, + remove_at_ratio = false + }; var response = ProcessRequest(settings, "core.add_torrent_file", filename, fileContent, options); @@ -167,7 +167,10 @@ public void SetTorrentConfiguration(string hash, string key, object value, Delug public void SetTorrentSeedingConfiguration(string hash, TorrentSeedConfiguration seedConfiguration, DelugeSettings settings) { - if (seedConfiguration == null) return; + if (seedConfiguration == null) + { + return; + } var ratioArguments = new Dictionary(); @@ -224,6 +227,7 @@ protected TResult ProcessRequest(DelugeSettings settings, string method { return response.Result; } + error = response.Error.ToObject(); throw new DownloadClientAuthenticationException(error.Message); @@ -294,6 +298,7 @@ private void AuthenticateClient(JsonRpcRequestBuilder requestBuilder, DelugeSett _logger.Debug("Deluge authentication failed."); throw new DownloadClientAuthenticationException("Failed to authenticate with Deluge."); } + _logger.Debug("Deluge authentication succeeded."); cookies = response.GetCookies(); @@ -326,7 +331,7 @@ private void ConnectDaemon(JsonRpcRequestBuilder requestBuilder) if (resultHosts.Result != null) { // The returned list contains the id, ip, port and status of each available connection. We want the 127.0.0.1 - var connection = resultHosts.Result.FirstOrDefault(v => "127.0.0.1" == (v[1] as string)); + var connection = resultHosts.Result.FirstOrDefault(v => (v[1] as string) == "127.0.0.1"); if (connection != null) { @@ -337,7 +342,7 @@ private void ConnectDaemon(JsonRpcRequestBuilder requestBuilder) } } - throw new DownloadClientException("Failed to connect to Deluge daemon."); + throw new DownloadClientException("Failed to connect to Deluge daemon."); } private DelugeTorrent[] GetTorrents(DelugeUpdateUIResult result) diff --git a/src/NzbDrone.Core/Download/Clients/Deluge/DelugeTorrentStatus.cs b/src/NzbDrone.Core/Download/Clients/Deluge/DelugeTorrentStatus.cs index bb8f06396f..e9f5a6a706 100644 --- a/src/NzbDrone.Core/Download/Clients/Deluge/DelugeTorrentStatus.cs +++ b/src/NzbDrone.Core/Download/Clients/Deluge/DelugeTorrentStatus.cs @@ -1,6 +1,6 @@ namespace NzbDrone.Core.Download.Clients.Deluge { - class DelugeTorrentStatus + internal class DelugeTorrentStatus { public const string Paused = "Paused"; public const string Queued = "Queued"; diff --git a/src/NzbDrone.Core/Download/Clients/DownloadClientAuthenticationException.cs b/src/NzbDrone.Core/Download/Clients/DownloadClientAuthenticationException.cs index 38c9564790..6d27bb9bd6 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadClientAuthenticationException.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadClientAuthenticationException.cs @@ -7,19 +7,16 @@ public class DownloadClientAuthenticationException : DownloadClientException public DownloadClientAuthenticationException(string message, params object[] args) : base(message, args) { - } public DownloadClientAuthenticationException(string message) : base(message) { - } public DownloadClientAuthenticationException(string message, Exception innerException, params object[] args) : base(message, innerException, args) { - } public DownloadClientAuthenticationException(string message, Exception innerException) diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/DiskStationApiInfo.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/DiskStationApiInfo.cs index 67d150a9be..60f84c6727 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/DiskStationApiInfo.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/DiskStationApiInfo.cs @@ -16,7 +16,10 @@ public class DiskStationApiInfo public string Path { - get { return _path; } + get + { + return _path; + } set { diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationSettings.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationSettings.cs index 11ff9d7a72..e21d7a7189 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationSettings.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationSettings.cs @@ -53,8 +53,8 @@ public class DownloadStationSettings : IProviderConfig public DownloadStationSettings() { - this.Host = "127.0.0.1"; - this.Port = 5000; + Host = "127.0.0.1"; + Port = 5000; } public NzbDroneValidationResult Validate() diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTask.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTask.cs index 5b4a612532..41faac6334 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTask.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTask.cs @@ -29,13 +29,18 @@ public class DownloadStationTask public override string ToString() { - return this.Title; + return Title; } } public enum DownloadStationTaskType { - BT, NZB, http, ftp, eMule, https + BT, + NZB, + http, + ftp, + eMule, + https } public enum DownloadStationTaskStatus diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTaskAdditional.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTaskAdditional.cs index 45c9fd1377..81e55569e3 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTaskAdditional.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/DownloadStationTaskAdditional.cs @@ -1,5 +1,5 @@ -using Newtonsoft.Json; -using System.Collections.Generic; +using System.Collections.Generic; +using Newtonsoft.Json; namespace NzbDrone.Core.Download.Clients.DownloadStation { diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DSMInfoProxy.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DSMInfoProxy.cs index 3aad129a70..322296c06b 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DSMInfoProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DSMInfoProxy.cs @@ -12,8 +12,8 @@ public interface IDSMInfoProxy public class DSMInfoProxy : DiskStationProxyBase, IDSMInfoProxy { - public DSMInfoProxy(IHttpClient httpClient, ICacheManager cacheManager, Logger logger) : - base(DiskStationApi.DSMInfo, "SYNO.DSM.Info", httpClient, cacheManager, logger) + public DSMInfoProxy(IHttpClient httpClient, ICacheManager cacheManager, Logger logger) + : base(DiskStationApi.DSMInfo, "SYNO.DSM.Info", httpClient, cacheManager, logger) { } diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DiskStationProxyBase.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DiskStationProxyBase.cs index 2b2ea6ca7d..d0f817df2b 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DiskStationProxyBase.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DiskStationProxyBase.cs @@ -60,7 +60,8 @@ private string GenerateSessionCacheKey(DownloadStationSettings settings) protected DiskStationResponse ProcessRequest(HttpRequestBuilder requestBuilder, string operation, - DownloadStationSettings settings) where T : new() + DownloadStationSettings settings) + where T : new() { return ProcessRequest(requestBuilder, operation, _apiType, settings); } @@ -68,7 +69,8 @@ protected DiskStationResponse ProcessRequest(HttpRequestBuilder requestBui private DiskStationResponse ProcessRequest(HttpRequestBuilder requestBuilder, string operation, DiskStationApi api, - DownloadStationSettings settings) where T : new() + DownloadStationSettings settings) + where T : new() { var request = requestBuilder.Build(); HttpResponse response; diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DownloadStationInfoProxy.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DownloadStationInfoProxy.cs index 9b0cb00eda..1723fcc807 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DownloadStationInfoProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Proxies/DownloadStationInfoProxy.cs @@ -1,7 +1,7 @@ -using NLog; -using NzbDrone.Common.Http; -using System.Collections.Generic; +using System.Collections.Generic; +using NLog; using NzbDrone.Common.Cache; +using NzbDrone.Common.Http; namespace NzbDrone.Core.Download.Clients.DownloadStation.Proxies { @@ -12,8 +12,8 @@ public interface IDownloadStationInfoProxy : IDiskStationProxy public class DownloadStationInfoProxy : DiskStationProxyBase, IDownloadStationInfoProxy { - public DownloadStationInfoProxy(IHttpClient httpClient, ICacheManager cacheManager, Logger logger) : - base(DiskStationApi.DownloadStationInfo, "SYNO.DownloadStation.Info", httpClient, cacheManager, logger) + public DownloadStationInfoProxy(IHttpClient httpClient, ICacheManager cacheManager, Logger logger) + : base(DiskStationApi.DownloadStationInfo, "SYNO.DownloadStation.Info", httpClient, cacheManager, logger) { } diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationError.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationError.cs index edb82465b1..50758d3afa 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationError.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationError.cs @@ -47,7 +47,7 @@ static DiskStationError() FileStationMessages = new Dictionary { - { 160, "Permission denied. Give your user access to FileStation."}, + { 160, "Permission denied. Give your user access to FileStation." }, { 400, "Invalid parameter of file operation" }, { 401, "Unknown error of file operation" }, { 402, "System is too busy" }, @@ -100,7 +100,7 @@ public string GetMessage(DiskStationApi api) return CommonMessages[Code]; } - return $"{ Code } - Unknown error"; + return $"{Code} - Unknown error"; } } } diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationInfoResponse.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationInfoResponse.cs index 54ac7dc8b2..6c40ae75c2 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationInfoResponse.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationInfoResponse.cs @@ -4,6 +4,5 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Responses { public class DiskStationApiInfoResponse : Dictionary { - } } diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationResponse.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationResponse.cs index de7aadfc66..43c9816691 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationResponse.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DiskStationResponse.cs @@ -1,6 +1,7 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Responses { - public class DiskStationResponse where T:new() + public class DiskStationResponse + where T : new() { public bool Success { get; set; } diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DownloadStationTaskInfoResponse.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DownloadStationTaskInfoResponse.cs index 1d974b9135..ebd79f3d70 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DownloadStationTaskInfoResponse.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/DownloadStationTaskInfoResponse.cs @@ -5,7 +5,7 @@ namespace NzbDrone.Core.Download.Clients.DownloadStation.Responses public class DownloadStationTaskInfoResponse { public int Offset { get; set; } - public List Tasks {get;set;} + public List Tasks { get; set; } public int Total { get; set; } } } diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/FileStationListFileInfoResponse.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/FileStationListFileInfoResponse.cs index 2f689a48bb..f31d51a687 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/FileStationListFileInfoResponse.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/Responses/FileStationListFileInfoResponse.cs @@ -7,6 +7,6 @@ public class FileStationListFileInfoResponse public bool IsDir { get; set; } public string Name { get; set; } public string Path { get; set; } - public Dictionary Additional { get; set; } + public Dictionary Additional { get; set; } } } diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/SerialNumberProvider.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/SerialNumberProvider.cs index ddf971384f..88a419d224 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/SerialNumberProvider.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/SerialNumberProvider.cs @@ -15,8 +15,8 @@ public interface ISerialNumberProvider public class SerialNumberProvider : ISerialNumberProvider { private readonly IDSMInfoProxy _proxy; - private ICached _cache; private readonly ILogger _logger; + private ICached _cache; public SerialNumberProvider(ICacheManager cacheManager, IDSMInfoProxy proxy, diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/SharedFolderResolver.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/SharedFolderResolver.cs index d1db18db0a..25ff176f62 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/SharedFolderResolver.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/SharedFolderResolver.cs @@ -14,8 +14,8 @@ public interface ISharedFolderResolver public class SharedFolderResolver : ISharedFolderResolver { private readonly IFileStationProxy _proxy; - private ICached _cache; private readonly ILogger _logger; + private ICached _cache; public SharedFolderResolver(ICacheManager cacheManager, IFileStationProxy proxy, diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/TorrentDownloadStation.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/TorrentDownloadStation.cs index a6e0d8e0ca..3613fedf9e 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/TorrentDownloadStation.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/TorrentDownloadStation.cs @@ -196,7 +196,11 @@ protected override string AddFromTorrentFile(RemoteMovie remoteMovie, string has protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestOutputPath()); failures.AddIfNotNull(TestGetTorrents()); } @@ -208,7 +212,7 @@ protected bool IsFinished(DownloadStationTask torrent) protected bool IsCompleted(DownloadStationTask torrent) { - return torrent.Status == DownloadStationTaskStatus.Seeding || IsFinished(torrent) || (torrent.Status == DownloadStationTaskStatus.Waiting && torrent.Size != 0 && GetRemainingSize(torrent) <= 0); + return torrent.Status == DownloadStationTaskStatus.Seeding || IsFinished(torrent) || (torrent.Status == DownloadStationTaskStatus.Waiting && torrent.Size != 0 && GetRemainingSize(torrent) <= 0); } protected string GetMessage(DownloadStationTask torrent) @@ -339,7 +343,7 @@ protected ValidationFailure TestOutputPath() return null; } - catch (DownloadClientAuthenticationException ex) // User could not have permission to access to downloadstation + catch (DownloadClientAuthenticationException ex) { _logger.Error(ex, ex.Message); return new NzbDroneValidationFailure(string.Empty, ex.Message); @@ -376,6 +380,7 @@ protected ValidationFailure TestConnection() DetailedDescription = "Please verify the hostname and port." }; } + return new NzbDroneValidationFailure(string.Empty, $"Unknown exception: {ex.Message}"); } catch (Exception ex) diff --git a/src/NzbDrone.Core/Download/Clients/DownloadStation/UsenetDownloadStation.cs b/src/NzbDrone.Core/Download/Clients/DownloadStation/UsenetDownloadStation.cs index 892f407df5..1ea58ba870 100644 --- a/src/NzbDrone.Core/Download/Clients/DownloadStation/UsenetDownloadStation.cs +++ b/src/NzbDrone.Core/Download/Clients/DownloadStation/UsenetDownloadStation.cs @@ -36,9 +36,8 @@ public UsenetDownloadStation(ISharedFolderResolver sharedFolderResolver, IDiskProvider diskProvider, IRemotePathMappingService remotePathMappingService, IValidateNzbs nzbValidationService, - Logger logger - ) - : base(httpClient, configService, namingConfigService, diskProvider, remotePathMappingService, nzbValidationService, logger) + Logger logger) + : base(httpClient, configService, namingConfigService, diskProvider, remotePathMappingService, nzbValidationService, logger) { _dsInfoProxy = dsInfoProxy; _dsTaskProxy = dsTaskProxy; @@ -191,7 +190,11 @@ protected override string AddFromNzbFile(RemoteMovie remoteMovie, string filenam protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestOutputPath()); failures.AddIfNotNull(TestGetNZB()); } @@ -238,7 +241,7 @@ protected ValidationFailure TestOutputPath() return null; } - catch (DownloadClientAuthenticationException ex) // User could not have permission to access to downloadstation + catch (DownloadClientAuthenticationException ex) { _logger.Error(ex, ex.Message); return new NzbDroneValidationFailure(string.Empty, ex.Message); @@ -275,6 +278,7 @@ protected ValidationFailure TestConnection() DetailedDescription = "Please verify the hostname and port." }; } + return new NzbDroneValidationFailure(string.Empty, "Unknown exception: " + ex.Message); } catch (Exception ex) diff --git a/src/NzbDrone.Core/Download/Clients/Hadouken/Hadouken.cs b/src/NzbDrone.Core/Download/Clients/Hadouken/Hadouken.cs index e64144654b..1488c8988a 100644 --- a/src/NzbDrone.Core/Download/Clients/Hadouken/Hadouken.cs +++ b/src/NzbDrone.Core/Download/Clients/Hadouken/Hadouken.cs @@ -76,7 +76,7 @@ public override IEnumerable GetItems() Title = torrent.Name, TotalSize = torrent.TotalSize, SeedRatio = torrent.DownloadedBytes <= 0 ? 0 : - (double) torrent.UploadedBytes / torrent.DownloadedBytes + (double)torrent.UploadedBytes / torrent.DownloadedBytes }; if (!string.IsNullOrEmpty(torrent.Error)) @@ -101,7 +101,7 @@ public override IEnumerable GetItems() item.Status = DownloadItemStatus.Downloading; } - item.CanMoveFiles = item.CanBeRemoved = (torrent.IsFinished && torrent.State == HadoukenTorrentState.Paused); + item.CanMoveFiles = item.CanBeRemoved = torrent.IsFinished && torrent.State == HadoukenTorrentState.Paused; items.Add(item); } @@ -142,7 +142,11 @@ public override DownloadClientInfo GetStatus() protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestGetTorrents()); } @@ -189,7 +193,7 @@ private ValidationFailure TestGetTorrents() catch (Exception ex) { _logger.Error(ex, ex.Message); - return new NzbDroneValidationFailure(String.Empty, "Failed to get the list of torrents: " + ex.Message); + return new NzbDroneValidationFailure(string.Empty, "Failed to get the list of torrents: " + ex.Message); } return null; diff --git a/src/NzbDrone.Core/Download/Clients/Hadouken/HadoukenProxy.cs b/src/NzbDrone.Core/Download/Clients/Hadouken/HadoukenProxy.cs index 6083851d58..4ab8f67c12 100644 --- a/src/NzbDrone.Core/Download/Clients/Hadouken/HadoukenProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/Hadouken/HadoukenProxy.cs @@ -145,7 +145,7 @@ private HadoukenTorrent MapTorrent(object[] item) SavePath = Convert.ToString(item[26]) }; } - catch(Exception ex) + catch (Exception ex) { _logger.Error(ex, "Failed to map Hadouken torrent data."); } diff --git a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortex.cs b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortex.cs index 2b812a9f5b..6841a460ed 100644 --- a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortex.cs +++ b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortex.cs @@ -8,10 +8,10 @@ using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Validation; -using NzbDrone.Core.RemotePathMappings; using NzbDrone.Core.Organizer; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.Validation; namespace NzbDrone.Core.Download.Clients.NzbVortex { @@ -82,22 +82,25 @@ public override IEnumerable GetItems() { queueItem.Status = DownloadItemStatus.Paused; } - else switch (vortexQueueItem.State) + else { - case NzbVortexStateType.Waiting: - queueItem.Status = DownloadItemStatus.Queued; - break; - case NzbVortexStateType.Done: - queueItem.Status = DownloadItemStatus.Completed; - break; - case NzbVortexStateType.UncompressFailed: - case NzbVortexStateType.CheckFailedDataCorrupt: - case NzbVortexStateType.BadlyEncoded: - queueItem.Status = DownloadItemStatus.Failed; - break; - default: - queueItem.Status = DownloadItemStatus.Downloading; - break; + switch (vortexQueueItem.State) + { + case NzbVortexStateType.Waiting: + queueItem.Status = DownloadItemStatus.Queued; + break; + case NzbVortexStateType.Done: + queueItem.Status = DownloadItemStatus.Completed; + break; + case NzbVortexStateType.UncompressFailed: + case NzbVortexStateType.CheckFailedDataCorrupt: + case NzbVortexStateType.BadlyEncoded: + queueItem.Status = DownloadItemStatus.Failed; + break; + default: + queueItem.Status = DownloadItemStatus.Downloading; + break; + } } queueItem.OutputPath = GetOutputPath(vortexQueueItem, queueItem); @@ -127,7 +130,6 @@ public override void RemoveItem(string downloadId, bool deleteData) { _proxy.Remove(id, deleteData, Settings); } - else { var queue = _proxy.GetQueue(30, Settings); diff --git a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexAuthenticationException.cs b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexAuthenticationException.cs index 10178b9ce2..6c8d3e34bd 100644 --- a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexAuthenticationException.cs +++ b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexAuthenticationException.cs @@ -2,21 +2,25 @@ namespace NzbDrone.Core.Download.Clients.NzbVortex { - class NzbVortexAuthenticationException : DownloadClientException + internal class NzbVortexAuthenticationException : DownloadClientException { - public NzbVortexAuthenticationException(string message, params object[] args) : base(message, args) + public NzbVortexAuthenticationException(string message, params object[] args) + : base(message, args) { } - public NzbVortexAuthenticationException(string message) : base(message) + public NzbVortexAuthenticationException(string message) + : base(message) { } - public NzbVortexAuthenticationException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public NzbVortexAuthenticationException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } - public NzbVortexAuthenticationException(string message, Exception innerException) : base(message, innerException) + public NzbVortexAuthenticationException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexNotLoggedInException.cs b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexNotLoggedInException.cs index 61bbb27d63..8735cb383b 100644 --- a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexNotLoggedInException.cs +++ b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexNotLoggedInException.cs @@ -2,25 +2,30 @@ namespace NzbDrone.Core.Download.Clients.NzbVortex { - class NzbVortexNotLoggedInException : DownloadClientException + internal class NzbVortexNotLoggedInException : DownloadClientException { - public NzbVortexNotLoggedInException() : this("Authentication is required") + public NzbVortexNotLoggedInException() + : this("Authentication is required") { } - public NzbVortexNotLoggedInException(string message, params object[] args) : base(message, args) + public NzbVortexNotLoggedInException(string message, params object[] args) + : base(message, args) { } - public NzbVortexNotLoggedInException(string message) : base(message) + public NzbVortexNotLoggedInException(string message) + : base(message) { } - public NzbVortexNotLoggedInException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public NzbVortexNotLoggedInException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } - public NzbVortexNotLoggedInException(string message, Exception innerException) : base(message, innerException) + public NzbVortexNotLoggedInException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexProxy.cs b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexProxy.cs index 7c78559ef5..4014e63346 100644 --- a/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/NzbVortex/NzbVortexProxy.cs @@ -92,7 +92,6 @@ public List GetQueue(int doneLimit, NzbVortexSettings settin { var requestBuilder = BuildRequest(settings).Resource("nzb"); - if (settings.TvCategory.IsNotNullOrWhiteSpace()) { requestBuilder.AddQueryParam("groupName", settings.TvCategory); diff --git a/src/NzbDrone.Core/Download/Clients/Nzbget/Nzbget.cs b/src/NzbDrone.Core/Download/Clients/Nzbget/Nzbget.cs index ad9a496aaa..3c3a047340 100644 --- a/src/NzbDrone.Core/Download/Clients/Nzbget/Nzbget.cs +++ b/src/NzbDrone.Core/Download/Clients/Nzbget/Nzbget.cs @@ -10,10 +10,10 @@ using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.Exceptions; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Validation; -using NzbDrone.Core.RemotePathMappings; using NzbDrone.Core.Organizer; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.Validation; namespace NzbDrone.Core.Download.Clients.Nzbget { @@ -21,7 +21,7 @@ public class Nzbget : UsenetClientBase { private readonly INzbgetProxy _proxy; private readonly string[] _successStatus = { "SUCCESS", "NONE" }; - private readonly string[] _deleteFailedStatus = { "HEALTH", "DUPE", "SCAN", "COPY" }; + private readonly string[] _deleteFailedStatus = { "HEALTH", "DUPE", "SCAN", "COPY" }; public Nzbget(INzbgetProxy proxy, IHttpClient httpClient, @@ -79,7 +79,7 @@ private IEnumerable GetQueue() queueItem.CanMoveFiles = true; queueItem.CanBeRemoved = true; - if (globalStatus.DownloadPaused || remainingSize == pausedSize && remainingSize != 0) + if (globalStatus.DownloadPaused || (remainingSize == pausedSize && remainingSize != 0)) { queueItem.Status = DownloadItemStatus.Paused; queueItem.RemainingSize = remainingSize; @@ -223,7 +223,10 @@ protected IEnumerable GetCategories(Dictionary c { var name = config.GetValueOrDefault("Category" + i + ".Name"); - if (name == null) yield break; + if (name == null) + { + yield break; + } var destDir = config.GetValueOrDefault("Category" + i + ".DestDir"); @@ -273,6 +276,7 @@ private ValidationFailure TestConnection() { return new ValidationFailure("Username", "Authentication failed"); } + _logger.Error(ex, "Unable to connect to NZBGet"); return new ValidationFailure("Host", "Unable to connect to NZBGet"); } diff --git a/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetProxy.cs b/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetProxy.cs index 7c1690dab6..092325bc99 100644 --- a/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetProxy.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Net; using NLog; +using NzbDrone.Common.Cache; using NzbDrone.Common.Http; using NzbDrone.Common.Serializer; -using System.Net; -using NzbDrone.Common.Cache; namespace NzbDrone.Core.Download.Clients.Nzbget { @@ -102,6 +102,7 @@ private string DownloadNzbLegacy13(byte[] nzbData, string title, string category return droneId; } + private string DownloadNzbLegacy12(byte[] nzbData, string title, string category, int priority, NzbgetSettings settings) { var response = ProcessRequest(settings, "append", title, category, priority, false, nzbData); @@ -158,7 +159,6 @@ public Dictionary GetConfig(NzbgetSettings settings) return ProcessRequest>(settings, "config").ToDictionary(v => v.Name, v => v.Value); } - public void RemoveItem(string id, NzbgetSettings settings) { var queue = GetQueue(settings); @@ -187,7 +187,6 @@ public void RemoveItem(string id, NzbgetSettings settings) _logger.Warn("Failed to remove item from NZBGet, {0} [{1}]", queueItem.NzbName, queueItem.NzbId); } } - else if (historyItem != null) { if (!EditQueue("HistoryDelete", 0, "", historyItem.Id, settings)) @@ -195,7 +194,6 @@ public void RemoveItem(string id, NzbgetSettings settings) _logger.Warn("Failed to remove item from NZBGet history, {0} [{1}]", historyItem.Name, historyItem.Id); } } - else { _logger.Warn("Unable to remove item from NZBGet, Unknown ID: {0}", id); diff --git a/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetResponse.cs b/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetResponse.cs index a41667824c..c6132fbae3 100644 --- a/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetResponse.cs +++ b/src/NzbDrone.Core/Download/Clients/Nzbget/NzbgetResponse.cs @@ -5,6 +5,5 @@ public class NzbgetResponse public string Version { get; set; } public T Result { get; set; } - } } diff --git a/src/NzbDrone.Core/Download/Clients/Pneumatic/Pneumatic.cs b/src/NzbDrone.Core/Download/Clients/Pneumatic/Pneumatic.cs index 0911d74e43..c84a40b3dd 100644 --- a/src/NzbDrone.Core/Download/Clients/Pneumatic/Pneumatic.cs +++ b/src/NzbDrone.Core/Download/Clients/Pneumatic/Pneumatic.cs @@ -8,9 +8,9 @@ using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.Indexers; -using NzbDrone.Core.RemotePathMappings; using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.RemotePathMappings; namespace NzbDrone.Core.Download.Clients.Pneumatic { @@ -43,7 +43,6 @@ public override string Download(RemoteMovie remoteMovie) //{ // 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) @@ -56,7 +55,6 @@ public override string Download(RemoteMovie remoteMovie) var strmFile = WriteStrmFile(title, nzbFile); - return GetDownloadClientId(strmFile); } diff --git a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrent.cs b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrent.cs index 3a6cd6a735..0d43b54fc3 100644 --- a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrent.cs +++ b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrent.cs @@ -1,18 +1,18 @@ using System; using System.Collections.Generic; +using System.Net; +using FluentValidation.Results; +using NLog; +using NzbDrone.Common.Cache; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles.TorrentInfo; -using NLog; -using NzbDrone.Core.Validation; -using FluentValidation.Results; -using System.Net; +using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.RemotePathMappings; -using NzbDrone.Core.Organizer; -using NzbDrone.Common.Cache; +using NzbDrone.Core.Validation; namespace NzbDrone.Core.Download.Clients.QBittorrent { @@ -57,8 +57,7 @@ public override void MarkItemAsImported(DownloadClientItem downloadClientItem) } catch (DownloadClientException) { - _logger.Warn("Failed to set post-import torrent label \"{0}\" for {1} in qBittorrent. Does the label exist?", - Settings.MovieImportedCategory, downloadClientItem.Title); + _logger.Warn("Failed to set post-import torrent label \"{0}\" for {1} in qBittorrent. Does the label exist?", Settings.MovieImportedCategory, downloadClientItem.Title); } } } @@ -74,8 +73,8 @@ protected override string AddFromMagnetLink(RemoteMovie remoteMovie, string hash var isRecentMovie = remoteMovie.Movie.IsRecentMovie; - if (isRecentMovie && Settings.RecentMoviePriority == (int)QBittorrentPriority.First || - !isRecentMovie && Settings.OlderMoviePriority == (int)QBittorrentPriority.First) + if ((isRecentMovie && Settings.RecentMoviePriority == (int)QBittorrentPriority.First) || + (!isRecentMovie && Settings.OlderMoviePriority == (int)QBittorrentPriority.First)) { Proxy.MoveTorrentToTopInQueue(hash.ToLower(), Settings); } @@ -90,7 +89,7 @@ protected override string AddFromMagnetLink(RemoteMovie remoteMovie, string hash return hash; } - protected override string AddFromTorrentFile(RemoteMovie remoteMovie, string hash, string filename, Byte[] fileContent) + protected override string AddFromTorrentFile(RemoteMovie remoteMovie, string hash, string filename, byte[] fileContent) { Proxy.AddTorrentFromFile(filename, fileContent, Settings); @@ -98,8 +97,8 @@ protected override string AddFromTorrentFile(RemoteMovie remoteMovie, string has { var isRecentMovie = remoteMovie.Movie.IsRecentMovie; - if (isRecentMovie && Settings.RecentMoviePriority == (int)QBittorrentPriority.First || - !isRecentMovie && Settings.OlderMoviePriority == (int)QBittorrentPriority.First) + if ((isRecentMovie && Settings.RecentMoviePriority == (int)QBittorrentPriority.First) || + (!isRecentMovie && Settings.OlderMoviePriority == (int)QBittorrentPriority.First)) { Proxy.MoveTorrentToTopInQueue(hash.ToLower(), Settings); } @@ -145,7 +144,7 @@ public override IEnumerable GetItems() // Avoid removing torrents that haven't reached the global max ratio. // Removal also requires the torrent to be paused, in case a higher max ratio was set on the torrent itself (which is not exposed by the api). - item.CanMoveFiles = item.CanBeRemoved = (torrent.State == "pausedUP" && HasReachedSeedLimit(torrent, config)); + item.CanMoveFiles = item.CanBeRemoved = torrent.State == "pausedUP" && HasReachedSeedLimit(torrent, config); if (!item.OutputPath.IsEmpty && item.OutputPath.FileName != torrent.Name) { @@ -193,6 +192,7 @@ public override IEnumerable GetItems() item.Status = DownloadItemStatus.Warning; item.Message = "qBittorrent cannot resolve magnet link with DHT disabled"; } + break; case "forcedDL": //torrent is being downloaded, and was forced started @@ -235,7 +235,11 @@ public override DownloadClientInfo GetStatus() protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestCategory()); failures.AddIfNotNull(TestPrioritySupport()); failures.AddIfNotNull(TestGetTorrents()); @@ -279,7 +283,7 @@ private ValidationFailure TestConnection() var config = Proxy.GetConfig(Settings); if ((config.MaxRatioEnabled || config.MaxSeedingTimeEnabled) && config.RemoveOnMaxRatio) { - return new NzbDroneValidationFailure(String.Empty, "qBittorrent is configured to remove torrents when they reach their Share Ratio Limit") + return new NzbDroneValidationFailure(string.Empty, "qBittorrent is configured to remove torrents when they reach their Share Ratio Limit") { DetailedDescription = "Radarr will be unable to perform Completed Download Handling as configured. You can fix this in qBittorrent ('Tools -> Options...' in the menu) by changing 'Options -> BitTorrent -> Share Ratio Limiting' from 'Remove them' to 'Pause them'." }; @@ -303,12 +307,13 @@ private ValidationFailure TestConnection() DetailedDescription = "Please verify the hostname and port." }; } - return new NzbDroneValidationFailure(String.Empty, "Unknown exception: " + ex.Message); + + return new NzbDroneValidationFailure(string.Empty, "Unknown exception: " + ex.Message); } catch (Exception ex) { _logger.Error(ex, "Unable to test qBittorrent"); - return new NzbDroneValidationFailure(String.Empty, "Unknown exception: " + ex.Message); + return new NzbDroneValidationFailure(string.Empty, "Unknown exception: " + ex.Message); } return null; @@ -390,7 +395,7 @@ private ValidationFailure TestPrioritySupport() catch (Exception ex) { _logger.Error(ex, "Failed to test qBittorrent"); - return new NzbDroneValidationFailure(String.Empty, "Unknown exception: " + ex.Message); + return new NzbDroneValidationFailure(string.Empty, "Unknown exception: " + ex.Message); } return null; @@ -405,7 +410,7 @@ private ValidationFailure TestGetTorrents() catch (Exception ex) { _logger.Error(ex, "Failed to get torrents"); - return new NzbDroneValidationFailure(String.Empty, "Failed to get the list of torrents: " + ex.Message); + return new NzbDroneValidationFailure(string.Empty, "Failed to get the list of torrents: " + ex.Message); } return null; @@ -454,15 +459,23 @@ protected bool HasReachedSeedLimit(QBittorrentTorrent torrent, QBittorrentPrefer { if (torrent.RatioLimit >= 0) { - if (torrent.Ratio >= torrent.RatioLimit) return true; + if (torrent.Ratio >= torrent.RatioLimit) + { + return true; + } } else if (torrent.RatioLimit == -2 && config.MaxRatioEnabled) { - if (torrent.Ratio >= config.MaxRatio) return true; + if (torrent.Ratio >= config.MaxRatio) + { + return true; + } } - if (HasReachedSeedingTimeLimit(torrent, config)) return true; - + if (HasReachedSeedingTimeLimit(torrent, config)) + { + return true; + } return false; } diff --git a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxySelector.cs b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxySelector.cs index 0f1777b884..bbd308eea3 100644 --- a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxySelector.cs +++ b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxySelector.cs @@ -6,7 +6,6 @@ using NzbDrone.Common.Http; - namespace NzbDrone.Core.Download.Clients.QBittorrent { public interface IQBittorrentProxy @@ -19,9 +18,9 @@ public interface IQBittorrentProxy QBittorrentTorrentProperties GetTorrentProperties(string hash, QBittorrentSettings settings); void AddTorrentFromUrl(string torrentUrl, QBittorrentSettings settings); - void AddTorrentFromFile(string fileName, Byte[] fileContent, QBittorrentSettings settings); + void AddTorrentFromFile(string fileName, byte[] fileContent, QBittorrentSettings settings); - void RemoveTorrent(string hash, Boolean removeData, QBittorrentSettings settings); + void RemoveTorrent(string hash, bool removeData, QBittorrentSettings settings); void SetTorrentLabel(string hash, string label, QBittorrentSettings settings); void AddLabel(string label, QBittorrentSettings settings); Dictionary GetLabels(QBittorrentSettings settings); @@ -46,7 +45,7 @@ public class QBittorrentProxySelector : IQBittorrentProxySelector private readonly IQBittorrentProxy _proxyV1; private readonly IQBittorrentProxy _proxyV2; - public QBittorrentProxySelector(QBittorrentProxyV1 proxyV1, + public QBittorrentProxySelector(QBittorrentProxyV1 proxyV1, QBittorrentProxyV2 proxyV2, IHttpClient httpClient, ICacheManager cacheManager, diff --git a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV1.cs b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV1.cs index b317ce6750..a2d6905037 100644 --- a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV1.cs +++ b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV1.cs @@ -10,7 +10,6 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent { // API https://github.com/qbittorrent/qBittorrent/wiki/WebUI-API-Documentation - public class QBittorrentProxyV1 : IQBittorrentProxy { private readonly IHttpClient _httpClient; @@ -22,7 +21,6 @@ public QBittorrentProxyV1(IHttpClient httpClient, ICacheManager cacheManager, Lo _httpClient = httpClient; _logger = logger; _authCookieCache = cacheManager.GetCache>(GetType(), "authCookies"); - } public bool IsApiSupported(QBittorrentSettings settings) @@ -93,6 +91,7 @@ public List GetTorrents(QBittorrentSettings settings) request.AddQueryParam("label", settings.MovieCategory); request.AddQueryParam("category", settings.MovieCategory); } + var response = ProcessRequest>(request, settings); return response; @@ -131,7 +130,7 @@ public void AddTorrentFromUrl(string torrentUrl, QBittorrentSettings settings) } } - public void AddTorrentFromFile(string fileName, Byte[] fileContent, QBittorrentSettings settings) + public void AddTorrentFromFile(string fileName, byte[] fileContent, QBittorrentSettings settings) { var request = BuildRequest(settings).Resource("/command/upload") .Post() @@ -156,7 +155,7 @@ public void AddTorrentFromFile(string fileName, Byte[] fileContent, QBittorrentS } } - public void RemoveTorrent(string hash, Boolean removeData, QBittorrentSettings settings) + public void RemoveTorrent(string hash, bool removeData, QBittorrentSettings settings) { var request = BuildRequest(settings).Resource(removeData ? "/command/deletePerm" : "/command/delete") .Post() @@ -227,7 +226,6 @@ public void MoveTorrentToTopInQueue(string hash, QBittorrentSettings settings) throw; } - } public void PauseTorrent(string hash, QBittorrentSettings settings) @@ -325,7 +323,7 @@ private void AuthenticateClient(HttpRequestBuilder requestBuilder, QBittorrentSe { _authCookieCache.Remove(authKey); - var authLoginRequest = BuildRequest(settings).Resource( "/login") + var authLoginRequest = BuildRequest(settings).Resource("/login") .Post() .AddFormParameter("username", settings.Username ?? string.Empty) .AddFormParameter("password", settings.Password ?? string.Empty) @@ -351,7 +349,8 @@ private void AuthenticateClient(HttpRequestBuilder requestBuilder, QBittorrentSe throw new DownloadClientUnavailableException("Failed to connect to qBittorrent, please check your settings.", ex); } - if (response.Content != "Ok.") // returns "Fails." on bad login + // returns "Fails." on bad login + if (response.Content != "Ok.") { _logger.Debug("qbitTorrent authentication failed."); throw new DownloadClientAuthenticationException("Failed to authenticate with qBittorrent."); diff --git a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV2.cs b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV2.cs index 7350d5f0ca..2e26b13893 100644 --- a/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV2.cs +++ b/src/NzbDrone.Core/Download/Clients/QBittorrent/QBittorrentProxyV2.cs @@ -10,7 +10,6 @@ namespace NzbDrone.Core.Download.Clients.QBittorrent { // API https://github.com/qbittorrent/qBittorrent/wiki/Web-API-Documentation - public class QBittorrentProxyV2 : IQBittorrentProxy { private readonly IHttpClient _httpClient; @@ -91,6 +90,7 @@ public List GetTorrents(QBittorrentSettings settings) { request.AddQueryParam("category", settings.MovieCategory); } + var response = ProcessRequest>(request, settings); return response; @@ -129,7 +129,7 @@ public void AddTorrentFromUrl(string torrentUrl, QBittorrentSettings settings) } } - public void AddTorrentFromFile(string fileName, Byte[] fileContent, QBittorrentSettings settings) + public void AddTorrentFromFile(string fileName, byte[] fileContent, QBittorrentSettings settings) { var request = BuildRequest(settings).Resource("/api/v2/torrents/add") .Post() @@ -154,7 +154,7 @@ public void AddTorrentFromFile(string fileName, Byte[] fileContent, QBittorrentS } } - public void RemoveTorrent(string hash, Boolean removeData, QBittorrentSettings settings) + public void RemoveTorrent(string hash, bool removeData, QBittorrentSettings settings) { var request = BuildRequest(settings).Resource("/api/v2/torrents/delete") .Post() @@ -238,7 +238,6 @@ public void MoveTorrentToTopInQueue(string hash, QBittorrentSettings settings) throw; } - } public void PauseTorrent(string hash, QBittorrentSettings settings) @@ -329,6 +328,7 @@ private void AuthenticateClient(HttpRequestBuilder requestBuilder, QBittorrentSe { throw new DownloadClientAuthenticationException("Failed to authenticate with qBittorrent."); } + return; } @@ -366,7 +366,8 @@ private void AuthenticateClient(HttpRequestBuilder requestBuilder, QBittorrentSe throw new DownloadClientUnavailableException("Failed to connect to qBittorrent, please check your settings.", ex); } - if (response.Content != "Ok.") // returns "Fails." on bad login + // returns "Fails." on bad login + if (response.Content != "Ok.") { _logger.Debug("qbitTorrent authentication failed."); throw new DownloadClientAuthenticationException("Failed to authenticate with qBittorrent."); diff --git a/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdPriorityTypeConverter.cs b/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdPriorityTypeConverter.cs index 17557abccc..246b5b5588 100644 --- a/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdPriorityTypeConverter.cs +++ b/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdPriorityTypeConverter.cs @@ -8,7 +8,7 @@ public class SabnzbdPriorityTypeConverter : JsonConverter public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var priorityType = (SabnzbdPriority)value; - writer.WriteValue(priorityType.ToString()); + writer.WriteValue(priorityType.ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) diff --git a/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdQueueTimeConverter.cs b/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdQueueTimeConverter.cs index c5274efb1c..10efa12b2c 100644 --- a/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdQueueTimeConverter.cs +++ b/src/NzbDrone.Core/Download/Clients/Sabnzbd/JsonConverters/SabnzbdQueueTimeConverter.cs @@ -9,7 +9,7 @@ public class SabnzbdQueueTimeConverter : JsonConverter public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var ts = (TimeSpan)value; - writer.WriteValue(ts.ToString()); + writer.WriteValue(ts.ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) @@ -19,7 +19,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist switch (split.Count()) { case 4: - return new TimeSpan(split[0] * 24 + split[1], split[2], split[3]); + return new TimeSpan((split[0] * 24) + split[1], split[2], split[3]); case 3: return new TimeSpan(split[0], split[1], split[2]); default: diff --git a/src/NzbDrone.Core/Download/Clients/Sabnzbd/Sabnzbd.cs b/src/NzbDrone.Core/Download/Clients/Sabnzbd/Sabnzbd.cs index 3d0d7b6b52..9592b80afa 100644 --- a/src/NzbDrone.Core/Download/Clients/Sabnzbd/Sabnzbd.cs +++ b/src/NzbDrone.Core/Download/Clients/Sabnzbd/Sabnzbd.cs @@ -9,10 +9,10 @@ using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.Exceptions; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Validation; -using NzbDrone.Core.RemotePathMappings; using NzbDrone.Core.Organizer; +using NzbDrone.Core.Parser.Model; +using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.Validation; namespace NzbDrone.Core.Download.Clients.Sabnzbd { @@ -150,8 +150,9 @@ private IEnumerable GetHistory() { historyItem.Status = DownloadItemStatus.Completed; } - else // Verifying/Moving etc + else { + // Verifying/Moving etc historyItem.Status = DownloadItemStatus.Downloading; } @@ -168,11 +169,11 @@ private IEnumerable GetHistory() { historyItem.OutputPath = parent; } + parent = parent.Directory; } } - historyItems.Add(historyItem); } @@ -185,7 +186,7 @@ public override IEnumerable GetItems() { foreach (var downloadClientItem in GetQueue().Concat(GetHistory())) { - if (downloadClientItem.Category == Settings.MovieCategory || downloadClientItem.Category == "*" && Settings.MovieCategory.IsNullOrWhiteSpace()) + if (downloadClientItem.Category == Settings.MovieCategory || (downloadClientItem.Category == "*" && Settings.MovieCategory.IsNullOrWhiteSpace())) { yield return downloadClientItem; } @@ -326,7 +327,6 @@ private Version ParseVersion(string version) minor = Convert.ToInt32(parsed.Groups["minor"].Value); patch = Convert.ToInt32(parsed.Groups["patch"].Value.Replace("x", "0")); } - else { if (!version.Equals("develop", StringComparison.InvariantCultureIgnoreCase)) @@ -394,10 +394,12 @@ private ValidationFailure TestAuthentication() { return new ValidationFailure("APIKey", "API Key Incorrect"); } + if (ex.Message.ContainsIgnoreCase("API Key Required")) { return new ValidationFailure("APIKey", "API Key Required"); } + throw; } @@ -446,6 +448,7 @@ private ValidationFailure TestCategory() }; } } + if (config.Misc.enable_tv_sorting && ContainsCategory(config.Misc.tv_categories, Settings.MovieCategory)) { return new NzbDroneValidationFailure("MovieCategory", "Disable TV Sorting") @@ -454,6 +457,7 @@ private ValidationFailure TestCategory() DetailedDescription = "You must disable SABnzbd TV Sorting for the category Radarr uses to prevent import issues. Go to SABnzbd to fix it." }; } + if (config.Misc.enable_movie_sorting && ContainsCategory(config.Misc.movie_categories, Settings.MovieCategory)) { return new NzbDroneValidationFailure("MovieCategory", "Disable Movie Sorting") @@ -462,6 +466,7 @@ private ValidationFailure TestCategory() DetailedDescription = "You must disable SABnzbd Movie Sorting for the category Radarr uses to prevent import issues. Go to SABnzbd to fix it." }; } + if (config.Misc.enable_date_sorting && ContainsCategory(config.Misc.date_categories, Settings.MovieCategory)) { return new NzbDroneValidationFailure("MovieCategory", "Disable Date Sorting") diff --git a/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdProxy.cs b/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdProxy.cs index 0f52347275..f725e303d8 100644 --- a/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/Sabnzbd/SabnzbdProxy.cs @@ -1,11 +1,11 @@ using System; +using System.Net; using Newtonsoft.Json.Linq; using NLog; using NzbDrone.Common.Extensions; +using NzbDrone.Common.Http; using NzbDrone.Common.Serializer; using NzbDrone.Core.Download.Clients.Sabnzbd.Responses; -using NzbDrone.Common.Http; -using System.Net; namespace NzbDrone.Core.Download.Clients.Sabnzbd { @@ -13,7 +13,7 @@ public interface ISabnzbdProxy { string GetBaseUrl(SabnzbdSettings settings, string relativePath = null); SabnzbdAddResponse DownloadNzb(byte[] nzbData, string filename, string category, int priority, SabnzbdSettings settings); - void RemoveFrom(string source, string id,bool deleteData, SabnzbdSettings settings); + void RemoveFrom(string source, string id, bool deleteData, SabnzbdSettings settings); string GetVersion(SabnzbdSettings settings); SabnzbdConfig GetConfig(SabnzbdSettings settings); SabnzbdFullStatus GetFullStatus(SabnzbdSettings settings); @@ -166,6 +166,7 @@ private HttpRequestBuilder BuildRequest(string mode, SabnzbdSettings settings) requestBuilder.AddSuffixQueryParam("ma_username", settings.Username); requestBuilder.AddSuffixQueryParam("ma_password", settings.Password); } + requestBuilder.AddSuffixQueryParam("output", "json"); return requestBuilder; @@ -211,7 +212,6 @@ private void CheckForError(HttpResponse response) result.Status = "false"; result.Error = response.Content.Replace("error: ", ""); } - else { result.Status = "true"; diff --git a/src/NzbDrone.Core/Download/Clients/Transmission/Transmission.cs b/src/NzbDrone.Core/Download/Clients/Transmission/Transmission.cs index 3c2e25e367..38909b8a40 100644 --- a/src/NzbDrone.Core/Download/Clients/Transmission/Transmission.cs +++ b/src/NzbDrone.Core/Download/Clients/Transmission/Transmission.cs @@ -1,13 +1,13 @@ using System; using System.Text.RegularExpressions; +using FluentValidation.Results; +using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; -using NLog; -using FluentValidation.Results; using NzbDrone.Core.MediaFiles.TorrentInfo; -using NzbDrone.Core.RemotePathMappings; using NzbDrone.Core.Organizer; +using NzbDrone.Core.RemotePathMappings; namespace NzbDrone.Core.Download.Clients.Transmission { diff --git a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionBase.cs b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionBase.cs index 15d8df5dc5..bd4e9aa987 100644 --- a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionBase.cs +++ b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionBase.cs @@ -42,18 +42,27 @@ public override IEnumerable GetItems() foreach (var torrent in torrents) { // If totalsize == 0 the torrent is a magnet downloading metadata - if (torrent.TotalSize == 0) continue; + if (torrent.TotalSize == 0) + { + continue; + } var outputPath = new OsPath(torrent.DownloadDir); if (Settings.MovieDirectory.IsNotNullOrWhiteSpace()) { - if (!new OsPath(Settings.MovieDirectory).Contains(outputPath)) continue; + if (!new OsPath(Settings.MovieDirectory).Contains(outputPath)) + { + continue; + } } else if (Settings.MovieCategory.IsNotNullOrWhiteSpace()) { var directories = outputPath.FullPath.Split('\\', '/'); - if (!directories.Contains(Settings.MovieCategory)) continue; + if (!directories.Contains(Settings.MovieCategory)) + { + continue; + } } outputPath = _remotePathMappingService.RemapRemoteToLocal(Settings.Host, outputPath); @@ -69,7 +78,7 @@ public override IEnumerable GetItems() item.TotalSize = torrent.TotalSize; item.RemainingSize = torrent.LeftUntilDone; item.SeedRatio = torrent.DownloadedEver <= 0 ? 0 : - (double) torrent.UploadedEver / torrent.DownloadedEver; + (double)torrent.UploadedEver / torrent.DownloadedEver; if (torrent.Eta >= 0) { @@ -179,8 +188,8 @@ protected override string AddFromMagnetLink(RemoteMovie remoteMovie, string hash var isRecentMovie = remoteMovie.Movie.IsRecentMovie; - if (isRecentMovie && Settings.RecentMoviePriority == (int)TransmissionPriority.First || - !isRecentMovie && Settings.OlderMoviePriority == (int)TransmissionPriority.First) + if ((isRecentMovie && Settings.RecentMoviePriority == (int)TransmissionPriority.First) || + (!isRecentMovie && Settings.OlderMoviePriority == (int)TransmissionPriority.First)) { _proxy.MoveTorrentToTopInQueue(hash, Settings); } @@ -195,8 +204,8 @@ protected override string AddFromTorrentFile(RemoteMovie remoteMovie, string has var isRecentMovie = remoteMovie.Movie.IsRecentMovie; - if (isRecentMovie && Settings.RecentMoviePriority == (int)TransmissionPriority.First || - !isRecentMovie && Settings.OlderMoviePriority == (int)TransmissionPriority.First) + if ((isRecentMovie && Settings.RecentMoviePriority == (int)TransmissionPriority.First) || + (!isRecentMovie && Settings.OlderMoviePriority == (int)TransmissionPriority.First)) { _proxy.MoveTorrentToTopInQueue(hash, Settings); } @@ -207,7 +216,11 @@ protected override string AddFromTorrentFile(RemoteMovie remoteMovie, string has protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestGetTorrents()); } @@ -223,7 +236,10 @@ protected string GetDownloadDirectory() return Settings.MovieDirectory; } - if (!Settings.MovieCategory.IsNotNullOrWhiteSpace()) return null; + if (!Settings.MovieCategory.IsNotNullOrWhiteSpace()) + { + return null; + } var config = _proxy.GetConfig(Settings); var destDir = config.DownloadDir; diff --git a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionException.cs b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionException.cs index f89ee42da3..3b91b4ce35 100644 --- a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionException.cs +++ b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionException.cs @@ -5,7 +5,6 @@ public class TransmissionException : DownloadClientException public TransmissionException(string message) : base(message) { - } } } diff --git a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionProxy.cs b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionProxy.cs index dd0b0a0cf2..de5c1e4e33 100644 --- a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionProxy.cs @@ -1,11 +1,11 @@ using System; -using System.Net; using System.Collections.Generic; -using NzbDrone.Common.Extensions; -using NLog; +using System.Net; using Newtonsoft.Json.Linq; -using NzbDrone.Common.Http; +using NLog; using NzbDrone.Common.Cache; +using NzbDrone.Common.Extensions; +using NzbDrone.Common.Http; using NzbDrone.Common.Serializer; namespace NzbDrone.Core.Download.Clients.Transmission @@ -23,7 +23,7 @@ public interface ITransmissionProxy void MoveTorrentToTopInQueue(string hashString, TransmissionSettings settings); } - public class TransmissionProxy: ITransmissionProxy + public class TransmissionProxy : ITransmissionProxy { private readonly IHttpClient _httpClient; private readonly Logger _logger; @@ -77,7 +77,10 @@ public void AddTorrentFromData(byte[] torrentData, string downloadDirectory, Tra public void SetTorrentSeedingConfiguration(string hash, TorrentSeedConfiguration seedConfiguration, TransmissionSettings settings) { - if (seedConfiguration == null) return; + if (seedConfiguration == null) + { + return; + } var arguments = new Dictionary(); arguments.Add("ids", new[] { hash }); @@ -139,7 +142,6 @@ public void MoveTorrentToTopInQueue(string hashString, TransmissionSettings sett private TransmissionResponse GetSessionVariables(TransmissionSettings settings) { // Retrieve transmission information such as the default download directory, bandwith throttling and seed ratio. - return ProcessRequest("session-get", null, settings); } @@ -155,7 +157,8 @@ private TransmissionResponse GetTorrentStatus(TransmissionSettings settings) private TransmissionResponse GetTorrentStatus(IEnumerable hashStrings, TransmissionSettings settings) { - var fields = new string[]{ + var fields = new string[] + { "id", "hashString", // Unique torrent ID. Use this instead of the client id? "name", diff --git a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionSettings.cs b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionSettings.cs index b8ae790d46..9d9df1c0ff 100644 --- a/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionSettings.cs +++ b/src/NzbDrone.Core/Download/Clients/Transmission/TransmissionSettings.cs @@ -1,9 +1,9 @@ using System.Text.RegularExpressions; using FluentValidation; +using NzbDrone.Common.Extensions; using NzbDrone.Core.Annotations; using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Validation; -using NzbDrone.Common.Extensions; namespace NzbDrone.Core.Download.Clients.Transmission { diff --git a/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrent.cs b/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrent.cs index 232b96b4f9..f6c393e940 100644 --- a/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrent.cs +++ b/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrent.cs @@ -1,21 +1,21 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using System.Threading; +using FluentValidation.Results; +using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; -using NzbDrone.Core.MediaFiles.TorrentInfo; -using NLog; -using NzbDrone.Core.Validation; -using FluentValidation.Results; using NzbDrone.Core.Download.Clients.rTorrent; using NzbDrone.Core.Exceptions; +using NzbDrone.Core.MediaFiles.TorrentInfo; +using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.RemotePathMappings; using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Organizer; +using NzbDrone.Core.Validation; namespace NzbDrone.Core.Download.Clients.RTorrent { @@ -51,8 +51,10 @@ public override void MarkItemAsImported(DownloadClientItem downloadClientItem) } catch (Exception ex) { - _logger.Warn(ex, "Failed to set torrent post-import label \"{0}\" for {1} in rTorrent. Does the label exist?", - Settings.MovieImportedCategory, downloadClientItem.Title); + _logger.Warn(ex, + "Failed to set torrent post-import label \"{0}\" for {1} in rTorrent. Does the label exist?", + Settings.MovieImportedCategory, + downloadClientItem.Title); } } } @@ -109,7 +111,10 @@ public override IEnumerable GetItems() foreach (RTorrentTorrent torrent in torrents) { // Don't concern ourselves with categories other than specified - if (Settings.MovieCategory.IsNotNullOrWhiteSpace() && torrent.Category != Settings.MovieCategory) continue; + if (Settings.MovieCategory.IsNotNullOrWhiteSpace() && torrent.Category != Settings.MovieCategory) + { + continue; + } if (torrent.Path.StartsWith(".")) { @@ -171,7 +176,6 @@ public override void RemoveItem(string downloadId, bool deleteData) public override DownloadClientInfo GetStatus() { // XXX: This function's correctness has not been considered - var status = new DownloadClientInfo { IsLocalhost = Settings.Host == "127.0.0.1" || Settings.Host == "localhost" @@ -183,7 +187,11 @@ public override DownloadClientInfo GetStatus() protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestGetTorrents()); failures.AddIfNotNull(TestDirectory()); } diff --git a/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrentProxy.cs b/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrentProxy.cs index 044eaa9f71..39f4d2cc22 100644 --- a/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrentProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/rTorrent/RTorrentProxy.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using System.Net; +using CookComputing.XmlRpc; using NLog; using NzbDrone.Common.Extensions; -using CookComputing.XmlRpc; namespace NzbDrone.Core.Download.Clients.RTorrent { @@ -73,7 +73,9 @@ public List GetTorrents(RTorrentSettings settings) _logger.Debug("Executing remote method: d.multicall2"); var client = BuildClient(settings); - var ret = ExecuteRequest(() => client.TorrentMulticall("", "", + var ret = ExecuteRequest(() => client.TorrentMulticall( + "", + "", "d.name=", // string "d.hash=", // string "d.base_path=", // string @@ -84,8 +86,7 @@ public List GetTorrents(RTorrentSettings settings) "d.ratio=", // long "d.is_open=", // long "d.is_active=", // long - "d.complete=") //long - ); + "d.complete=")); //long var items = new List(); diff --git a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrent.cs b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrent.cs index a1140277f9..e3ed91759a 100644 --- a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrent.cs +++ b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrent.cs @@ -1,19 +1,19 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; +using System.Net; +using FluentValidation.Results; +using NLog; +using NzbDrone.Common.Cache; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles.TorrentInfo; -using NLog; -using NzbDrone.Core.Validation; -using FluentValidation.Results; -using System.Net; +using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.RemotePathMappings; -using NzbDrone.Common.Cache; -using NzbDrone.Core.Organizer; +using NzbDrone.Core.Validation; namespace NzbDrone.Core.Download.Clients.UTorrent { @@ -66,8 +66,8 @@ protected override string AddFromMagnetLink(RemoteMovie remoteMovie, string hash var isRecentMovie = remoteMovie.Movie.IsRecentMovie; - if (isRecentMovie && Settings.RecentMoviePriority == (int)UTorrentPriority.First || - !isRecentMovie && Settings.OlderMoviePriority == (int)UTorrentPriority.First) + if ((isRecentMovie && Settings.RecentMoviePriority == (int)UTorrentPriority.First) || + (!isRecentMovie && Settings.OlderMoviePriority == (int)UTorrentPriority.First)) { _proxy.MoveTorrentToTopInQueue(hash, Settings); } @@ -89,8 +89,8 @@ protected override string AddFromTorrentFile(RemoteMovie remoteMovie, string has var isRecentEpisode = remoteMovie.Movie.IsRecentMovie; - if (isRecentEpisode && Settings.RecentMoviePriority == (int)UTorrentPriority.First || - !isRecentEpisode && Settings.OlderMoviePriority == (int)UTorrentPriority.First) + if ((isRecentEpisode && Settings.RecentMoviePriority == (int)UTorrentPriority.First) || + (!isRecentEpisode && Settings.OlderMoviePriority == (int)UTorrentPriority.First)) { _proxy.MoveTorrentToTopInQueue(hash, Settings); } @@ -250,7 +250,11 @@ public override DownloadClientInfo GetStatus() protected override void Test(List failures) { failures.AddIfNotNull(TestConnection()); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestGetTorrents()); } @@ -283,6 +287,7 @@ private ValidationFailure TestConnection() DetailedDescription = "Please verify the hostname and port." }; } + return new NzbDroneValidationFailure(string.Empty, "Unknown exception: " + ex.Message); } catch (Exception ex) diff --git a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentProxy.cs b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentProxy.cs index f8a76892bd..b95a2aeac1 100644 --- a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentProxy.cs +++ b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentProxy.cs @@ -107,7 +107,10 @@ public void AddTorrentFromFile(string fileName, byte[] fileContent, UTorrentSett public void SetTorrentSeedingConfiguration(string hash, TorrentSeedConfiguration seedConfiguration, UTorrentSettings settings) { - if (seedConfiguration == null) return; + if (seedConfiguration == null) + { + return; + } var requestBuilder = BuildRequest(settings) .AddQueryParam("action", "setprops") diff --git a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentTorrent.cs b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentTorrent.cs index 30f4c33a8c..027b138e09 100644 --- a/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentTorrent.cs +++ b/src/NzbDrone.Core/Download/Clients/uTorrent/UTorrentTorrent.cs @@ -39,7 +39,7 @@ public class UTorrentTorrent public object Unknown28 { get; set; } } - class UTorrentTorrentJsonConverter : JsonConverter + internal class UTorrentTorrentJsonConverter : JsonConverter { public override bool CanConvert(Type objectType) { @@ -78,7 +78,6 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist reader.Read(); // Builds before 25406 don't return the remaining items. - if (reader.TokenType != JsonToken.EndArray) { result.DownloadUrl = (string)reader.Value; @@ -101,8 +100,10 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist reader.Read(); result.Unknown28 = reader.Value; - while(reader.TokenType != JsonToken.EndArray) + while (reader.TokenType != JsonToken.EndArray) + { reader.Read(); + } } return result; diff --git a/src/NzbDrone.Core/Download/CompletedDownloadService.cs b/src/NzbDrone.Core/Download/CompletedDownloadService.cs index 1ffce2830d..d235597035 100644 --- a/src/NzbDrone.Core/Download/CompletedDownloadService.cs +++ b/src/NzbDrone.Core/Download/CompletedDownloadService.cs @@ -9,8 +9,8 @@ using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.MovieImport; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Parser; using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser; namespace NzbDrone.Core.Download { @@ -125,6 +125,7 @@ private void Import(TrackedDownload trackedDownload) { return new TrackedDownloadStatusMessage("", v.Errors); } + return new TrackedDownloadStatusMessage(Path.GetFileName(v.ImportDecision.LocalMovie.Path), v.Errors); }) .ToArray(); diff --git a/src/NzbDrone.Core/Download/DownloadClientBase.cs b/src/NzbDrone.Core/Download/DownloadClientBase.cs index 051a97b514..88c6c13ae9 100644 --- a/src/NzbDrone.Core/Download/DownloadClientBase.cs +++ b/src/NzbDrone.Core/Download/DownloadClientBase.cs @@ -1,17 +1,17 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using FluentValidation.Results; using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Core.Configuration; using NzbDrone.Core.Indexers; +using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.RemotePathMappings; using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Validation; -using NzbDrone.Core.Organizer; namespace NzbDrone.Core.Download { @@ -34,7 +34,10 @@ public abstract class DownloadClientBase : IDownloadClient public ProviderDefinition Definition { get; set; } - public virtual object RequestAction(string action, IDictionary query) { return null; } + public virtual object RequestAction(string action, IDictionary query) + { + return null; + } protected TSettings Settings => (TSettings)Definition.Settings; @@ -154,7 +157,7 @@ protected ValidationFailure TestFolder(string folder, string propertyName, bool public virtual void MarkItemAsImported(DownloadClientItem downloadClientItem) { - throw new NotSupportedException(this.Name + " does not support marking items as imported"); + throw new NotSupportedException(Name + " does not support marking items as imported"); } } } diff --git a/src/NzbDrone.Core/Download/DownloadClientProvider.cs b/src/NzbDrone.Core/Download/DownloadClientProvider.cs index 978f9ea60f..3ad8f66151 100644 --- a/src/NzbDrone.Core/Download/DownloadClientProvider.cs +++ b/src/NzbDrone.Core/Download/DownloadClientProvider.cs @@ -1,8 +1,8 @@ -using System.Linq; -using System.Collections.Generic; -using NzbDrone.Core.Indexers; -using NzbDrone.Common.Cache; +using System.Collections.Generic; +using System.Linq; using NLog; +using NzbDrone.Common.Cache; +using NzbDrone.Core.Indexers; namespace NzbDrone.Core.Download { @@ -32,7 +32,10 @@ public IDownloadClient GetDownloadClient(DownloadProtocol downloadProtocol) { var availableProviders = _downloadClientFactory.GetAvailableProviders().Where(v => v.Protocol == downloadProtocol).ToList(); - if (!availableProviders.Any()) return null; + if (!availableProviders.Any()) + { + return null; + } var blockedProviders = new HashSet(_downloadClientStatusService.GetBlockedProviders().Select(v => v.ProviderId)); diff --git a/src/NzbDrone.Core/Download/DownloadClientRepository.cs b/src/NzbDrone.Core/Download/DownloadClientRepository.cs index 1d04b56f31..704dababc2 100644 --- a/src/NzbDrone.Core/Download/DownloadClientRepository.cs +++ b/src/NzbDrone.Core/Download/DownloadClientRepository.cs @@ -6,7 +6,6 @@ namespace NzbDrone.Core.Download { public interface IDownloadClientRepository : IProviderRepository { - } public class DownloadClientRepository : ProviderRepository, IDownloadClientRepository diff --git a/src/NzbDrone.Core/Download/DownloadClientStatus.cs b/src/NzbDrone.Core/Download/DownloadClientStatus.cs index f4d8194245..a6d3881258 100644 --- a/src/NzbDrone.Core/Download/DownloadClientStatus.cs +++ b/src/NzbDrone.Core/Download/DownloadClientStatus.cs @@ -4,6 +4,5 @@ namespace NzbDrone.Core.Download { public class DownloadClientStatus : ProviderStatusBase { - } } diff --git a/src/NzbDrone.Core/Download/DownloadClientStatusRepository.cs b/src/NzbDrone.Core/Download/DownloadClientStatusRepository.cs index 4f6fd6dfa1..f7c2b8f08f 100644 --- a/src/NzbDrone.Core/Download/DownloadClientStatusRepository.cs +++ b/src/NzbDrone.Core/Download/DownloadClientStatusRepository.cs @@ -6,7 +6,6 @@ namespace NzbDrone.Core.Download { public interface IDownloadClientStatusRepository : IProviderStatusRepository { - } public class DownloadClientStatusRepository : ProviderStatusRepository, IDownloadClientStatusRepository diff --git a/src/NzbDrone.Core/Download/DownloadClientStatusService.cs b/src/NzbDrone.Core/Download/DownloadClientStatusService.cs index 11eecfe890..19f11d4b74 100644 --- a/src/NzbDrone.Core/Download/DownloadClientStatusService.cs +++ b/src/NzbDrone.Core/Download/DownloadClientStatusService.cs @@ -8,7 +8,6 @@ namespace NzbDrone.Core.Download { public interface IDownloadClientStatusService : IProviderStatusServiceBase { - } public class DownloadClientStatusService : ProviderStatusServiceBase, IDownloadClientStatusService diff --git a/src/NzbDrone.Core/Download/DownloadEventHub.cs b/src/NzbDrone.Core/Download/DownloadEventHub.cs index 8b235c9b7e..fa7b6aabff 100644 --- a/src/NzbDrone.Core/Download/DownloadEventHub.cs +++ b/src/NzbDrone.Core/Download/DownloadEventHub.cs @@ -60,7 +60,6 @@ public void Handle(DownloadFailedEvent message) RemoveFromDownloadClient(trackedDownload); } - private void RemoveFromDownloadClient(TrackedDownload trackedDownload) { var downloadClient = _downloadClientProvider.Get(trackedDownload.DownloadClient); diff --git a/src/NzbDrone.Core/Download/DownloadFailedEvent.cs b/src/NzbDrone.Core/Download/DownloadFailedEvent.cs index 6af3aed514..494d8eb56c 100644 --- a/src/NzbDrone.Core/Download/DownloadFailedEvent.cs +++ b/src/NzbDrone.Core/Download/DownloadFailedEvent.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using NzbDrone.Common.Messaging; using NzbDrone.Core.Download.TrackedDownloads; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Languages; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Download { diff --git a/src/NzbDrone.Core/Download/DownloadService.cs b/src/NzbDrone.Core/Download/DownloadService.cs index f0110ef6c3..cdfc2bc2cc 100644 --- a/src/NzbDrone.Core/Download/DownloadService.cs +++ b/src/NzbDrone.Core/Download/DownloadService.cs @@ -18,7 +18,6 @@ public interface IDownloadService void DownloadReport(RemoteMovie remoteMovie); } - public class DownloadService : IDownloadService { private readonly IProvideDownloadClient _downloadClientProvider; @@ -91,6 +90,7 @@ public void DownloadReport(RemoteMovie remoteMovie) { _indexerStatusService.RecordFailure(remoteMovie.Release.IndexerId); } + throw; } diff --git a/src/NzbDrone.Core/Download/InvalidNzbException.cs b/src/NzbDrone.Core/Download/InvalidNzbException.cs index 5607590d96..5fde39c542 100644 --- a/src/NzbDrone.Core/Download/InvalidNzbException.cs +++ b/src/NzbDrone.Core/Download/InvalidNzbException.cs @@ -5,19 +5,23 @@ namespace NzbDrone.Core.Download { public class InvalidNzbException : NzbDroneException { - public InvalidNzbException(string message, params object[] args) : base(message, args) + public InvalidNzbException(string message, params object[] args) + : base(message, args) { } - public InvalidNzbException(string message) : base(message) + public InvalidNzbException(string message) + : base(message) { } - public InvalidNzbException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public InvalidNzbException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } - public InvalidNzbException(string message, Exception innerException) : base(message, innerException) + public InvalidNzbException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/Download/Pending/PendingReleaseService.cs b/src/NzbDrone.Core/Download/Pending/PendingReleaseService.cs index 7be49b99a5..aecdbbba9e 100644 --- a/src/NzbDrone.Core/Download/Pending/PendingReleaseService.cs +++ b/src/NzbDrone.Core/Download/Pending/PendingReleaseService.cs @@ -8,14 +8,14 @@ using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Indexers; using NzbDrone.Core.Jobs; +using NzbDrone.Core.Languages; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Movies.Events; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles.Delay; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; -using NzbDrone.Core.Movies.Events; -using NzbDrone.Core.Languages; namespace NzbDrone.Core.Download.Pending { @@ -195,9 +195,7 @@ public List GetPendingRemoteMovies(int movieId) }; queued.Add(queue); - } - } //Return best quality release for each movie @@ -274,7 +272,10 @@ private List IncludeRemoteMovies(List releases, var movie = movieMap.GetValueOrDefault(release.MovieId); // Just in case the series was removed, but wasn't cleaned up yet (housekeeper will clean it up) - if (movie == null) return null; + if (movie == null) + { + return null; + } release.RemoteMovie = new RemoteMovie { @@ -337,7 +338,6 @@ private void RemoveGrabbed(RemoteMovie remoteMovie) { var pendingReleases = GetPendingReleases(remoteMovie.Movie.Id); - var existingReports = pendingReleases.Where(r => r.RemoteMovie.Movie.Id == remoteMovie.Movie.Id) .ToList(); diff --git a/src/NzbDrone.Core/Download/ProcessDownloadDecisions.cs b/src/NzbDrone.Core/Download/ProcessDownloadDecisions.cs index fb6d7b8e0a..78ef519e11 100644 --- a/src/NzbDrone.Core/Download/ProcessDownloadDecisions.cs +++ b/src/NzbDrone.Core/Download/ProcessDownloadDecisions.cs @@ -63,8 +63,8 @@ public ProcessedDecisions ProcessDecisions(List decisions) continue; } - if (downloadProtocol == DownloadProtocol.Usenet && usenetFailed || - downloadProtocol == DownloadProtocol.Torrent && torrentFailed) + if ((downloadProtocol == DownloadProtocol.Usenet && usenetFailed) || + (downloadProtocol == DownloadProtocol.Torrent && torrentFailed)) { PreparePending(pendingAddQueue, grabbed, pending, report, PendingReleaseReason.DownloadClientUnavailable); continue; @@ -134,7 +134,6 @@ private void PreparePending(List> // If a higher quality release failed to add to the download client, but a lower quality release // was sent to another client we still list it normally so it apparent that it'll grab next time. // Delayed is treated the same, but only the first is listed the subsequent items as stored as Fallback. - if (IsMovieProcessed(grabbed, report) || IsMovieProcessed(pending, report)) { diff --git a/src/NzbDrone.Core/Download/RedownloadFailedDownloadService.cs b/src/NzbDrone.Core/Download/RedownloadFailedDownloadService.cs index 87c924d525..d739631140 100644 --- a/src/NzbDrone.Core/Download/RedownloadFailedDownloadService.cs +++ b/src/NzbDrone.Core/Download/RedownloadFailedDownloadService.cs @@ -1,10 +1,10 @@ +using System.Collections.Generic; using NLog; using NzbDrone.Core.Configuration; using NzbDrone.Core.IndexerSearch; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Movies; -using System.Collections.Generic; namespace NzbDrone.Core.Download { diff --git a/src/NzbDrone.Core/Download/TorrentClientBase.cs b/src/NzbDrone.Core/Download/TorrentClientBase.cs index b5397ca330..0b78aebfbf 100644 --- a/src/NzbDrone.Core/Download/TorrentClientBase.cs +++ b/src/NzbDrone.Core/Download/TorrentClientBase.cs @@ -1,18 +1,18 @@ using System; using System.Net; using MonoTorrent; +using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; +using NzbDrone.Core.Configuration; using NzbDrone.Core.Exceptions; using NzbDrone.Core.Indexers; using NzbDrone.Core.MediaFiles.TorrentInfo; using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Configuration; -using NLog; using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.ThingiProvider; namespace NzbDrone.Core.Download { @@ -193,7 +193,8 @@ private string DownloadFromWebUrl(RemoteMovie remoteMovie, string torrentUrl) { _logger.Debug( "{0} did not return the expected InfoHash for '{1}', Radarr could potentially lose track of the download in progress.", - Definition.Implementation, remoteMovie.Release.DownloadUrl); + Definition.Implementation, + remoteMovie.Release.DownloadUrl); } return actualHash; @@ -224,7 +225,8 @@ private string DownloadFromMagnetUrl(RemoteMovie remoteMovie, string magnetUrl) { _logger.Debug( "{0} did not return the expected InfoHash for '{1}', Radarr could potentially lose track of the download in progress.", - Definition.Implementation, remoteMovie.Release.DownloadUrl); + Definition.Implementation, + remoteMovie.Release.DownloadUrl); } return actualHash; diff --git a/src/NzbDrone.Core/Download/TrackedDownloads/DownloadMonitoringService.cs b/src/NzbDrone.Core/Download/TrackedDownloads/DownloadMonitoringService.cs index 4fe4f79989..7d4998dc38 100644 --- a/src/NzbDrone.Core/Download/TrackedDownloads/DownloadMonitoringService.cs +++ b/src/NzbDrone.Core/Download/TrackedDownloads/DownloadMonitoringService.cs @@ -103,7 +103,6 @@ private List ProcessClientDownloads(IDownloadClient downloadCli } return trackedDownloads; - } private void RemoveCompletedDownloads(List trackedDownloads) @@ -128,11 +127,9 @@ private List ProcessClientItems(IDownloadClient downloadClient, { _completedDownloadService.Process(trackedDownload); } - } trackedDownloads.AddIfNotNull(trackedDownload); - } catch (Exception e) { diff --git a/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownload.cs b/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownload.cs index 6148b51a9a..7b1a78aa87 100644 --- a/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownload.cs +++ b/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownload.cs @@ -17,7 +17,7 @@ public class TrackedDownload public TrackedDownload() { - StatusMessages = new TrackedDownloadStatusMessage[] {}; + StatusMessages = new TrackedDownloadStatusMessage[] { }; } public void Warn(string message, params object[] args) diff --git a/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadService.cs b/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadService.cs index 43bc662642..49d86fea47 100644 --- a/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadService.cs +++ b/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadService.cs @@ -97,12 +97,12 @@ public TrackedDownload TrackDownload(DownloadClientDefinition downloadClient, Do try { - var historyItems = _historyService.FindByDownloadId(downloadItem.DownloadId); var grabbedHistoryItem = historyItems.OrderByDescending(h => h.Date).FirstOrDefault(h => h.EventType == HistoryEventType.Grabbed); var firstHistoryItem = historyItems.OrderByDescending(h => h.Date).FirstOrDefault(); + //TODO: Create release info from history and use that here, so we don't loose indexer flags! - var parsedMovieInfo = _parsingService.ParseMovieInfo(trackedDownload.DownloadItem.Title, new List{grabbedHistoryItem}); + var parsedMovieInfo = _parsingService.ParseMovieInfo(trackedDownload.DownloadItem.Title, new List { grabbedHistoryItem }); if (parsedMovieInfo != null) { @@ -120,7 +120,7 @@ public TrackedDownload TrackDownload(DownloadClientDefinition downloadClient, Do trackedDownload.RemoteMovie == null || trackedDownload.RemoteMovie.Movie == null) { - parsedMovieInfo = _parsingService.ParseMovieInfo(firstHistoryItem.SourceTitle, new List{grabbedHistoryItem}); + parsedMovieInfo = _parsingService.ParseMovieInfo(firstHistoryItem.SourceTitle, new List { grabbedHistoryItem }); if (parsedMovieInfo != null) { @@ -170,9 +170,10 @@ private void LogItemChange(TrackedDownload trackedDownload, DownloadClientItem e existingItem.CanMoveFiles != downloadItem.CanMoveFiles) { _logger.Debug("Tracking '{0}:{1}': ClientState={2}{3} SonarrStage={4} Episode='{5}' OutputPath={6}.", - downloadItem.DownloadClient, downloadItem.Title, - downloadItem.Status, downloadItem.CanBeRemoved ? "" : - downloadItem.CanMoveFiles ? " (busy)" : " (readonly)", + downloadItem.DownloadClient, + downloadItem.Title, + downloadItem.Status, + downloadItem.CanBeRemoved ? "" : downloadItem.CanMoveFiles ? " (busy)" : " (readonly)", trackedDownload.State, trackedDownload.RemoteMovie?.ParsedMovieInfo, downloadItem.OutputPath); diff --git a/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadStatusMessage.cs b/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadStatusMessage.cs index e0537b8c3c..2d8a30cfe5 100644 --- a/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadStatusMessage.cs +++ b/src/NzbDrone.Core/Download/TrackedDownloads/TrackedDownloadStatusMessage.cs @@ -7,7 +7,6 @@ public class TrackedDownloadStatusMessage public string Title { get; set; } public List Messages { get; set; } - public TrackedDownloadStatusMessage(string title, List messages) { Title = title; diff --git a/src/NzbDrone.Core/Download/UsenetClientBase.cs b/src/NzbDrone.Core/Download/UsenetClientBase.cs index 0a2a9541da..7909856292 100644 --- a/src/NzbDrone.Core/Download/UsenetClientBase.cs +++ b/src/NzbDrone.Core/Download/UsenetClientBase.cs @@ -1,14 +1,14 @@ using System.Net; +using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.Http; +using NzbDrone.Core.Configuration; using NzbDrone.Core.Exceptions; using NzbDrone.Core.Indexers; using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Configuration; -using NLog; using NzbDrone.Core.RemotePathMappings; +using NzbDrone.Core.ThingiProvider; namespace NzbDrone.Core.Download { diff --git a/src/NzbDrone.Core/Exceptions/BadRequestException.cs b/src/NzbDrone.Core/Exceptions/BadRequestException.cs index adf8bf57f3..b74559d051 100644 --- a/src/NzbDrone.Core/Exceptions/BadRequestException.cs +++ b/src/NzbDrone.Core/Exceptions/BadRequestException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Exceptions { public class BadRequestException : DownstreamException { - public BadRequestException(string message) : base(HttpStatusCode.BadRequest, message) + public BadRequestException(string message) + : base(HttpStatusCode.BadRequest, message) { } - public BadRequestException(string message, params object[] args) : base(HttpStatusCode.BadRequest, message, args) + public BadRequestException(string message, params object[] args) + : base(HttpStatusCode.BadRequest, message, args) { } } diff --git a/src/NzbDrone.Core/Exceptions/DownstreamException.cs b/src/NzbDrone.Core/Exceptions/DownstreamException.cs index 0ce8f1a943..88bf850fad 100644 --- a/src/NzbDrone.Core/Exceptions/DownstreamException.cs +++ b/src/NzbDrone.Core/Exceptions/DownstreamException.cs @@ -7,7 +7,8 @@ public class DownstreamException : NzbDroneException { public HttpStatusCode StatusCode { get; private set; } - public DownstreamException(HttpStatusCode statusCode, string message, params object[] args) : base(message, args) + public DownstreamException(HttpStatusCode statusCode, string message, params object[] args) + : base(message, args) { StatusCode = statusCode; } diff --git a/src/NzbDrone.Core/Exceptions/NzbDroneClientException.cs b/src/NzbDrone.Core/Exceptions/NzbDroneClientException.cs index d9225eb2c9..ed44e447c9 100644 --- a/src/NzbDrone.Core/Exceptions/NzbDroneClientException.cs +++ b/src/NzbDrone.Core/Exceptions/NzbDroneClientException.cs @@ -7,7 +7,8 @@ public class NzbDroneClientException : NzbDroneException { public HttpStatusCode StatusCode { get; private set; } - public NzbDroneClientException(HttpStatusCode statusCode, string message, params object[] args) : base(message, args) + public NzbDroneClientException(HttpStatusCode statusCode, string message, params object[] args) + : base(message, args) { StatusCode = statusCode; } diff --git a/src/NzbDrone.Core/Exceptions/ReleaseDownloadException.cs b/src/NzbDrone.Core/Exceptions/ReleaseDownloadException.cs index c9582ddde7..b891b6d3b9 100644 --- a/src/NzbDrone.Core/Exceptions/ReleaseDownloadException.cs +++ b/src/NzbDrone.Core/Exceptions/ReleaseDownloadException.cs @@ -8,7 +8,8 @@ public class ReleaseDownloadException : NzbDroneException { public ReleaseInfo Release { get; set; } - public ReleaseDownloadException(ReleaseInfo release, string message, params object[] args) : base(message, args) + public ReleaseDownloadException(ReleaseInfo release, string message, params object[] args) + : base(message, args) { Release = release; } diff --git a/src/NzbDrone.Core/Exceptions/SearchFailedException.cs b/src/NzbDrone.Core/Exceptions/SearchFailedException.cs index e5f42595c4..356a343df5 100644 --- a/src/NzbDrone.Core/Exceptions/SearchFailedException.cs +++ b/src/NzbDrone.Core/Exceptions/SearchFailedException.cs @@ -4,7 +4,8 @@ namespace NzbDrone.Core.Exceptions { public class SearchFailedException : NzbDroneException { - public SearchFailedException(string message) : base(message) + public SearchFailedException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/Extras/ExtraService.cs b/src/NzbDrone.Core/Extras/ExtraService.cs index 0aa901d5a8..f87add16d1 100644 --- a/src/NzbDrone.Core/Extras/ExtraService.cs +++ b/src/NzbDrone.Core/Extras/ExtraService.cs @@ -11,8 +11,8 @@ using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.Extras { @@ -78,7 +78,6 @@ public void ImportExtraFiles(LocalMovie localMovie, MovieFile movieFile, bool is foreach (var matchingFilename in matchingFilenames) { // Filter out duplicate NFO files - if (matchingFilename.EndsWith(".nfo", StringComparison.InvariantCultureIgnoreCase)) { if (hasNfo) diff --git a/src/NzbDrone.Core/Extras/Files/ExtraFileManager.cs b/src/NzbDrone.Core/Extras/Files/ExtraFileManager.cs index 24ee8e1df3..882b0edb33 100644 --- a/src/NzbDrone.Core/Extras/Files/ExtraFileManager.cs +++ b/src/NzbDrone.Core/Extras/Files/ExtraFileManager.cs @@ -23,7 +23,6 @@ public interface IManageExtraFiles public abstract class ExtraFileManager : IManageExtraFiles where TExtraFile : ExtraFile, new() - { private readonly IConfigService _configService; private readonly IDiskProvider _diskProvider; @@ -113,4 +112,3 @@ protected TExtraFile MoveFile(Movie movie, MovieFile movieFile, TExtraFile extra } } } - diff --git a/src/NzbDrone.Core/Extras/Files/ExtraFileRepository.cs b/src/NzbDrone.Core/Extras/Files/ExtraFileRepository.cs index c5d7cba478..716725b842 100644 --- a/src/NzbDrone.Core/Extras/Files/ExtraFileRepository.cs +++ b/src/NzbDrone.Core/Extras/Files/ExtraFileRepository.cs @@ -5,7 +5,8 @@ namespace NzbDrone.Core.Extras.Files { - public interface IExtraFileRepository : IBasicRepository where TExtraFile : ExtraFile, new() + public interface IExtraFileRepository : IBasicRepository + where TExtraFile : ExtraFile, new() { void DeleteForMovie(int movieId); void DeleteForMovieFile(int movieFileId); diff --git a/src/NzbDrone.Core/Extras/Files/ExtraFileService.cs b/src/NzbDrone.Core/Extras/Files/ExtraFileService.cs index 819de5b025..bf934a3689 100644 --- a/src/NzbDrone.Core/Extras/Files/ExtraFileService.cs +++ b/src/NzbDrone.Core/Extras/Files/ExtraFileService.cs @@ -108,7 +108,6 @@ public void HandleAsync(MovieFileDeletedEvent message) { _logger.Debug("Removing movie file from DB as part of cleanup routine, not deleting extra files from disk."); } - else { var movie = _movieService.GetMovie(message.MovieFile.MovieId); diff --git a/src/NzbDrone.Core/Extras/Metadata/Consumers/MediaBrowser/MediaBrowserMetadata.cs b/src/NzbDrone.Core/Extras/Metadata/Consumers/MediaBrowser/MediaBrowserMetadata.cs index 210217dc0a..89bb2b0717 100644 --- a/src/NzbDrone.Core/Extras/Metadata/Consumers/MediaBrowser/MediaBrowserMetadata.cs +++ b/src/NzbDrone.Core/Extras/Metadata/Consumers/MediaBrowser/MediaBrowserMetadata.cs @@ -29,14 +29,17 @@ public override MetadataFile FindMetadataFile(Movie movie, string path) { var filename = Path.GetFileName(path); - if (filename == null) return null; + if (filename == null) + { + return null; + } var metadata = new MetadataFile - { - MovieId = movie.Id, - Consumer = GetType().Name, - RelativePath = movie.Path.GetRelativePath(path) - }; + { + MovieId = movie.Id, + Consumer = GetType().Name, + RelativePath = movie.Path.GetRelativePath(path) + }; if (filename.Equals("movie.xml", StringComparison.InvariantCultureIgnoreCase)) { diff --git a/src/NzbDrone.Core/Extras/Metadata/Consumers/Roksbox/RoksboxMetadata.cs b/src/NzbDrone.Core/Extras/Metadata/Consumers/Roksbox/RoksboxMetadata.cs index 733253d9d8..af8d9ef650 100644 --- a/src/NzbDrone.Core/Extras/Metadata/Consumers/Roksbox/RoksboxMetadata.cs +++ b/src/NzbDrone.Core/Extras/Metadata/Consumers/Roksbox/RoksboxMetadata.cs @@ -32,7 +32,6 @@ public RoksboxMetadata(IMapCoversToLocal mediaCoverService, //Re-enable when/if we store and use mpaa certification //private static List ValidCertification = new List { "G", "NC-17", "PG", "PG-13", "R", "UR", "UNRATED", "NR", "TV-Y", "TV-Y7", "TV-Y7-FV", "TV-G", "TV-PG", "TV-14", "TV-MA" }; - public override string Name => "Roksbox"; public override string GetFilenameAfterMove(Movie movie, MovieFile movieFile, MetadataFile metadataFile) @@ -57,15 +56,19 @@ public override MetadataFile FindMetadataFile(Movie movie, string path) { var filename = Path.GetFileName(path); - if (filename == null) return null; + if (filename == null) + { + return null; + } + var parentdir = Directory.GetParent(path); var metadata = new MetadataFile - { - MovieId = movie.Id, - Consumer = GetType().Name, - RelativePath = movie.Path.GetRelativePath(path) - }; + { + MovieId = movie.Id, + Consumer = GetType().Name, + RelativePath = movie.Path.GetRelativePath(path) + }; var parseResult = Parser.Parser.ParseMovieTitle(filename, false); @@ -103,29 +106,28 @@ public override MetadataFileResult MovieMetadata(Movie movie, MovieFile movieFil var xmlResult = string.Empty; - var sb = new StringBuilder(); - var xws = new XmlWriterSettings(); - xws.OmitXmlDeclaration = true; - xws.Indent = false; + var sb = new StringBuilder(); + var xws = new XmlWriterSettings(); + xws.OmitXmlDeclaration = true; + xws.Indent = false; - using (var xw = XmlWriter.Create(sb, xws)) - { - var doc = new XDocument(); + using (var xw = XmlWriter.Create(sb, xws)) + { + var doc = new XDocument(); - var details = new XElement("video"); - details.Add(new XElement("title", movie.Title)); + var details = new XElement("video"); + details.Add(new XElement("title", movie.Title)); - details.Add(new XElement("genre", string.Join(" / ", movie.Genres))); - details.Add(new XElement("description", movie.Overview)); - details.Add(new XElement("length", movie.Runtime)); + details.Add(new XElement("genre", string.Join(" / ", movie.Genres))); + details.Add(new XElement("description", movie.Overview)); + details.Add(new XElement("length", movie.Runtime)); - doc.Add(details); - doc.Save(xw); - - xmlResult += doc.ToString(); - xmlResult += Environment.NewLine; - } + doc.Add(details); + doc.Save(xw); + xmlResult += doc.ToString(); + xmlResult += Environment.NewLine; + } return new MetadataFileResult(GetMovieFileMetadataFilename(movieFile.RelativePath), xmlResult.Trim(Environment.NewLine.ToCharArray())); } diff --git a/src/NzbDrone.Core/Extras/Metadata/Consumers/Wdtv/WdtvMetadata.cs b/src/NzbDrone.Core/Extras/Metadata/Consumers/Wdtv/WdtvMetadata.cs index ad67947b4f..b1b2c5a424 100644 --- a/src/NzbDrone.Core/Extras/Metadata/Consumers/Wdtv/WdtvMetadata.cs +++ b/src/NzbDrone.Core/Extras/Metadata/Consumers/Wdtv/WdtvMetadata.cs @@ -48,21 +48,23 @@ public override string GetFilenameAfterMove(Movie movie, MovieFile movieFile, Me _logger.Debug("Unknown movie file metadata: {0}", metadataFile.RelativePath); return Path.Combine(movie.Path, metadataFile.RelativePath); - } public override MetadataFile FindMetadataFile(Movie movie, string path) { var filename = Path.GetFileName(path); - if (filename == null) return null; + if (filename == null) + { + return null; + } var metadata = new MetadataFile - { - MovieId = movie.Id, - Consumer = GetType().Name, - RelativePath = movie.Path.GetRelativePath(path) - }; + { + MovieId = movie.Id, + Consumer = GetType().Name, + RelativePath = movie.Path.GetRelativePath(path) + }; if (Path.GetFileName(filename).Equals("folder.jpg", StringComparison.InvariantCultureIgnoreCase)) { @@ -83,7 +85,6 @@ public override MetadataFile FindMetadataFile(Movie movie, string path) metadata.Type = MetadataType.MovieImage; return metadata; } - } return null; @@ -100,28 +101,27 @@ public override MetadataFileResult MovieMetadata(Movie movie, MovieFile movieFil var xmlResult = string.Empty; - var sb = new StringBuilder(); - var xws = new XmlWriterSettings(); - xws.OmitXmlDeclaration = true; - xws.Indent = false; + var sb = new StringBuilder(); + var xws = new XmlWriterSettings(); + xws.OmitXmlDeclaration = true; + xws.Indent = false; - using (var xw = XmlWriter.Create(sb, xws)) - { - var doc = new XDocument(); + using (var xw = XmlWriter.Create(sb, xws)) + { + var doc = new XDocument(); - var details = new XElement("details"); - details.Add(new XElement("id", movie.Id)); - details.Add(new XElement("title", movie.Title)); - details.Add(new XElement("genre", string.Join(" / ", movie.Genres))); - details.Add(new XElement("overview", movie.Overview)); + var details = new XElement("details"); + details.Add(new XElement("id", movie.Id)); + details.Add(new XElement("title", movie.Title)); + details.Add(new XElement("genre", string.Join(" / ", movie.Genres))); + details.Add(new XElement("overview", movie.Overview)); - doc.Add(details); - doc.Save(xw); - - xmlResult += doc.ToString(); - xmlResult += Environment.NewLine; - } + doc.Add(details); + doc.Save(xw); + xmlResult += doc.ToString(); + xmlResult += Environment.NewLine; + } var filename = GetMovieFileMetadataFilename(movieFile.RelativePath); diff --git a/src/NzbDrone.Core/Extras/Metadata/Consumers/Xbmc/XbmcMetadata.cs b/src/NzbDrone.Core/Extras/Metadata/Consumers/Xbmc/XbmcMetadata.cs index b688332a62..ffc4e14aa7 100644 --- a/src/NzbDrone.Core/Extras/Metadata/Consumers/Xbmc/XbmcMetadata.cs +++ b/src/NzbDrone.Core/Extras/Metadata/Consumers/Xbmc/XbmcMetadata.cs @@ -33,7 +33,6 @@ public XbmcMetadata(IDetectXbmcNfo detectNfo, _mediaCoverService = mediaCoverService; _diskProvider = diskProvider; _detectNfo = detectNfo; - } private static readonly Regex MovieImagesRegex = new Regex(@"^(?poster|banner|fanart|clearart|discart|landscape|logo|backdrop|clearlogo)\.(?:png|jpg)", RegexOptions.Compiled | RegexOptions.IgnoreCase); @@ -59,7 +58,10 @@ public override MetadataFile FindMetadataFile(Movie movie, string path) { var filename = Path.GetFileName(path); - if (filename == null) return null; + if (filename == null) + { + return null; + } var metadata = new MetadataFile { @@ -162,7 +164,6 @@ public override MetadataFileResult MovieMetadata(Movie movie, MovieFile movieFil { details.Add(new XElement("thumb")); } - else { details.Add(new XElement("thumb", thumbnail.Url)); @@ -186,6 +187,7 @@ public override MetadataFileResult MovieMetadata(Movie movie, MovieFile movieFil fanartElement.Add(new XElement("thumb", fanart.Url)); } } + details.Add(fanartElement); } @@ -240,6 +242,7 @@ public override MetadataFileResult MovieMetadata(Movie movie, MovieFile movieFil xmlResult += Environment.NewLine; } } + if (Settings.MovieMetadataURL) { xmlResult += "https://www.themoviedb.org/movie/" + movie.TmdbId; diff --git a/src/NzbDrone.Core/Extras/Metadata/ExistingMetadataImporter.cs b/src/NzbDrone.Core/Extras/Metadata/ExistingMetadataImporter.cs index 850a83c5ed..4c26623034 100644 --- a/src/NzbDrone.Core/Extras/Metadata/ExistingMetadataImporter.cs +++ b/src/NzbDrone.Core/Extras/Metadata/ExistingMetadataImporter.cs @@ -5,8 +5,8 @@ using NzbDrone.Core.Extras.Files; using NzbDrone.Core.Extras.Metadata.Files; using NzbDrone.Core.Extras.Subtitles; -using NzbDrone.Core.Parser; using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser; namespace NzbDrone.Core.Extras.Metadata { @@ -41,7 +41,6 @@ public override IEnumerable ProcessFiles(Movie movie, List fi foreach (var possibleMetadataFile in filterResult.FilesOnDisk) { // Don't process files that have known Subtitle file extensions (saves a bit of unecessary processing) - if (SubtitleFileExtensions.Extensions.Contains(Path.GetExtension(possibleMetadataFile))) { continue; @@ -81,7 +80,6 @@ public override IEnumerable ProcessFiles(Movie movie, List fi // Return files that were just imported along with files that were // previously imported so previously imported files aren't imported twice - return metadataFiles.Concat(filterResult.PreviouslyImported); } } diff --git a/src/NzbDrone.Core/Extras/Metadata/IMetadata.cs b/src/NzbDrone.Core/Extras/Metadata/IMetadata.cs index e3d0b06246..746d52c6fa 100644 --- a/src/NzbDrone.Core/Extras/Metadata/IMetadata.cs +++ b/src/NzbDrone.Core/Extras/Metadata/IMetadata.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using NzbDrone.Core.Extras.Metadata.Files; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Movies; +using NzbDrone.Core.ThingiProvider; namespace NzbDrone.Core.Extras.Metadata { diff --git a/src/NzbDrone.Core/Extras/Metadata/MetadataBase.cs b/src/NzbDrone.Core/Extras/Metadata/MetadataBase.cs index 7358d7f5a5..ea4f4df65a 100644 --- a/src/NzbDrone.Core/Extras/Metadata/MetadataBase.cs +++ b/src/NzbDrone.Core/Extras/Metadata/MetadataBase.cs @@ -4,12 +4,13 @@ using FluentValidation.Results; using NzbDrone.Core.Extras.Metadata.Files; using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Movies; +using NzbDrone.Core.ThingiProvider; namespace NzbDrone.Core.Extras.Metadata { - public abstract class MetadataBase : IMetadata where TSettings : IProviderConfig, new() + public abstract class MetadataBase : IMetadata + where TSettings : IProviderConfig, new() { public abstract string Name { get; } @@ -40,7 +41,10 @@ public virtual string GetFilenameAfterMove(Movie movie, MovieFile movieFile, Met public abstract MetadataFileResult MovieMetadata(Movie movie, MovieFile movieFile); public abstract List MovieImages(Movie movie); - public virtual object RequestAction(string action, IDictionary query) { return null; } + public virtual object RequestAction(string action, IDictionary query) + { + return null; + } protected TSettings Settings => (TSettings)Definition.Settings; diff --git a/src/NzbDrone.Core/Extras/Metadata/MetadataService.cs b/src/NzbDrone.Core/Extras/Metadata/MetadataService.cs index 5566a18c90..65972c0078 100644 --- a/src/NzbDrone.Core/Extras/Metadata/MetadataService.cs +++ b/src/NzbDrone.Core/Extras/Metadata/MetadataService.cs @@ -133,7 +133,6 @@ public override IEnumerable MoveFilesAfterRename(Movie movie, List existingMet _metadataFileService.Delete(file.Id); } - return matchingMetadataFiles.First(); } } diff --git a/src/NzbDrone.Core/Extras/Others/ExistingOtherExtraImporter.cs b/src/NzbDrone.Core/Extras/Others/ExistingOtherExtraImporter.cs index eb6f6f95ac..a30f9fa17a 100644 --- a/src/NzbDrone.Core/Extras/Others/ExistingOtherExtraImporter.cs +++ b/src/NzbDrone.Core/Extras/Others/ExistingOtherExtraImporter.cs @@ -4,8 +4,8 @@ using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Core.Extras.Files; -using NzbDrone.Core.Parser; using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser; namespace NzbDrone.Core.Extras.Others { @@ -68,7 +68,6 @@ public override IEnumerable ProcessFiles(Movie movie, List fi // Return files that were just imported along with files that were // previously imported so previously imported files aren't imported twice - return extraFiles.Concat(filterResult.PreviouslyImported); } } diff --git a/src/NzbDrone.Core/Extras/Subtitles/ExistingSubtitleImporter.cs b/src/NzbDrone.Core/Extras/Subtitles/ExistingSubtitleImporter.cs index a75dc54c5c..8d1e23f3ed 100644 --- a/src/NzbDrone.Core/Extras/Subtitles/ExistingSubtitleImporter.cs +++ b/src/NzbDrone.Core/Extras/Subtitles/ExistingSubtitleImporter.cs @@ -4,8 +4,8 @@ using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Core.Extras.Files; -using NzbDrone.Core.Parser; using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser; namespace NzbDrone.Core.Extras.Subtitles { @@ -18,7 +18,7 @@ public class ExistingSubtitleImporter : ImportExistingExtraFilesBase subtitleFileService, IParsingService parsingService, Logger logger) - : base (subtitleFileService) + : base(subtitleFileService) { _subtitleFileService = subtitleFileService; _parsingService = parsingService; @@ -49,13 +49,13 @@ public override IEnumerable ProcessFiles(Movie movie, List fi } var subtitleFile = new SubtitleFile - { - MovieId = movie.Id, - MovieFileId = movie.MovieFileId, - RelativePath = movie.Path.GetRelativePath(possibleSubtitleFile), - Language = LanguageParser.ParseSubtitleLanguage(possibleSubtitleFile), - Extension = extension - }; + { + MovieId = movie.Id, + MovieFileId = movie.MovieFileId, + RelativePath = movie.Path.GetRelativePath(possibleSubtitleFile), + Language = LanguageParser.ParseSubtitleLanguage(possibleSubtitleFile), + Extension = extension + }; subtitleFiles.Add(subtitleFile); } @@ -66,7 +66,6 @@ public override IEnumerable ProcessFiles(Movie movie, List fi // Return files that were just imported along with files that were // previously imported so previously imported files aren't imported twice - return subtitleFiles.Concat(filterResult.PreviouslyImported); } } diff --git a/src/NzbDrone.Core/Extras/Subtitles/SubtitleService.cs b/src/NzbDrone.Core/Extras/Subtitles/SubtitleService.cs index 41cfd7cf82..851b90727b 100644 --- a/src/NzbDrone.Core/Extras/Subtitles/SubtitleService.cs +++ b/src/NzbDrone.Core/Extras/Subtitles/SubtitleService.cs @@ -7,10 +7,10 @@ using NzbDrone.Common.Extensions; using NzbDrone.Core.Configuration; using NzbDrone.Core.Extras.Files; -using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Parser; -using NzbDrone.Core.Movies; using NzbDrone.Core.Languages; +using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser; namespace NzbDrone.Core.Extras.Subtitles { diff --git a/src/NzbDrone.Core/Fluent.cs b/src/NzbDrone.Core/Fluent.cs index dd63c1de94..02f993f4e2 100644 --- a/src/NzbDrone.Core/Fluent.cs +++ b/src/NzbDrone.Core/Fluent.cs @@ -43,7 +43,6 @@ public static long Gigabytes(this double gigabytes) return Convert.ToInt64(gigabytes * 1024L * 1024L * 1024L); } - public static long Round(this long number, long level) { return Convert.ToInt64(Math.Floor((decimal)number / level) * level); @@ -52,16 +51,24 @@ public static long Round(this long number, long level) public static string ToBestDateString(this DateTime dateTime) { if (dateTime == DateTime.Today.AddDays(-1)) + { return "Yesterday"; + } if (dateTime == DateTime.Today) + { return "Today"; + } if (dateTime == DateTime.Today.AddDays(1)) + { return "Tomorrow"; + } if (dateTime > DateTime.Today.AddDays(1) && dateTime < DateTime.Today.AddDays(7)) + { return dateTime.DayOfWeek.ToString(); + } return dateTime.ToShortDateString(); } @@ -69,12 +76,16 @@ public static string ToBestDateString(this DateTime dateTime) public static int MaxOrDefault(this IEnumerable ints) { if (ints == null) + { return 0; + } var intList = ints.ToList(); if (!intList.Any()) + { return 0; + } return intList.Max(); } @@ -82,7 +93,10 @@ public static int MaxOrDefault(this IEnumerable ints) public static string Truncate(this string s, int maxLength) { if (Encoding.UTF8.GetByteCount(s) <= maxLength) + { return s; + } + var cs = s.ToCharArray(); int length = 0; int i = 0; @@ -90,7 +104,10 @@ public static string Truncate(this string s, int maxLength) { int charSize = 1; if (i < (cs.Length - 1) && char.IsSurrogate(cs[i])) + { charSize = 2; + } + int byteSize = Encoding.UTF8.GetByteCount(cs, i, charSize); if ((byteSize + length) <= maxLength) { @@ -98,20 +115,27 @@ public static string Truncate(this string s, int maxLength) length += byteSize; } else + { break; + } } + return s.Substring(0, i); } public static int MinOrDefault(this IEnumerable ints) { if (ints == null) + { return 0; + } var intsList = ints.ToList(); if (!intsList.Any()) + { return 0; + } return intsList.Min(); } diff --git a/src/NzbDrone.Core/HealthCheck/CheckOnAttribute.cs b/src/NzbDrone.Core/HealthCheck/CheckOnAttribute.cs index 7e7b9d259e..dd1dcb3bee 100644 --- a/src/NzbDrone.Core/HealthCheck/CheckOnAttribute.cs +++ b/src/NzbDrone.Core/HealthCheck/CheckOnAttribute.cs @@ -3,7 +3,7 @@ namespace NzbDrone.Core.HealthCheck { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] - public class CheckOnAttribute: Attribute + public class CheckOnAttribute : Attribute { public Type EventType { get; set; } public CheckOnCondition Condition { get; set; } diff --git a/src/NzbDrone.Core/HealthCheck/Checks/DotnetVersionCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/DotnetVersionCheck.cs index dce62085e5..212af23170 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/DotnetVersionCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/DotnetVersionCheck.cs @@ -37,12 +37,14 @@ public override HealthCheck Check() if (dotnetVersion >= stableVersion) { _logger.Debug("Dotnet version is {0} or better: {1}", stableVersion, dotnetVersion); - return new HealthCheck(GetType(), HealthCheckResult.Notice, + return new HealthCheck(GetType(), + HealthCheckResult.Notice, $"Currently installed .Net Framework {dotnetVersion} is supported but we recommend upgrading to at least {targetVersion}.", "#currently-installed-net-framework-is-supported-but-upgrading-is-recommended"); } - return new HealthCheck(GetType(), HealthCheckResult.Error, + return new HealthCheck(GetType(), + HealthCheckResult.Error, $"Currently installed .Net Framework {dotnetVersion} is old and unsupported. Please upgrade the .Net Framework to at least {targetVersion}.", "#currently-installed-net-framework-is-old-and-unsupported"); } diff --git a/src/NzbDrone.Core/HealthCheck/Checks/ImportMechanismCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/ImportMechanismCheck.cs index a62f82c191..ebb0c26094 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/ImportMechanismCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/ImportMechanismCheck.cs @@ -18,7 +18,6 @@ public class ImportMechanismCheck : HealthCheckBase private readonly IConfigService _configService; private readonly IProvideDownloadClient _provideDownloadClient; - public ImportMechanismCheck(IConfigService configService, IProvideDownloadClient provideDownloadClient) { _configService = configService; diff --git a/src/NzbDrone.Core/HealthCheck/Checks/IndexerRssCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/IndexerRssCheck.cs index f15874770c..03f60031ba 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/IndexerRssCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/IndexerRssCheck.cs @@ -30,7 +30,7 @@ public override HealthCheck Check() if (active.Empty()) { - return new HealthCheck(GetType(), HealthCheckResult.Warning, "All rss-capable indexers are temporarily unavailable due to recent indexer errors"); + return new HealthCheck(GetType(), HealthCheckResult.Warning, "All rss-capable indexers are temporarily unavailable due to recent indexer errors"); } return new HealthCheck(GetType()); diff --git a/src/NzbDrone.Core/HealthCheck/Checks/MonoVersionCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/MonoVersionCheck.cs index 0bdc8466c0..70d3dd68a0 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/MonoVersionCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/MonoVersionCheck.cs @@ -28,7 +28,8 @@ public override HealthCheck Check() if (monoVersion == new Version("4.4.0") || monoVersion == new Version("4.4.1")) { _logger.Debug("Mono version {0}", monoVersion); - return new HealthCheck(GetType(), HealthCheckResult.Error, + return new HealthCheck(GetType(), + HealthCheckResult.Error, $"Currently installed Mono version {monoVersion} has a bug that causes issues connecting to indexers/download clients. You should upgrade to a higher version", "#currently-installed-mono-version-is-old-and-unsupported"); } @@ -47,7 +48,8 @@ public override HealthCheck Check() if (monoVersion >= stableVersion) { _logger.Debug("Mono version is {0} or better: {1}", stableVersion, monoVersion); - return new HealthCheck(GetType(), HealthCheckResult.Notice, + return new HealthCheck(GetType(), + HealthCheckResult.Notice, $"Currently installed Mono version {monoVersion} is supported but upgrading to {bestVersion} is recommended.", "#currently-installed-mono-version-is-supported-but-upgrading-is-recommended"); } @@ -57,12 +59,14 @@ public override HealthCheck Check() if (monoVersion >= supportedVersion) { _logger.Debug("Mono version is {0} or better: {1}", supportedVersion, monoVersion); - return new HealthCheck(GetType(), HealthCheckResult.Warning, + return new HealthCheck(GetType(), + HealthCheckResult.Warning, $"Currently installed Mono version {monoVersion} is supported but has some known issues. Please upgrade Mono to version {bestVersion}.", "#currently-installed-mono-version-is-supported-but-upgrading-is-recommended"); } - return new HealthCheck(GetType(), HealthCheckResult.Error, + return new HealthCheck(GetType(), + HealthCheckResult.Error, $"Currently installed Mono version {monoVersion} is old and unsupported. Please upgrade Mono to version {bestVersion}.", "#currently-installed-mono-version-is-old-and-unsupported"); } diff --git a/src/NzbDrone.Core/HealthCheck/Checks/ProxyCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/ProxyCheck.cs index 029c2e6b8c..e6b0b7576a 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/ProxyCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/ProxyCheck.cs @@ -1,10 +1,10 @@ -using NLog; -using NzbDrone.Common.Http; -using NzbDrone.Core.Configuration; -using System; +using System; using System.Linq; using System.Net; +using NLog; using NzbDrone.Common.Cloud; +using NzbDrone.Common.Http; +using NzbDrone.Core.Configuration; using NzbDrone.Core.Configuration.Events; namespace NzbDrone.Core.HealthCheck.Checks diff --git a/src/NzbDrone.Core/HealthCheck/Checks/UpdateCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/UpdateCheck.cs index 5b8c2f3a57..82b640a7a1 100644 --- a/src/NzbDrone.Core/HealthCheck/Checks/UpdateCheck.cs +++ b/src/NzbDrone.Core/HealthCheck/Checks/UpdateCheck.cs @@ -38,21 +38,24 @@ public override HealthCheck Check() { if (OsInfo.IsOsx && startupFolder.GetAncestorFolders().Contains("AppTranslocation")) { - return new HealthCheck(GetType(), HealthCheckResult.Error, + return new HealthCheck(GetType(), + HealthCheckResult.Error, string.Format("Cannot install update because startup folder '{0}' is in an App Translocation folder.", startupFolder), "Cannot install update because startup folder is in an App Translocation folder."); } if (!_diskProvider.FolderWritable(startupFolder)) { - return new HealthCheck(GetType(), HealthCheckResult.Error, + return new HealthCheck(GetType(), + HealthCheckResult.Error, string.Format("Cannot install update because startup folder '{0}' is not writable by the user '{1}'.", startupFolder, Environment.UserName), "Cannot install update because startup folder is not writable by the user"); } if (!_diskProvider.FolderWritable(uiFolder)) { - return new HealthCheck(GetType(), HealthCheckResult.Error, + return new HealthCheck(GetType(), + HealthCheckResult.Error, string.Format("Cannot install update because UI folder '{0}' is not writable by the user '{1}'.", uiFolder, Environment.UserName), "Cannot install update because UI folder is not writable by the user"); } diff --git a/src/NzbDrone.Core/HealthCheck/HealthCheckService.cs b/src/NzbDrone.Core/HealthCheck/HealthCheckService.cs index 643863c2b8..761e9f7d0a 100644 --- a/src/NzbDrone.Core/HealthCheck/HealthCheckService.cs +++ b/src/NzbDrone.Core/HealthCheck/HealthCheckService.cs @@ -73,7 +73,6 @@ private void PerformHealthCheck(IProvideHealthCheck[] healthChecks) { _healthCheckResults.Remove(result.Source.Name); } - else { if (_healthCheckResults.Find(result.Source.Name) == null) @@ -145,9 +144,7 @@ public void HandleAsync(IEvent message) } } - // TODO: Add debounce - PerformHealthCheck(filteredChecks.ToArray()); } } diff --git a/src/NzbDrone.Core/History/History.cs b/src/NzbDrone.Core/History/History.cs index f022d65b40..fe58239c38 100644 --- a/src/NzbDrone.Core/History/History.cs +++ b/src/NzbDrone.Core/History/History.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using NzbDrone.Core.Datastore; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; using NzbDrone.Core.Languages; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.History { @@ -26,16 +26,17 @@ public History() public List Languages { get; set; } public string DownloadId { get; set; } - } public enum HistoryEventType { Unknown = 0, Grabbed = 1, + // SeriesFolderImported = 2, // deprecated DownloadFolderImported = 3, DownloadFailed = 4, + // EpisodeFileDeleted = 5, // deprecated MovieFileDeleted = 6, MovieFolderImported = 7, // not used yet diff --git a/src/NzbDrone.Core/History/HistoryRepository.cs b/src/NzbDrone.Core/History/HistoryRepository.cs index dde58ccb98..7be0674da6 100644 --- a/src/NzbDrone.Core/History/HistoryRepository.cs +++ b/src/NzbDrone.Core/History/HistoryRepository.cs @@ -4,8 +4,8 @@ using Marr.Data.QGen; using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Movies; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.History { @@ -23,7 +23,6 @@ public interface IHistoryRepository : IBasicRepository public class HistoryRepository : BasicRepository, IHistoryRepository { - public HistoryRepository(IMainDatabase database, IEventAggregator eventAggregator) : base(database, eventAggregator) { @@ -55,8 +54,8 @@ public List FindDownloadHistory(int idMovieId, QualityModel quality) h.Quality == quality && (h.EventType == HistoryEventType.Grabbed || h.EventType == HistoryEventType.DownloadFailed || - h.EventType == HistoryEventType.DownloadFolderImported) - ).ToList(); + h.EventType == HistoryEventType.DownloadFolderImported)) + .ToList(); } public List GetByMovieId(int movieId, HistoryEventType? eventType) diff --git a/src/NzbDrone.Core/History/HistoryService.cs b/src/NzbDrone.Core/History/HistoryService.cs index f453efcd6c..ba259ac460 100644 --- a/src/NzbDrone.Core/History/HistoryService.cs +++ b/src/NzbDrone.Core/History/HistoryService.cs @@ -9,10 +9,10 @@ using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Movies.Events; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Profiles; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies.Events; namespace NzbDrone.Core.History { @@ -249,21 +249,22 @@ private string FindDownloadId(MovieImportedEvent trackedDownload) //foreach (var matchingHistory in trackedDownload.EpisodeInfo.Episodes.Select(e => stillDownloading.Where(c => c.MovieId == e.Id).ToList())) //foreach (var matchingHistory in stillDownloading.Where(c => c.MovieId == e.Id).ToList()) //{ - if (stillDownloading.Count != 1) - { - return null; - } + if (stillDownloading.Count != 1) + { + return null; + } - var newDownloadId = stillDownloading.Single().DownloadId; + var newDownloadId = stillDownloading.Single().DownloadId; + + if (downloadId == null || downloadId == newDownloadId) + { + downloadId = newDownloadId; + } + else + { + return null; + } - if (downloadId == null || downloadId == newDownloadId) - { - downloadId = newDownloadId; - } - else - { - return null; - } //} } diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupAdditionalNamingSpecs.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupAdditionalNamingSpecs.cs index e63fd2dfa7..8546cd37c6 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupAdditionalNamingSpecs.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupAdditionalNamingSpecs.cs @@ -15,7 +15,6 @@ public void Clean() { using (var mapper = _database.GetDataMapper()) { - mapper.ExecuteNonQuery(@"DELETE FROM NamingConfig WHERE ID NOT IN ( SELECT ID FROM NamingConfig diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupAdditionalUsers.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupAdditionalUsers.cs index 4dde12d143..4064d453e4 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupAdditionalUsers.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupAdditionalUsers.cs @@ -15,7 +15,6 @@ public void Clean() { using (var mapper = _database.GetDataMapper()) { - mapper.ExecuteNonQuery(@"DELETE FROM Users WHERE ID NOT IN ( SELECT ID FROM Users @@ -24,4 +23,3 @@ SELECT ID FROM Users } } } - diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupDownloadClientUnavailablePendingReleases.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupDownloadClientUnavailablePendingReleases.cs index 51c3ba3f95..a7b36639e7 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupDownloadClientUnavailablePendingReleases.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupDownloadClientUnavailablePendingReleases.cs @@ -22,11 +22,11 @@ public void Clean() (p.Reason == PendingReleaseReason.DownloadClientUnavailable || p.Reason == PendingReleaseReason.Fallback)); -// mapper.AddParameter("twoWeeksAgo", $"{DateTime.UtcNow.AddDays(-14).ToString("s")}Z"); + // mapper.AddParameter("twoWeeksAgo", $"{DateTime.UtcNow.AddDays(-14).ToString("s")}Z"); -// mapper.ExecuteNonQuery(@"DELETE FROM PendingReleases -// WHERE Added < @twoWeeksAgo -// AND (Reason = 'DownloadClientUnavailable' OR Reason = 'Fallback')"); + // mapper.ExecuteNonQuery(@"DELETE FROM PendingReleases + // WHERE Added < @twoWeeksAgo + // AND (Reason = 'DownloadClientUnavailable' OR Reason = 'Fallback')"); } } } diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupDuplicateMetadataFiles.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupDuplicateMetadataFiles.cs index 5a405de77a..8ce13e95c6 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupDuplicateMetadataFiles.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupDuplicateMetadataFiles.cs @@ -21,7 +21,6 @@ private void DeleteDuplicateMovieMetadata() { using (var mapper = _database.GetDataMapper()) { - mapper.ExecuteNonQuery(@"DELETE FROM MetadataFiles WHERE Id IN ( SELECT Id FROM MetadataFiles @@ -36,7 +35,6 @@ private void DeleteDuplicateMovieFileMetadata() { using (var mapper = _database.GetDataMapper()) { - mapper.ExecuteNonQuery(@"DELETE FROM MetadataFiles WHERE Id IN ( SELECT Id FROM MetadataFiles diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedAlternativeTitles.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedAlternativeTitles.cs index 6ef15ac2f6..62e8de4c83 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedAlternativeTitles.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedAlternativeTitles.cs @@ -15,7 +15,6 @@ public void Clean() { using (var mapper = _database.GetDataMapper()) { - mapper.ExecuteNonQuery(@"DELETE FROM AlternativeTitles WHERE Id IN ( SELECT AlternativeTitles.Id FROM AlternativeTitles diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedBlacklist.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedBlacklist.cs index 7816c5ab95..609236cb44 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedBlacklist.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedBlacklist.cs @@ -15,7 +15,6 @@ public void Clean() { using (var mapper = _database.GetDataMapper()) { - mapper.ExecuteNonQuery(@"DELETE FROM Blacklist WHERE Id IN ( SELECT Blacklist.Id FROM Blacklist diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedHistoryItems.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedHistoryItems.cs index d69112d97f..a8d071365a 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedHistoryItems.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedHistoryItems.cs @@ -20,7 +20,6 @@ private void CleanupOrphanedByMovie() { using (var mapper = _database.GetDataMapper()) { - mapper.ExecuteNonQuery(@"DELETE FROM History WHERE Id IN ( SELECT History.Id FROM History diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedIndexerStatus.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedIndexerStatus.cs index 60c956b99a..6f6a612671 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedIndexerStatus.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedIndexerStatus.cs @@ -15,7 +15,6 @@ public void Clean() { using (var mapper = _database.GetDataMapper()) { - mapper.ExecuteNonQuery(@"DELETE FROM IndexerStatus WHERE Id IN ( SELECT IndexerStatus.Id FROM IndexerStatus diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedMetadataFiles.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedMetadataFiles.cs index 1c89b1c464..bf10b4fcfe 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedMetadataFiles.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedMetadataFiles.cs @@ -22,7 +22,6 @@ private void DeleteOrphanedByMovie() { using (var mapper = _database.GetDataMapper()) { - mapper.ExecuteNonQuery(@"DELETE FROM MetadataFiles WHERE Id IN ( SELECT MetadataFiles.Id FROM MetadataFiles @@ -36,7 +35,6 @@ private void DeleteOrphanedByMovieFile() { using (var mapper = _database.GetDataMapper()) { - mapper.ExecuteNonQuery(@"DELETE FROM MetadataFiles WHERE Id IN ( SELECT MetadataFiles.Id FROM MetadataFiles @@ -51,7 +49,6 @@ private void DeleteWhereMovieFileIsZero() { using (var mapper = _database.GetDataMapper()) { - mapper.ExecuteNonQuery(@"DELETE FROM MetadataFiles WHERE Id IN ( SELECT Id FROM MetadataFiles diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedPendingReleases.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedPendingReleases.cs index bed514b93f..71e9eded60 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedPendingReleases.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupOrphanedPendingReleases.cs @@ -15,7 +15,6 @@ public void Clean() { using (var mapper = _database.GetDataMapper()) { - mapper.ExecuteNonQuery(@"DELETE FROM PendingReleases WHERE Id IN ( SELECT PendingReleases.Id FROM PendingReleases diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupUnusedTags.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupUnusedTags.cs index f8ead0292a..4f473b1585 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupUnusedTags.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/CleanupUnusedTags.cs @@ -19,8 +19,7 @@ public void Clean() { using (var mapper = _database.GetDataMapper()) { - - var usedTags = new[] {"Movies", "Notifications", "DelayProfiles", "Restrictions", "NetImport"} + var usedTags = new[] { "Movies", "Notifications", "DelayProfiles", "Restrictions", "NetImport" } .SelectMany(v => GetUsedTags(v, mapper)) .Distinct() .ToArray(); diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/DeleteBadMediaCovers.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/DeleteBadMediaCovers.cs index 0b91194255..1ba7f83d51 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/DeleteBadMediaCovers.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/DeleteBadMediaCovers.cs @@ -32,7 +32,10 @@ public DeleteBadMediaCovers(IMetadataFileService metaFileService, public void Clean() { - if (!_configService.CleanupMetadataImages) return; + if (!_configService.CleanupMetadataImages) + { + return; + } var movies = _movieService.GetAllMovies(); @@ -59,7 +62,6 @@ public void Clean() } } - _configService.CleanupMetadataImages = false; } @@ -75,7 +77,11 @@ private bool IsValid(string path) using (var imageStream = _diskProvider.OpenReadStream(path)) { - if (imageStream.Length < buffer.Length) return false; + if (imageStream.Length < buffer.Length) + { + return false; + } + imageStream.Read(buffer, 0, buffer.Length); } diff --git a/src/NzbDrone.Core/Housekeeping/Housekeepers/FixFutureProviderStatusTimes.cs b/src/NzbDrone.Core/Housekeeping/Housekeepers/FixFutureProviderStatusTimes.cs index 80bf5c8b93..55a4c6b3da 100644 --- a/src/NzbDrone.Core/Housekeeping/Housekeepers/FixFutureProviderStatusTimes.cs +++ b/src/NzbDrone.Core/Housekeeping/Housekeepers/FixFutureProviderStatusTimes.cs @@ -5,7 +5,8 @@ namespace NzbDrone.Core.Housekeeping.Housekeepers { - public abstract class FixFutureProviderStatusTimes where TModel : ProviderStatusBase, new() + public abstract class FixFutureProviderStatusTimes + where TModel : ProviderStatusBase, new() { private readonly IProviderStatusRepository _repo; diff --git a/src/NzbDrone.Core/Housekeeping/HousekeepingService.cs b/src/NzbDrone.Core/Housekeeping/HousekeepingService.cs index eb8cedd9eb..277065511d 100644 --- a/src/NzbDrone.Core/Housekeeping/HousekeepingService.cs +++ b/src/NzbDrone.Core/Housekeeping/HousekeepingService.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using NLog; -using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Datastore; +using NzbDrone.Core.Messaging.Commands; namespace NzbDrone.Core.Housekeeping { @@ -30,7 +30,6 @@ private void Clean() _logger.Debug("Starting {0}", housekeeper.GetType().Name); housekeeper.Clean(); _logger.Debug("Completed {0}", housekeeper.GetType().Name); - } catch (Exception ex) { diff --git a/src/NzbDrone.Core/Http/CloudFlare/CloudFlareHttpInterceptor.cs b/src/NzbDrone.Core/Http/CloudFlare/CloudFlareHttpInterceptor.cs index e5590c63c7..dca1d12c0c 100644 --- a/src/NzbDrone.Core/Http/CloudFlare/CloudFlareHttpInterceptor.cs +++ b/src/NzbDrone.Core/Http/CloudFlare/CloudFlareHttpInterceptor.cs @@ -7,9 +7,8 @@ namespace NzbDrone.Core.Http.CloudFlare { public class CloudFlareHttpInterceptor : IHttpRequestInterceptor { - private readonly Logger _logger; - private const string _cloudFlareChallengeScript = "cdn-cgi/scripts/cf.challenge.js"; + private readonly Logger _logger; private static readonly Regex _cloudFlareRegex = new Regex(@"data-ray=""(?[\w-_]+)"".*?data-sitekey=""(?[\w-_]+)"".*?data-stoken=""(?[\w-_]+)""", RegexOptions.Compiled); public CloudFlareHttpInterceptor(Logger logger) diff --git a/src/NzbDrone.Core/IndexerSearch/Definitions/MovieSearchCriteria.cs b/src/NzbDrone.Core/IndexerSearch/Definitions/MovieSearchCriteria.cs index b35f508a34..567dae930a 100644 --- a/src/NzbDrone.Core/IndexerSearch/Definitions/MovieSearchCriteria.cs +++ b/src/NzbDrone.Core/IndexerSearch/Definitions/MovieSearchCriteria.cs @@ -2,7 +2,6 @@ namespace NzbDrone.Core.IndexerSearch.Definitions { public class MovieSearchCriteria : SearchCriteriaBase { - public override string ToString() { return string.Format("[{0}]", Movie.Title); diff --git a/src/NzbDrone.Core/IndexerSearch/Definitions/SearchCriteriaBase.cs b/src/NzbDrone.Core/IndexerSearch/Definitions/SearchCriteriaBase.cs index c5d3b482d5..da55ef55f9 100644 --- a/src/NzbDrone.Core/IndexerSearch/Definitions/SearchCriteriaBase.cs +++ b/src/NzbDrone.Core/IndexerSearch/Definitions/SearchCriteriaBase.cs @@ -23,7 +23,7 @@ public abstract class SearchCriteriaBase public static string GetQueryTitle(string title) { - Ensure.That(title,() => title).IsNotNullOrWhiteSpace(); + Ensure.That(title, () => title).IsNotNullOrWhiteSpace(); var cleanTitle = BeginningThe.Replace(title, string.Empty); diff --git a/src/NzbDrone.Core/IndexerSearch/MoviesSearchCommand.cs b/src/NzbDrone.Core/IndexerSearch/MoviesSearchCommand.cs index 09c4c87364..9e84593446 100644 --- a/src/NzbDrone.Core/IndexerSearch/MoviesSearchCommand.cs +++ b/src/NzbDrone.Core/IndexerSearch/MoviesSearchCommand.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.Messaging.Commands; -using System.Collections.Generic; +using System.Collections.Generic; +using NzbDrone.Core.Messaging.Commands; namespace NzbDrone.Core.IndexerSearch { diff --git a/src/NzbDrone.Core/IndexerSearch/MoviesSearchService.cs b/src/NzbDrone.Core/IndexerSearch/MoviesSearchService.cs index 608b03efcc..9ae982aef5 100644 --- a/src/NzbDrone.Core/IndexerSearch/MoviesSearchService.cs +++ b/src/NzbDrone.Core/IndexerSearch/MoviesSearchService.cs @@ -1,14 +1,14 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using NLog; using NzbDrone.Common.Instrumentation.Extensions; +using NzbDrone.Core.Datastore; +using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Movies; -using NzbDrone.Core.Datastore; using NzbDrone.Core.Queue; -using NzbDrone.Core.DecisionEngine; namespace NzbDrone.Core.IndexerSearch { @@ -49,10 +49,10 @@ public void Execute(MoviesSearchCommand message) continue; } - var decisions = _nzbSearchService.MovieSearch(movieId, false, false);//_nzbSearchService.SeasonSearch(message.MovieId, season.SeasonNumber, false, message.Trigger == CommandTrigger.Manual); + var decisions = _nzbSearchService.MovieSearch(movieId, false, false); //_nzbSearchService.SeasonSearch(message.MovieId, season.SeasonNumber, false, message.Trigger == CommandTrigger.Manual); downloadedCount += _processDownloadDecisions.ProcessDecisions(decisions).Grabbed.Count; - } + _logger.ProgressInfo("Movie search completed. {0} reports downloaded.", downloadedCount); } @@ -73,7 +73,6 @@ public void Execute(MissingMoviesSearchCommand message) var missing = movies.Where(e => !queue.Contains(e.Id)).ToList(); SearchForMissingMovies(missing, message.Trigger == CommandTrigger.Manual); - } public void Execute(CutoffUnmetMoviesSearchCommand message) @@ -94,7 +93,6 @@ public void Execute(CutoffUnmetMoviesSearchCommand message) var missing = movies.Where(e => !queue.Contains(e.Id)).ToList(); SearchForMissingMovies(missing, message.Trigger == CommandTrigger.Manual); - } private void SearchForMissingMovies(List movies, bool userInvokedSearch) @@ -112,7 +110,7 @@ private void SearchForMissingMovies(List movies, bool userInvokedSearch) } catch (Exception ex) { - var message = String.Format("Unable to search for missing movie {0}", movieId.Key); + var message = string.Format("Unable to search for missing movie {0}", movieId.Key); _logger.Error(ex, message); continue; } @@ -124,8 +122,5 @@ private void SearchForMissingMovies(List movies, bool userInvokedSearch) _logger.ProgressInfo("Completed missing search for {0} movies. {1} reports downloaded.", movies.Count, downloadedCount); } - - - } } diff --git a/src/NzbDrone.Core/IndexerSearch/NzbSearchService.cs b/src/NzbDrone.Core/IndexerSearch/NzbSearchService.cs index c4c74d2d42..0d72198922 100644 --- a/src/NzbDrone.Core/IndexerSearch/NzbSearchService.cs +++ b/src/NzbDrone.Core/IndexerSearch/NzbSearchService.cs @@ -1,15 +1,15 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Threading.Tasks; using NLog; using NzbDrone.Common.Instrumentation.Extensions; -using NzbDrone.Core.DecisionEngine; -using NzbDrone.Core.IndexerSearch.Definitions; -using NzbDrone.Core.Indexers; -using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Movies; -using System.Linq; using NzbDrone.Common.TPL; +using NzbDrone.Core.DecisionEngine; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.IndexerSearch.Definitions; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.IndexerSearch { @@ -51,14 +51,15 @@ public List MovieSearch(Movie movie, bool userInvokedSearch, b return Dispatch(indexer => indexer.Fetch(searchSpec), searchSpec); } - private TSpec Get(Movie movie, bool userInvokedSearch, bool interactiveSearch) where TSpec : SearchCriteriaBase, new() + private TSpec Get(Movie movie, bool userInvokedSearch, bool interactiveSearch) + where TSpec : SearchCriteriaBase, new() { var spec = new TSpec() { Movie = movie, UserInvokedSearch = userInvokedSearch, InteractiveSearch = interactiveSearch - }; + }; return spec; } diff --git a/src/NzbDrone.Core/Indexers/AwesomeHD/AwesomeHD.cs b/src/NzbDrone.Core/Indexers/AwesomeHD/AwesomeHD.cs index afe7892a03..edfee09cca 100644 --- a/src/NzbDrone.Core/Indexers/AwesomeHD/AwesomeHD.cs +++ b/src/NzbDrone.Core/Indexers/AwesomeHD/AwesomeHD.cs @@ -15,7 +15,8 @@ public class AwesomeHD : HttpIndexerBase public AwesomeHD(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) - { } + { + } public override IIndexerRequestGenerator GetRequestGenerator() { diff --git a/src/NzbDrone.Core/Indexers/AwesomeHD/AwesomeHDRequestGenerator.cs b/src/NzbDrone.Core/Indexers/AwesomeHD/AwesomeHDRequestGenerator.cs index a5dbe8d7ca..8b4e2c68e7 100644 --- a/src/NzbDrone.Core/Indexers/AwesomeHD/AwesomeHDRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/AwesomeHD/AwesomeHDRequestGenerator.cs @@ -36,7 +36,6 @@ private IEnumerable GetRequest(string searchParameters) { yield return new IndexerRequest($"{Settings.BaseUrl.Trim().TrimEnd('/')}/searchapi.php?action=latestmovies&passkey={Settings.Passkey.Trim()}", HttpAccept.Rss); } - } } } diff --git a/src/NzbDrone.Core/Indexers/AwesomeHD/AwesomeHDRssParser.cs b/src/NzbDrone.Core/Indexers/AwesomeHD/AwesomeHDRssParser.cs index 9fa65a71df..44384dac56 100644 --- a/src/NzbDrone.Core/Indexers/AwesomeHD/AwesomeHDRssParser.cs +++ b/src/NzbDrone.Core/Indexers/AwesomeHD/AwesomeHDRssParser.cs @@ -1,12 +1,12 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; +using System.Linq; using System.Net; +using System.Xml; +using System.Xml.Linq; using NzbDrone.Common.Http; using NzbDrone.Core.Indexers.Exceptions; using NzbDrone.Core.Parser.Model; -using System; -using System.Linq; -using System.Xml; -using System.Xml.Linq; namespace NzbDrone.Core.Indexers.AwesomeHD { @@ -125,7 +125,6 @@ public IList ParseResponse(IndexerResponse indexerResponse) "An error occurred while processing feed, feed invalid"); } - return torrentInfos.OrderByDescending(o => ((dynamic)o).Seeders).ToArray(); } diff --git a/src/NzbDrone.Core/Indexers/Exceptions/ApiKeyException.cs b/src/NzbDrone.Core/Indexers/Exceptions/ApiKeyException.cs index 41d0d4d5e4..eb4e266543 100644 --- a/src/NzbDrone.Core/Indexers/Exceptions/ApiKeyException.cs +++ b/src/NzbDrone.Core/Indexers/Exceptions/ApiKeyException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Indexers.Exceptions { public class ApiKeyException : NzbDroneException { - public ApiKeyException(string message, params object[] args) : base(message, args) + public ApiKeyException(string message, params object[] args) + : base(message, args) { } - public ApiKeyException(string message) : base(message) + public ApiKeyException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/Indexers/Exceptions/SizeParsingException.cs b/src/NzbDrone.Core/Indexers/Exceptions/SizeParsingException.cs index 6fe085dd43..08e5d72f46 100644 --- a/src/NzbDrone.Core/Indexers/Exceptions/SizeParsingException.cs +++ b/src/NzbDrone.Core/Indexers/Exceptions/SizeParsingException.cs @@ -4,7 +4,8 @@ namespace NzbDrone.Core.Indexers.Exceptions { public class SizeParsingException : NzbDroneException { - public SizeParsingException(string message, params object[] args) : base(message, args) + public SizeParsingException(string message, params object[] args) + : base(message, args) { } } diff --git a/src/NzbDrone.Core/Indexers/FetchAndParseRssService.cs b/src/NzbDrone.Core/Indexers/FetchAndParseRssService.cs index 48773d2c6e..298d7f4feb 100644 --- a/src/NzbDrone.Core/Indexers/FetchAndParseRssService.cs +++ b/src/NzbDrone.Core/Indexers/FetchAndParseRssService.cs @@ -1,10 +1,11 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using NLog; -using NzbDrone.Core.Parser.Model; using NzbDrone.Common.TPL; -using System; +using NzbDrone.Core.Parser.Model; + namespace NzbDrone.Core.Indexers { public interface IFetchAndParseRss diff --git a/src/NzbDrone.Core/Indexers/HDBits/HDBits.cs b/src/NzbDrone.Core/Indexers/HDBits/HDBits.cs index 5185433a5a..c52a2f496d 100644 --- a/src/NzbDrone.Core/Indexers/HDBits/HDBits.cs +++ b/src/NzbDrone.Core/Indexers/HDBits/HDBits.cs @@ -15,7 +15,8 @@ public class HDBits : HttpIndexerBase public HDBits(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) - { } + { + } public override IIndexerRequestGenerator GetRequestGenerator() { diff --git a/src/NzbDrone.Core/Indexers/HDBits/HDBitsParser.cs b/src/NzbDrone.Core/Indexers/HDBits/HDBitsParser.cs index 0a163f4ce6..a772e9f747 100644 --- a/src/NzbDrone.Core/Indexers/HDBits/HDBitsParser.cs +++ b/src/NzbDrone.Core/Indexers/HDBits/HDBitsParser.cs @@ -51,7 +51,7 @@ public IList ParseResponse(IndexerResponse indexerResponse) foreach (var result in queryResults) { var id = result.Id; - var internalRelease = (result.TypeOrigin == 1 ? true : false); + var internalRelease = result.TypeOrigin == 1 ? true : false; IndexerFlags flags = 0; @@ -104,7 +104,6 @@ private string GetInfoUrl(string torrentId) .AddQueryParam("id", torrentId); return url.FullUri; - } } } diff --git a/src/NzbDrone.Core/Indexers/HDBits/HDBitsRequestGenerator.cs b/src/NzbDrone.Core/Indexers/HDBits/HDBitsRequestGenerator.cs index 71ff7ade92..3dbe3e5262 100644 --- a/src/NzbDrone.Core/Indexers/HDBits/HDBitsRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/HDBits/HDBitsRequestGenerator.cs @@ -43,6 +43,7 @@ private bool TryAddSearchParameters(TorrentQuery query, SearchCriteriaBase searc query.ImdbInfo.Id = imdbId; return true; } + return false; } diff --git a/src/NzbDrone.Core/Indexers/HDBits/HDBitsSettings.cs b/src/NzbDrone.Core/Indexers/HDBits/HDBitsSettings.cs index be003121f2..82cea616b4 100644 --- a/src/NzbDrone.Core/Indexers/HDBits/HDBitsSettings.cs +++ b/src/NzbDrone.Core/Indexers/HDBits/HDBitsSettings.cs @@ -1,7 +1,7 @@ +using System.Collections.Generic; using FluentValidation; using NzbDrone.Core.Annotations; using NzbDrone.Core.Validation; -using System.Collections.Generic; namespace NzbDrone.Core.Indexers.HDBits { diff --git a/src/NzbDrone.Core/Indexers/HttpIndexerBase.cs b/src/NzbDrone.Core/Indexers/HttpIndexerBase.cs index 71fc0b4c38..99aa310922 100644 --- a/src/NzbDrone.Core/Indexers/HttpIndexerBase.cs +++ b/src/NzbDrone.Core/Indexers/HttpIndexerBase.cs @@ -63,7 +63,6 @@ protected IndexerPageableRequestChain GetRequestChain(SearchCriteriaBase searchC var generator = GetRequestGenerator(); //A func ensures cookies are always updated to the latest. This way, the first page could update the cookies and then can be reused by the second page. - generator.GetCookies = () => { var cookies = _indexerStatusService.GetIndexerCookies(Definition.Id); @@ -86,7 +85,6 @@ protected IndexerPageableRequestChain GetRequestChain(SearchCriteriaBase searchC return requests; } - protected virtual IList FetchReleases(Func pageableRequestChainSelector, bool isRecent = false) { var releases = new List(); @@ -133,6 +131,7 @@ protected virtual IList FetchReleases(Func v.PublishDate).Min(); if (oldestReleaseDate < lastReleaseInfo.PublishDate || page.Any(v => v.DownloadUrl == lastReleaseInfo.DownloadUrl)) { @@ -177,6 +176,7 @@ protected virtual IList FetchReleases(Func FetchReleases(Func FetchPage(IndexerRequest request, IParseInd } catch (Exception ex) { - ex.WithData(response.HttpResponse, 128*1024); + ex.WithData(response.HttpResponse, 128 * 1024); _logger.Trace("Unexpected Response content ({0} bytes): {1}", response.HttpResponse.ResponseData.Length, response.HttpResponse.Content); throw; } @@ -385,5 +386,4 @@ protected virtual ValidationFailure TestConnection() return null; } } - } diff --git a/src/NzbDrone.Core/Indexers/IIndexerSettings.cs b/src/NzbDrone.Core/Indexers/IIndexerSettings.cs index ab76c2ffd9..1bc6075611 100644 --- a/src/NzbDrone.Core/Indexers/IIndexerSettings.cs +++ b/src/NzbDrone.Core/Indexers/IIndexerSettings.cs @@ -6,6 +6,7 @@ namespace NzbDrone.Core.Indexers public interface IIndexerSettings : IProviderConfig { string BaseUrl { get; set; } + // TODO: Need to Create UI field for this and turn functionality back on per indexer. IEnumerable MultiLanguages { get; set; } } diff --git a/src/NzbDrone.Core/Indexers/IPTorrents/IPTorrents.cs b/src/NzbDrone.Core/Indexers/IPTorrents/IPTorrents.cs index 633f27bd0c..6b74949ba2 100644 --- a/src/NzbDrone.Core/Indexers/IPTorrents/IPTorrents.cs +++ b/src/NzbDrone.Core/Indexers/IPTorrents/IPTorrents.cs @@ -1,7 +1,7 @@ +using NLog; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.Parser; -using NLog; namespace NzbDrone.Core.Indexers.IPTorrents { @@ -16,7 +16,6 @@ public class IPTorrents : HttpIndexerBase public IPTorrents(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) { - } public override IIndexerRequestGenerator GetRequestGenerator() diff --git a/src/NzbDrone.Core/Indexers/IndexerBase.cs b/src/NzbDrone.Core/Indexers/IndexerBase.cs index ed258365f9..265a1b144f 100644 --- a/src/NzbDrone.Core/Indexers/IndexerBase.cs +++ b/src/NzbDrone.Core/Indexers/IndexerBase.cs @@ -58,7 +58,10 @@ public virtual IEnumerable DefaultDefinitions public virtual ProviderDefinition Definition { get; set; } - public virtual object RequestAction(string action, IDictionary query) { return null; } + public virtual object RequestAction(string action, IDictionary query) + { + return null; + } protected TSettings Settings => (TSettings)Definition.Settings; diff --git a/src/NzbDrone.Core/Indexers/IndexerPageableRequestChain.cs b/src/NzbDrone.Core/Indexers/IndexerPageableRequestChain.cs index 427617b61b..1671ff1c10 100644 --- a/src/NzbDrone.Core/Indexers/IndexerPageableRequestChain.cs +++ b/src/NzbDrone.Core/Indexers/IndexerPageableRequestChain.cs @@ -27,7 +27,10 @@ public IEnumerable GetTier(int index) public void Add(IEnumerable request) { - if (request == null) return; + if (request == null) + { + return; + } _chains.Last().Add(new IndexerPageableRequest(request)); } @@ -40,7 +43,10 @@ public void AddTier(IEnumerable request) public void AddTier() { - if (_chains.Last().Count == 0) return; + if (_chains.Last().Count == 0) + { + return; + } _chains.Add(new List()); } diff --git a/src/NzbDrone.Core/Indexers/IndexerRepository.cs b/src/NzbDrone.Core/Indexers/IndexerRepository.cs index 50d07d66db..c4858f4159 100644 --- a/src/NzbDrone.Core/Indexers/IndexerRepository.cs +++ b/src/NzbDrone.Core/Indexers/IndexerRepository.cs @@ -2,7 +2,6 @@ using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.ThingiProvider; - namespace NzbDrone.Core.Indexers { public interface IIndexerRepository : IProviderRepository diff --git a/src/NzbDrone.Core/Indexers/IndexerStatus.cs b/src/NzbDrone.Core/Indexers/IndexerStatus.cs index a556036cbb..ea277e6da8 100644 --- a/src/NzbDrone.Core/Indexers/IndexerStatus.cs +++ b/src/NzbDrone.Core/Indexers/IndexerStatus.cs @@ -11,6 +11,5 @@ public class IndexerStatus : ProviderStatusBase public IDictionary Cookies { get; set; } public DateTime? CookiesExpirationDate { get; set; } - } } diff --git a/src/NzbDrone.Core/Indexers/IndexerStatusRepository.cs b/src/NzbDrone.Core/Indexers/IndexerStatusRepository.cs index 78d2cc41cf..5df1f15238 100644 --- a/src/NzbDrone.Core/Indexers/IndexerStatusRepository.cs +++ b/src/NzbDrone.Core/Indexers/IndexerStatusRepository.cs @@ -6,7 +6,6 @@ namespace NzbDrone.Core.Indexers { public interface IIndexerStatusRepository : IProviderStatusRepository { - } public class IndexerStatusRepository : ProviderStatusRepository, IIndexerStatusRepository diff --git a/src/NzbDrone.Core/Indexers/IndexerStatusService.cs b/src/NzbDrone.Core/Indexers/IndexerStatusService.cs index 847b30caa1..9254a5b3e0 100644 --- a/src/NzbDrone.Core/Indexers/IndexerStatusService.cs +++ b/src/NzbDrone.Core/Indexers/IndexerStatusService.cs @@ -23,7 +23,6 @@ public class IndexerStatusService : ProviderStatusServiceBase DefaultDefinitions yield return GetDefinition("PFmonkey", GetSettings("https://www.pfmonkey.com")); yield return GetDefinition("SimplyNZBs", GetSettings("https://simplynzbs.com")); yield return GetDefinition("Usenet Crawler", GetSettings("https://www.usenet-crawler.com")); - } } @@ -66,17 +65,17 @@ public Newznab(INewznabCapabilitiesProvider capabilitiesProvider, IHttpClient ht private IndexerDefinition GetDefinition(string name, NewznabSettings settings) { return new IndexerDefinition - { - EnableRss = false, - EnableAutomaticSearch = false, - EnableInteractiveSearch = false, - Name = name, - Implementation = GetType().Name, - Settings = settings, - Protocol = DownloadProtocol.Usenet, - SupportsRss = SupportsRss, - SupportsSearch = SupportsSearch - }; + { + EnableRss = false, + EnableAutomaticSearch = false, + EnableInteractiveSearch = false, + Name = name, + Implementation = GetType().Name, + Settings = settings, + Protocol = DownloadProtocol.Usenet, + SupportsRss = SupportsRss, + SupportsSearch = SupportsSearch + }; } private NewznabSettings GetSettings(string url, string apiPath = null, int[] categories = null) @@ -99,7 +98,11 @@ private NewznabSettings GetSettings(string url, string apiPath = null, int[] cat protected override void Test(List failures) { base.Test(failures); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestCapabilities()); } @@ -110,7 +113,9 @@ protected static List CategoryIds(List categories) foreach (var category in categories) { if (category.Subcategories != null) + { l.AddRange(CategoryIds(category.Subcategories)); + } } return l; @@ -128,7 +133,9 @@ protected virtual ValidationFailure TestCapabilities() { _logger.Warn($"{Definition.Name} does not support the following categories: {string.Join(", ", notSupported)}. You should probably remove them."); if (notSupported.Count() == Settings.Categories.Count()) + { return new ValidationFailure(string.Empty, $"This indexer does not support any of the selected categories! (You may need to turn on advanced settings to see them)"); + } } if (capabilities.SupportedSearchParameters != null && capabilities.SupportedSearchParameters.Contains("q")) diff --git a/src/NzbDrone.Core/Indexers/Newznab/NewznabCapabilitiesProvider.cs b/src/NzbDrone.Core/Indexers/Newznab/NewznabCapabilitiesProvider.cs index f8b7136372..e1a27cefe9 100644 --- a/src/NzbDrone.Core/Indexers/Newznab/NewznabCapabilitiesProvider.cs +++ b/src/NzbDrone.Core/Indexers/Newznab/NewznabCapabilitiesProvider.cs @@ -128,6 +128,7 @@ private NewznabCapabilities ParseCapabilities(HttpResponse response) capabilities.SupportedTvSearchParameters = xmlTvSearch.Attribute("supportedParams").Value.Split(','); capabilities.SupportsAggregateIdSearch = true; } + var xmlMovieSearch = xmlSearching.Element("movie-search"); if (xmlMovieSearch == null || xmlMovieSearch.Attribute("available").Value != "yes") { @@ -160,7 +161,6 @@ private NewznabCapabilities ParseCapabilities(HttpResponse response) Id = int.Parse(xmlSubcat.Attribute("id").Value), Name = xmlSubcat.Attribute("name").Value, Description = xmlSubcat.Attribute("description") != null ? xmlSubcat.Attribute("description").Value : string.Empty - }); } diff --git a/src/NzbDrone.Core/Indexers/Newznab/NewznabRequestGenerator.cs b/src/NzbDrone.Core/Indexers/Newznab/NewznabRequestGenerator.cs index 255b30cea9..4161dbb828 100644 --- a/src/NzbDrone.Core/Indexers/Newznab/NewznabRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/Newznab/NewznabRequestGenerator.cs @@ -65,12 +65,12 @@ public IndexerPageableRequestChain GetSearchRequests(MovieSearchCriteria searchC var altTitles = searchCriteria.Movie.AlternativeTitles.Take(5).Select(t => t.Title).ToList(); altTitles.Add(searchCriteria.Movie.Title); - var realMaxPages = (int)MaxPages / (altTitles.Count()); + var realMaxPages = (int)MaxPages / altTitles.Count(); //pageableRequests.Add(GetPagedRequests(MaxPages - (altTitles.Count() * realMaxPages), Settings.Categories, "search", $"&q={searchTitle}%20{searchCriteria.Movie.Year}")); //Also use alt titles for searching. - foreach (String altTitle in altTitles) + foreach (string altTitle in altTitles) { var searchAltTitle = System.Web.HttpUtility.UrlPathEncode(Parser.Parser.ReplaceGermanUmlauts(Parser.Parser.NormalizeTitle(altTitle))); var queryString = $"&q={searchAltTitle}"; @@ -78,6 +78,7 @@ public IndexerPageableRequestChain GetSearchRequests(MovieSearchCriteria searchC { queryString += $"%20{searchCriteria.Movie.Year}"; } + pageableRequests.Add(GetPagedRequests(realMaxPages, Settings.Categories, "search", queryString)); } } diff --git a/src/NzbDrone.Core/Indexers/Newznab/NewznabRssParser.cs b/src/NzbDrone.Core/Indexers/Newznab/NewznabRssParser.cs index a301c658d8..3921615aa6 100644 --- a/src/NzbDrone.Core/Indexers/Newznab/NewznabRssParser.cs +++ b/src/NzbDrone.Core/Indexers/Newznab/NewznabRssParser.cs @@ -27,7 +27,10 @@ protected override bool PreProcess(IndexerResponse indexerResponse) var xdoc = LoadXmlDocument(indexerResponse); var error = xdoc.Descendants("error").FirstOrDefault(); - if (error == null) return true; + if (error == null) + { + return true; + } var code = Convert.ToInt32(error.Attribute("code").Value); var errorMessage = error.Attribute("description").Value; @@ -74,7 +77,6 @@ protected override ReleaseInfo ProcessItem(XElement item, ReleaseInfo releaseInf releaseInfo = base.ProcessItem(item, releaseInfo); releaseInfo.ImdbId = GetImdbId(item); - //// This shouldn't be needed with changes to the DownloadDecisionMaker //var imdbMovieTitle = GetImdbTitle(item); //var imdbYear = GetImdbYear(item); @@ -90,7 +92,6 @@ protected override ReleaseInfo ProcessItem(XElement item, ReleaseInfo releaseInf // releaseInfo.Title = Regex.Replace(releaseInfo.Title, imdbMovieTitle, imdbMovieTitle + "." + imdbYear, RegexOptions.IgnoreCase); // } //} - return releaseInfo; } @@ -162,9 +163,7 @@ protected virtual string GetImdbTitle(XElement item) { return CultureInfo.CurrentCulture.TextInfo.ToTitleCase( Parser.Parser.ReplaceGermanUmlauts( - Parser.Parser.NormalizeTitle(imdbTitle).Replace(" ", ".") - ) - ); + Parser.Parser.NormalizeTitle(imdbTitle).Replace(" ", "."))); } return string.Empty; diff --git a/src/NzbDrone.Core/Indexers/Newznab/NewznabSettings.cs b/src/NzbDrone.Core/Indexers/Newznab/NewznabSettings.cs index 8b747203b3..820c00c2a4 100644 --- a/src/NzbDrone.Core/Indexers/Newznab/NewznabSettings.cs +++ b/src/NzbDrone.Core/Indexers/Newznab/NewznabSettings.cs @@ -84,17 +84,22 @@ public NewznabSettings() [FieldDefinition(5, Label = "Additional Parameters", HelpText = "Additional Newznab parameters", Advanced = true)] public string AdditionalParameters { get; set; } - [FieldDefinition(6, Label = "Remove year from search string", - HelpText = "Should Radarr remove the year after the title when searching this indexer?", Advanced = true, Type = FieldType.Checkbox)] + [FieldDefinition(6, + Label = "Remove year from search string", + HelpText = "Should Radarr remove the year after the title when searching this indexer?", + Advanced = true, + Type = FieldType.Checkbox)] public bool RemoveYear { get; set; } - [FieldDefinition(7, Label = "Search by Title", + [FieldDefinition(7, + Label = "Search by Title", HelpText = "By default, Radarr will try to search by IMDB ID if your indexer supports that. However, some indexers are not very good at tagging their releases correctly, so you can force Radarr to search that indexer by title instead.", - Advanced = true, Type = FieldType.Checkbox)] + Advanced = true, + Type = FieldType.Checkbox)] public bool SearchByTitle { get; set; } + // Field 8 is used by TorznabSettings MinimumSeeders // If you need to add another field here, update TorznabSettings as well and this comment - public virtual NzbDroneValidationResult Validate() { return new NzbDroneValidationResult(Validator.Validate(this)); diff --git a/src/NzbDrone.Core/Indexers/Nyaa/Nyaa.cs b/src/NzbDrone.Core/Indexers/Nyaa/Nyaa.cs index 748a33ef60..d2d63cbf0e 100644 --- a/src/NzbDrone.Core/Indexers/Nyaa/Nyaa.cs +++ b/src/NzbDrone.Core/Indexers/Nyaa/Nyaa.cs @@ -15,7 +15,6 @@ public class Nyaa : HttpIndexerBase public Nyaa(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) { - } public override IIndexerRequestGenerator GetRequestGenerator() diff --git a/src/NzbDrone.Core/Indexers/Nyaa/NyaaSettings.cs b/src/NzbDrone.Core/Indexers/Nyaa/NyaaSettings.cs index 8a650f7e64..c1eae6680e 100644 --- a/src/NzbDrone.Core/Indexers/Nyaa/NyaaSettings.cs +++ b/src/NzbDrone.Core/Indexers/Nyaa/NyaaSettings.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; +using System.Text.RegularExpressions; using FluentValidation; using NzbDrone.Core.Annotations; using NzbDrone.Core.Validation; -using System.Text.RegularExpressions; namespace NzbDrone.Core.Indexers.Nyaa { diff --git a/src/NzbDrone.Core/Indexers/Omgwtfnzbs/Omgwtfnzbs.cs b/src/NzbDrone.Core/Indexers/Omgwtfnzbs/Omgwtfnzbs.cs index d957b5cbd0..e4f1bb56b4 100644 --- a/src/NzbDrone.Core/Indexers/Omgwtfnzbs/Omgwtfnzbs.cs +++ b/src/NzbDrone.Core/Indexers/Omgwtfnzbs/Omgwtfnzbs.cs @@ -14,7 +14,6 @@ public class Omgwtfnzbs : HttpIndexerBase public Omgwtfnzbs(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) { - } public override IIndexerRequestGenerator GetRequestGenerator() diff --git a/src/NzbDrone.Core/Indexers/Omgwtfnzbs/OmgwtfnzbsRssParser.cs b/src/NzbDrone.Core/Indexers/Omgwtfnzbs/OmgwtfnzbsRssParser.cs index a2cb63bd06..b3c345bebf 100644 --- a/src/NzbDrone.Core/Indexers/Omgwtfnzbs/OmgwtfnzbsRssParser.cs +++ b/src/NzbDrone.Core/Indexers/Omgwtfnzbs/OmgwtfnzbsRssParser.cs @@ -19,9 +19,15 @@ protected override bool PreProcess(IndexerResponse indexerResponse) var xdoc = LoadXmlDocument(indexerResponse); var notice = xdoc.Descendants("notice").FirstOrDefault(); - if (notice == null) return true; + if (notice == null) + { + return true; + } - if (!notice.Value.ContainsIgnoreCase("api")) return true; + if (!notice.Value.ContainsIgnoreCase("api")) + { + return true; + } throw new ApiKeyException(notice.Value); } @@ -29,8 +35,9 @@ protected override bool PreProcess(IndexerResponse indexerResponse) protected override string GetInfoUrl(XElement item) { //Todo: Me thinks I need to parse details to get this... - var match = Regex.Match(item.Description(), @"(?:\View NZB\:\<\/b\>\s\.+?)(?:\"")", - RegexOptions.IgnoreCase | RegexOptions.Compiled); + var match = Regex.Match(item.Description(), + @"(?:\View NZB\:\<\/b\>\s\.+?)(?:\"")", + RegexOptions.IgnoreCase | RegexOptions.Compiled); if (match.Success) { diff --git a/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcorn.cs b/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcorn.cs index 2d393e72da..786747f63b 100644 --- a/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcorn.cs +++ b/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcorn.cs @@ -14,8 +14,12 @@ public class PassThePopcorn : HttpIndexerBase public override bool SupportsSearch => true; public override int PageSize => 50; - public PassThePopcorn(IHttpClient httpClient, ICacheManager cacheManager, IIndexerStatusService indexerStatusService, - IConfigService configService, IParsingService parsingService, Logger logger) + public PassThePopcorn(IHttpClient httpClient, + ICacheManager cacheManager, + IIndexerStatusService indexerStatusService, + IConfigService configService, + IParsingService parsingService, + Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) { } diff --git a/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcornApi.cs b/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcornApi.cs index 3c1be48c96..4ff21e0264 100644 --- a/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcornApi.cs +++ b/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcornApi.cs @@ -61,7 +61,5 @@ public class PassThePopcornAuthResponse public string Result { get; set; } public string Popcron { get; set; } public string AntiCsrfToken { get; set; } - } - } diff --git a/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcornParser.cs b/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcornParser.cs index 9caec8fed3..d675d8fd30 100644 --- a/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcornParser.cs +++ b/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcornParser.cs @@ -2,11 +2,11 @@ using System.Collections.Generic; using System.Net; using Newtonsoft.Json; +using NLog; +using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.Indexers.Exceptions; using NzbDrone.Core.Parser.Model; -using NLog; -using NzbDrone.Common.Extensions; namespace NzbDrone.Core.Indexers.PassThePopcorn { @@ -33,6 +33,7 @@ public IList ParseResponse(IndexerResponse indexerResponse) CookiesUpdater(null, null); throw new IndexerException(indexerResponse, "We are being redirected to the PTP login page. Most likely your session expired or was killed. Try testing the indexer in the settings."); } + throw new IndexerException(indexerResponse, $"Unexpected response status {indexerResponse.HttpResponse.StatusCode} code from API request"); } @@ -43,6 +44,7 @@ public IList ParseResponse(IndexerResponse indexerResponse) CookiesUpdater(null, null); throw new IndexerException(indexerResponse, "We are currently on the login page. Most likely your session expired or was killed. Try testing the indexer in the settings."); } + // Remove cookie cache throw new IndexerException(indexerResponse, $"Unexpected response header {indexerResponse.HttpResponse.Headers.ContentType} from API request, expected {HttpAccept.Json.Value}"); } @@ -55,7 +57,6 @@ public IList ParseResponse(IndexerResponse indexerResponse) return torrentInfos; } - foreach (var result in jsonResponse.Movies) { foreach (var torrent in result.Torrents) @@ -66,12 +67,12 @@ public IList ParseResponse(IndexerResponse indexerResponse) if (torrent.GoldenPopcorn) { - flags |= IndexerFlags.PTP_Golden;//title = $"{title} 🍿"; + flags |= IndexerFlags.PTP_Golden; //title = $"{title} 🍿"; } if (torrent.Checked) { - flags |= IndexerFlags.PTP_Approved;//title = $"{title} ✔"; + flags |= IndexerFlags.PTP_Approved; //title = $"{title} ✔"; } if (torrent.FreeleechType == "Freeleech") @@ -100,7 +101,7 @@ public IList ParseResponse(IndexerResponse indexerResponse) Golden = torrent.GoldenPopcorn, Scene = torrent.Scene, Approved = torrent.Checked, - ImdbId = (result.ImdbId.IsNotNullOrWhiteSpace() ? int.Parse(result.ImdbId) : 0), + ImdbId = result.ImdbId.IsNotNullOrWhiteSpace() ? int.Parse(result.ImdbId) : 0, IndexerFlags = flags }); } @@ -116,13 +117,11 @@ public IList ParseResponse(IndexerResponse indexerResponse) "}. Please immediately report this info on https://github.com/Radarr/Radarr/issues/1584."); throw; } - - } } + return torrentInfos; - } public Action, DateTime?> CookiesUpdater { get; set; } diff --git a/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcornRequestGenerator.cs b/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcornRequestGenerator.cs index 8a19112c19..d0e91f1614 100644 --- a/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcornRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/PassThePopcorn/PassThePopcornRequestGenerator.cs @@ -1,15 +1,14 @@ using System; using System.Collections.Generic; -using NzbDrone.Common.Http; -using NzbDrone.Core.IndexerSearch.Definitions; using NLog; using NzbDrone.Common.Extensions; +using NzbDrone.Common.Http; +using NzbDrone.Core.IndexerSearch.Definitions; namespace NzbDrone.Core.Indexers.PassThePopcorn { public class PassThePopcornRequestGenerator : IIndexerRequestGenerator { - public PassThePopcornSettings Settings { get; set; } public IDictionary Cookies { get; set; } diff --git a/src/NzbDrone.Core/Indexers/Rarbg/RarbgParser.cs b/src/NzbDrone.Core/Indexers/Rarbg/RarbgParser.cs index 44f50adf8c..89b82e0808 100644 --- a/src/NzbDrone.Core/Indexers/Rarbg/RarbgParser.cs +++ b/src/NzbDrone.Core/Indexers/Rarbg/RarbgParser.cs @@ -23,6 +23,7 @@ public IList ParseResponse(IndexerResponse indexerResponse) { throw new IndexerException(indexerResponse, "Indexer API call returned an unexpected StatusCode [{0}]", indexerResponse.HttpResponse.StatusCode); } + break; } @@ -53,7 +54,7 @@ public IList ParseResponse(IndexerResponse indexerResponse) torrentInfo.Title = torrent.title; torrentInfo.Size = torrent.size; torrentInfo.DownloadUrl = torrent.download; - torrentInfo.InfoUrl = torrent.info_page + "&app_id=Radarr"; ; + torrentInfo.InfoUrl = torrent.info_page + "&app_id=Radarr"; torrentInfo.PublishDate = torrent.pubdate.ToUniversalTime(); torrentInfo.Seeders = torrent.seeders; torrentInfo.Peers = torrent.leechers + torrent.seeders; @@ -92,6 +93,5 @@ private string GetGuid(RarbgTorrent torrent) return string.Format("rarbg-{0}", torrent.download); } } - } } diff --git a/src/NzbDrone.Core/Indexers/Rarbg/RarbgRequestGenerator.cs b/src/NzbDrone.Core/Indexers/Rarbg/RarbgRequestGenerator.cs index 0314a21157..1881e0479f 100644 --- a/src/NzbDrone.Core/Indexers/Rarbg/RarbgRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/Rarbg/RarbgRequestGenerator.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using NzbDrone.Common.EnvironmentInfo; using System.Linq; +using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.IndexerSearch.Definitions; @@ -96,7 +96,6 @@ private IEnumerable GetMovieRequest(MovieSearchCriteria searchCr requestBuilder.AddQueryParam("search_string", $"{searchCriteria.Movie.Title} {searchCriteria.Movie.Year}"); } - if (!Settings.RankedOnly) { requestBuilder.AddQueryParam("ranked", "0"); diff --git a/src/NzbDrone.Core/Indexers/Rarbg/RarbgTokenProvider.cs b/src/NzbDrone.Core/Indexers/Rarbg/RarbgTokenProvider.cs index 44aa875996..b4d84ff813 100644 --- a/src/NzbDrone.Core/Indexers/Rarbg/RarbgTokenProvider.cs +++ b/src/NzbDrone.Core/Indexers/Rarbg/RarbgTokenProvider.cs @@ -27,7 +27,8 @@ public RarbgTokenProvider(IHttpClient httpClient, ICacheManager cacheManager, Lo public string GetToken(RarbgSettings settings) { - return _tokenCache.Get(settings.BaseUrl, () => + return _tokenCache.Get(settings.BaseUrl, + () => { var requestBuilder = new HttpRequestBuilder(settings.BaseUrl.Trim('/')) .WithRateLimit(3.0) @@ -43,7 +44,8 @@ public string GetToken(RarbgSettings settings) var response = _httpClient.Get(requestBuilder.Build()); return response.Resource["token"].ToString(); - }, TimeSpan.FromMinutes(14.0)); + }, + TimeSpan.FromMinutes(14.0)); } } } diff --git a/src/NzbDrone.Core/Indexers/RssIndexerRequestGenerator.cs b/src/NzbDrone.Core/Indexers/RssIndexerRequestGenerator.cs index 87788e3661..7897af38fb 100644 --- a/src/NzbDrone.Core/Indexers/RssIndexerRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/RssIndexerRequestGenerator.cs @@ -14,7 +14,6 @@ public RssIndexerRequestGenerator(string baseUrl) _baseUrl = baseUrl; } - public virtual IndexerPageableRequestChain GetRecentRequests() { var pageableRequests = new IndexerPageableRequestChain(); diff --git a/src/NzbDrone.Core/Indexers/RssParser.cs b/src/NzbDrone.Core/Indexers/RssParser.cs index d92e249b34..8ae83a624e 100644 --- a/src/NzbDrone.Core/Indexers/RssParser.cs +++ b/src/NzbDrone.Core/Indexers/RssParser.cs @@ -232,6 +232,7 @@ protected virtual long GetSize(XElement item) { return GetEnclosureLength(item); } + if (ParseSizeInDescription && item.Element("description") != null) { return ParseSize(item.Element("description").Value, true); @@ -260,11 +261,11 @@ protected virtual RssEnclosure[] GetEnclosures(XElement item) try { return new RssEnclosure - { - Url = v.Attribute("url").Value, - Type = v.Attribute("type").Value, - Length = (long)v.Attribute("length") - }; + { + Url = v.Attribute("url").Value, + Type = v.Attribute("type").Value, + Length = (long)v.Attribute("length") + }; } catch (Exception e) { @@ -394,6 +395,7 @@ public static long ParseSize(string sizeString, bool defaultToBinaryPrefix) return (long)value; } } + return 0; } diff --git a/src/NzbDrone.Core/Indexers/RssSyncCommand.cs b/src/NzbDrone.Core/Indexers/RssSyncCommand.cs index aad80d1cea..47b9cca67f 100644 --- a/src/NzbDrone.Core/Indexers/RssSyncCommand.cs +++ b/src/NzbDrone.Core/Indexers/RssSyncCommand.cs @@ -4,7 +4,6 @@ namespace NzbDrone.Core.Indexers { public class RssSyncCommand : Command { - public override bool SendUpdatesToClient => true; } } diff --git a/src/NzbDrone.Core/Indexers/RssSyncService.cs b/src/NzbDrone.Core/Indexers/RssSyncService.cs index 27c0256e4b..8f4a07a046 100644 --- a/src/NzbDrone.Core/Indexers/RssSyncService.cs +++ b/src/NzbDrone.Core/Indexers/RssSyncService.cs @@ -39,7 +39,6 @@ public RssSyncService(IIndexerStatusService indexerStatusService, _logger = logger; } - private ProcessedDecisions Sync() { _logger.ProgressInfo("Starting RSS Sync"); diff --git a/src/NzbDrone.Core/Indexers/SeedConfigProvider.cs b/src/NzbDrone.Core/Indexers/SeedConfigProvider.cs index 284a99b54b..e61116feb0 100644 --- a/src/NzbDrone.Core/Indexers/SeedConfigProvider.cs +++ b/src/NzbDrone.Core/Indexers/SeedConfigProvider.cs @@ -21,8 +21,15 @@ public SeedConfigProvider(IIndexerFactory indexerFactory) public TorrentSeedConfiguration GetSeedConfiguration(RemoteMovie remoteMovie) { - if (remoteMovie.Release.DownloadProtocol != DownloadProtocol.Torrent) return null; - if (remoteMovie.Release.IndexerId == 0) return null; + if (remoteMovie.Release.DownloadProtocol != DownloadProtocol.Torrent) + { + return null; + } + + if (remoteMovie.Release.IndexerId == 0) + { + return null; + } try { diff --git a/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotato.cs b/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotato.cs index fb3f9b4e08..a1aebdb26c 100644 --- a/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotato.cs +++ b/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotato.cs @@ -16,7 +16,6 @@ public class TorrentPotato : HttpIndexerBase public TorrentPotato(IHttpClient httpClient, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, indexerStatusService, configService, parsingService, logger) { - } private IndexerDefinition GetDefinition(string name, TorrentPotatoSettings settings) @@ -44,7 +43,5 @@ public override IParseIndexerResponse GetParser() { return new TorrentPotatoParser(); } - - } } diff --git a/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotatoParser.cs b/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotatoParser.cs index 14aeb132c4..847a965d34 100644 --- a/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotatoParser.cs +++ b/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotatoParser.cs @@ -23,6 +23,7 @@ public IList ParseResponse(IndexerResponse indexerResponse) { throw new IndexerException(indexerResponse, "Indexer API call returned an unexpected StatusCode [{0}]", indexerResponse.HttpResponse.StatusCode); } + break; } @@ -34,7 +35,7 @@ public IList ParseResponse(IndexerResponse indexerResponse) torrentInfo.Guid = GetGuid(torrent); torrentInfo.Title = torrent.release_name; - torrentInfo.Size = (long)torrent.size*1000*1000; + torrentInfo.Size = (long)torrent.size * 1000 * 1000; torrentInfo.DownloadUrl = torrent.download_url; torrentInfo.InfoUrl = torrent.details_url; torrentInfo.PublishDate = torrent.publish_date.ToUniversalTime(); @@ -63,6 +64,5 @@ private string GetGuid(Result torrent) return string.Format("potato-{0}", torrent.download_url); } } - } } diff --git a/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotatoRequestGenerator.cs b/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotatoRequestGenerator.cs index d404516b61..1879a8933a 100644 --- a/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotatoRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotatoRequestGenerator.cs @@ -8,12 +8,10 @@ namespace NzbDrone.Core.Indexers.TorrentPotato { public class TorrentPotatoRequestGenerator : IIndexerRequestGenerator { - public TorrentPotatoSettings Settings { get; set; } public TorrentPotatoRequestGenerator() { - } public virtual IndexerPageableRequestChain GetRecentRequests() diff --git a/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotatoResponse.cs b/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotatoResponse.cs index b9d6dc5273..ca89524eb5 100644 --- a/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotatoResponse.cs +++ b/src/NzbDrone.Core/Indexers/TorrentPotato/TorrentPotatoResponse.cs @@ -2,7 +2,6 @@ namespace NzbDrone.Core.Indexers.TorrentPotato { - public class TorrentPotatoResponse { public Result[] results { get; set; } @@ -22,5 +21,4 @@ public class Result public int seeders { get; set; } public DateTime publish_date { get; set; } } - } diff --git a/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssIndexerSettings.cs b/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssIndexerSettings.cs index 4c1dc64f03..5103d5c6db 100644 --- a/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssIndexerSettings.cs +++ b/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssIndexerSettings.cs @@ -17,7 +17,7 @@ public TorrentRssIndexerSettingsValidator() public class TorrentRssIndexerSettings : ITorrentIndexerSettings { - private static readonly TorrentRssIndexerSettingsValidator validator = new TorrentRssIndexerSettingsValidator(); + private static readonly TorrentRssIndexerSettingsValidator Validator = new TorrentRssIndexerSettingsValidator(); public TorrentRssIndexerSettings() { @@ -34,7 +34,7 @@ public TorrentRssIndexerSettings() [FieldDefinition(1, Label = "Cookie", HelpText = "If you site requires a login cookie to access the rss, you'll have to retrieve it via a browser.")] public string Cookie { get; set; } - [FieldDefinition(2, Type = FieldType.Checkbox, Label = "Allow Zero Size", HelpText="Enabling this will allow you to use feeds that don't specify release size, but be careful, size related checks will not be performed.")] + [FieldDefinition(2, Type = FieldType.Checkbox, Label = "Allow Zero Size", HelpText = "Enabling this will allow you to use feeds that don't specify release size, but be careful, size related checks will not be performed.")] public bool AllowZeroSize { get; set; } // [FieldDefinition(3, Type = FieldType.Tag, SelectOptions = typeof(Language), Label = "Multi Languages", HelpText = "What languages are normally in a multi release on this indexer?", Advanced = true)] @@ -51,7 +51,7 @@ public TorrentRssIndexerSettings() public NzbDroneValidationResult Validate() { - return new NzbDroneValidationResult(validator.Validate(this)); + return new NzbDroneValidationResult(Validator.Validate(this)); } } } diff --git a/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssSettingsDetector.cs b/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssSettingsDetector.cs index 6c85e47585..35d2fd5f65 100644 --- a/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssSettingsDetector.cs +++ b/src/NzbDrone.Core/Indexers/TorrentRss/TorrentRssSettingsDetector.cs @@ -1,6 +1,6 @@ using System; -using System.Linq; using System.IO; +using System.Linq; using System.Xml; using System.Xml.Linq; using NLog; @@ -18,12 +18,12 @@ public interface ITorrentRssSettingsDetector public class TorrentRssSettingsDetector : ITorrentRssSettingsDetector { + private const long ValidSizeThreshold = 2 * 1024 * 1024; + protected readonly Logger _logger; private readonly IHttpClient _httpClient; - private const long ValidSizeThreshold = 2 * 1024 * 1024; - public TorrentRssSettingsDetector(IHttpClient httpClient, Logger logger) { _httpClient = httpClient; @@ -174,6 +174,7 @@ private TorrentRssIndexerParserSettings GetGenericTorrentRssParserSettings(Index { _logger.Debug("Feed {0} contains very small releases.", response.Request.Url); } + _logger.Trace("Feed has valid size in description."); return settings; } @@ -235,7 +236,6 @@ private TorrentInfo[] ParseResponse(IParseIndexerResponse parser, IndexerRespons { var releases = parser.ParseResponse(response).Cast().ToArray(); return releases; - } catch (Exception ex) { @@ -270,7 +270,6 @@ private void ValidateReleases(TorrentInfo[] releases, TorrentRssIndexerSettings if (distinct.Length != total.Length) { - throw new UnsupportedFeedException("Feed contains releases with same guid, rejecting malformed rss feed."); } } diff --git a/src/NzbDrone.Core/Indexers/Torznab/Torznab.cs b/src/NzbDrone.Core/Indexers/Torznab/Torznab.cs index 0f1f01a219..a5d33c85b1 100644 --- a/src/NzbDrone.Core/Indexers/Torznab/Torznab.cs +++ b/src/NzbDrone.Core/Indexers/Torznab/Torznab.cs @@ -54,17 +54,17 @@ public Torznab(INewznabCapabilitiesProvider capabilitiesProvider, IHttpClient ht private IndexerDefinition GetDefinition(string name, TorznabSettings settings) { return new IndexerDefinition - { - EnableRss = false, - EnableAutomaticSearch = false, - EnableInteractiveSearch = false, - Name = name, - Implementation = GetType().Name, - Settings = settings, - Protocol = DownloadProtocol.Usenet, - SupportsRss = SupportsRss, - SupportsSearch = SupportsSearch - }; + { + EnableRss = false, + EnableAutomaticSearch = false, + EnableInteractiveSearch = false, + Name = name, + Implementation = GetType().Name, + Settings = settings, + Protocol = DownloadProtocol.Usenet, + SupportsRss = SupportsRss, + SupportsSearch = SupportsSearch + }; } private TorznabSettings GetSettings(string url, string apiPath = null, int[] categories = null) @@ -87,7 +87,11 @@ private TorznabSettings GetSettings(string url, string apiPath = null, int[] cat protected override void Test(List failures) { base.Test(failures); - if (failures.HasErrors()) return; + if (failures.HasErrors()) + { + return; + } + failures.AddIfNotNull(TestCapabilities()); } @@ -98,7 +102,9 @@ protected static List CategoryIds(List categories) foreach (var category in categories) { if (category.Subcategories != null) + { l.AddRange(CategoryIds(category.Subcategories)); + } } return l; @@ -116,7 +122,9 @@ protected virtual ValidationFailure TestCapabilities() { _logger.Warn($"{Definition.Name} does not support the following categories: {string.Join(", ", notSupported)}. You should probably remove them."); if (notSupported.Count() == Settings.Categories.Count()) + { return new ValidationFailure(string.Empty, $"This indexer does not support any of the selected categories! (You may need to turn on advanced settings to see them)"); + } } if (capabilities.SupportedSearchParameters != null && capabilities.SupportedSearchParameters.Contains("q")) diff --git a/src/NzbDrone.Core/Indexers/Torznab/TorznabException.cs b/src/NzbDrone.Core/Indexers/Torznab/TorznabException.cs index 258a12492a..4c8836a885 100644 --- a/src/NzbDrone.Core/Indexers/Torznab/TorznabException.cs +++ b/src/NzbDrone.Core/Indexers/Torznab/TorznabException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Indexers.Torznab { public class TorznabException : NzbDroneException { - public TorznabException(string message, params object[] args) : base(message, args) + public TorznabException(string message, params object[] args) + : base(message, args) { } - public TorznabException(string message) : base(message) + public TorznabException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/Indexers/Torznab/TorznabRssParser.cs b/src/NzbDrone.Core/Indexers/Torznab/TorznabRssParser.cs index 0d9fd16b70..7ea6839d77 100644 --- a/src/NzbDrone.Core/Indexers/Torznab/TorznabRssParser.cs +++ b/src/NzbDrone.Core/Indexers/Torznab/TorznabRssParser.cs @@ -22,12 +22,18 @@ protected override bool PreProcess(IndexerResponse indexerResponse) var xdoc = LoadXmlDocument(indexerResponse); var error = xdoc.Descendants("error").FirstOrDefault(); - if (error == null) return true; + if (error == null) + { + return true; + } var code = Convert.ToInt32(error.Attribute("code").Value); var errorMessage = error.Attribute("description").Value; - if (code >= 100 && code <= 199) throw new ApiKeyException("Invalid API key"); + if (code >= 100 && code <= 199) + { + throw new ApiKeyException("Invalid API key"); + } if (!indexerResponse.Request.Url.FullUri.Contains("apikey=") && errorMessage == "Missing parameter") { @@ -58,7 +64,6 @@ protected override ReleaseInfo ProcessItem(XElement item, ReleaseInfo releaseInf return torrentInfo; } - protected override bool PostProcess(IndexerResponse indexerResponse, List items, List releases) { var enclosureTypes = items.SelectMany(GetEnclosures).Select(v => v.Type).Distinct().ToArray(); @@ -122,7 +127,7 @@ protected override string GetDownloadUrl(XElement item) protected virtual string GetImdbId(XElement item) { var imdbIdString = TryGetTorznabAttribute(item, "imdbid"); - return (!imdbIdString.IsNullOrWhiteSpace() ? imdbIdString.Substring(2) : null); + return !imdbIdString.IsNullOrWhiteSpace() ? imdbIdString.Substring(2) : null; } protected override string GetInfoHash(XElement item) diff --git a/src/NzbDrone.Core/Indexers/XElementExtensions.cs b/src/NzbDrone.Core/Indexers/XElementExtensions.cs index ef2b8b0641..1c4ca66341 100644 --- a/src/NzbDrone.Core/Indexers/XElementExtensions.cs +++ b/src/NzbDrone.Core/Indexers/XElementExtensions.cs @@ -25,10 +25,7 @@ public static XElement StripNameSpace(this XElement root) { var res = new XElement( root.Name.LocalName, - root.HasElements ? - root.Elements().Select(StripNameSpace) : - (object)root.Value - ); + root.HasElements ? root.Elements().Select(StripNameSpace) : (object)root.Value); res.ReplaceAttributes( root.Attributes().Where(attr => (!attr.IsNamespaceDeclaration))); @@ -46,6 +43,7 @@ public static DateTime ParseDate(string dateString) dateString = RemoveTimeZoneRegex.Replace(dateString, ""); result = DateTime.Parse(dateString, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal); } + return result.ToUniversalTime(); } catch (FormatException e) @@ -109,7 +107,6 @@ public static T TryGetValue(this XElement item, string elementName, T default { return (T)Convert.ChangeType(element.Value, typeof(T)); } - catch (InvalidCastException) { return defaultValue; diff --git a/src/NzbDrone.Core/Indexers/XmlCleaner.cs b/src/NzbDrone.Core/Indexers/XmlCleaner.cs index f40d2e2af0..9d1f956543 100644 --- a/src/NzbDrone.Core/Indexers/XmlCleaner.cs +++ b/src/NzbDrone.Core/Indexers/XmlCleaner.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.Indexers { public static class XmlCleaner { - private static readonly Regex ReplaceEntitiesRegex = new Regex("&[a-z]+;", RegexOptions.Compiled | RegexOptions.IgnoreCase); private static readonly Regex ReplaceUnicodeRegex = new Regex(@"[^\x09\x0A\x0D\u0020-\uD7FF\uE000-\uFFFD]", RegexOptions.Compiled | RegexOptions.IgnoreCase); diff --git a/src/NzbDrone.Core/Instrumentation/DatabaseTarget.cs b/src/NzbDrone.Core/Instrumentation/DatabaseTarget.cs index e95095f178..f761f3f7c4 100644 --- a/src/NzbDrone.Core/Instrumentation/DatabaseTarget.cs +++ b/src/NzbDrone.Core/Instrumentation/DatabaseTarget.cs @@ -1,8 +1,8 @@ using System.Data; using System.Data.SQLite; +using NLog; using NLog.Common; using NLog.Config; -using NLog; using NLog.Targets; using NzbDrone.Common.Instrumentation; using NzbDrone.Core.Datastore; @@ -13,11 +13,11 @@ namespace NzbDrone.Core.Instrumentation { public class DatabaseTarget : TargetWithLayout, IHandle { - private readonly IConnectionStringFactory _connectionStringFactory; - - const string INSERT_COMMAND = "INSERT INTO [Logs]([Message],[Time],[Logger],[Exception],[ExceptionType],[Level]) " + + private const string INSERT_COMMAND = "INSERT INTO [Logs]([Message],[Time],[Logger],[Exception],[ExceptionType],[Level]) " + "VALUES(@Message,@Time,@Logger,@Exception,@ExceptionType,@Level)"; + private readonly IConnectionStringFactory _connectionStringFactory; + public DatabaseTarget(IConnectionStringFactory connectionStringFactory) { _connectionStringFactory = connectionStringFactory; @@ -101,7 +101,6 @@ protected override void Write(LogEventInfo logEvent) sqlCommand.ExecuteNonQuery(); } } - } catch (SQLiteException ex) { diff --git a/src/NzbDrone.Core/Instrumentation/Log.cs b/src/NzbDrone.Core/Instrumentation/Log.cs index acd421596c..91e4710b0b 100644 --- a/src/NzbDrone.Core/Instrumentation/Log.cs +++ b/src/NzbDrone.Core/Instrumentation/Log.cs @@ -1,12 +1,10 @@ using System; using NzbDrone.Core.Datastore; - namespace NzbDrone.Core.Instrumentation { public class Log : ModelBase { - public string Message { get; set; } public DateTime Time { get; set; } diff --git a/src/NzbDrone.Core/Instrumentation/LogRepository.cs b/src/NzbDrone.Core/Instrumentation/LogRepository.cs index 0400e3b258..69bcbe474e 100644 --- a/src/NzbDrone.Core/Instrumentation/LogRepository.cs +++ b/src/NzbDrone.Core/Instrumentation/LogRepository.cs @@ -2,7 +2,6 @@ using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; - namespace NzbDrone.Core.Instrumentation { public interface ILogRepository : IBasicRepository diff --git a/src/NzbDrone.Core/Instrumentation/ReconfigureLogging.cs b/src/NzbDrone.Core/Instrumentation/ReconfigureLogging.cs index 27a7a91433..a0c0adead5 100644 --- a/src/NzbDrone.Core/Instrumentation/ReconfigureLogging.cs +++ b/src/NzbDrone.Core/Instrumentation/ReconfigureLogging.cs @@ -26,11 +26,17 @@ public void Reconfigure() LogLevel minimumConsoleLogLevel; if (_configFileProvider.ConsoleLogLevel.IsNotNullOrWhiteSpace()) + { minimumConsoleLogLevel = LogLevel.FromString(_configFileProvider.ConsoleLogLevel); + } else if (minimumLogLevel > LogLevel.Info) + { minimumConsoleLogLevel = minimumLogLevel; + } else + { minimumConsoleLogLevel = LogLevel.Info; + } var rules = LogManager.Configuration.LoggingRules; @@ -64,7 +70,6 @@ private void SetMinimumLogLevel(LoggingRule rule, LogLevel minimumLogLevel) { rule.DisableLoggingForLevel(logLevel); } - else { rule.EnableLoggingForLevel(logLevel); @@ -77,7 +82,7 @@ private void ReconfigureSentry() var sentryTarget = LogManager.Configuration.AllTargets.OfType().FirstOrDefault(); if (sentryTarget != null) { - sentryTarget.SentryEnabled = RuntimeInfo.IsProduction && _configFileProvider.AnalyticsEnabled || RuntimeInfo.IsDevelopment; + sentryTarget.SentryEnabled = (RuntimeInfo.IsProduction && _configFileProvider.AnalyticsEnabled) || RuntimeInfo.IsDevelopment; sentryTarget.FilterEvents = _configFileProvider.FilterSentryEvents; } } diff --git a/src/NzbDrone.Core/Instrumentation/SlowRunningAsyncTargetWrapper.cs b/src/NzbDrone.Core/Instrumentation/SlowRunningAsyncTargetWrapper.cs index 994aedc505..d64178f815 100644 --- a/src/NzbDrone.Core/Instrumentation/SlowRunningAsyncTargetWrapper.cs +++ b/src/NzbDrone.Core/Instrumentation/SlowRunningAsyncTargetWrapper.cs @@ -13,7 +13,6 @@ public class SlowRunningAsyncTargetWrapper : AsyncTargetWrapper public SlowRunningAsyncTargetWrapper(Target wrappedTarget) : base(wrappedTarget) { - } protected override void StopLazyWriterThread() @@ -37,7 +36,6 @@ protected override void Write(AsyncLogEventInfo logEvent) protected override void StartLazyWriterTimer() { // Is executed when the background task has finished processing the queue. (also executed by base.InitializeTarget once) - if (Interlocked.Decrement(ref _state) == 1) { // There might be more work. Restart timer. base.StartLazyWriterTimer(); diff --git a/src/NzbDrone.Core/Jobs/ScheduledTaskRepository.cs b/src/NzbDrone.Core/Jobs/ScheduledTaskRepository.cs index 90a3e6ecf6..4b46b2efcf 100644 --- a/src/NzbDrone.Core/Jobs/ScheduledTaskRepository.cs +++ b/src/NzbDrone.Core/Jobs/ScheduledTaskRepository.cs @@ -3,7 +3,6 @@ using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; - namespace NzbDrone.Core.Jobs { public interface IScheduledTaskRepository : IBasicRepository @@ -14,7 +13,6 @@ public interface IScheduledTaskRepository : IBasicRepository public class ScheduledTaskRepository : BasicRepository, IScheduledTaskRepository { - public ScheduledTaskRepository(IMainDatabase database, IEventAggregator eventAggregator) : base(database, eventAggregator) { @@ -28,11 +26,11 @@ public ScheduledTask GetDefinition(Type type) public void SetLastExecutionTime(int id, DateTime executionTime, DateTime startTime) { var task = new ScheduledTask - { - Id = id, - LastExecution = executionTime, - LastStartTime = startTime - }; + { + Id = id, + LastExecution = executionTime, + LastStartTime = startTime + }; SetFields(task, scheduledTask => scheduledTask.LastExecution, scheduledTask => scheduledTask.LastStartTime); } diff --git a/src/NzbDrone.Core/Jobs/Scheduler.cs b/src/NzbDrone.Core/Jobs/Scheduler.cs index 80ddae00da..dffe4dba7f 100644 --- a/src/NzbDrone.Core/Jobs/Scheduler.cs +++ b/src/NzbDrone.Core/Jobs/Scheduler.cs @@ -2,11 +2,11 @@ using System.Threading; using System.Threading.Tasks; using NLog; +using NzbDrone.Common.TPL; using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; using Timer = System.Timers.Timer; -using NzbDrone.Common.TPL; namespace NzbDrone.Core.Jobs { @@ -42,7 +42,6 @@ private void ExecuteCommands() _commandQueueManager.Push(task.TypeName, task.LastExecution, task.LastStartTime, CommandPriority.Low, CommandTrigger.Scheduled); } } - finally { if (!_cancellationTokenSource.IsCancellationRequested) diff --git a/src/NzbDrone.Core/Jobs/TaskManager.cs b/src/NzbDrone.Core/Jobs/TaskManager.cs index e1981f4de3..35b5b6d7d1 100644 --- a/src/NzbDrone.Core/Jobs/TaskManager.cs +++ b/src/NzbDrone.Core/Jobs/TaskManager.cs @@ -13,10 +13,10 @@ using NzbDrone.Core.MediaFiles.Commands; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.NetImport; -using NzbDrone.Core.Movies.Commands; -using NzbDrone.Core.Update.Commands; using NzbDrone.Core.MetadataSource.PreDB; +using NzbDrone.Core.Movies.Commands; +using NzbDrone.Core.NetImport; +using NzbDrone.Core.Update.Commands; namespace NzbDrone.Core.Jobs { @@ -71,14 +71,15 @@ public void Handle(ApplicationStartedEvent message) var defaultTasks = new[] { - new ScheduledTask{ Interval = 1*60, TypeName = typeof(PreDBSyncCommand).FullName}, - new ScheduledTask{ Interval = 5, TypeName = typeof(MessagingCleanupCommand).FullName}, - new ScheduledTask{ Interval = updateInterval, TypeName = typeof(ApplicationUpdateCommand).FullName}, - // new ScheduledTask{ Interval = 3*60, TypeName = typeof(UpdateSceneMappingCommand).FullName}, - new ScheduledTask{ Interval = 6*60, TypeName = typeof(CheckHealthCommand).FullName}, - new ScheduledTask{ Interval = 24*60, TypeName = typeof(RefreshMovieCommand).FullName}, - new ScheduledTask{ Interval = 24*60, TypeName = typeof(HousekeepingCommand).FullName}, - new ScheduledTask{ Interval = 24*60, TypeName = typeof(CleanUpRecycleBinCommand).FullName}, + new ScheduledTask { Interval = 1 * 60, TypeName = typeof(PreDBSyncCommand).FullName }, + new ScheduledTask { Interval = 5, TypeName = typeof(MessagingCleanupCommand).FullName }, + new ScheduledTask { Interval = updateInterval, TypeName = typeof(ApplicationUpdateCommand).FullName }, + + // new ScheduledTask { Interval = 3 * 60, TypeName = typeof(UpdateSceneMappingCommand).FullName }, + new ScheduledTask { Interval = 6 * 60, TypeName = typeof(CheckHealthCommand).FullName }, + new ScheduledTask { Interval = 24 * 60, TypeName = typeof(RefreshMovieCommand).FullName }, + new ScheduledTask { Interval = 24 * 60, TypeName = typeof(HousekeepingCommand).FullName }, + new ScheduledTask { Interval = 24 * 60, TypeName = typeof(CleanUpRecycleBinCommand).FullName }, new ScheduledTask { diff --git a/src/NzbDrone.Core/Languages/Language.cs b/src/NzbDrone.Core/Languages/Language.cs index 681935a683..1490733372 100644 --- a/src/NzbDrone.Core/Languages/Language.cs +++ b/src/NzbDrone.Core/Languages/Language.cs @@ -32,15 +32,30 @@ public override int GetHashCode() public bool Equals(Language other) { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; + if (ReferenceEquals(null, other)) + { + return false; + } + + if (ReferenceEquals(this, other)) + { + return true; + } + return Id.Equals(other.Id); } public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; + if (ReferenceEquals(null, obj)) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } return Equals(obj as Language); } @@ -55,34 +70,33 @@ public override bool Equals(object obj) return !Equals(left, right); } - public static Language Unknown { get { return new Language(0, "Unknown"); } } - public static Language English { get { return new Language(1, "English"); } } - public static Language French { get { return new Language(2, "French"); } } - public static Language Spanish { get { return new Language(3, "Spanish"); } } - public static Language German { get { return new Language(4, "German"); } } - public static Language Italian { get { return new Language(5, "Italian"); } } - public static Language Danish { get { return new Language(6, "Danish"); } } - public static Language Dutch { get { return new Language(7, "Dutch"); } } - public static Language Japanese { get { return new Language(8, "Japanese"); } } - public static Language Icelandic { get { return new Language(9, "Icelandic"); } } - public static Language Chinese { get { return new Language(10, "Chinese"); } } - public static Language Russian { get { return new Language(11, "Russian"); } } - public static Language Polish { get { return new Language(12, "Polish"); } } - public static Language Vietnamese { get { return new Language(13, "Vietnamese"); } } - public static Language Swedish { get { return new Language(14, "Swedish"); } } - public static Language Norwegian { get { return new Language(15, "Norwegian"); } } - public static Language Finnish { get { return new Language(16, "Finnish"); } } - public static Language Turkish { get { return new Language(17, "Turkish"); } } - public static Language Portuguese { get { return new Language(18, "Portuguese"); } } - public static Language Flemish { get { return new Language(19, "Flemish"); } } - public static Language Greek { get { return new Language(20, "Greek"); } } - public static Language Korean { get { return new Language(21, "Korean"); } } - public static Language Hungarian { get { return new Language(22, "Hungarian"); } } - public static Language Hebrew { get { return new Language(23, "Hebrew"); } } - public static Language Lithuanian { get { return new Language(24, "Lithuanian"); } } - public static Language Czech { get { return new Language(25, "Czech"); } } - public static Language Any { get { return new Language(-1, "Any"); } } - + public static Language Unknown => new Language(0, "Unknown"); + public static Language English => new Language(1, "English"); + public static Language French => new Language(2, "French"); + public static Language Spanish => new Language(3, "Spanish"); + public static Language German => new Language(4, "German"); + public static Language Italian => new Language(5, "Italian"); + public static Language Danish => new Language(6, "Danish"); + public static Language Dutch => new Language(7, "Dutch"); + public static Language Japanese => new Language(8, "Japanese"); + public static Language Icelandic => new Language(9, "Icelandic"); + public static Language Chinese => new Language(10, "Chinese"); + public static Language Russian => new Language(11, "Russian"); + public static Language Polish => new Language(12, "Polish"); + public static Language Vietnamese => new Language(13, "Vietnamese"); + public static Language Swedish => new Language(14, "Swedish"); + public static Language Norwegian => new Language(15, "Norwegian"); + public static Language Finnish => new Language(16, "Finnish"); + public static Language Turkish => new Language(17, "Turkish"); + public static Language Portuguese => new Language(18, "Portuguese"); + public static Language Flemish => new Language(19, "Flemish"); + public static Language Greek => new Language(20, "Greek"); + public static Language Korean => new Language(21, "Korean"); + public static Language Hungarian => new Language(22, "Hungarian"); + public static Language Hebrew => new Language(23, "Hebrew"); + public static Language Lithuanian => new Language(24, "Lithuanian"); + public static Language Czech => new Language(25, "Czech"); + public static Language Any => new Language(-1, "Any"); public static List All { @@ -123,7 +137,10 @@ public static List All public static Language FindById(int id) { - if (id == 0) return Unknown; + if (id == 0) + { + return Unknown; + } Language language = All.FirstOrDefault(v => v.Id == id); diff --git a/src/NzbDrone.Core/Lifecycle/ApplicationStartedEvent.cs b/src/NzbDrone.Core/Lifecycle/ApplicationStartedEvent.cs index e3b460fb84..8e0d45e155 100644 --- a/src/NzbDrone.Core/Lifecycle/ApplicationStartedEvent.cs +++ b/src/NzbDrone.Core/Lifecycle/ApplicationStartedEvent.cs @@ -4,6 +4,5 @@ namespace NzbDrone.Core.Lifecycle { public class ApplicationStartedEvent : IEvent { - } } diff --git a/src/NzbDrone.Core/Lifecycle/LifecycleService.cs b/src/NzbDrone.Core/Lifecycle/LifecycleService.cs index e4d727b0d9..9ed36a42e9 100644 --- a/src/NzbDrone.Core/Lifecycle/LifecycleService.cs +++ b/src/NzbDrone.Core/Lifecycle/LifecycleService.cs @@ -21,7 +21,6 @@ public class LifecycleService : ILifecycleService, IExecute, IE private readonly IServiceProvider _serviceProvider; private readonly Logger _logger; - public LifecycleService(IEventAggregator eventAggregator, IRuntimeInfo runtimeInfo, IServiceProvider serviceProvider, diff --git a/src/NzbDrone.Core/MediaCover/CoverAlreadyExistsSpecification.cs b/src/NzbDrone.Core/MediaCover/CoverAlreadyExistsSpecification.cs index a8493a1788..d6c303d88f 100644 --- a/src/NzbDrone.Core/MediaCover/CoverAlreadyExistsSpecification.cs +++ b/src/NzbDrone.Core/MediaCover/CoverAlreadyExistsSpecification.cs @@ -1,6 +1,6 @@ -using NzbDrone.Common.Disk; +using NLog; +using NzbDrone.Common.Disk; using NzbDrone.Common.Http; -using NLog; namespace NzbDrone.Core.MediaCover { diff --git a/src/NzbDrone.Core/MediaCover/EnsureMediaCoversCommand.cs b/src/NzbDrone.Core/MediaCover/EnsureMediaCoversCommand.cs index 2dac416683..fa3d6cc8a2 100644 --- a/src/NzbDrone.Core/MediaCover/EnsureMediaCoversCommand.cs +++ b/src/NzbDrone.Core/MediaCover/EnsureMediaCoversCommand.cs @@ -8,7 +8,6 @@ public class EnsureMediaCoversCommand : Command public EnsureMediaCoversCommand() { - } public EnsureMediaCoversCommand(int movieId) diff --git a/src/NzbDrone.Core/MediaCover/ImageResizer.cs b/src/NzbDrone.Core/MediaCover/ImageResizer.cs index 3e8d36bce3..2bb46f33f1 100644 --- a/src/NzbDrone.Core/MediaCover/ImageResizer.cs +++ b/src/NzbDrone.Core/MediaCover/ImageResizer.cs @@ -41,7 +41,10 @@ public ImageResizer(IDiskProvider diskProvider, IPlatformInfo platformInfo) public void Resize(string source, string destination, int height) { - if (!_enabled) return; + if (!_enabled) + { + return; + } try { @@ -57,6 +60,7 @@ public void Resize(string source, string destination, int height) { _diskProvider.DeleteFile(destination); } + throw; } } diff --git a/src/NzbDrone.Core/MediaCover/MediaCover.cs b/src/NzbDrone.Core/MediaCover/MediaCover.cs index 22b143b365..459fa6373d 100644 --- a/src/NzbDrone.Core/MediaCover/MediaCover.cs +++ b/src/NzbDrone.Core/MediaCover/MediaCover.cs @@ -2,7 +2,6 @@ namespace NzbDrone.Core.MediaCover { - public enum MediaCoverTypes { Unknown = 0, diff --git a/src/NzbDrone.Core/MediaCover/MediaCoverService.cs b/src/NzbDrone.Core/MediaCover/MediaCoverService.cs index 9a33141b68..b3e215696a 100644 --- a/src/NzbDrone.Core/MediaCover/MediaCoverService.cs +++ b/src/NzbDrone.Core/MediaCover/MediaCoverService.cs @@ -24,6 +24,7 @@ public interface IMapCoversToLocal public class MediaCoverService : IHandleAsync, + //IHandleAsync, IHandleAsync, IExecute, @@ -45,7 +46,6 @@ public class MediaCoverService : // So limit the number of concurrent resizing tasks private static SemaphoreSlim _semaphore = new SemaphoreSlim((int)Math.Ceiling(Environment.ProcessorCount / 2.0)); - public MediaCoverService(IImageResizer resizer, IHttpClient httpClient, IDiskProvider diskProvider, @@ -224,6 +224,7 @@ public void HandleAsync(MovieUpdatedEvent message) //EnsureCovers(message.Movie); _logger.Info("Testing: {0}, {1}", _commandQueue, message.Movie.Id); _commandQueue.Push(new EnsureMediaCoversCommand(message.Movie.Id)); + //_eventAggregator.PublishEvent(new MediaCoversUpdatedEvent(message.Movie)); } diff --git a/src/NzbDrone.Core/MediaFiles/Commands/RenameMovieCommand.cs b/src/NzbDrone.Core/MediaFiles/Commands/RenameMovieCommand.cs index cef92d62b0..ca1f3a49f9 100644 --- a/src/NzbDrone.Core/MediaFiles/Commands/RenameMovieCommand.cs +++ b/src/NzbDrone.Core/MediaFiles/Commands/RenameMovieCommand.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.Messaging.Commands; using System.Collections.Generic; +using NzbDrone.Core.Messaging.Commands; namespace NzbDrone.Core.MediaFiles.Commands { diff --git a/src/NzbDrone.Core/MediaFiles/Commands/RenameMovieFolderCommand.cs b/src/NzbDrone.Core/MediaFiles/Commands/RenameMovieFolderCommand.cs index 1a15844039..b4a5403c3f 100644 --- a/src/NzbDrone.Core/MediaFiles/Commands/RenameMovieFolderCommand.cs +++ b/src/NzbDrone.Core/MediaFiles/Commands/RenameMovieFolderCommand.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.Messaging.Commands; -using System.Collections.Generic; +using System.Collections.Generic; +using NzbDrone.Core.Messaging.Commands; namespace NzbDrone.Core.MediaFiles.Commands { @@ -11,7 +11,7 @@ public class RenameMovieFolderCommand : Command public RenameMovieFolderCommand(List ids) { - MovieIds = ids; + MovieIds = ids; } } } diff --git a/src/NzbDrone.Core/MediaFiles/DiskScanService.cs b/src/NzbDrone.Core/MediaFiles/DiskScanService.cs index 2bf772c47b..c3f336043b 100644 --- a/src/NzbDrone.Core/MediaFiles/DiskScanService.cs +++ b/src/NzbDrone.Core/MediaFiles/DiskScanService.cs @@ -10,8 +10,8 @@ using NzbDrone.Common.Instrumentation.Extensions; using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles.Commands; -using NzbDrone.Core.MediaFiles.MovieImport; using NzbDrone.Core.MediaFiles.Events; +using NzbDrone.Core.MediaFiles.MovieImport; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Movies; @@ -190,10 +190,8 @@ private void SetPermissions(string path) var permissions = _configService.FolderChmod; _diskProvider.SetPermissions(path, permissions, _configService.ChownUser, _configService.ChownGroup); } - catch (Exception ex) { - _logger.Warn(ex, "Unable to apply permissions to: " + path); _logger.Debug(ex, ex.Message); } @@ -221,7 +219,6 @@ public void Execute(RescanMovieCommand message) var movie = _movieService.GetMovie(message.MovieId.Value); Scan(movie); } - else { var allMovies = _movieService.GetAllMovies(); diff --git a/src/NzbDrone.Core/MediaFiles/DownloadedMovieCommandService.cs b/src/NzbDrone.Core/MediaFiles/DownloadedMovieCommandService.cs index 277f699545..6d3bc19893 100644 --- a/src/NzbDrone.Core/MediaFiles/DownloadedMovieCommandService.cs +++ b/src/NzbDrone.Core/MediaFiles/DownloadedMovieCommandService.cs @@ -1,3 +1,6 @@ +using System; +using System.Collections.Generic; +using System.Linq; using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; @@ -6,9 +9,6 @@ using NzbDrone.Core.MediaFiles.Commands; using NzbDrone.Core.MediaFiles.MovieImport; using NzbDrone.Core.Messaging.Commands; -using System; -using System.Collections.Generic; -using System.Linq; namespace NzbDrone.Core.MediaFiles { diff --git a/src/NzbDrone.Core/MediaFiles/DownloadedMovieImportService.cs b/src/NzbDrone.Core/MediaFiles/DownloadedMovieImportService.cs index 7ae4e02843..dcd44ca5b4 100644 --- a/src/NzbDrone.Core/MediaFiles/DownloadedMovieImportService.cs +++ b/src/NzbDrone.Core/MediaFiles/DownloadedMovieImportService.cs @@ -7,11 +7,11 @@ using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Core.Configuration; using NzbDrone.Core.DecisionEngine; -using NzbDrone.Core.MediaFiles.MovieImport; -using NzbDrone.Core.Parser; -using NzbDrone.Core.Movies; using NzbDrone.Core.Download; using NzbDrone.Core.History; +using NzbDrone.Core.MediaFiles.MovieImport; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.MediaFiles @@ -172,7 +172,7 @@ private List ProcessFolder(DirectoryInfo directoryInfo, ImportMode var cleanedUpName = GetCleanedUpFolderName(directoryInfo.Name); var historyItems = _historyService.FindByDownloadId(downloadClientItem?.DownloadId ?? ""); var firstHistoryItem = historyItems?.OrderByDescending(h => h.Date).FirstOrDefault(); - var folderInfo = _parsingService.ParseMovieInfo(cleanedUpName, new List{firstHistoryItem}); + var folderInfo = _parsingService.ParseMovieInfo(cleanedUpName, new List { firstHistoryItem }); if (folderInfo != null) { diff --git a/src/NzbDrone.Core/MediaFiles/Events/MovieDownloadedEvent.cs b/src/NzbDrone.Core/MediaFiles/Events/MovieDownloadedEvent.cs index d5d98b24bf..d8ec20ddd0 100644 --- a/src/NzbDrone.Core/MediaFiles/Events/MovieDownloadedEvent.cs +++ b/src/NzbDrone.Core/MediaFiles/Events/MovieDownloadedEvent.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using NzbDrone.Common.Messaging; -using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Download; +using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.MediaFiles.Events { diff --git a/src/NzbDrone.Core/MediaFiles/MediaFileAttributeService.cs b/src/NzbDrone.Core/MediaFiles/MediaFileAttributeService.cs index 3e0839cb45..bf60d9be68 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaFileAttributeService.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaFileAttributeService.cs @@ -52,7 +52,6 @@ public void SetFilePermissions(string path) } } } - else { SetMonoPermissions(path, _configService.FileChmod); @@ -87,10 +86,8 @@ private void SetMonoPermissions(string path, string permissions) { _diskProvider.SetPermissions(path, permissions, _configService.ChownUser, _configService.ChownGroup); } - catch (Exception ex) { - _logger.Warn(ex, "Unable to apply permissions to: " + path); } } diff --git a/src/NzbDrone.Core/MediaFiles/MediaFileExtensions.cs b/src/NzbDrone.Core/MediaFiles/MediaFileExtensions.cs index b85ffaf1be..e63ed07091 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaFileExtensions.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaFileExtensions.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using NzbDrone.Core.Qualities; - namespace NzbDrone.Core.MediaFiles { public static class MediaFileExtensions @@ -63,12 +62,12 @@ static MediaFileExtensions() //HD { ".mkv", Quality.WEBDL720p }, - { ".mk3d", Quality.WEBDL720p}, + { ".mk3d", Quality.WEBDL720p }, { ".ts", Quality.SDTV }, { ".wtv", Quality.SDTV }, //Bluray - { ".m2ts", Quality.Bluray720p} + { ".m2ts", Quality.Bluray720p } }; } @@ -83,6 +82,5 @@ public static Quality GetQualityForExtension(string extension) return Quality.Unknown; } - } } diff --git a/src/NzbDrone.Core/MediaFiles/MediaFileRepository.cs b/src/NzbDrone.Core/MediaFiles/MediaFileRepository.cs index 6ef40f4090..4864a9ad36 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaFileRepository.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaFileRepository.cs @@ -2,7 +2,6 @@ using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; - namespace NzbDrone.Core.MediaFiles { public interface IMediaFileRepository : IBasicRepository @@ -11,7 +10,6 @@ public interface IMediaFileRepository : IBasicRepository List GetFilesWithoutMediaInfo(); } - public class MediaFileRepository : BasicRepository, IMediaFileRepository { public MediaFileRepository(IMainDatabase database, IEventAggregator eventAggregator) diff --git a/src/NzbDrone.Core/MediaFiles/MediaFileService.cs b/src/NzbDrone.Core/MediaFiles/MediaFileService.cs index 75a6c6d59c..0b7f51faf4 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaFileService.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaFileService.cs @@ -2,11 +2,11 @@ using System.IO; using System.Linq; using NLog; +using NzbDrone.Common; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Movies; using NzbDrone.Core.Movies.Events; -using NzbDrone.Common; namespace NzbDrone.Core.MediaFiles { @@ -30,7 +30,8 @@ public class MediaFileService : IMediaFileService, IHandleAsync FilterExistingFiles(List files, Movie movie) { var movieFiles = GetFilesByMovie(movie.Id).Select(f => Path.Combine(movie.Path, f.RelativePath)).ToList(); - if (!movieFiles.Any()) return files; + if (!movieFiles.Any()) + { + return files; + } return files.Except(movieFiles, PathEqualityComparer.Instance).ToList(); } @@ -102,10 +107,8 @@ public MovieFile GetMovie(int id) public void HandleAsync(MovieDeletedEvent message) { - var files = GetFilesByMovie(message.Movie.Id); _mediaFileRepository.DeleteMany(files); - } } } diff --git a/src/NzbDrone.Core/MediaFiles/MediaFileTableCleanupService.cs b/src/NzbDrone.Core/MediaFiles/MediaFileTableCleanupService.cs index 817cbaec70..97cdf650d6 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaFileTableCleanupService.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaFileTableCleanupService.cs @@ -33,7 +33,7 @@ public void Clean(Movie movie, List filesOnDisk) var filesOnDiskKeys = new HashSet(filesOnDisk, PathEqualityComparer.Instance); - foreach(var movieFile in movieFiles) + foreach (var movieFile in movieFiles) { var movieFilePath = Path.Combine(movie.Path, movieFile.RelativePath); @@ -55,7 +55,6 @@ public void Clean(Movie movie, List filesOnDisk) // continue; //} } - catch (Exception ex) { var errorMessage = string.Format("Unable to cleanup MovieFile in DB: {0}", movieFile.Id); diff --git a/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoFormatter.cs b/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoFormatter.cs index 9167a27ed7..5fd835753f 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoFormatter.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoFormatter.cs @@ -12,6 +12,9 @@ namespace NzbDrone.Core.MediaFiles.MediaInfo { public static class MediaInfoFormatter { + private const string ValidHdrColourPrimaries = "BT.2020"; + private static readonly string[] ValidHdrTransferFunctions = { "PQ", "HLG" }; + private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(MediaInfoFormatter)); public static decimal FormatAudioChannels(MediaInfoModel mediaInfo) @@ -42,7 +45,7 @@ public static string FormatAudioCodec(MediaInfoModel mediaInfo, string sceneName var audioCodecID = mediaInfo.AudioCodecID ?? string.Empty; var audioProfile = mediaInfo.AudioProfile ?? string.Empty; var audioCodecLibrary = mediaInfo.AudioCodecLibrary ?? string.Empty; - var splitAdditionalFeatures = (mediaInfo.AudioAdditionalFeatures ?? string.Empty).Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); + var splitAdditionalFeatures = (mediaInfo.AudioAdditionalFeatures ?? string.Empty).Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (audioFormat.Empty()) { @@ -82,6 +85,7 @@ public static string FormatAudioCodec(MediaInfoModel mediaInfo, string sceneName { return "DTS-X"; } + return "DTS-HD MA"; } @@ -457,10 +461,12 @@ public static string FormatVideoCodecLegacy(MediaInfoModel mediaInfo, string sce if (audioChannelPositions.Contains("/")) { - return Regex.Replace(audioChannelPositions, @"^\d+\sobjects", "", + return Regex.Replace(audioChannelPositions, + @"^\d+\sobjects", + "", RegexOptions.Compiled | RegexOptions.IgnoreCase) .Replace("Object Based / ", "") - .Split(new string[] {" / "}, StringSplitOptions.RemoveEmptyEntries) + .Split(new string[] { " / " }, StringSplitOptions.RemoveEmptyEntries) .FirstOrDefault() ?.Split('/') .Sum(s => decimal.Parse(s, CultureInfo.InvariantCulture)); @@ -527,9 +533,6 @@ private static string GetSceneNameMatch(string sceneName, params string[] tokens return tokens.Last(); } - private static readonly string[] ValidHdrTransferFunctions = {"PQ", "HLG"}; - private const string ValidHdrColourPrimaries = "BT.2020"; - public static string FormatVideoDynamicRange(MediaInfoModel mediaInfo) { // assume SDR by default diff --git a/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoLib.cs b/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoLib.cs index 17474c89b9..0f25334b8b 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoLib.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoLib.cs @@ -55,8 +55,7 @@ public enum InfoFileOptions FileOption_NoRecursive = 0x01, FileOption_CloseAll = 0x02, FileOption_Max = 0x04 - }; - + } public class MediaInfo : IDisposable { @@ -87,6 +86,7 @@ public void Dispose() { MediaInfo_Delete(_handle); } + GC.SuppressFinalize(this); } @@ -132,7 +132,7 @@ private void InitializeEncoding() return; } - throw new NotSupportedException("Unsupported MediaInfoLib encoding, version check responses (may be gibberish, show it to the Sonarr devs): " + responses.Join(", ") ); + throw new NotSupportedException("Unsupported MediaInfoLib encoding, version check responses (may be gibberish, show it to the Sonarr devs): " + responses.Join(", ")); } } @@ -233,7 +233,8 @@ public int Open(Stream stream) seekStart = seekPos; MediaInfo_Open_Buffer_Init(_handle, stream.Length, seekPos); } - } while (bufferRead > 0); + } + while (bufferRead > 0); MediaInfo_Open_Buffer_Finalize(_handle); @@ -337,7 +338,7 @@ public int Count_Get(StreamKind streamKind, int streamNumber = -1) [DllImport("mediainfo")] private static extern IntPtr MediaInfo_State_Get(IntPtr handle); [DllImport("mediainfo")] - private static extern IntPtr MediaInfo_Count_Get(IntPtr handle, IntPtr StreamKind, IntPtr streamNumber); + private static extern IntPtr MediaInfo_Count_Get(IntPtr handle, IntPtr streamKind, IntPtr streamNumber); [DllImport("mediainfo")] private static extern IntPtr MediaInfoA_New(); @@ -364,6 +365,6 @@ public int Count_Get(StreamKind streamKind, int streamNumber = -1) [DllImport("mediainfo")] private static extern IntPtr MediaInfoA_State_Get(IntPtr handle); [DllImport("mediainfo")] - private static extern IntPtr MediaInfoA_Count_Get(IntPtr handle, IntPtr StreamKind, IntPtr streamNumber); + private static extern IntPtr MediaInfoA_Count_Get(IntPtr handle, IntPtr streamKind, IntPtr streamNumber); } } diff --git a/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoModel.cs b/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoModel.cs index 9923671ef9..1d028e54a0 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoModel.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaInfo/MediaInfoModel.cs @@ -6,6 +6,7 @@ namespace NzbDrone.Core.MediaFiles.MediaInfo public class MediaInfoModel : IEmbeddedDocument { public string ContainerFormat { get; set; } + // Deprecated according to MediaInfo public string VideoCodec { get; set; } public string VideoFormat { get; set; } diff --git a/src/NzbDrone.Core/MediaFiles/MediaInfo/UpdateMediaInfoService.cs b/src/NzbDrone.Core/MediaFiles/MediaInfo/UpdateMediaInfoService.cs index 13c6d7afee..50036e259d 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaInfo/UpdateMediaInfoService.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaInfo/UpdateMediaInfoService.cs @@ -1,11 +1,11 @@ using System.IO; +using System.Linq; using NLog; using NzbDrone.Common.Disk; +using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Movies; -using System.Linq; -using NzbDrone.Core.Configuration; namespace NzbDrone.Core.MediaFiles.MediaInfo { diff --git a/src/NzbDrone.Core/MediaFiles/MediaInfo/VideoFileInfoReader.cs b/src/NzbDrone.Core/MediaFiles/MediaInfo/VideoFileInfoReader.cs index 9841d65ce7..422c4bc1ee 100644 --- a/src/NzbDrone.Core/MediaFiles/MediaInfo/VideoFileInfoReader.cs +++ b/src/NzbDrone.Core/MediaFiles/MediaInfo/VideoFileInfoReader.cs @@ -26,7 +26,6 @@ public VideoFileInfoReader(IDiskProvider diskProvider, Logger logger) _logger = logger; } - public MediaInfoModel GetMediaInfo(string filename) { if (!_diskProvider.FileExists(filename)) @@ -37,7 +36,6 @@ public MediaInfoModel GetMediaInfo(string filename) MediaInfo mediaInfo = null; // TODO: Cache media info by path, mtime and length so we don't need to read files multiple times - try { mediaInfo = new MediaInfo(); @@ -105,6 +103,7 @@ public MediaInfoModel GetMediaInfo(string filename) { int.TryParse(mediaInfo.Get(StreamKind.Video, 0, "BitRate_Nominal"), out videoBitRate); } + decimal.TryParse(mediaInfo.Get(StreamKind.Video, 0, "FrameRate"), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out videoFrameRate); int.TryParse(mediaInfo.Get(StreamKind.Video, 0, "BitDepth"), out videoBitDepth); int.TryParse(mediaInfo.Get(StreamKind.Video, 0, "MultiView_Count"), out videoMultiViewCount); @@ -119,7 +118,6 @@ public MediaInfoModel GetMediaInfo(string filename) int.TryParse(aBitRate, out audioBitRate); int.TryParse(mediaInfo.Get(StreamKind.Audio, 0, "StreamCount"), out streamCount); - string audioChannelsStr = mediaInfo.Get(StreamKind.Audio, 0, "Channel(s)").Split(new string[] { " /" }, StringSplitOptions.None)[0].Trim(); var audioChannelPositions = mediaInfo.Get(StreamKind.Audio, 0, "ChannelPositions/String2"); diff --git a/src/NzbDrone.Core/MediaFiles/MovieFile.cs b/src/NzbDrone.Core/MediaFiles/MovieFile.cs index 6e74a16e3a..24efa96db2 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieFile.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieFile.cs @@ -1,12 +1,12 @@ using System; using System.Collections.Generic; using Marr.Data; -using NzbDrone.Core.Datastore; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; -using NzbDrone.Core.MediaFiles.MediaInfo; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Datastore; using NzbDrone.Core.Languages; +using NzbDrone.Core.MediaFiles.MediaInfo; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.MediaFiles { @@ -43,6 +43,6 @@ public string GetSceneOrFileName() } return string.Empty; -} + } } } diff --git a/src/NzbDrone.Core/MediaFiles/MovieFileMovingService.cs b/src/NzbDrone.Core/MediaFiles/MovieFileMovingService.cs index 2751e02e75..48c1ac056e 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieFileMovingService.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieFileMovingService.cs @@ -8,9 +8,9 @@ using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Movies; using NzbDrone.Core.Organizer; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.MediaFiles { @@ -101,7 +101,7 @@ public MovieFile CopyMovieFile(MovieFile movieFile, LocalMovie localMovie) private MovieFile TransferFile(MovieFile movieFile, Movie movie, string destinationFilePath, TransferMode mode) { Ensure.That(movieFile, () => movieFile).IsNotNull(); - Ensure.That(movie,() => movie).IsNotNull(); + Ensure.That(movie, () => movie).IsNotNull(); Ensure.That(destinationFilePath, () => destinationFilePath).IsValidPath(); var movieFilePath = movieFile.Path ?? Path.Combine(movie.Path, movieFile.RelativePath); @@ -132,7 +132,6 @@ private MovieFile TransferFile(MovieFile movieFile, Movie movie, string destinat { _mediaFileAttributeService.SetFolderLastWriteTime(movie.Path, movieFile.DateAdded); } - catch (Exception ex) { _logger.Warn(ex, "Unable to set last write time"); @@ -140,7 +139,7 @@ private MovieFile TransferFile(MovieFile movieFile, Movie movie, string destinat _mediaFileAttributeService.SetFilePermissions(destinationFilePath); - if(oldMoviePath != newMoviePath && _diskProvider.FolderExists(oldMoviePath)) + if (oldMoviePath != newMoviePath && _diskProvider.FolderExists(oldMoviePath)) { //Let's move the old files before deleting the old folder. We could just do move folder, but the main file (movie file) is already moved, so eh. var files = _diskProvider.GetFiles(oldMoviePath, SearchOption.AllDirectories); @@ -182,7 +181,8 @@ private void EnsureMovieFolder(MovieFile movieFile, LocalMovie localMovie, strin private void EnsureMovieFolder(MovieFile movieFile, Movie movie, string filePath) { var movieFolder = Path.GetDirectoryName(filePath); - //movie.Path = movieFolder; + + //movie.Path = movieFolder; var rootFolder = new OsPath(movieFolder).Directory.FullPath; var fileName = Path.GetFileName(filePath); diff --git a/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/AggregationFailedException.cs b/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/AggregationFailedException.cs index 8269cf9e24..6bf59aefd1 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/AggregationFailedException.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/AggregationFailedException.cs @@ -5,19 +5,23 @@ namespace NzbDrone.Core.MediaFiles.MovieImport.Aggregation { public class AugmentingFailedException : NzbDroneException { - public AugmentingFailedException(string message, params object[] args) : base(message, args) + public AugmentingFailedException(string message, params object[] args) + : base(message, args) { } - public AugmentingFailedException(string message) : base(message) + public AugmentingFailedException(string message) + : base(message) { } - public AugmentingFailedException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public AugmentingFailedException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } - public AugmentingFailedException(string message, Exception innerException) : base(message, innerException) + public AugmentingFailedException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/AggregationService.cs b/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/AggregationService.cs index 715f522bc0..6c0ba11147 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/AggregationService.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/AggregationService.cs @@ -4,8 +4,8 @@ using NLog; using NzbDrone.Common.Disk; using NzbDrone.Core.Configuration; -using NzbDrone.Core.MediaFiles.MovieImport.Aggregation.Aggregators; using NzbDrone.Core.MediaFiles.MediaInfo; +using NzbDrone.Core.MediaFiles.MovieImport.Aggregation.Aggregators; using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.MediaFiles.MovieImport.Aggregation diff --git a/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/Aggregators/AggregateLanguage.cs b/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/Aggregators/AggregateLanguage.cs index 48601cb1cd..cdac2a0df4 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/Aggregators/AggregateLanguage.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/Aggregators/AggregateLanguage.cs @@ -20,7 +20,6 @@ public LocalMovie Aggregate(LocalMovie localMovie, bool otherFiles) // Get languages in preferred order, download client item, folder and finally file. // Non-English languages will be preferred later, in the event there is a conflict // between parsed languages the more preferred item will be used. - var languages = new List(); languages.AddRange(GetLanguage(localMovie.DownloadClientMovieInfo)); @@ -41,7 +40,6 @@ private List GetLanguage(ParsedMovieInfo parsedMovieInfo) if (parsedMovieInfo == null) { // English is the default language when otherwise unknown - return new List { Language.English }; } diff --git a/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/Aggregators/AggregateQuality.cs b/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/Aggregators/AggregateQuality.cs index 1d939fa6db..3962c579cf 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/Aggregators/AggregateQuality.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/Aggregators/AggregateQuality.cs @@ -38,21 +38,21 @@ public LocalMovie Aggregate(LocalMovie localMovie, bool otherFiles) foreach (var augmentedQuality in augmentedQualities) { if (augmentedQuality.Source > source || - augmentedQuality.SourceConfidence > sourceConfidence && augmentedQuality.Source != Source.UNKNOWN) + (augmentedQuality.SourceConfidence > sourceConfidence && augmentedQuality.Source != Source.UNKNOWN)) { source = augmentedQuality.Source; sourceConfidence = augmentedQuality.SourceConfidence; } if (augmentedQuality.Resolution > resolution || - augmentedQuality.ResolutionConfidence > resolutionConfidence && augmentedQuality.Resolution > 0) + (augmentedQuality.ResolutionConfidence > resolutionConfidence && augmentedQuality.Resolution > 0)) { resolution = augmentedQuality.Resolution; resolutionConfidence = augmentedQuality.ResolutionConfidence; } if (augmentedQuality.Modifier > modifier || - augmentedQuality.ModifierConfidence > modifierConfidence && augmentedQuality.Modifier != Modifier.NONE) + (augmentedQuality.ModifierConfidence > modifierConfidence && augmentedQuality.Modifier != Modifier.NONE)) { modifier = augmentedQuality.Modifier; modifierConfidence = augmentedQuality.ModifierConfidence; diff --git a/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/Aggregators/Augmenters/Quality/AugmentQualityResult.cs b/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/Aggregators/Augmenters/Quality/AugmentQualityResult.cs index d7876c33f8..b1ed51ab84 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/Aggregators/Augmenters/Quality/AugmentQualityResult.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieImport/Aggregation/Aggregators/Augmenters/Quality/AugmentQualityResult.cs @@ -1,6 +1,6 @@ +using System.Collections.Generic; using NzbDrone.Core.CustomFormats; using NzbDrone.Core.Qualities; -using System.Collections.Generic; namespace NzbDrone.Core.MediaFiles.MovieImport.Aggregation.Aggregators.Augmenters.Quality { diff --git a/src/NzbDrone.Core/MediaFiles/MovieImport/ImportApprovedMovie.cs b/src/NzbDrone.Core/MediaFiles/MovieImport/ImportApprovedMovie.cs index d5d839fd9e..2618e69c1b 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieImport/ImportApprovedMovie.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieImport/ImportApprovedMovie.cs @@ -5,14 +5,13 @@ using NLog; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Download; +using NzbDrone.Core.Extras; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Download; -using NzbDrone.Core.Extras; - namespace NzbDrone.Core.MediaFiles.MovieImport { @@ -52,13 +51,11 @@ public List Import(List decisions, bool newDownloa //I added a null op for the rare case that the quality is null. TODO: find out why that would even happen in the first place. var qualifiedImports = decisions.Where(c => c.Approved) .GroupBy(c => c.LocalMovie.Movie.Id, (i, s) => s - .OrderByDescending(c => c.LocalMovie.Quality ?? new QualityModel{Quality = Quality.Unknown}, new QualityModelComparer(s.First().LocalMovie.Movie.Profile)) + .OrderByDescending(c => c.LocalMovie.Quality ?? new QualityModel { Quality = Quality.Unknown }, new QualityModelComparer(s.First().LocalMovie.Movie.Profile)) .ThenByDescending(c => c.LocalMovie.Size)) .SelectMany(c => c) .ToList(); - - var importResults = new List(); foreach (var importDecision in qualifiedImports.OrderByDescending(e => e.LocalMovie.Size)) diff --git a/src/NzbDrone.Core/MediaFiles/MovieImport/ImportDecision.cs b/src/NzbDrone.Core/MediaFiles/MovieImport/ImportDecision.cs index 618294b786..5b648c0c3d 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieImport/ImportDecision.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieImport/ImportDecision.cs @@ -17,6 +17,7 @@ public ImportDecision(LocalMovie localMovie, params Rejection[] rejections) { LocalMovie = localMovie; Rejections = rejections.ToList(); + //LocalMovie = new LocalMovie //{ // Quality = localMovie.Quality, diff --git a/src/NzbDrone.Core/MediaFiles/MovieImport/ImportDecisionMaker.cs b/src/NzbDrone.Core/MediaFiles/MovieImport/ImportDecisionMaker.cs index 87bea36f9f..b3606293ac 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieImport/ImportDecisionMaker.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieImport/ImportDecisionMaker.cs @@ -6,11 +6,10 @@ using NzbDrone.Common.Extensions; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download; +using NzbDrone.Core.MediaFiles.MovieImport.Aggregation; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Movies; -using NzbDrone.Core.MediaFiles.MovieImport.Aggregation; - namespace NzbDrone.Core.MediaFiles.MovieImport { diff --git a/src/NzbDrone.Core/MediaFiles/MovieImport/Manual/ManualImportItem.cs b/src/NzbDrone.Core/MediaFiles/MovieImport/Manual/ManualImportItem.cs index 51cf8a13dd..613cc6ca79 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieImport/Manual/ManualImportItem.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieImport/Manual/ManualImportItem.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using NzbDrone.Core.DecisionEngine; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; using NzbDrone.Core.Languages; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.MediaFiles.MovieImport.Manual { diff --git a/src/NzbDrone.Core/MediaFiles/MovieImport/Manual/ManualImportService.cs b/src/NzbDrone.Core/MediaFiles/MovieImport/Manual/ManualImportService.cs index 889ba18fc2..c4763fe0aa 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieImport/Manual/ManualImportService.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieImport/Manual/ManualImportService.cs @@ -11,12 +11,12 @@ using NzbDrone.Core.Download; using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.History; +using NzbDrone.Core.MediaFiles.MovieImport.Aggregation; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; -using NzbDrone.Core.Movies; -using NzbDrone.Core.MediaFiles.MovieImport.Aggregation; namespace NzbDrone.Core.MediaFiles.MovieImport.Manual { @@ -183,7 +183,7 @@ private ManualImportItem ProcessFile(string rootFolder, string baseFolder, strin return MapItem(new ImportDecision(localMovie, new Rejection("Unknown Movie")), rootFolder, downloadId, null); } - var importDecisions = _importDecisionMaker.GetImportDecisions(new List {file}, movie, downloadClientItem, null, SceneSource(movie, baseFolder)); + var importDecisions = _importDecisionMaker.GetImportDecisions(new List { file }, movie, downloadClientItem, null, SceneSource(movie, baseFolder)); if (importDecisions.Any()) { @@ -274,7 +274,6 @@ public void Execute(ManualImportCommand message) localMovie.Quality = file.Quality; //TODO: Cleanup non-tracked downloads - var importDecision = new ImportDecision(localMovie); if (trackedDownload == null) @@ -288,10 +287,10 @@ public void Execute(ManualImportCommand message) imported.Add(importResult); importedTrackedDownload.Add(new ManuallyImportedFile - { - TrackedDownload = trackedDownload, - ImportResult = importResult - }); + { + TrackedDownload = trackedDownload, + ImportResult = importResult + }); } } @@ -311,7 +310,8 @@ public void Execute(ManualImportCommand message) } } - if (groupedTrackedDownload.Select(c => c.ImportResult).Count(c => c.Result == ImportResultType.Imported) >= Math.Max(1, 1)) //TODO: trackedDownload.RemoteMovie.Movie.Count is always 1? + //TODO: trackedDownload.RemoteMovie.Movie.Count is always 1? + if (groupedTrackedDownload.Select(c => c.ImportResult).Count(c => c.Result == ImportResultType.Imported) >= Math.Max(1, 1)) { trackedDownload.State = TrackedDownloadStage.Imported; _eventAggregator.PublishEvent(new DownloadCompletedEvent(trackedDownload)); diff --git a/src/NzbDrone.Core/MediaFiles/MovieImport/Specifications/FreeSpaceSpecification.cs b/src/NzbDrone.Core/MediaFiles/MovieImport/Specifications/FreeSpaceSpecification.cs index 9fc4b3aeac..af0eb0ec71 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieImport/Specifications/FreeSpaceSpecification.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieImport/Specifications/FreeSpaceSpecification.cs @@ -15,7 +15,7 @@ public class FreeSpaceSpecification : IImportDecisionEngineSpecification private readonly IConfigService _configService; private readonly Logger _logger; - public FreeSpaceSpecification(IDiskProvider diskProvider, IConfigService configService, Logger logger) + public FreeSpaceSpecification(IDiskProvider diskProvider, IConfigService configService, Logger logger) { _diskProvider = diskProvider; _configService = configService; diff --git a/src/NzbDrone.Core/MediaFiles/MovieImport/Specifications/GrabbedReleaseQualitySpecification.cs b/src/NzbDrone.Core/MediaFiles/MovieImport/Specifications/GrabbedReleaseQualitySpecification.cs index c4ec2c200d..ca88939b36 100644 --- a/src/NzbDrone.Core/MediaFiles/MovieImport/Specifications/GrabbedReleaseQualitySpecification.cs +++ b/src/NzbDrone.Core/MediaFiles/MovieImport/Specifications/GrabbedReleaseQualitySpecification.cs @@ -16,7 +16,8 @@ public class GrabbedReleaseQualitySpecification : IImportDecisionEngineSpecifica private readonly IHistoryService _historyService; private readonly IParsingService _parsingService; - public GrabbedReleaseQualitySpecification(Logger logger, IHistoryService historyService, + public GrabbedReleaseQualitySpecification(Logger logger, + IHistoryService historyService, IParsingService parsingService) { _logger = logger; diff --git a/src/NzbDrone.Core/MediaFiles/RecycleBinProvider.cs b/src/NzbDrone.Core/MediaFiles/RecycleBinProvider.cs index 9484765b86..7dd2ac926d 100644 --- a/src/NzbDrone.Core/MediaFiles/RecycleBinProvider.cs +++ b/src/NzbDrone.Core/MediaFiles/RecycleBinProvider.cs @@ -27,7 +27,6 @@ public class RecycleBinProvider : IExecute, IRecycleBi private readonly IConfigService _configService; private readonly Logger _logger; - public RecycleBinProvider(IDiskTransferService diskTransferService, IDiskProvider diskProvider, IConfigService configService, @@ -50,7 +49,6 @@ public void DeleteFolder(string path) _diskProvider.DeleteFolder(path, true); _logger.Debug("Folder has been permanently deleted: {0}", path); } - else { var destination = Path.Combine(recyclingBin, new DirectoryInfo(path).Name); @@ -86,7 +84,6 @@ public void DeleteFile(string path, string subfolder = "") _diskProvider.DeleteFile(path); _logger.Debug("File has been permanently deleted: {0}", path); } - else { var fileInfo = new FileInfo(path); diff --git a/src/NzbDrone.Core/MediaFiles/RenameMovieFileService.cs b/src/NzbDrone.Core/MediaFiles/RenameMovieFileService.cs index d36b48f7d9..ed398f23f2 100644 --- a/src/NzbDrone.Core/MediaFiles/RenameMovieFileService.cs +++ b/src/NzbDrone.Core/MediaFiles/RenameMovieFileService.cs @@ -1,26 +1,26 @@ using System; using System.Collections.Generic; using System.Data.SQLite; -using System.Linq; using System.IO; +using System.Linq; using NLog; -using NzbDrone.Core.Messaging.Commands; -using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.MediaFiles.Commands; -using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Common.Instrumentation.Extensions; -using NzbDrone.Core.Organizer; -using NzbDrone.Core.Movies; using NzbDrone.Core.Configuration; +using NzbDrone.Core.MediaFiles.Commands; +using NzbDrone.Core.MediaFiles.Events; +using NzbDrone.Core.Messaging.Commands; +using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Organizer; namespace NzbDrone.Core.MediaFiles { public interface IRenameMovieFileService { List GetRenamePreviews(int movieId); - void RenameMoviePath(Movie movie, bool shouldRenameFiles); + void RenameMoviePath(Movie movie, bool shouldRenameFiles); } public class RenameMovieFileService : IRenameMovieFileService, @@ -65,32 +65,30 @@ public List GetRenamePreviews(int movieId) var file = _mediaFileService.GetFilesByMovie(movieId); return GetPreviews(movie, file).OrderByDescending(m => m.MovieId).ToList(); //TODO: Would really like to not have these be lists - } private IEnumerable GetPreviews(Movie movie, List files) { - foreach(var file in files) + foreach (var file in files) { var movieFilePath = Path.Combine(movie.Path, file.RelativePath); var newName = _filenameBuilder.BuildFileName(movie, file); var newPath = _filenameBuilder.BuildFilePath(movie, newName, Path.GetExtension(movieFilePath)); - if(!movieFilePath.PathEquals(newPath, StringComparison.Ordinal)) + if (!movieFilePath.PathEquals(newPath, StringComparison.Ordinal)) { yield return new RenameMovieFilePreview { MovieId = movie.Id, MovieFileId = file.Id, ExistingPath = movieFilePath, + //NewPath = movie.Path.GetRelativePath(newPath) NewPath = newPath }; } - } - } private void RenameFiles(List movieFiles, Movie movie, string oldMoviePath = null) @@ -119,7 +117,6 @@ private void RenameFiles(List movieFiles, Movie movie, string oldMovi _logger.Debug("Renamed movie file: {0}", movieFile); _eventAggregator.PublishEvent(new MovieFileRenamedEvent(movie, movieFile, oldMovieFilePath)); - } catch (SameFilenameException ex) { @@ -142,14 +139,13 @@ public void RenameMoviePath(Movie movie, bool shouldRenameFiles = true) var newFolder = _filenameBuilder.BuildMoviePath(movie); if (newFolder != movie.Path && movie.PathState == MoviePathState.Dynamic) { - if (!_configService.AutoRenameFolders) { _logger.Info("{0}'s movie should be {1} according to your naming config.", movie, newFolder); return; } - _logger.Info("{0}'s movie folder changed to: {1}", movie, newFolder); + _logger.Info("{0}'s movie folder changed to: {1}", movie, newFolder); var oldFolder = movie.Path; movie.Path = newFolder; @@ -162,15 +158,12 @@ public void RenameMoviePath(Movie movie, bool shouldRenameFiles = true) // RenameFiles(movieFiles, movie, oldFolder); // _logger.ProgressInfo("All movie files renamed for {0}", movie.Title); // } - _movieService.UpdateMovie(movie); if (_diskProvider.GetFiles(oldFolder, SearchOption.AllDirectories).Count() == 0) { _recycleBinProvider.DeleteFolder(oldFolder); } - - } if (movie.PathState == MoviePathState.StaticOnce) @@ -195,34 +188,33 @@ public void Execute(RenameMovieCommand message) _logger.Debug("Renaming movie files for selected movie"); var moviesToRename = _movieService.GetMovies(message.MovieIds); - foreach(var movie in moviesToRename) + foreach (var movie in moviesToRename) { var movieFiles = _mediaFileService.GetFilesByMovie(movie.Id); _logger.ProgressInfo("Renaming movie files for {0}", movie.Title); RenameFiles(movieFiles, movie); _logger.ProgressInfo("All movie files renamed for {0}", movie.Title); } - } - public void Execute(RenameMovieFolderCommand message) - { - try + public void Execute(RenameMovieFolderCommand message) { - _logger.Debug("Renaming movie folder for selected movie if necessary"); - var moviesToRename = _movieService.GetMovies(message.MovieIds); - foreach(var movie in moviesToRename) + try { - var movieFiles = _mediaFileService.GetFilesByMovie(movie.Id); - //_logger.ProgressInfo("Renaming movie folder for {0}", movie.Title); - RenameMoviePath(movie); + _logger.Debug("Renaming movie folder for selected movie if necessary"); + var moviesToRename = _movieService.GetMovies(message.MovieIds); + foreach (var movie in moviesToRename) + { + var movieFiles = _mediaFileService.GetFilesByMovie(movie.Id); + + //_logger.ProgressInfo("Renaming movie folder for {0}", movie.Title); + RenameMoviePath(movie); + } + } + catch (SQLiteException ex) + { + _logger.Warn(ex, "wtf: {0}, {1}", ex.ResultCode, ex.Data); } } - catch (SQLiteException ex) - { - _logger.Warn(ex, "wtf: {0}, {1}", ex.ResultCode, ex.Data); - } - - } } } diff --git a/src/NzbDrone.Core/MediaFiles/SameFilenameException.cs b/src/NzbDrone.Core/MediaFiles/SameFilenameException.cs index c2a8cbd1f3..d191bf55d5 100644 --- a/src/NzbDrone.Core/MediaFiles/SameFilenameException.cs +++ b/src/NzbDrone.Core/MediaFiles/SameFilenameException.cs @@ -6,7 +6,8 @@ public class SameFilenameException : Exception { public string Filename { get; set; } - public SameFilenameException(string message, string filename) : base(message) + public SameFilenameException(string message, string filename) + : base(message) { Filename = filename; } diff --git a/src/NzbDrone.Core/MediaFiles/TorrentInfo/TorrentFileInfoReader.cs b/src/NzbDrone.Core/MediaFiles/TorrentInfo/TorrentFileInfoReader.cs index 996b4211a4..a3bb71acc4 100644 --- a/src/NzbDrone.Core/MediaFiles/TorrentInfo/TorrentFileInfoReader.cs +++ b/src/NzbDrone.Core/MediaFiles/TorrentInfo/TorrentFileInfoReader.cs @@ -7,7 +7,7 @@ public interface ITorrentFileInfoReader string GetHashFromTorrentFile(byte[] fileContents); } - public class TorrentFileInfoReader: ITorrentFileInfoReader + public class TorrentFileInfoReader : ITorrentFileInfoReader { public string GetHashFromTorrentFile(byte[] fileContents) { diff --git a/src/NzbDrone.Core/MediaFiles/UpdateMovieFileQualityService.cs b/src/NzbDrone.Core/MediaFiles/UpdateMovieFileQualityService.cs index 93da29f05a..11078be8b5 100644 --- a/src/NzbDrone.Core/MediaFiles/UpdateMovieFileQualityService.cs +++ b/src/NzbDrone.Core/MediaFiles/UpdateMovieFileQualityService.cs @@ -15,7 +15,6 @@ namespace NzbDrone.Core.MediaFiles { public interface IUpdateMovieFileQualityService { - } public class UpdateMovieFileQualityService : IUpdateMovieFileQualityService, IExecute @@ -57,7 +56,7 @@ public void Execute(UpdateMovieFileQualityCommand command) var sizeMovie = new LocalMovie(); sizeMovie.Size = movieFile.Size; - var helpers = new List{sizeMovie}; + var helpers = new List { sizeMovie }; if (movieFile.MediaInfo != null) { @@ -96,7 +95,6 @@ public void Execute(UpdateMovieFileQualityCommand command) count++; } - } } } diff --git a/src/NzbDrone.Core/MediaFiles/UpdateMovieFileService.cs b/src/NzbDrone.Core/MediaFiles/UpdateMovieFileService.cs index 13ae565190..d2fecfc140 100644 --- a/src/NzbDrone.Core/MediaFiles/UpdateMovieFileService.cs +++ b/src/NzbDrone.Core/MediaFiles/UpdateMovieFileService.cs @@ -90,7 +90,6 @@ private bool ChangeFileDate(string filePath, DateTime date) return true; } - catch (Exception ex) { _logger.Warn(ex, "Unable to set date of file [" + filePath + "]"); @@ -130,7 +129,6 @@ public void Handle(MovieScannedEvent message) { _logger.ProgressDebug("Changed file date for {0} files of {1} in {2}", updated.Count, movieFiles.Count, message.Movie.Title); } - else { _logger.ProgressDebug("No file dates changed for {0}", message.Movie.Title); @@ -155,14 +153,12 @@ private bool ChangeFileDateToLocalAirDate(string filePath, string fileDate, stri return true; } - catch (Exception ex) { _logger.Warn(ex, "Unable to set date of file [" + filePath + "]"); } } } - else { _logger.Debug("Could not create valid date to change file [{0}]", filePath); @@ -184,7 +180,6 @@ private bool ChangeFileDateToUtcAirDate(string filePath, DateTime airDateUtc) return true; } - catch (Exception ex) { _logger.Warn(ex, "Unable to set date of file [" + filePath + "]"); diff --git a/src/NzbDrone.Core/MediaFiles/UpgradeMediaFileService.cs b/src/NzbDrone.Core/MediaFiles/UpgradeMediaFileService.cs index 1ffbcb9f98..883bee45fb 100644 --- a/src/NzbDrone.Core/MediaFiles/UpgradeMediaFileService.cs +++ b/src/NzbDrone.Core/MediaFiles/UpgradeMediaFileService.cs @@ -15,7 +15,7 @@ public class UpgradeMediaFileService : IUpgradeMediaFiles private readonly IRecycleBinProvider _recycleBinProvider; private readonly IMediaFileService _mediaFileService; private readonly IMoveMovieFiles _movieFileMover; - private readonly IRenameMovieFileService _movieFileRenamer; + private readonly IRenameMovieFileService _movieFileRenamer; private readonly IDiskProvider _diskProvider; private readonly Logger _logger; @@ -55,9 +55,9 @@ public MovieFileMoveResult UpgradeMovieFile(MovieFile movieFile, LocalMovie loca _mediaFileService.Delete(existingFile, DeleteMediaFileReason.Upgrade); } - //Temporary for correctly getting path - localMovie.Movie.MovieFileId = 1; - localMovie.Movie.MovieFile = movieFile; + //Temporary for correctly getting path + localMovie.Movie.MovieFileId = 1; + localMovie.Movie.MovieFile = movieFile; if (copyOnly) { @@ -71,8 +71,7 @@ public MovieFileMoveResult UpgradeMovieFile(MovieFile movieFile, LocalMovie loca localMovie.Movie.MovieFileId = existingFile?.Id ?? 0; localMovie.Movie.MovieFile = existingFile; - //_movieFileRenamer.RenameMoviePath(localMovie.Movie, false); - + //_movieFileRenamer.RenameMoviePath(localMovie.Movie, false); return moveFileResult; } } diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandEqualityComparer.cs b/src/NzbDrone.Core/Messaging/Commands/CommandEqualityComparer.cs index 65f21b935b..ea24a29df5 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandEqualityComparer.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandEqualityComparer.cs @@ -10,12 +10,14 @@ public class CommandEqualityComparer : IEqualityComparer private CommandEqualityComparer() { - } public bool Equals(Command x, Command y) { - if(x.GetType() != y.GetType()) return false; + if (x.GetType() != y.GetType()) + { + return false; + } var xProperties = x.GetType().GetProperties(); var yProperties = y.GetType().GetProperties(); @@ -27,7 +29,7 @@ public bool Equals(Command x, Command y) continue; } - if (xProperty.DeclaringType == typeof (Command)) + if (xProperty.DeclaringType == typeof(Command)) { continue; } @@ -60,7 +62,6 @@ public bool Equals(Command x, Command y) return false; } } - else if (!xValue.Equals(yValue)) { return false; diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandExecutor.cs b/src/NzbDrone.Core/Messaging/Commands/CommandExecutor.cs index b507229b4b..f430aa4df4 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandExecutor.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandExecutor.cs @@ -11,15 +11,16 @@ namespace NzbDrone.Core.Messaging.Commands public class CommandExecutor : IHandle, IHandle { + private const int THREAD_UPPER_BOUND = 10; + private const int THREAD_LOWER_BOUND = 2; + private const int THREAD_LIMIT = 2; + private readonly Logger _logger; private readonly IServiceFactory _serviceFactory; private readonly IManageCommandQueue _commandQueueManager; private readonly IEventAggregator _eventAggregator; private static CancellationTokenSource _cancellationTokenSource; - private const int THREAD_UPPER_BOUND = 10; - private const int THREAD_LOWER_BOUND = 2; - private const int THREAD_LIMIT = 2; public CommandExecutor(IServiceFactory serviceFactory, IManageCommandQueue commandQueueManager, @@ -40,7 +41,7 @@ private void ExecuteCommands() { try { - ExecuteCommand((dynamic) command.Body, command); + ExecuteCommand((dynamic)command.Body, command); } catch (Exception ex) { @@ -63,7 +64,8 @@ private void ExecuteCommands() } } - private void ExecuteCommand(TCommand command, CommandModel commandModel) where TCommand : Command + private void ExecuteCommand(TCommand command, CommandModel commandModel) + where TCommand : Command { var handlerContract = typeof(IExecute<>).MakeGenericType(command.GetType()); var handler = (IExecute)_serviceFactory.Build(handlerContract); @@ -125,7 +127,10 @@ public void Handle(ApplicationStartedEvent message) var envLimit = Environment.GetEnvironmentVariable("THREAD_LIMIT") ?? $"{THREAD_LIMIT}"; int threadLimit = THREAD_LIMIT; - if (int.TryParse(envLimit, out int parsedLimit)) threadLimit = parsedLimit; + if (int.TryParse(envLimit, out int parsedLimit)) + { + threadLimit = parsedLimit; + } threadLimit = Math.Max(THREAD_LOWER_BOUND, threadLimit); threadLimit = Math.Min(THREAD_UPPER_BOUND, threadLimit); diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandFailedException.cs b/src/NzbDrone.Core/Messaging/Commands/CommandFailedException.cs index 3dcbf60cc7..cfb41883f5 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandFailedException.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandFailedException.cs @@ -5,19 +5,23 @@ namespace NzbDrone.Core.Messaging.Commands { public class CommandFailedException : NzbDroneException { - public CommandFailedException(string message, params object[] args) : base(message, args) + public CommandFailedException(string message, params object[] args) + : base(message, args) { } - public CommandFailedException(string message) : base(message) + public CommandFailedException(string message) + : base(message) { } - public CommandFailedException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public CommandFailedException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } - public CommandFailedException(string message, Exception innerException) : base(message, innerException) + public CommandFailedException(string message, Exception innerException) + : base(message, innerException) { } diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandNotFoundException.cs b/src/NzbDrone.Core/Messaging/Commands/CommandNotFoundException.cs index 656037138e..503dadadf9 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandNotFoundException.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandNotFoundException.cs @@ -8,6 +8,5 @@ public CommandNotFoundException(string contract) : base("Couldn't find command " + contract) { } - } } diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandQueue.cs b/src/NzbDrone.Core/Messaging/Commands/CommandQueue.cs index 0aef57ac65..d8489785d5 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandQueue.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandQueue.cs @@ -70,6 +70,7 @@ public void RemoveMany(IEnumerable commands) } } } + public bool RemoveIfQueued(int id) { var rval = false; @@ -137,27 +138,32 @@ public bool TryGet(out CommandModel item) return c.Status == CommandStatus.Queued && !c.Body.RequiresDiskAccess; } + return c.Status == CommandStatus.Queued; }) .OrderByDescending(c => c.Priority) .ThenBy(c => c.QueuedAt) .FirstOrDefault(); + // Nothing queued that meets the requirements if (localItem == null) { rval = false; } + // If any executing command is exclusive don't want return another command until it completes. else if (startedCommands.Any(c => c.Body.IsExclusive)) { rval = false; } + // If the next command to execute is exclusive wait for executing commands to complete. // This will prevent other tasks from starting so the exclusive task executes in the order it should. else if (localItem.Body.IsExclusive && startedCommands.Any()) { rval = false; } + // A command ready to execute else { diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandQueueManager.cs b/src/NzbDrone.Core/Messaging/Commands/CommandQueueManager.cs index 6095d3b4ec..e8fc4cf584 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandQueueManager.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandQueueManager.cs @@ -1,22 +1,24 @@ -using NLog; -using NzbDrone.Common; -using NzbDrone.Common.EnsureThat; -using NzbDrone.Common.Serializer; -using NzbDrone.Core.Lifecycle; -using NzbDrone.Core.Messaging.Events; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; +using NLog; +using NzbDrone.Common; +using NzbDrone.Common.EnsureThat; +using NzbDrone.Common.Serializer; using NzbDrone.Core.Exceptions; +using NzbDrone.Core.Lifecycle; +using NzbDrone.Core.Messaging.Events; namespace NzbDrone.Core.Messaging.Commands { public interface IManageCommandQueue { - List PushMany(List commands) where TCommand : Command; - CommandModel Push(TCommand command, CommandPriority priority = CommandPriority.Normal, CommandTrigger trigger = CommandTrigger.Unspecified) where TCommand : Command; + List PushMany(List commands) + where TCommand : Command; + CommandModel Push(TCommand command, CommandPriority priority = CommandPriority.Normal, CommandTrigger trigger = CommandTrigger.Unspecified) + where TCommand : Command; CommandModel Push(string commandName, DateTime? lastExecutionTime, DateTime? lastStartTime, CommandPriority priority = CommandPriority.Normal, CommandTrigger trigger = CommandTrigger.Unspecified); IEnumerable Queue(CancellationToken cancellationToken); List All(); @@ -50,7 +52,8 @@ public CommandQueueManager(ICommandRepository repo, _commandQueue = new CommandQueue(); } - public List PushMany(List commands) where TCommand : Command + public List PushMany(List commands) + where TCommand : Command { _logger.Trace("Publishing {0} commands", commands.Count); @@ -89,7 +92,8 @@ public List PushMany(List commands) where TCom return commandModels; } - public CommandModel Push(TCommand command, CommandPriority priority = CommandPriority.Normal, CommandTrigger trigger = CommandTrigger.Unspecified) where TCommand : Command + public CommandModel Push(TCommand command, CommandPriority priority = CommandPriority.Normal, CommandTrigger trigger = CommandTrigger.Unspecified) + where TCommand : Command { Ensure.That(command, () => command).IsNotNull(); diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandRepository.cs b/src/NzbDrone.Core/Messaging/Commands/CommandRepository.cs index 173d6c6ebf..7c6460cbc2 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandRepository.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandRepository.cs @@ -39,9 +39,8 @@ public void OrphanStarted() { using (var mapper = _database.GetDataMapper()) { - - mapper.Parameters.Add(new SQLiteParameter("@orphaned", (int) CommandStatus.Orphaned)); - mapper.Parameters.Add(new SQLiteParameter("@started", (int) CommandStatus.Started)); + mapper.Parameters.Add(new SQLiteParameter("@orphaned", (int)CommandStatus.Orphaned)); + mapper.Parameters.Add(new SQLiteParameter("@started", (int)CommandStatus.Started)); mapper.Parameters.Add(new SQLiteParameter("@ended", DateTime.UtcNow)); mapper.ExecuteNonQuery(@"UPDATE Commands diff --git a/src/NzbDrone.Core/Messaging/Commands/IExecute.cs b/src/NzbDrone.Core/Messaging/Commands/IExecute.cs index fa93c83444..63bcc02d6a 100644 --- a/src/NzbDrone.Core/Messaging/Commands/IExecute.cs +++ b/src/NzbDrone.Core/Messaging/Commands/IExecute.cs @@ -1,6 +1,7 @@ namespace NzbDrone.Core.Messaging.Commands { - public interface IExecute : IProcessMessage where TCommand : Command + public interface IExecute : IProcessMessage + where TCommand : Command { void Execute(TCommand message); } diff --git a/src/NzbDrone.Core/Messaging/Events/EventAggregator.cs b/src/NzbDrone.Core/Messaging/Events/EventAggregator.cs index 4f49324a9a..f660cd790e 100644 --- a/src/NzbDrone.Core/Messaging/Events/EventAggregator.cs +++ b/src/NzbDrone.Core/Messaging/Events/EventAggregator.cs @@ -17,7 +17,8 @@ public class EventAggregator : IEventAggregator private readonly TaskFactory _taskFactory; private readonly Dictionary _eventSubscribers; - private class EventSubscribers where TEvent : class, IEvent + private class EventSubscribers + where TEvent : class, IEvent { private IServiceFactory _serviceFactory; @@ -49,7 +50,8 @@ public EventAggregator(Logger logger, IServiceFactory serviceFactory) _eventSubscribers = new Dictionary(); } - public void PublishEvent(TEvent @event) where TEvent : class, IEvent + public void PublishEvent(TEvent @event) + where TEvent : class, IEvent { Ensure.That(@event, () => @event).IsNotNull(); @@ -137,21 +139,22 @@ private static string GetEventName(Type eventType) return string.Format("{0}<{1}>", eventType.Name.Remove(eventType.Name.IndexOf('`')), eventType.GetGenericArguments()[0].Name); } - internal static int GetEventHandleOrder(IHandle eventHandler) where TEvent : class, IEvent + internal static int GetEventHandleOrder(IHandle eventHandler) + where TEvent : class, IEvent { // TODO: Convert "Handle" to nameof(eventHandler.Handle) after .net 4.5 - var method = eventHandler.GetType().GetMethod("Handle", new Type[] {typeof(TEvent)}); + var method = eventHandler.GetType().GetMethod("Handle", new Type[] { typeof(TEvent) }); if (method == null) { - return (int) EventHandleOrder.Any; + return (int)EventHandleOrder.Any; } var attribute = method.GetCustomAttributes(typeof(EventHandleOrderAttribute), true).FirstOrDefault() as EventHandleOrderAttribute; if (attribute == null) { - return (int) EventHandleOrder.Any; + return (int)EventHandleOrder.Any; } return (int)attribute.EventHandleOrder; diff --git a/src/NzbDrone.Core/Messaging/Events/IEventAggregator.cs b/src/NzbDrone.Core/Messaging/Events/IEventAggregator.cs index 7a83cbbf74..924cac454e 100644 --- a/src/NzbDrone.Core/Messaging/Events/IEventAggregator.cs +++ b/src/NzbDrone.Core/Messaging/Events/IEventAggregator.cs @@ -4,6 +4,7 @@ namespace NzbDrone.Core.Messaging.Events { public interface IEventAggregator { - void PublishEvent(TEvent @event) where TEvent : class, IEvent; + void PublishEvent(TEvent @event) + where TEvent : class, IEvent; } } diff --git a/src/NzbDrone.Core/Messaging/Events/IHandle.cs b/src/NzbDrone.Core/Messaging/Events/IHandle.cs index dc389a18f1..17c232e623 100644 --- a/src/NzbDrone.Core/Messaging/Events/IHandle.cs +++ b/src/NzbDrone.Core/Messaging/Events/IHandle.cs @@ -2,12 +2,14 @@ namespace NzbDrone.Core.Messaging.Events { - public interface IHandle : IProcessMessage where TEvent : IEvent + public interface IHandle : IProcessMessage + where TEvent : IEvent { void Handle(TEvent message); } - public interface IHandleAsync : IProcessMessageAsync where TEvent : IEvent + public interface IHandleAsync : IProcessMessageAsync + where TEvent : IEvent { void HandleAsync(TEvent message); } diff --git a/src/NzbDrone.Core/Messaging/IProcessMessage.cs b/src/NzbDrone.Core/Messaging/IProcessMessage.cs index 4a4b3d80c2..f0463ce2ef 100644 --- a/src/NzbDrone.Core/Messaging/IProcessMessage.cs +++ b/src/NzbDrone.Core/Messaging/IProcessMessage.cs @@ -1,10 +1,18 @@ namespace NzbDrone.Core.Messaging { - public interface IProcessMessage { } + public interface IProcessMessage + { + } - public interface IProcessMessageAsync : IProcessMessage { } + public interface IProcessMessageAsync : IProcessMessage + { + } - public interface IProcessMessage : IProcessMessage { } + public interface IProcessMessage : IProcessMessage + { + } - public interface IProcessMessageAsync : IProcessMessageAsync { } + public interface IProcessMessageAsync : IProcessMessageAsync + { + } } diff --git a/src/NzbDrone.Core/MetadataSource/IProvideMovieInfo.cs b/src/NzbDrone.Core/MetadataSource/IProvideMovieInfo.cs index ad12c0c8c1..c86d2f55a0 100644 --- a/src/NzbDrone.Core/MetadataSource/IProvideMovieInfo.cs +++ b/src/NzbDrone.Core/MetadataSource/IProvideMovieInfo.cs @@ -1,14 +1,14 @@ using System; using System.Collections.Generic; -using NzbDrone.Core.Profiles; using NzbDrone.Core.Movies; +using NzbDrone.Core.Profiles; namespace NzbDrone.Core.MetadataSource { public interface IProvideMovieInfo { - Movie GetMovieInfo(string ImdbId); - Movie GetMovieInfo(int TmdbId, Profile profile, bool hasPreDBEntry); + Movie GetMovieInfo(string imdbId); + Movie GetMovieInfo(int tmdbId, Profile profile, bool hasPreDBEntry); HashSet GetChangedMovies(DateTime startTime); } } diff --git a/src/NzbDrone.Core/MetadataSource/PreDB/PreDBResult.cs b/src/NzbDrone.Core/MetadataSource/PreDB/PreDBResult.cs index eda48e6282..3a6d6593a6 100644 --- a/src/NzbDrone.Core/MetadataSource/PreDB/PreDBResult.cs +++ b/src/NzbDrone.Core/MetadataSource/PreDB/PreDBResult.cs @@ -1,9 +1,8 @@ namespace NzbDrone.Core.MetadataSource.PreDB { - class PreDBResult + internal class PreDBResult { public string Title { get; set; } public string Link { get; set; } - } } diff --git a/src/NzbDrone.Core/MetadataSource/PreDB/PreDBService.cs b/src/NzbDrone.Core/MetadataSource/PreDB/PreDBService.cs index 9ffe1e4eec..8ec39ba4a8 100644 --- a/src/NzbDrone.Core/MetadataSource/PreDB/PreDBService.cs +++ b/src/NzbDrone.Core/MetadataSource/PreDB/PreDBService.cs @@ -1,17 +1,17 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using NLog; +using NzbDrone.Common.Http; using NzbDrone.Common.Instrumentation.Extensions; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.Download; using NzbDrone.Core.Download.Pending; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.IndexerSearch.Definitions; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Indexers; -using NzbDrone.Common.Http; using NzbDrone.Core.Movies; -using System; using NzbDrone.Core.Parser; -using NzbDrone.Core.IndexerSearch.Definitions; namespace NzbDrone.Core.MetadataSource.PreDB { @@ -131,9 +131,6 @@ private List FindMatchesToResults(List results) return matches; } - - - private List Sync() { _logger.ProgressInfo("Starting PreDB Sync"); @@ -168,33 +165,33 @@ public void Execute(PreDBSyncCommand message) public bool HasReleases(Movie movie) { - try - { - var results = GetResults("movies", movie.Title); - - foreach (PreDBResult result in results) + try { - var parsed = Parser.Parser.ParseMovieTitle(result.Title, true); - if (parsed == null) - { - parsed = new Parser.Model.ParsedMovieInfo { MovieTitle = result.Title, Year = 0 }; - } - var match = _parsingService.Map(parsed, "", new MovieSearchCriteria { Movie = movie }); + var results = GetResults("movies", movie.Title); - if (match != null && match.RemoteMovie.Movie != null && match.RemoteMovie.Movie.Id == movie.Id) + foreach (PreDBResult result in results) { - return true; + var parsed = Parser.Parser.ParseMovieTitle(result.Title, true); + if (parsed == null) + { + parsed = new Parser.Model.ParsedMovieInfo { MovieTitle = result.Title, Year = 0 }; + } + + var match = _parsingService.Map(parsed, "", new MovieSearchCriteria { Movie = movie }); + + if (match != null && match.RemoteMovie.Movie != null && match.RemoteMovie.Movie.Id == movie.Id) + { + return true; + } } + + return false; + } + catch (Exception ex) + { + _logger.Warn(ex, "Error while looking on predb.me."); + return false; } - - return false; - } - catch (Exception ex) - { - _logger.Warn(ex, "Error while looking on predb.me."); - return false; - } - } } } diff --git a/src/NzbDrone.Core/MetadataSource/PreDB/PreDBSyncCommand.cs b/src/NzbDrone.Core/MetadataSource/PreDB/PreDBSyncCommand.cs index fffb532fc2..89438e8195 100644 --- a/src/NzbDrone.Core/MetadataSource/PreDB/PreDBSyncCommand.cs +++ b/src/NzbDrone.Core/MetadataSource/PreDB/PreDBSyncCommand.cs @@ -4,7 +4,6 @@ namespace NzbDrone.Core.MetadataSource.PreDB { public class PreDBSyncCommand : Command { - public override bool SendUpdatesToClient => true; } } diff --git a/src/NzbDrone.Core/MetadataSource/PreDB/PreDBSyncEvent.cs b/src/NzbDrone.Core/MetadataSource/PreDB/PreDBSyncEvent.cs index c1d4b9d1bc..5311b21708 100644 --- a/src/NzbDrone.Core/MetadataSource/PreDB/PreDBSyncEvent.cs +++ b/src/NzbDrone.Core/MetadataSource/PreDB/PreDBSyncEvent.cs @@ -1,5 +1,5 @@ -using NzbDrone.Common.Messaging; -using System.Collections.Generic; +using System.Collections.Generic; +using NzbDrone.Common.Messaging; using NzbDrone.Core.Movies; namespace NzbDrone.Core.MetadataSource.PreDB diff --git a/src/NzbDrone.Core/MetadataSource/RadarrAPI/RadarrAPIClient.cs b/src/NzbDrone.Core/MetadataSource/RadarrAPI/RadarrAPIClient.cs index e4f95e6d20..a0860d1a40 100644 --- a/src/NzbDrone.Core/MetadataSource/RadarrAPI/RadarrAPIClient.cs +++ b/src/NzbDrone.Core/MetadataSource/RadarrAPI/RadarrAPIClient.cs @@ -1,9 +1,9 @@ -using NzbDrone.Common.Http; -using NzbDrone.Core.Configuration; using System; -using Newtonsoft.Json; using System.Collections.Generic; using System.Linq; +using Newtonsoft.Json; +using NzbDrone.Common.Http; +using NzbDrone.Core.Configuration; using NzbDrone.Core.MetadataSource.SkyHook.Resource; using NzbDrone.Core.Movies.AlternativeTitles; using NzbDrone.Core.Parser; @@ -14,9 +14,9 @@ public interface IRadarrAPIClient { IHttpRequestBuilderFactory RadarrAPI { get; } List DiscoverMovies(string action, Func enhanceRequest); - List AlternativeTitlesForMovie(int TmdbId); + List AlternativeTitlesForMovie(int tmdbId); Tuple, AlternativeYear> AlternativeTitlesAndYearForMovie(int tmdbId); - AlternativeTitle AddNewAlternativeTitle(AlternativeTitle title, int TmdbId); + AlternativeTitle AddNewAlternativeTitle(AlternativeTitle title, int tmdbId); AlternativeYear AddNewAlternativeYear(int year, int tmdbId); string APIURL { get; } } @@ -40,7 +40,7 @@ public RadarrAPIClient(IConfigFileProvider configFile, IHttpClient httpClient) APIURL = "https://api.radarr.video/v2"; } - RadarrAPI = new HttpRequestBuilder(APIURL+"/{route}/{action}") + RadarrAPI = new HttpRequestBuilder(APIURL + "/{route}/{action}") .CreateFactory(); } @@ -82,7 +82,6 @@ private T Execute(HttpRequest request) //No error! } - if (response.StatusCode != System.Net.HttpStatusCode.OK) { throw new HttpException(request, response); @@ -91,7 +90,7 @@ private T Execute(HttpRequest request) return JsonConvert.DeserializeObject(response.Content); } - public List DiscoverMovies(string action, Func enhanceRequest = null ) + public List DiscoverMovies(string action, Func enhanceRequest = null) { var request = RadarrAPI.Create().SetSegment("route", "discovery").SetSegment("action", action).Build(); @@ -103,10 +102,9 @@ public List DiscoverMovies(string action, Func>(request); } - - public List AlternativeTitlesForMovie(int TmdbId) + public List AlternativeTitlesForMovie(int tmdbId) { - var request = RadarrAPI.Create().SetSegment("route", "mappings").SetSegment("action", "find").AddQueryParam("tmdbid", TmdbId).Build(); + var request = RadarrAPI.Create().SetSegment("route", "mappings").SetSegment("action", "find").AddQueryParam("tmdbid", tmdbId).Build(); var mappings = Execute(request); @@ -149,10 +147,10 @@ public Tuple, AlternativeYear> AlternativeTitlesAndYearFo return new Tuple, AlternativeYear>(titles, newYear); } - public AlternativeTitle AddNewAlternativeTitle(AlternativeTitle title, int TmdbId) + public AlternativeTitle AddNewAlternativeTitle(AlternativeTitle title, int tmdbId) { var request = RadarrAPI.Create().SetSegment("route", "mappings").SetSegment("action", "add") - .AddQueryParam("tmdbid", TmdbId).AddQueryParam("type", "title") + .AddQueryParam("tmdbid", tmdbId).AddQueryParam("type", "title") .AddQueryParam("language", IsoLanguages.Get(title.Language).TwoLetterCode) .AddQueryParam("aka_title", title.Title).Build(); diff --git a/src/NzbDrone.Core/MetadataSource/RadarrAPI/RadarrResources.cs b/src/NzbDrone.Core/MetadataSource/RadarrAPI/RadarrResources.cs index f948ff4895..5c14c86ba2 100644 --- a/src/NzbDrone.Core/MetadataSource/RadarrAPI/RadarrResources.cs +++ b/src/NzbDrone.Core/MetadataSource/RadarrAPI/RadarrResources.cs @@ -29,7 +29,8 @@ public class RadarrAPIException : Exception { public RadarrError APIErrors; - public RadarrAPIException(RadarrError apiError) : base(HumanReadable(apiError)) + public RadarrAPIException(RadarrError apiError) + : base(HumanReadable(apiError)) { APIErrors = apiError; } @@ -41,13 +42,12 @@ private static string HumanReadable(RadarrError apiErrors) { return $"{error.Title} ({error.Status}, RayId: {error.RayId}), Details: {error.Detail}"; })); - return $"Error while calling api: {firstError.Title}\nFull error(s): {details}"; + return $"Error while calling api: {firstError.Title}\nFull error(s): {details}"; } } public class TitleInfo { - [JsonProperty("id")] public int Id { get; set; } @@ -60,7 +60,6 @@ public class TitleInfo public class YearInfo { - [JsonProperty("id")] public int Id { get; set; } @@ -70,7 +69,6 @@ public class YearInfo public class Title { - [JsonProperty("id")] public int Id { get; set; } @@ -98,7 +96,6 @@ public class Title public class Year { - [JsonProperty("id")] public int Id { get; set; } @@ -126,7 +123,6 @@ public class Year public class Mappings { - [JsonProperty("titles")] public IList Titles { get; set; } @@ -136,7 +132,6 @@ public class Mappings public class Mapping { - [JsonProperty("id")] public int Id { get; set; } @@ -152,7 +147,6 @@ public class Mapping public class AddTitleMapping { - [JsonProperty("tmdbid")] public string Tmdbid { get; set; } @@ -180,7 +174,6 @@ public class AddTitleMapping public class AddYearMapping { - [JsonProperty("tmdbid")] public string Tmdbid { get; set; } @@ -205,5 +198,4 @@ public class AddYearMapping [JsonProperty("locked")] public bool Locked { get; set; } } - } diff --git a/src/NzbDrone.Core/MetadataSource/SearchMovieComparer.cs b/src/NzbDrone.Core/MetadataSource/SearchMovieComparer.cs index 16a1a6bc79..50bd18bbdd 100644 --- a/src/NzbDrone.Core/MetadataSource/SearchMovieComparer.cs +++ b/src/NzbDrone.Core/MetadataSource/SearchMovieComparer.cs @@ -39,23 +39,38 @@ public int Compare(Movie x, Movie y) // Prefer exact matches result = Compare(x, y, s => CleanPunctuation(s.Title).Equals(CleanPunctuation(SearchQuery))); - if (result != 0) return -result; + if (result != 0) + { + return -result; + } // Remove Articles (a/an/the) result = Compare(x, y, s => CleanArticles(s.Title).Equals(CleanArticles(SearchQuery))); - if (result != 0) return -result; + if (result != 0) + { + return -result; + } // Prefer close matches result = Compare(x, y, s => CleanPunctuation(s.Title).LevenshteinDistance(CleanPunctuation(SearchQuery)) <= 1); - if (result != 0) return -result; + if (result != 0) + { + return -result; + } // Compare clean matches by year "Battlestar Galactica 1978" result = CompareWithYear(x, y, s => CleanTitle(s.Title).LevenshteinDistance(_searchQueryWithoutYear) <= 1); - if (result != 0) return -result; + if (result != 0) + { + return -result; + } // Compare prefix matches by year "(CSI: ..." result = CompareWithYear(x, y, s => s.Title.ToLowerInvariant().StartsWith(_searchQueryWithoutYear + ":")); - if (result != 0) return -result; + if (result != 0) + { + return -result; + } return Compare(x, y, s => SearchQuery.LevenshteinDistanceClean(s.Title) - GetYearFactor(s)); } @@ -79,7 +94,10 @@ public int CompareWithYear(Movie x, Movie y, Predicate<Movie> canMatch) if (_year.HasValue) { var result = Compare(x, y, s => s.Year == _year.Value); - if (result != 0) return result; + if (result != 0) + { + return result; + } } return Compare(x, y, s => s.Year); @@ -117,7 +135,7 @@ private int GetYearFactor(Movie movie) var offset = Math.Abs(movie.Year - _year.Value); if (offset <= 1) { - return 20 - 10 * offset; + return 20 - (10 * offset); } } diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ConfigurationResource.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ConfigurationResource.cs index 07c5ce01d0..f04bc38e13 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ConfigurationResource.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/ConfigurationResource.cs @@ -1,6 +1,5 @@ namespace NzbDrone.Core.MetadataSource.SkyHook.Resource { - public class ConfigResource { public Images images { get; set; } @@ -17,5 +16,4 @@ public class Images public string[] profile_sizes { get; set; } public string[] still_sizes { get; set; } } - } diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/MovieResource.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/MovieResource.cs index 5319bb202f..2ede0ad866 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/MovieResource.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/MovieResource.cs @@ -1,19 +1,19 @@ namespace NzbDrone.Core.MetadataSource.SkyHook.Resource { public class ImdbResource - { - public int v { get; set; } - public string q { get; set; } - public MovieResource[] d { get; set; } - } + { + public int v { get; set; } + public string q { get; set; } + public MovieResource[] d { get; set; } + } - public class MovieResource - { - public string l { get; set; } - public string id { get; set; } - public string s { get; set; } - public int y { get; set; } - public string q { get; set; } - public object[] i { get; set; } - } + public class MovieResource + { + public string l { get; set; } + public string id { get; set; } + public string s { get; set; } + public int y { get; set; } + public string q { get; set; } + public object[] i { get; set; } + } } diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/TMDBResources.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/TMDBResources.cs index cad37f8e26..6c4c3c4761 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/TMDBResources.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/Resource/TMDBResources.cs @@ -2,11 +2,11 @@ namespace NzbDrone.Core.MetadataSource.SkyHook.Resource { - public class FindRoot { public MovieResult[] movie_results { get; set; } } + public class MovieSearchRoot { public int page { get; set; } @@ -37,7 +37,6 @@ public class MovieResult public string physical_release_note { get; set; } } - public class MovieResourceRoot { public bool adult { get; set; } @@ -173,5 +172,4 @@ public class Item : MovieResult public string name { get; set; } public string original_name { get; set; } } - } diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookException.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookException.cs index a9591fd6bf..aabfe757f9 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookException.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookException.cs @@ -5,7 +5,8 @@ namespace NzbDrone.Core.MetadataSource.SkyHook { public class SkyHookException : NzbDroneClientException { - public SkyHookException(string message) : base(HttpStatusCode.ServiceUnavailable, message) + public SkyHookException(string message) + : base(HttpStatusCode.ServiceUnavailable, message) { } diff --git a/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookProxy.cs b/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookProxy.cs index e471eaa6a0..6dc182a925 100644 --- a/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookProxy.cs +++ b/src/NzbDrone.Core/MetadataSource/SkyHook/SkyHookProxy.cs @@ -1,24 +1,24 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Net; +using System.Threading; using NLog; using NzbDrone.Common.Cloud; using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.Exceptions; -using NzbDrone.Core.MediaCover; -using NzbDrone.Core.MetadataSource.SkyHook.Resource; -using NzbDrone.Core.MetadataSource.PreDB; -using NzbDrone.Core.Movies; -using System.Threading; -using NzbDrone.Core.Parser; using NzbDrone.Core.Languages; -using NzbDrone.Core.Profiles; -using NzbDrone.Core.NetImport.ImportExclusions; +using NzbDrone.Core.MediaCover; +using NzbDrone.Core.MetadataSource.PreDB; using NzbDrone.Core.MetadataSource.RadarrAPI; +using NzbDrone.Core.MetadataSource.SkyHook.Resource; +using NzbDrone.Core.Movies; using NzbDrone.Core.Movies.AlternativeTitles; -using System.Globalization; +using NzbDrone.Core.NetImport.ImportExclusions; +using NzbDrone.Core.Parser; +using NzbDrone.Core.Profiles; namespace NzbDrone.Core.MetadataSource.SkyHook { @@ -35,8 +35,15 @@ public class SkyHookProxy : IProvideMovieInfo, ISearchForNewMovie, IDiscoverNewM private readonly IAlternativeTitleService _altTitleService; private readonly IRadarrAPIClient _radarrAPI; - public SkyHookProxy(IHttpClient httpClient, IRadarrCloudRequestBuilder requestBuilder, ITmdbConfigService configService, IMovieService movieService, - IPreDBService predbService, IImportExclusionsService exclusionService, IAlternativeTitleService altTitleService, IRadarrAPIClient radarrAPI, Logger logger) + public SkyHookProxy(IHttpClient httpClient, + IRadarrCloudRequestBuilder requestBuilder, + ITmdbConfigService configService, + IMovieService movieService, + IPreDBService predbService, + IImportExclusionsService exclusionService, + IAlternativeTitleService altTitleService, + IRadarrAPIClient radarrAPI, + Logger logger) { _httpClient = httpClient; _movieBuilder = requestBuilder.TMDB; @@ -50,7 +57,7 @@ public SkyHookProxy(IHttpClient httpClient, IRadarrCloudRequestBuilder requestBu _logger = logger; } - public HashSet<int> GetChangedMovies (DateTime startTime) + public HashSet<int> GetChangedMovies(DateTime startTime) { var startDate = startTime.ToString("o"); @@ -69,16 +76,17 @@ public HashSet<int> GetChangedMovies (DateTime startTime) return new HashSet<int>(response.Resource.results.Select(c => c.id)); } - public Movie GetMovieInfo(int TmdbId, Profile profile = null, bool hasPreDBEntry = false) + public Movie GetMovieInfo(int tmdbId, Profile profile = null, bool hasPreDBEntry = false) { var langCode = profile != null ? IsoLanguages.Get(profile.Language)?.TwoLetterCode ?? "en" : "en"; var request = _movieBuilder.Create() .SetSegment("route", "movie") - .SetSegment("id", TmdbId.ToString()) + .SetSegment("id", tmdbId.ToString()) .SetSegment("secondaryRoute", "") .AddQueryParam("append_to_response", "alternative_titles,release_dates,videos") .AddQueryParam("language", langCode.ToUpper()) + // .AddQueryParam("country", "US") .Build(); @@ -91,6 +99,7 @@ public Movie GetMovieInfo(int TmdbId, Profile profile = null, bool hasPreDBEntry { throw new MovieNotFoundException("Movie not found."); } + if (response.StatusCode != HttpStatusCode.OK) { throw new HttpException(request, response); @@ -104,7 +113,6 @@ public Movie GetMovieInfo(int TmdbId, Profile profile = null, bool hasPreDBEntry // The dude abides, so should us, Lets be nice to TMDb // var allowed = int.Parse(response.Headers.GetValues("X-RateLimit-Limit").First()); // get allowed // var reset = long.Parse(response.Headers.GetValues("X-RateLimit-Reset").First()); // get time when it resets - if (response.Headers.ContainsKey("X-RateLimit-Remaining")) { var remaining = int.Parse(response.Headers.GetValues("X-RateLimit-Remaining").First()); @@ -120,7 +128,7 @@ public Movie GetMovieInfo(int TmdbId, Profile profile = null, bool hasPreDBEntry { if (resource.status_code == 34) { - _logger.Warn("Movie with TmdbId {0} could not be found. This is probably the case when the movie was deleted from TMDB.", TmdbId); + _logger.Warn("Movie with TmdbId {0} could not be found. This is probably the case when the movie was deleted from TMDB.", tmdbId); return null; } @@ -136,7 +144,7 @@ public Movie GetMovieInfo(int TmdbId, Profile profile = null, bool hasPreDBEntry var iso = IsoLanguages.Find(resource.original_language); if (iso != null) { - altTitles.Add(new AlternativeTitle(resource.original_title, SourceType.TMDB, TmdbId, iso.Language)); + altTitles.Add(new AlternativeTitle(resource.original_title, SourceType.TMDB, tmdbId, iso.Language)); } } @@ -144,15 +152,15 @@ public Movie GetMovieInfo(int TmdbId, Profile profile = null, bool hasPreDBEntry { if (alternativeTitle.iso_3166_1.ToLower() == langCode) { - altTitles.Add(new AlternativeTitle(alternativeTitle.title, SourceType.TMDB, TmdbId, IsoLanguages.Find(alternativeTitle.iso_3166_1.ToLower())?.Language ?? Language.English)); + altTitles.Add(new AlternativeTitle(alternativeTitle.title, SourceType.TMDB, tmdbId, IsoLanguages.Find(alternativeTitle.iso_3166_1.ToLower())?.Language ?? Language.English)); } else if (alternativeTitle.iso_3166_1.ToLower() == "us") { - altTitles.Add(new AlternativeTitle(alternativeTitle.title, SourceType.TMDB, TmdbId, Language.English)); + altTitles.Add(new AlternativeTitle(alternativeTitle.title, SourceType.TMDB, tmdbId, Language.English)); } } - movie.TmdbId = TmdbId; + movie.TmdbId = tmdbId; movie.ImdbId = resource.imdb_id; movie.Title = resource.title; movie.TitleSlug = Parser.Parser.ToUrlSlug(resource.title); @@ -174,12 +182,13 @@ public Movie GetMovieInfo(int TmdbId, Profile profile = null, bool hasPreDBEntry lowestYear.Add(DateTime.Parse(releaseDate.release_date).Year); } } + movie.Year = lowestYear.Min(); } movie.TitleSlug += "-" + movie.TmdbId.ToString(); - movie.Images.Add(_configService.GetCoverForURL(resource.poster_path, MediaCoverTypes.Poster));//TODO: Update to load image specs from tmdb page! + movie.Images.Add(_configService.GetCoverForURL(resource.poster_path, MediaCoverTypes.Poster)); //TODO: Update to load image specs from tmdb page! movie.Images.Add(_configService.GetCoverForURL(resource.backdrop_path, MediaCoverTypes.Fanart)); movie.Runtime = resource.runtime; @@ -187,10 +196,9 @@ public Movie GetMovieInfo(int TmdbId, Profile profile = null, bool hasPreDBEntry //{ // movie.AlternativeTitles.Add(title.title); //} - - foreach(ReleaseDates releaseDates in resource.release_dates.results) + foreach (ReleaseDates releaseDates in resource.release_dates.results) { - foreach(ReleaseDate releaseDate in releaseDates.release_dates) + foreach (ReleaseDate releaseDate in releaseDates.release_dates) { if (releaseDate.type == 5 || releaseDate.type == 4) { @@ -215,32 +223,43 @@ public Movie GetMovieInfo(int TmdbId, Profile profile = null, bool hasPreDBEntry movie.Ratings.Votes = resource.vote_count; movie.Ratings.Value = (decimal)resource.vote_average; - foreach(Genre genre in resource.genres) + foreach (Genre genre in resource.genres) { movie.Genres.Add(genre.name); } var now = DateTime.Now; + //handle the case when we have both theatrical and physical release dates if (movie.InCinemas.HasValue && movie.PhysicalRelease.HasValue) { if (now < movie.InCinemas) + { movie.Status = MovieStatusType.Announced; + } else if (now >= movie.InCinemas) + { movie.Status = MovieStatusType.InCinemas; + } + if (now >= movie.PhysicalRelease) + { movie.Status = MovieStatusType.Released; + } } + //handle the case when we have theatrical release dates but we dont know the physical release date else if (movie.InCinemas.HasValue && (now >= movie.InCinemas)) { movie.Status = MovieStatusType.InCinemas; } + //handle the case where we only have a physical release date else if (movie.PhysicalRelease.HasValue && (now >= movie.PhysicalRelease)) { movie.Status = MovieStatusType.Released; } + //otherwise the title has only been announced else { @@ -248,7 +267,7 @@ public Movie GetMovieInfo(int TmdbId, Profile profile = null, bool hasPreDBEntry } //since TMDB lacks alot of information lets assume that stuff is released if its been in cinemas for longer than 3 months. - if (!movie.PhysicalRelease.HasValue && (movie.Status == MovieStatusType.InCinemas) && (((DateTime.Now).Subtract(movie.InCinemas.Value)).TotalSeconds > 60*60*24*30*3)) + if (!movie.PhysicalRelease.HasValue && (movie.Status == MovieStatusType.InCinemas) && (DateTime.Now.Subtract(movie.InCinemas.Value).TotalSeconds > 60 * 60 * 24 * 30 * 3)) { movie.Status = MovieStatusType.Released; } @@ -303,8 +322,8 @@ public Movie GetMovieInfo(string imdbId) .Build(); request.AllowAutoRedirect = true; - // request.SuppressHttpError = true; + // request.SuppressHttpError = true; var response = _httpClient.Get<FindRoot>(request); if (response.HasHttpError) @@ -376,13 +395,15 @@ public List<Movie> DiscoverNewMovies(string action) private string StripTrailingTheFromTitle(string title) { - if(title.EndsWith(",the")) + if (title.EndsWith(",the")) { title = title.Substring(0, title.Length - 4); - } else if(title.EndsWith(", the")) + } + else if (title.EndsWith(", the")) { title = title.Substring(0, title.Length - 5); } + return title; } @@ -417,7 +438,6 @@ public List<Movie> SearchForNewMovie(string title) { return new List<Movie>(); } - } } @@ -450,7 +470,7 @@ public List<Movie> SearchForNewMovie(string title) int tmdbid = -1; - if (slug.IsNullOrWhiteSpace() || slug.Any(char.IsWhiteSpace) || !(int.TryParse(slug, out tmdbid))) + if (slug.IsNullOrWhiteSpace() || slug.Any(char.IsWhiteSpace) || !int.TryParse(slug, out tmdbid)) { return new List<Movie>(); } @@ -530,29 +550,38 @@ public Movie MapMovie(MovieResult result) _logger.Debug("Not a valid date time."); } - - var now = DateTime.Now; + //handle the case when we have both theatrical and physical release dates if (imdbMovie.InCinemas.HasValue && imdbMovie.PhysicalRelease.HasValue) { if (now < imdbMovie.InCinemas) + { imdbMovie.Status = MovieStatusType.Announced; + } else if (now >= imdbMovie.InCinemas) + { imdbMovie.Status = MovieStatusType.InCinemas; + } + if (now >= imdbMovie.PhysicalRelease) + { imdbMovie.Status = MovieStatusType.Released; + } } + //handle the case when we have theatrical release dates but we dont know the physical release date else if (imdbMovie.InCinemas.HasValue && (now >= imdbMovie.InCinemas)) { imdbMovie.Status = MovieStatusType.InCinemas; } + //handle the case where we only have a physical release date else if (imdbMovie.PhysicalRelease.HasValue && (now >= imdbMovie.PhysicalRelease)) { imdbMovie.Status = MovieStatusType.Released; } + //otherwise the title has only been announced else { @@ -560,7 +589,7 @@ public Movie MapMovie(MovieResult result) } //since TMDB lacks alot of information lets assume that stuff is released if its been in cinemas for longer than 3 months. - if (!imdbMovie.PhysicalRelease.HasValue && (imdbMovie.Status == MovieStatusType.InCinemas) && (((DateTime.Now).Subtract(imdbMovie.InCinemas.Value)).TotalSeconds > 60 * 60 * 24 * 30 * 3)) + if (!imdbMovie.PhysicalRelease.HasValue && (imdbMovie.Status == MovieStatusType.InCinemas) && (DateTime.Now.Subtract(imdbMovie.InCinemas.Value).TotalSeconds > 60 * 60 * 24 * 30 * 3)) { imdbMovie.Status = MovieStatusType.Released; } @@ -569,7 +598,7 @@ public Movie MapMovie(MovieResult result) imdbMovie.Images = new List<MediaCover.MediaCover>(); imdbMovie.Overview = result.overview; - imdbMovie.Ratings = new Ratings { Value = (decimal)result.vote_average, Votes = result.vote_count}; + imdbMovie.Ratings = new Ratings { Value = (decimal)result.vote_average, Votes = result.vote_count }; try { @@ -587,7 +616,6 @@ public Movie MapMovie(MovieResult result) { imdbMovie.YouTubeTrailerId = result.trailer_key; } - } return imdbMovie; @@ -661,7 +689,7 @@ public Movie MapMovieToTmdbMovie(Movie movie) { try { - Movie newMovie = movie; + Movie newMovie = movie; if (movie.TmdbId > 0) { newMovie = GetMovieInfo(movie.TmdbId); @@ -677,6 +705,7 @@ public Movie MapMovieToTmdbMovie(Movie movie) { yearStr = $" {movie.Year}"; } + newMovie = SearchForNewMovie(movie.Title + yearStr).FirstOrDefault(); } @@ -699,7 +728,7 @@ public Movie MapMovieToTmdbMovie(Movie movie) catch (Exception ex) { _logger.Warn(ex, "Couldn't map movie {0} to a movie on The Movie DB. It will not be added :(", movie.Title); - return null; + return null; } } } diff --git a/src/NzbDrone.Core/MetadataSource/TmdbConfigurationService.cs b/src/NzbDrone.Core/MetadataSource/TmdbConfigurationService.cs index be72c81fdd..4cead20ed6 100644 --- a/src/NzbDrone.Core/MetadataSource/TmdbConfigurationService.cs +++ b/src/NzbDrone.Core/MetadataSource/TmdbConfigurationService.cs @@ -1,8 +1,8 @@ using System.Linq; -using NzbDrone.Core.MediaCover; using NzbDrone.Common.Cache; -using NzbDrone.Common.Http; using NzbDrone.Common.Cloud; +using NzbDrone.Common.Http; +using NzbDrone.Core.MediaCover; using NzbDrone.Core.MetadataSource.SkyHook.Resource; namespace NzbDrone.Core.MetadataSource @@ -12,7 +12,7 @@ public interface ITmdbConfigService MediaCover.MediaCover GetCoverForURL(string url, MediaCover.MediaCoverTypes type); } - class TmdbConfigService : ITmdbConfigService + internal class TmdbConfigService : ITmdbConfigService { private readonly ICached<ConfigResource> _configurationCache; private readonly IHttpClient _httpClient; diff --git a/src/NzbDrone.Core/Movies/AlternativeTitles/AlternativeTitle.cs b/src/NzbDrone.Core/Movies/AlternativeTitles/AlternativeTitle.cs index 6930bddf7e..07c7db2921 100644 --- a/src/NzbDrone.Core/Movies/AlternativeTitles/AlternativeTitle.cs +++ b/src/NzbDrone.Core/Movies/AlternativeTitles/AlternativeTitle.cs @@ -1,7 +1,7 @@ using Marr.Data; using NzbDrone.Core.Datastore; -using NzbDrone.Core.Parser; using NzbDrone.Core.Languages; +using NzbDrone.Core.Parser; namespace NzbDrone.Core.Movies.AlternativeTitles { @@ -19,7 +19,6 @@ public class AlternativeTitle : ModelBase public AlternativeTitle() { - } public AlternativeTitle(string title, SourceType sourceType = SourceType.TMDB, int sourceId = 0, Language language = null) @@ -51,7 +50,7 @@ public override bool Equals(object obj) return false; } - return item.CleanTitle == this.CleanTitle; + return item.CleanTitle == CleanTitle; } public override int GetHashCode() @@ -59,7 +58,7 @@ public override int GetHashCode() return CleanTitle.GetHashCode(); } - public override String ToString() + public override string ToString() { return Title; } diff --git a/src/NzbDrone.Core/Movies/AlternativeTitles/AlternativeTitleService.cs b/src/NzbDrone.Core/Movies/AlternativeTitles/AlternativeTitleService.cs index 1b4fc197f6..8df5706d8f 100644 --- a/src/NzbDrone.Core/Movies/AlternativeTitles/AlternativeTitleService.cs +++ b/src/NzbDrone.Core/Movies/AlternativeTitles/AlternativeTitleService.cs @@ -1,9 +1,9 @@ -using NLog; -using NzbDrone.Core.Configuration; -using NzbDrone.Core.Messaging.Events; using System.Collections.Generic; using System.Linq; +using NLog; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Configuration; +using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Movies.Events; namespace NzbDrone.Core.Movies.AlternativeTitles @@ -25,7 +25,6 @@ public class AlternativeTitleService : IAlternativeTitleService, IHandleAsync<Mo private readonly IEventAggregator _eventAggregator; private readonly Logger _logger; - public AlternativeTitleService(IAlternativeTitleRepository titleRepo, IEventAggregator eventAggregator, IConfigService configService, @@ -73,10 +72,13 @@ public void RemoveTitle(AlternativeTitle title) public List<AlternativeTitle> UpdateTitles(List<AlternativeTitle> titles, Movie movie) { int movieId = movie.Id; + // First update the movie ids so we can correlate them later. titles.ForEach(t => t.MovieId = movieId); + // Then make sure none of them are the same as the main title. titles = titles.Where(t => t.CleanTitle != movie.CleanTitle).ToList(); + // Then make sure they are all distinct titles titles = titles.DistinctBy(t => t.CleanTitle).ToList(); @@ -98,7 +100,6 @@ public void HandleAsync(MovieDeletedEvent message) { var title = GetAllTitlesForMovie(message.Movie.Id); _titleRepo.DeleteMany(title); - } } } diff --git a/src/NzbDrone.Core/Movies/Movie.cs b/src/NzbDrone.Core/Movies/Movie.cs index 2ecf68b7d4..60eecceb15 100644 --- a/src/NzbDrone.Core/Movies/Movie.cs +++ b/src/NzbDrone.Core/Movies/Movie.cs @@ -3,9 +3,9 @@ using Marr.Data; using NzbDrone.Common.Extensions; using NzbDrone.Core.Datastore; -using NzbDrone.Core.Profiles; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.Movies.AlternativeTitles; +using NzbDrone.Core.Profiles; namespace NzbDrone.Core.Movies { @@ -19,6 +19,7 @@ public Movie() Tags = new HashSet<int>(); AlternativeTitles = new List<AlternativeTitle>(); } + public int TmdbId { get; set; } public string ImdbId { get; set; } public string Title { get; set; } @@ -45,18 +46,19 @@ public Movie() public DateTime Added { get; set; } public DateTime? InCinemas { get; set; } public DateTime? PhysicalRelease { get; set; } - public String PhysicalReleaseNote { get; set; } + public string PhysicalReleaseNote { get; set; } public LazyLoaded<Profile> Profile { get; set; } public HashSet<int> Tags { get; set; } public AddMovieOptions AddOptions { get; set; } public MovieFile MovieFile { get; set; } public bool HasPreDBEntry { get; set; } public int MovieFileId { get; set; } + //Get Loaded via a Join Query public List<AlternativeTitle> AlternativeTitles { get; set; } public int? SecondaryYear { get; set; } public int SecondaryYearSourceId { get; set; } - public string YouTubeTrailerId{ get; set; } + public string YouTubeTrailerId { get; set; } public string Studio { get; set; } public bool IsRecentMovie @@ -85,6 +87,7 @@ public string FolderName() { return ""; } + //Well what about Path = Null? //return new DirectoryInfo(Path).Name; return Path; @@ -96,24 +99,29 @@ public bool IsAvailable(int delay = 0) //return (Status >= MinimumAvailability || (MinimumAvailability == MovieStatusType.PreDB && Status >= MovieStatusType.Released)); //This more complex sequence handles the delay - DateTime MinimumAvailabilityDate; + DateTime minimumAvailabilityDate; switch (MinimumAvailability) { case MovieStatusType.TBA: case MovieStatusType.Announced: - MinimumAvailabilityDate = DateTime.MinValue; + minimumAvailabilityDate = DateTime.MinValue; break; case MovieStatusType.InCinemas: if (InCinemas.HasValue) - MinimumAvailabilityDate = InCinemas.Value; + { + minimumAvailabilityDate = InCinemas.Value; + } else - MinimumAvailabilityDate = DateTime.MaxValue; + { + minimumAvailabilityDate = DateTime.MaxValue; + } + break; case MovieStatusType.Released: case MovieStatusType.PreDB: default: - MinimumAvailabilityDate = PhysicalRelease.HasValue ? PhysicalRelease.Value : (InCinemas.HasValue ? InCinemas.Value.AddDays(90) : DateTime.MaxValue); + minimumAvailabilityDate = PhysicalRelease.HasValue ? PhysicalRelease.Value : (InCinemas.HasValue ? InCinemas.Value.AddDays(90) : DateTime.MaxValue); break; } @@ -122,13 +130,12 @@ public bool IsAvailable(int delay = 0) return true; } - if (MinimumAvailabilityDate == DateTime.MinValue || MinimumAvailabilityDate == DateTime.MaxValue) + if (minimumAvailabilityDate == DateTime.MinValue || minimumAvailabilityDate == DateTime.MaxValue) { - return DateTime.Now >= MinimumAvailabilityDate; + return DateTime.Now >= minimumAvailabilityDate; } - - return DateTime.Now >= MinimumAvailabilityDate.AddDays((double)delay); + return DateTime.Now >= minimumAvailabilityDate.AddDays((double)delay); } public DateTime PhysicalReleaseDate() diff --git a/src/NzbDrone.Core/Movies/MovieRepository.cs b/src/NzbDrone.Core/Movies/MovieRepository.cs index 619d42b190..b76bca4897 100644 --- a/src/NzbDrone.Core/Movies/MovieRepository.cs +++ b/src/NzbDrone.Core/Movies/MovieRepository.cs @@ -1,11 +1,11 @@ using System; -using System.Linq; using System.Collections.Generic; -using NzbDrone.Core.Datastore; -using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Datastore.Extensions; +using System.Linq; using Marr.Data.QGen; +using NzbDrone.Core.Datastore; +using NzbDrone.Core.Datastore.Extensions; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Movies.AlternativeTitles; using NzbDrone.Core.Parser.RomanNumerals; using NzbDrone.Core.Qualities; @@ -78,16 +78,16 @@ public Movie FindByTitleSlug(string slug) public List<Movie> MoviesBetweenDates(DateTime start, DateTime end, bool includeUnmonitored) { - var query = Query.Where(m => - (m.InCinemas >= start && m.InCinemas <= end) || - (m.PhysicalRelease >= start && m.PhysicalRelease <= end)); + var query = Query.Where(m => + (m.InCinemas >= start && m.InCinemas <= end) || + (m.PhysicalRelease >= start && m.PhysicalRelease <= end)); - if (!includeUnmonitored) - { - query.AndWhere(e => e.Monitored == true); - } + if (!includeUnmonitored) + { + query.AndWhere(e => e.Monitored == true); + } - return query.ToList(); + return query.ToList(); } public List<Movie> MoviesWithFiles(int movieId) @@ -216,9 +216,12 @@ public Movie FindByPath(string path) protected override QueryBuilder<TActual> AddJoinQueries<TActual>(QueryBuilder<TActual> baseQuery) { baseQuery = base.AddJoinQueries(baseQuery); - baseQuery = baseQuery.Join<Movie, AlternativeTitle>(JoinType.Left, m => m.AlternativeTitles, + baseQuery = baseQuery.Join<Movie, AlternativeTitle>(JoinType.Left, + m => m.AlternativeTitles, (m, t) => m.Id == t.MovieId); - baseQuery = baseQuery.Join<Movie, MovieFile>(JoinType.Left, m => m.MovieFile, (m, f) => m.Id == f.MovieId); + baseQuery = baseQuery.Join<Movie, MovieFile>(JoinType.Left, + m => m.MovieFile, + (m, f) => m.Id == f.MovieId); return baseQuery; } diff --git a/src/NzbDrone.Core/Movies/MovieScannedHandler.cs b/src/NzbDrone.Core/Movies/MovieScannedHandler.cs index 6432681709..8e16efd318 100644 --- a/src/NzbDrone.Core/Movies/MovieScannedHandler.cs +++ b/src/NzbDrone.Core/Movies/MovieScannedHandler.cs @@ -1,22 +1,21 @@ -using NLog; +using System.Collections.Generic; +using NLog; using NzbDrone.Core.IndexerSearch; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; -using System.Collections.Generic; namespace NzbDrone.Core.Movies { public class MovieScannedHandler : IHandle<MovieScannedEvent>, IHandle<MovieScanSkippedEvent> { - private readonly IMovieService _movieService; private readonly IManageCommandQueue _commandQueueManager; private readonly Logger _logger; - public MovieScannedHandler( IMovieService movieService, + public MovieScannedHandler(IMovieService movieService, IManageCommandQueue commandQueueManager, Logger logger) { @@ -34,8 +33,8 @@ private void HandleScanEvents(Movie movie) } _logger.Info("[{0}] was recently added, performing post-add actions", movie.Title); - //_episodeMonitoredService.SetEpisodeMonitoredStatus(movie, movie.AddOptions); + //_episodeMonitoredService.SetEpisodeMonitoredStatus(movie, movie.AddOptions); if (movie.AddOptions.SearchForMovie) { _commandQueueManager.Push(new MoviesSearchCommand { MovieIds = new List<int> { movie.Id } }); diff --git a/src/NzbDrone.Core/Movies/MovieService.cs b/src/NzbDrone.Core/Movies/MovieService.cs index 16b17bdb09..4488f39ffb 100644 --- a/src/NzbDrone.Core/Movies/MovieService.cs +++ b/src/NzbDrone.Core/Movies/MovieService.cs @@ -5,15 +5,15 @@ using NLog; using NzbDrone.Common.EnsureThat; using NzbDrone.Common.Extensions; -using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Organizer; -using NzbDrone.Core.Parser; +using NzbDrone.Core.Configuration; +using NzbDrone.Core.Datastore; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.Events; -using NzbDrone.Core.Datastore; -using NzbDrone.Core.Configuration; +using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Movies.Events; using NzbDrone.Core.NetImport.ImportExclusions; +using NzbDrone.Core.Organizer; +using NzbDrone.Core.Parser; namespace NzbDrone.Core.Movies { @@ -45,7 +45,7 @@ public interface IMovieService bool MoviePathExists(string folder); void RemoveAddOptions(Movie movie); List<Movie> MoviesWithFiles(int movieId); - System.Linq.Expressions.Expression<Func<Movie, bool>> ConstructFilterExpression(string FilterKey, string FilterValue, string filterType = null); + System.Linq.Expressions.Expression<Func<Movie, bool>> ConstructFilterExpression(string filterKey, string filterValue, string filterType = null); } public class MovieService : IMovieService, IHandle<MovieFileAddedEvent>, @@ -73,24 +73,23 @@ public MovieService(IMovieRepository movieRepository, _logger = logger; } - - public System.Linq.Expressions.Expression<Func<Movie, bool>> ConstructFilterExpression(string FilterKey, string FilterValue, string FilterType = null) + public System.Linq.Expressions.Expression<Func<Movie, bool>> ConstructFilterExpression(string filterKey, string filterValue, string filterType = null) { //if (FilterKey == "all" && FilterValue == "all") //{ // return v => v.Monitored == true || v.Monitored == false; //} - if (FilterKey == "monitored" && FilterValue == "false") + if (filterKey == "monitored" && filterValue == "false") { return v => v.Monitored == false; } - else if (FilterKey == "monitored" && FilterValue == "true") + else if (filterKey == "monitored" && filterValue == "true") { return v => v.Monitored == true; } - else if (FilterKey == "status") + else if (filterKey == "status") { - switch (FilterValue) + switch (filterValue) { case "released": return v => v.Status == MovieStatusType.Released; @@ -103,31 +102,32 @@ public System.Linq.Expressions.Expression<Func<Movie, bool>> ConstructFilterExpr ((v.MinimumAvailability == MovieStatusType.Released && v.Status >= MovieStatusType.Released) || (v.MinimumAvailability == MovieStatusType.InCinemas && v.Status >= MovieStatusType.InCinemas) || (v.MinimumAvailability == MovieStatusType.Announced && v.Status >= MovieStatusType.Announced) || - (v.MinimumAvailability == MovieStatusType.PreDB && v.Status >= MovieStatusType.Released || v.HasPreDBEntry == true)); + ((v.MinimumAvailability == MovieStatusType.PreDB && v.Status >= MovieStatusType.Released) || v.HasPreDBEntry == true)); } } - else if (FilterKey == "downloaded") + else if (filterKey == "downloaded") { return v => v.MovieFileId == 0; } - else if (FilterKey == "title") + else if (filterKey == "title") { - if (FilterValue == string.Empty || FilterValue == null) + if (filterValue == string.Empty || filterValue == null) { return v => true; } else { - if (FilterType == "contains") + if (filterType == "contains") { - return v => v.CleanTitle.Contains(FilterValue); + return v => v.CleanTitle.Contains(filterValue); } else { - return v => v.CleanTitle == FilterValue; + return v => v.CleanTitle == filterValue; } } } + return v => true; } @@ -155,6 +155,7 @@ public Movie AddMovie(Movie newMovie) { defaultState = MoviePathState.Dynamic; } + if (string.IsNullOrWhiteSpace(newMovie.Path)) { var folderName = _fileNameBuilder.GetMovieFolder(newMovie); @@ -184,11 +185,12 @@ public List<Movie> AddMovies(List<Movie> newMovies) newMovies.ForEach(m => { - MoviePathState defaultState = MoviePathState.Static; + MoviePathState defaultState = MoviePathState.Static; if (!_configService.PathsDefaultStatic) { defaultState = MoviePathState.Dynamic; } + if (string.IsNullOrWhiteSpace(m.Path)) { var folderName = _fileNameBuilder.GetMovieFolder(m); @@ -246,6 +248,7 @@ private List<Movie> FindByTitleInexactAll(string title) // no movie matched return list; } + // build ordered list of movie by position in the search string var query = list.Select(movie => new @@ -254,7 +257,7 @@ private List<Movie> FindByTitleInexactAll(string title) length = movie.CleanTitle.Length, movie = movie }) - .Where(s => (s.position>=0)) + .Where(s => (s.position >= 0)) .ToList() .OrderBy(s => s.position) .ThenByDescending(s => s.length) @@ -267,6 +270,7 @@ private List<Movie> FindByTitleInexactAll(string title) public Movie FindByTitleInexact(string title) { var query = FindByTitleInexactAll(title); + // get the leftmost movie that is the longest // movie are usually the first thing in release title, so we select the leftmost and longest match var match = query.First(); @@ -276,6 +280,7 @@ public Movie FindByTitleInexact(string title) { _logger.Debug("Multiple movie match candidate: {0} cleantitle: {1}", entry.Title, entry.CleanTitle); } + return match; } @@ -299,8 +304,9 @@ public void DeleteMovie(int movieId, bool deleteFiles, bool addExclusion = false var movie = _movieRepository.Get(movieId); if (addExclusion) { - _exclusionService.AddExclusion(new ImportExclusion {TmdbId = movie.TmdbId, MovieTitle = movie.Title, MovieYear = movie.Year } ); + _exclusionService.AddExclusion(new ImportExclusion { TmdbId = movie.TmdbId, MovieTitle = movie.Title, MovieYear = movie.Year }); } + _movieRepository.Delete(movieId); _eventAggregator.PublishEvent(new MovieDeletedEvent(movie, deleteFiles)); _logger.Info("Deleted movie {}", movie); @@ -339,7 +345,6 @@ public List<Movie> UpdateMovie(List<Movie> movie) s.Path = Path.Combine(s.RootFolderPath, folderName); _logger.Trace("Changing path for {0} to {1}", s.Title, s.Path); } - else { _logger.Trace("Not changing path for: {0}", s.Title); @@ -367,6 +372,7 @@ public void Handle(MovieFileAddedEvent message) var movie = message.MovieFile.Movie.Value; movie.MovieFileId = message.MovieFile.Id; _movieRepository.Update(movie); + //_movieRepository.SetFileId(message.MovieFile.Id, message.MovieFile.Movie.Value.Id); _logger.Info("Linking [{0}] > [{1}]", message.MovieFile.RelativePath, message.MovieFile.Movie.Value); } @@ -379,7 +385,6 @@ public void SetFileId(Movie movie, MovieFile movieFile) public void Handle(MovieFileDeletedEvent message) { - var movie = _movieRepository.GetMoviesByFileId(message.MovieFile.Id).First(); movie.MovieFileId = 0; _logger.Debug("Detaching movie {0} from file.", movie.Id); diff --git a/src/NzbDrone.Core/Movies/MovieStatusType.cs b/src/NzbDrone.Core/Movies/MovieStatusType.cs index f45ecb5f09..2e856e0b54 100644 --- a/src/NzbDrone.Core/Movies/MovieStatusType.cs +++ b/src/NzbDrone.Core/Movies/MovieStatusType.cs @@ -6,6 +6,6 @@ public enum MovieStatusType Announced = 1, //Movie is announced but Cinema date is in the future or unknown InCinemas = 2, //Been in Cinemas for less than 3 months (since TMDB lacks complete information) Released = 3, //Physical or Web Release or been in cinemas for > 3 months (since TMDB lacks complete information) - PreDB = 4 //this is only used for MinimumAvailability. Movie items should never be in this state. + PreDB = 4 //this is only used for MinimumAvailability. Movie items should never be in this state. } } diff --git a/src/NzbDrone.Core/Movies/MovieTitleNormalizer.cs b/src/NzbDrone.Core/Movies/MovieTitleNormalizer.cs index c5ca9edaf5..7b43027086 100644 --- a/src/NzbDrone.Core/Movies/MovieTitleNormalizer.cs +++ b/src/NzbDrone.Core/Movies/MovieTitleNormalizer.cs @@ -4,7 +4,7 @@ namespace NzbDrone.Core.Movies { public static class MovieTitleNormalizer { - private readonly static Dictionary<int, string> PreComputedTitles = new Dictionary<int, string> + private static readonly Dictionary<int, string> PreComputedTitles = new Dictionary<int, string> { { 999999999, "a to z" }, }; diff --git a/src/NzbDrone.Core/Movies/RefreshMovieService.cs b/src/NzbDrone.Core/Movies/RefreshMovieService.cs index 9498c60cc5..19807fcc14 100644 --- a/src/NzbDrone.Core/Movies/RefreshMovieService.cs +++ b/src/NzbDrone.Core/Movies/RefreshMovieService.cs @@ -5,6 +5,7 @@ using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Common.Instrumentation.Extensions; + //using NzbDrone.Core.DataAugmentation.DailyMovie; using NzbDrone.Core.Configuration; using NzbDrone.Core.Exceptions; @@ -86,6 +87,7 @@ private void RefreshMovieInfo(Movie movie) movie.Certification = movieInfo.Certification; movie.InCinemas = movieInfo.InCinemas; movie.Website = movieInfo.Website; + //movie.AlternativeTitles = movieInfo.AlternativeTitles; movie.Year = movieInfo.Year; movie.PhysicalRelease = movieInfo.PhysicalRelease; @@ -134,12 +136,12 @@ private void RefreshMovieInfo(Movie movie) _logger.Info(ex, "Unable to communicate with Mappings Server."); } - _movieService.UpdateMovie(movie); try { var newTitles = movieInfo.AlternativeTitles.Except(movie.AlternativeTitles); + //_titleService.AddAltTitles(newTitles.ToList(), movie); } catch (Exception e) @@ -245,7 +247,6 @@ public void Execute(RefreshMovieCommand message) RescanMovie(movie, false, trigger); } - else { _logger.Info("Skipping refresh of movie: {0}", movie.Title); diff --git a/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoAPI.cs b/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoAPI.cs index bea66105d1..45ec3eed62 100644 --- a/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoAPI.cs +++ b/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoAPI.cs @@ -40,6 +40,7 @@ public class Info public bool? via_tmdb { get; set; } public string[] actors { get; set; } public string[] writers { get; set; } + //public int? runtime { get; set; } public string type { get; set; } public string released { get; set; } diff --git a/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoImport.cs b/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoImport.cs index 5da56d71ef..130eb11441 100644 --- a/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoImport.cs +++ b/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoImport.cs @@ -13,7 +13,8 @@ public class CouchPotatoImport : HttpNetImportBase<CouchPotatoSettings> public CouchPotatoImport(IHttpClient httpClient, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, configService, parsingService, logger) - { } + { + } public override INetImportRequestGenerator GetRequestGenerator() { diff --git a/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoParser.cs b/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoParser.cs index 2a5ff2d64e..bdbd399e62 100644 --- a/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoParser.cs +++ b/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoParser.cs @@ -1,9 +1,9 @@ -using Newtonsoft.Json; -using NzbDrone.Core.NetImport.Exceptions; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using System.Net; +using Newtonsoft.Json; using NzbDrone.Common.Extensions; +using NzbDrone.Core.NetImport.Exceptions; namespace NzbDrone.Core.NetImport.CouchPotato { @@ -92,6 +92,5 @@ protected virtual bool PreProcess(NetImportResponse indexerResponse) return true; } - } } diff --git a/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoRequestGenerator.cs b/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoRequestGenerator.cs index 2d3310c4da..10146a821b 100644 --- a/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoRequestGenerator.cs +++ b/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoRequestGenerator.cs @@ -1,5 +1,5 @@ -using NzbDrone.Common.Http; -using System.Collections.Generic; +using System.Collections.Generic; +using NzbDrone.Common.Http; namespace NzbDrone.Core.NetImport.CouchPotato { diff --git a/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoSettings.cs b/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoSettings.cs index c3cdd65f08..aa04cc1782 100644 --- a/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoSettings.cs +++ b/src/NzbDrone.Core/NetImport/CouchPotato/CouchPotatoSettings.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.NetImport.CouchPotato { - public class CouchPotatoSettingsValidator : AbstractValidator<CouchPotatoSettings> { public CouchPotatoSettingsValidator() @@ -48,5 +47,4 @@ public NzbDroneValidationResult Validate() return new NzbDroneValidationResult(Validator.Validate(this)); } } - } diff --git a/src/NzbDrone.Core/NetImport/HttpNetImportBase.cs b/src/NzbDrone.Core/NetImport/HttpNetImportBase.cs index 1447c55e13..d236c8daf3 100644 --- a/src/NzbDrone.Core/NetImport/HttpNetImportBase.cs +++ b/src/NzbDrone.Core/NetImport/HttpNetImportBase.cs @@ -7,10 +7,10 @@ using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; +using NzbDrone.Core.Movies; using NzbDrone.Core.NetImport.Exceptions; using NzbDrone.Core.Parser; using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.NetImport { @@ -102,10 +102,10 @@ protected virtual NetImportFetchResult FetchMovies(NetImportPageableRequestChain { anyFailure = true; feedEx.Data.Add("FeedUrl", url); - _logger.Error(feedEx, "An error occurred while processing list feed {0}", url); + _logger.Error(feedEx, "An error occurred while processing list feed {0}", url); } - return new NetImportFetchResult {Movies = movies, AnyFailure = anyFailure}; + return new NetImportFetchResult { Movies = movies, AnyFailure = anyFailure }; } protected virtual IList<Movie> FetchPage(NetImportRequest request, IParseNetImportResponse parser) @@ -114,11 +114,11 @@ protected virtual IList<Movie> FetchPage(NetImportRequest request, IParseNetImpo return parser.ParseResponse(response).ToList().Select(m => { - m.RootFolderPath = ((NetImportDefinition) Definition).RootFolderPath; - m.ProfileId = ((NetImportDefinition) Definition).ProfileId; - m.Monitored = ((NetImportDefinition) Definition).ShouldMonitor; - m.MinimumAvailability = ((NetImportDefinition) Definition).MinimumAvailability; - m.Tags = ((NetImportDefinition) Definition).Tags; + m.RootFolderPath = ((NetImportDefinition)Definition).RootFolderPath; + m.ProfileId = ((NetImportDefinition)Definition).ProfileId; + m.Monitored = ((NetImportDefinition)Definition).ShouldMonitor; + m.MinimumAvailability = ((NetImportDefinition)Definition).MinimumAvailability; + m.Tags = ((NetImportDefinition)Definition).Tags; return m; }).ToList(); } @@ -171,5 +171,4 @@ protected virtual ValidationFailure TestConnection() return null; } } - } diff --git a/src/NzbDrone.Core/NetImport/ImportExclusions/ImportExclusion.cs b/src/NzbDrone.Core/NetImport/ImportExclusions/ImportExclusion.cs index 7291971b4d..afbd6a0c89 100644 --- a/src/NzbDrone.Core/NetImport/ImportExclusions/ImportExclusion.cs +++ b/src/NzbDrone.Core/NetImport/ImportExclusions/ImportExclusion.cs @@ -8,7 +8,7 @@ public class ImportExclusion : ModelBase public string MovieTitle { get; set; } public int MovieYear { get; set; } - new public string ToString() + public new string ToString() { return string.Format("Excluded Movie: [{0}][{1} {2}]", TmdbId, MovieTitle, MovieYear); } diff --git a/src/NzbDrone.Core/NetImport/ImportExclusions/ImportExclusionsService.cs b/src/NzbDrone.Core/NetImport/ImportExclusions/ImportExclusionsService.cs index 46e44fed44..26452f599c 100644 --- a/src/NzbDrone.Core/NetImport/ImportExclusions/ImportExclusionsService.cs +++ b/src/NzbDrone.Core/NetImport/ImportExclusions/ImportExclusionsService.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; using NLog; -using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Configuration; +using NzbDrone.Core.Messaging.Events; namespace NzbDrone.Core.NetImport.ImportExclusions { @@ -22,7 +22,6 @@ public class ImportExclusionsService : IImportExclusionsService private readonly IEventAggregator _eventAggregator; private readonly Logger _logger; - public ImportExclusionsService(IImportExclusionsRepository exclusionRepository, IEventAggregator eventAggregator, IConfigService configService, @@ -40,6 +39,7 @@ public ImportExclusion AddExclusion(ImportExclusion exclusion) { return _exclusionRepository.GetByTmdbid(exclusion.TmdbId); } + return _exclusionRepository.Insert(exclusion); } diff --git a/src/NzbDrone.Core/NetImport/NetImportBase.cs b/src/NzbDrone.Core/NetImport/NetImportBase.cs index 2345d46aa0..a12fcab84f 100644 --- a/src/NzbDrone.Core/NetImport/NetImportBase.cs +++ b/src/NzbDrone.Core/NetImport/NetImportBase.cs @@ -3,9 +3,9 @@ using FluentValidation.Results; using NLog; using NzbDrone.Core.Configuration; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser; using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.NetImport { @@ -47,7 +47,7 @@ public virtual IEnumerable<ProviderDefinition> DefaultDefinitions yield return new NetImportDefinition { - Name = this.Name, + Name = Name, Enabled = config.Validate().IsValid && Enabled, EnableAuto = true, ProfileId = 1, @@ -60,7 +60,10 @@ public virtual IEnumerable<ProviderDefinition> DefaultDefinitions public virtual ProviderDefinition Definition { get; set; } - public virtual object RequestAction(string action, IDictionary<string, string> query) { return null; } + public virtual object RequestAction(string action, IDictionary<string, string> query) + { + return null; + } protected TSettings Settings => (TSettings)Definition.Settings; @@ -87,6 +90,5 @@ public override string ToString() { return Definition.Name; } - } } diff --git a/src/NzbDrone.Core/NetImport/NetImportDefinition.cs b/src/NzbDrone.Core/NetImport/NetImportDefinition.cs index d08b71b7fb..3804722461 100644 --- a/src/NzbDrone.Core/NetImport/NetImportDefinition.cs +++ b/src/NzbDrone.Core/NetImport/NetImportDefinition.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using Marr.Data; +using NzbDrone.Core.Movies; using NzbDrone.Core.Profiles; using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.NetImport { diff --git a/src/NzbDrone.Core/NetImport/NetImportPageableRequestChain.cs b/src/NzbDrone.Core/NetImport/NetImportPageableRequestChain.cs index 589c4844a8..9b2f5ca870 100644 --- a/src/NzbDrone.Core/NetImport/NetImportPageableRequestChain.cs +++ b/src/NzbDrone.Core/NetImport/NetImportPageableRequestChain.cs @@ -27,7 +27,10 @@ public IEnumerable<NetImportPageableRequest> GetTier(int index) public void Add(IEnumerable<NetImportRequest> request) { - if (request == null) return; + if (request == null) + { + return; + } _chains.Last().Add(new NetImportPageableRequest(request)); } @@ -40,7 +43,10 @@ public void AddTier(IEnumerable<NetImportRequest> request) public void AddTier() { - if (_chains.Last().Count == 0) return; + if (_chains.Last().Count == 0) + { + return; + } _chains.Add(new List<NetImportPageableRequest>()); } diff --git a/src/NzbDrone.Core/NetImport/NetImportRepository.cs b/src/NzbDrone.Core/NetImport/NetImportRepository.cs index 83ebded94b..77ccfa092a 100644 --- a/src/NzbDrone.Core/NetImport/NetImportRepository.cs +++ b/src/NzbDrone.Core/NetImport/NetImportRepository.cs @@ -2,7 +2,6 @@ using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.ThingiProvider; - namespace NzbDrone.Core.NetImport { public interface INetImportRepository : IProviderRepository<NetImportDefinition> diff --git a/src/NzbDrone.Core/NetImport/NetImportSearchService.cs b/src/NzbDrone.Core/NetImport/NetImportSearchService.cs index 0fc8d11adc..6862fc8a95 100644 --- a/src/NzbDrone.Core/NetImport/NetImportSearchService.cs +++ b/src/NzbDrone.Core/NetImport/NetImportSearchService.cs @@ -1,15 +1,15 @@ using System.Collections.Generic; using System.Linq; using NLog; -using NzbDrone.Core.Messaging.Commands; -using NzbDrone.Core.MetadataSource; -using NzbDrone.Core.RootFolders; -using NzbDrone.Core.Movies; -using NzbDrone.Core.Configuration; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Configuration; using NzbDrone.Core.Download; using NzbDrone.Core.IndexerSearch; +using NzbDrone.Core.Messaging.Commands; +using NzbDrone.Core.MetadataSource; +using NzbDrone.Core.Movies; using NzbDrone.Core.NetImport.ImportExclusions; +using NzbDrone.Core.RootFolders; namespace NzbDrone.Core.NetImport { @@ -31,10 +31,13 @@ public class NetImportSearchService : IFetchNetImport, IExecute<NetImportSyncCom private readonly IProcessDownloadDecisions _processDownloadDecisions; private readonly IImportExclusionsService _exclusionService; - - public NetImportSearchService(INetImportFactory netImportFactory, IMovieService movieService, - ISearchForNewMovie movieSearch, IRootFolderService rootFolder, ISearchForNzb nzbSearchService, - IProcessDownloadDecisions processDownloadDecisions, IConfigService configService, + public NetImportSearchService(INetImportFactory netImportFactory, + IMovieService movieService, + ISearchForNewMovie movieSearch, + IRootFolderService rootFolder, + ISearchForNzb nzbSearchService, + IProcessDownloadDecisions processDownloadDecisions, + IConfigService configService, IImportExclusionsService exclusionService, Logger logger) { @@ -49,7 +52,6 @@ public NetImportSearchService(INetImportFactory netImportFactory, IMovieService _configService = configService; } - public NetImportFetchResult Fetch(int listId, bool onlyEnableAuto = false) { return MovieListSearch(listId, onlyEnableAuto); @@ -105,12 +107,10 @@ public NetImportFetchResult MovieListSearch(int listId, bool onlyEnableAuto = fa }; } - - public void Execute(NetImportSyncCommand message) { //if there are no lists that are enabled for automatic import then dont do anything - if((_netImportFactory.GetAvailableProviders()).Where(a => ((NetImportDefinition)a.Definition).EnableAuto).Empty()) + if (_netImportFactory.GetAvailableProviders().Where(a => ((NetImportDefinition)a.Definition).EnableAuto).Empty()) { _logger.Info("No lists are enabled for auto-import."); return; @@ -182,8 +182,8 @@ private void CleanLibrary(List<Movie> movies) foundMatch = true; break; } - } + if (!foundMatch) { switch (_configService.ListSyncLevel) @@ -203,6 +203,7 @@ private void CleanLibrary(List<Movie> movies) case "removeAndDelete": _logger.Info("{0} was in your library, but not found in your lists --> Removing from library and deleting files", movie); _movieService.DeleteMovie(movie.Id, true); + //TODO: for some reason the files are not deleted in this case... any idea why? break; default: diff --git a/src/NzbDrone.Core/NetImport/NetImportSyncCommand.cs b/src/NzbDrone.Core/NetImport/NetImportSyncCommand.cs index 73a379bafe..02584e3486 100644 --- a/src/NzbDrone.Core/NetImport/NetImportSyncCommand.cs +++ b/src/NzbDrone.Core/NetImport/NetImportSyncCommand.cs @@ -4,9 +4,8 @@ namespace NzbDrone.Core.NetImport { public class NetImportSyncCommand : Command { - public override bool SendUpdatesToClient => true; - public int listId = 0; + public int ListId = 0; } } diff --git a/src/NzbDrone.Core/NetImport/RSSImport/RSSImport.cs b/src/NzbDrone.Core/NetImport/RSSImport/RSSImport.cs index b5e16c57c6..06dcd6f3d0 100644 --- a/src/NzbDrone.Core/NetImport/RSSImport/RSSImport.cs +++ b/src/NzbDrone.Core/NetImport/RSSImport/RSSImport.cs @@ -15,7 +15,8 @@ public class RSSImport : HttpNetImportBase<RSSImportSettings> public RSSImport(IHttpClient httpClient, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, configService, parsingService, logger) - { } + { + } public override IEnumerable<ProviderDefinition> DefaultDefinitions { @@ -25,6 +26,7 @@ public override IEnumerable<ProviderDefinition> DefaultDefinitions { yield return def; } + yield return new NetImportDefinition { Name = "IMDb List", diff --git a/src/NzbDrone.Core/NetImport/RSSImport/RSSImportParser.cs b/src/NzbDrone.Core/NetImport/RSSImport/RSSImportParser.cs index 3aa2ba9eac..0e1df0b9cc 100644 --- a/src/NzbDrone.Core/NetImport/RSSImport/RSSImportParser.cs +++ b/src/NzbDrone.Core/NetImport/RSSImport/RSSImportParser.cs @@ -1,6 +1,4 @@ -using NzbDrone.Core.NetImport.Exceptions; -using NzbDrone.Core.Movies; -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -13,6 +11,8 @@ using NzbDrone.Common.Http; using NzbDrone.Core.Indexers; using NzbDrone.Core.Indexers.Exceptions; +using NzbDrone.Core.Movies; +using NzbDrone.Core.NetImport.Exceptions; namespace NzbDrone.Core.NetImport.RSSImport { @@ -128,7 +128,6 @@ protected Movie ProcessItem(XElement item) releaseInfo = ProcessItem(item, releaseInfo); //_logger.Trace("Parsed: {0}", releaseInfo.Title); - return PostProcess(item, releaseInfo); } @@ -143,7 +142,7 @@ protected virtual Movie ProcessItem(XElement item, Movie releaseInfo) } releaseInfo.Title = title; - var result = Parser.Parser.ParseMovieTitle(title, false);//Depreciated anyways + var result = Parser.Parser.ParseMovieTitle(title, false); //Depreciated anyways if (result != null) { @@ -158,7 +157,6 @@ protected virtual Movie ProcessItem(XElement item, Movie releaseInfo) { releaseInfo.ImdbId = GetImdbId(item); } - } catch (Exception) { @@ -197,6 +195,7 @@ protected virtual string GetImdbId(XElement item) { return ""; } + return Parser.Parser.ParseImdbId(url); } diff --git a/src/NzbDrone.Core/NetImport/RSSImport/RSSImportRequestGenerator.cs b/src/NzbDrone.Core/NetImport/RSSImport/RSSImportRequestGenerator.cs index 04adc0163e..9f59da5d40 100644 --- a/src/NzbDrone.Core/NetImport/RSSImport/RSSImportRequestGenerator.cs +++ b/src/NzbDrone.Core/NetImport/RSSImport/RSSImportRequestGenerator.cs @@ -20,7 +20,6 @@ public virtual NetImportPageableRequestChain GetMovies() //{ // return new NetImportPageableRequestChain(); //} - private IEnumerable<NetImportRequest> GetMovies(string searchParameters) { var request = new NetImportRequest($"{Settings.Link.Trim()}", HttpAccept.Rss); diff --git a/src/NzbDrone.Core/NetImport/Radarr/RadarrLists.cs b/src/NzbDrone.Core/NetImport/Radarr/RadarrLists.cs index f5b7347928..e0ec2bc070 100644 --- a/src/NzbDrone.Core/NetImport/Radarr/RadarrLists.cs +++ b/src/NzbDrone.Core/NetImport/Radarr/RadarrLists.cs @@ -2,10 +2,9 @@ using NLog; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; +using NzbDrone.Core.MetadataSource; using NzbDrone.Core.Parser; using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.MetadataSource; - namespace NzbDrone.Core.NetImport.Radarr { @@ -17,7 +16,10 @@ public class RadarrLists : HttpNetImportBase<RadarrSettings> private readonly ISearchForNewMovie _skyhookProxy; - public RadarrLists(IHttpClient httpClient, IConfigService configService, IParsingService parsingService, ISearchForNewMovie skyhookProxy, + public RadarrLists(IHttpClient httpClient, + IConfigService configService, + IParsingService parsingService, + ISearchForNewMovie skyhookProxy, Logger logger) : base(httpClient, configService, parsingService, logger) { diff --git a/src/NzbDrone.Core/NetImport/Radarr/RadarrParser.cs b/src/NzbDrone.Core/NetImport/Radarr/RadarrParser.cs index 8a4b99570b..fad9f082e4 100644 --- a/src/NzbDrone.Core/NetImport/Radarr/RadarrParser.cs +++ b/src/NzbDrone.Core/NetImport/Radarr/RadarrParser.cs @@ -1,22 +1,22 @@ -using Newtonsoft.Json; -using System.Collections.Generic; +using System.Collections.Generic; +using Newtonsoft.Json; using NzbDrone.Common.Extensions; -using NzbDrone.Core.MetadataSource.SkyHook.Resource; +using NzbDrone.Common.Http; using NzbDrone.Core.MetadataSource; using NzbDrone.Core.MetadataSource.RadarrAPI; -using NzbDrone.Common.Http; +using NzbDrone.Core.MetadataSource.SkyHook.Resource; namespace NzbDrone.Core.NetImport.Radarr { public class RadarrParser : IParseNetImportResponse { private readonly RadarrSettings _settings; - private NetImportResponse _importResponse; private readonly ISearchForNewMovie _skyhookProxy; + private NetImportResponse _importResponse; public RadarrParser(RadarrSettings settings, ISearchForNewMovie skyhookProxy) { - _skyhookProxy = skyhookProxy;//TinyIoC.TinyIoCContainer.Current.Resolve<ISearchForNewMovie>(); + _skyhookProxy = skyhookProxy; _settings = settings; } @@ -40,8 +40,6 @@ public RadarrParser(RadarrSettings settings, ISearchForNewMovie skyhookProxy) } return jsonResponse.SelectList(_skyhookProxy.MapMovie); - - } protected virtual bool PreProcess(NetImportResponse indexerResponse) @@ -60,7 +58,6 @@ protected virtual bool PreProcess(NetImportResponse indexerResponse) //No error! } - if (indexerResponse.HttpResponse.StatusCode != System.Net.HttpStatusCode.OK) { throw new HttpException(indexerResponse.HttpRequest, indexerResponse.HttpResponse); @@ -68,6 +65,5 @@ protected virtual bool PreProcess(NetImportResponse indexerResponse) return true; } - } } diff --git a/src/NzbDrone.Core/NetImport/Radarr/RadarrRequestGenerator.cs b/src/NzbDrone.Core/NetImport/Radarr/RadarrRequestGenerator.cs index 11ce376eec..60dbab9ad7 100644 --- a/src/NzbDrone.Core/NetImport/Radarr/RadarrRequestGenerator.cs +++ b/src/NzbDrone.Core/NetImport/Radarr/RadarrRequestGenerator.cs @@ -1,8 +1,8 @@ using System; -using NzbDrone.Common.Http; using System.Collections.Generic; using NLog; using NzbDrone.Common.Extensions; +using NzbDrone.Common.Http; namespace NzbDrone.Core.NetImport.Radarr { diff --git a/src/NzbDrone.Core/NetImport/Radarr/RadarrSettings.cs b/src/NzbDrone.Core/NetImport/Radarr/RadarrSettings.cs index 9ce34e3f27..cee94ad98b 100644 --- a/src/NzbDrone.Core/NetImport/Radarr/RadarrSettings.cs +++ b/src/NzbDrone.Core/NetImport/Radarr/RadarrSettings.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.NetImport.Radarr { - public class RadarrSettingsValidator : AbstractValidator<RadarrSettings> { public RadarrSettingsValidator() @@ -35,5 +34,4 @@ public NzbDroneValidationResult Validate() return new NzbDroneValidationResult(Validator.Validate(this)); } } - } diff --git a/src/NzbDrone.Core/NetImport/StevenLu/StevenLuImport.cs b/src/NzbDrone.Core/NetImport/StevenLu/StevenLuImport.cs index 643d4dd4ad..8ec74b9ca8 100644 --- a/src/NzbDrone.Core/NetImport/StevenLu/StevenLuImport.cs +++ b/src/NzbDrone.Core/NetImport/StevenLu/StevenLuImport.cs @@ -13,7 +13,8 @@ public class StevenLuImport : HttpNetImportBase<StevenLuSettings> public StevenLuImport(IHttpClient httpClient, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClient, configService, parsingService, logger) - { } + { + } public override INetImportRequestGenerator GetRequestGenerator() { diff --git a/src/NzbDrone.Core/NetImport/StevenLu/StevenLuParser.cs b/src/NzbDrone.Core/NetImport/StevenLu/StevenLuParser.cs index eb9a8d8cad..47d6e9862a 100644 --- a/src/NzbDrone.Core/NetImport/StevenLu/StevenLuParser.cs +++ b/src/NzbDrone.Core/NetImport/StevenLu/StevenLuParser.cs @@ -1,8 +1,8 @@ -using Newtonsoft.Json; -using NzbDrone.Core.NetImport.Exceptions; -using System.Collections.Generic; +using System.Collections.Generic; using System.Net; +using Newtonsoft.Json; using NzbDrone.Common.Extensions; +using NzbDrone.Core.NetImport.Exceptions; namespace NzbDrone.Core.NetImport.StevenLu { @@ -62,6 +62,5 @@ protected virtual bool PreProcess(NetImportResponse indexerResponse) return true; } - } } diff --git a/src/NzbDrone.Core/NetImport/StevenLu/StevenLuRequestGenerator.cs b/src/NzbDrone.Core/NetImport/StevenLu/StevenLuRequestGenerator.cs index d117279f5c..4d44e3e698 100644 --- a/src/NzbDrone.Core/NetImport/StevenLu/StevenLuRequestGenerator.cs +++ b/src/NzbDrone.Core/NetImport/StevenLu/StevenLuRequestGenerator.cs @@ -1,5 +1,5 @@ -using NzbDrone.Common.Http; -using System.Collections.Generic; +using System.Collections.Generic; +using NzbDrone.Common.Http; namespace NzbDrone.Core.NetImport.StevenLu { diff --git a/src/NzbDrone.Core/NetImport/StevenLu/StevenLuSettings.cs b/src/NzbDrone.Core/NetImport/StevenLu/StevenLuSettings.cs index 89fcdd488f..cbc8c2c676 100644 --- a/src/NzbDrone.Core/NetImport/StevenLu/StevenLuSettings.cs +++ b/src/NzbDrone.Core/NetImport/StevenLu/StevenLuSettings.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.NetImport.StevenLu { - public class StevenLuSettingsValidator : AbstractValidator<StevenLuSettings> { public StevenLuSettingsValidator() @@ -30,7 +29,5 @@ public NzbDroneValidationResult Validate() { return new NzbDroneValidationResult(Validator.Validate(this)); } - } - } diff --git a/src/NzbDrone.Core/NetImport/TMDb/TMDbImport.cs b/src/NzbDrone.Core/NetImport/TMDb/TMDbImport.cs index 53af40df1b..ec32da5f32 100644 --- a/src/NzbDrone.Core/NetImport/TMDb/TMDbImport.cs +++ b/src/NzbDrone.Core/NetImport/TMDb/TMDbImport.cs @@ -4,7 +4,6 @@ using NzbDrone.Core.MetadataSource; using NzbDrone.Core.Parser; - namespace NzbDrone.Core.NetImport.TMDb { public class TMDbImport : HttpNetImportBase<TMDbSettings> @@ -15,7 +14,10 @@ public class TMDbImport : HttpNetImportBase<TMDbSettings> private readonly ISearchForNewMovie _skyhookProxy; - public TMDbImport(IHttpClient httpClient, IConfigService configService, IParsingService parsingService, ISearchForNewMovie skyhookProxy, + public TMDbImport(IHttpClient httpClient, + IConfigService configService, + IParsingService parsingService, + ISearchForNewMovie skyhookProxy, Logger logger) : base(httpClient, configService, parsingService, logger) { diff --git a/src/NzbDrone.Core/NetImport/TMDb/TMDbParser.cs b/src/NzbDrone.Core/NetImport/TMDb/TMDbParser.cs index b0832b86b5..0f904df739 100644 --- a/src/NzbDrone.Core/NetImport/TMDb/TMDbParser.cs +++ b/src/NzbDrone.Core/NetImport/TMDb/TMDbParser.cs @@ -1,18 +1,18 @@ -using Newtonsoft.Json; -using NzbDrone.Core.NetImport.Exceptions; -using System.Collections.Generic; +using System.Collections.Generic; using System.Net; +using Newtonsoft.Json; using NzbDrone.Common.Extensions; -using NzbDrone.Core.MetadataSource.SkyHook.Resource; using NzbDrone.Core.MetadataSource; +using NzbDrone.Core.MetadataSource.SkyHook.Resource; +using NzbDrone.Core.NetImport.Exceptions; namespace NzbDrone.Core.NetImport.TMDb { public class TMDbParser : IParseNetImportResponse { private readonly TMDbSettings _settings; - private NetImportResponse _importResponse; private readonly ISearchForNewMovie _skyhookProxy; + private NetImportResponse _importResponse; public TMDbParser(TMDbSettings settings, ISearchForNewMovie skyhookProxy) { @@ -71,7 +71,6 @@ public TMDbParser(TMDbSettings settings, ISearchForNewMovie skyhookProxy) } } - return movies; } @@ -90,6 +89,5 @@ protected virtual bool PreProcess(NetImportResponse indexerResponse) return true; } - } } diff --git a/src/NzbDrone.Core/NetImport/TMDb/TMDbRequestGenerator.cs b/src/NzbDrone.Core/NetImport/TMDb/TMDbRequestGenerator.cs index a7433b9b36..bba6cb3b03 100644 --- a/src/NzbDrone.Core/NetImport/TMDb/TMDbRequestGenerator.cs +++ b/src/NzbDrone.Core/NetImport/TMDb/TMDbRequestGenerator.cs @@ -1,8 +1,8 @@ using System; -using NzbDrone.Common.Http; using System.Collections.Generic; using NLog; using NzbDrone.Common.Extensions; +using NzbDrone.Common.Http; using NzbDrone.Common.Serializer; using NzbDrone.Core.MetadataSource.SkyHook.Resource; @@ -72,6 +72,7 @@ public virtual NetImportPageableRequestChain GetMovies() requestBuilder.Resource(tmdbParams); var request = requestBuilder + // .AddQueryParam("api_key", "1a7373301961d03f97f853a876dd1212") .Accept(HttpAccept.Json) .Build(); @@ -112,7 +113,6 @@ private IEnumerable<NetImportRequest> GetMovies(string tmdbParams, int totalPage Logger.Info($"Importing TMDb movies from: {baseUrl}"); yield return new NetImportRequest($"{baseUrl}", HttpAccept.Json); } - } } } diff --git a/src/NzbDrone.Core/NetImport/TMDb/TMDbSettings.cs b/src/NzbDrone.Core/NetImport/TMDb/TMDbSettings.cs index c1d4dbcb03..e76c46a798 100644 --- a/src/NzbDrone.Core/NetImport/TMDb/TMDbSettings.cs +++ b/src/NzbDrone.Core/NetImport/TMDb/TMDbSettings.cs @@ -1,13 +1,12 @@ -using FluentValidation; +using System.Text.RegularExpressions; +using FluentValidation; using NzbDrone.Common.Extensions; using NzbDrone.Core.Annotations; using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Validation; -using System.Text.RegularExpressions; namespace NzbDrone.Core.NetImport.TMDb { - public class TMDbSettingsValidator : AbstractValidator<TMDbSettings> { public TMDbSettingsValidator() @@ -49,7 +48,6 @@ public TMDbSettingsValidator() .Matches(@"^\d+([,|]\d+)*$", RegexOptions.IgnoreCase) .When(c => c.ExcludeGenreIds.IsNotNullOrWhiteSpace()) .WithMessage("Genre Ids must be comma (,) or pipe (|) separated number ids"); - } } @@ -98,5 +96,4 @@ public NzbDroneValidationResult Validate() return new NzbDroneValidationResult(Validator.Validate(this)); } } - } diff --git a/src/NzbDrone.Core/NetImport/Trakt/TraktImport.cs b/src/NzbDrone.Core/NetImport/Trakt/TraktImport.cs index f161a2ab8e..695e777032 100644 --- a/src/NzbDrone.Core/NetImport/Trakt/TraktImport.cs +++ b/src/NzbDrone.Core/NetImport/Trakt/TraktImport.cs @@ -1,10 +1,10 @@ -using NLog; +using System; +using System.Collections.Generic; +using NLog; using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; using NzbDrone.Core.Parser; using NzbDrone.Core.Validation; -using System; -using System.Collections.Generic; namespace NzbDrone.Core.NetImport.Trakt { @@ -57,7 +57,6 @@ private void RefreshToken() { _logger.Warn($"Error refreshing trakt access token"); } - } public override INetImportRequestGenerator GetRequestGenerator() @@ -70,7 +69,7 @@ public override INetImportRequestGenerator GetRequestGenerator() RefreshToken(); } - return new TraktRequestGenerator() { Settings = Settings, _configService=_configService, HttpClient = _httpClient, }; + return new TraktRequestGenerator() { Settings = Settings, _configService = _configService, HttpClient = _httpClient, }; } public override IParseNetImportResponse GetParser() diff --git a/src/NzbDrone.Core/NetImport/Trakt/TraktParser.cs b/src/NzbDrone.Core/NetImport/Trakt/TraktParser.cs index 206af10937..72bde7be5a 100644 --- a/src/NzbDrone.Core/NetImport/Trakt/TraktParser.cs +++ b/src/NzbDrone.Core/NetImport/Trakt/TraktParser.cs @@ -1,8 +1,8 @@ -using Newtonsoft.Json; -using NzbDrone.Core.NetImport.Exceptions; -using System.Collections.Generic; +using System.Collections.Generic; using System.Net; +using Newtonsoft.Json; using NzbDrone.Common.Extensions; +using NzbDrone.Core.NetImport.Exceptions; namespace NzbDrone.Core.NetImport.Trakt { @@ -27,7 +27,7 @@ public TraktParser(TraktSettings settings) return movies; } - if (_settings.ListType == (int) TraktListType.Popular) + if (_settings.ListType == (int)TraktListType.Popular) { var jsonResponse = JsonConvert.DeserializeObject<List<Movie>>(_importResponse.Content); @@ -38,7 +38,7 @@ public TraktParser(TraktSettings settings) Title = movie.title, ImdbId = movie.ids.imdb, TmdbId = movie.ids.tmdb, - Year = (movie.year ?? 0) + Year = movie.year ?? 0 }); } } @@ -59,13 +59,12 @@ public TraktParser(TraktSettings settings) Title = movie.movie.title, ImdbId = movie.movie.ids.imdb, TmdbId = movie.movie.ids.tmdb, - Year = (movie.movie.year ?? 0) + Year = movie.movie.year ?? 0 }); } } return movies; - } protected virtual bool PreProcess(NetImportResponse indexerResponse) @@ -83,6 +82,5 @@ protected virtual bool PreProcess(NetImportResponse indexerResponse) return true; } - } } diff --git a/src/NzbDrone.Core/NetImport/Trakt/TraktRequestGenerator.cs b/src/NzbDrone.Core/NetImport/Trakt/TraktRequestGenerator.cs index c870390ebe..85b1d18fb5 100644 --- a/src/NzbDrone.Core/NetImport/Trakt/TraktRequestGenerator.cs +++ b/src/NzbDrone.Core/NetImport/Trakt/TraktRequestGenerator.cs @@ -1,9 +1,8 @@ -using NzbDrone.Common.Http; -using System.Collections.Generic; +using System.Collections.Generic; using NzbDrone.Common.Extensions; +using NzbDrone.Common.Http; using NzbDrone.Core.Configuration; - namespace NzbDrone.Core.NetImport.Trakt { public class RefreshRequestResponse @@ -24,6 +23,7 @@ public class TraktRequestGenerator : INetImportRequestGenerator public TraktRequestGenerator() { } + public virtual NetImportPageableRequestChain GetMovies() { var pageableRequests = new NetImportPageableRequestChain(); diff --git a/src/NzbDrone.Core/NetImport/Trakt/TraktSettings.cs b/src/NzbDrone.Core/NetImport/Trakt/TraktSettings.cs index b4fa9074d4..7f189f09e3 100644 --- a/src/NzbDrone.Core/NetImport/Trakt/TraktSettings.cs +++ b/src/NzbDrone.Core/NetImport/Trakt/TraktSettings.cs @@ -1,14 +1,13 @@ -using FluentValidation; +using System; +using System.Text.RegularExpressions; +using FluentValidation; using NzbDrone.Common.Extensions; using NzbDrone.Core.Annotations; using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Validation; -using System; -using System.Text.RegularExpressions; namespace NzbDrone.Core.NetImport.Trakt { - public class TraktSettingsValidator : AbstractValidator<TraktSettings> { public TraktSettingsValidator() @@ -51,6 +50,7 @@ public TraktSettingsValidator() // Limit not smaller than 1 and not larger than 100 RuleFor(c => c.Limit) .GreaterThan(0) + // .InclusiveBetween(1, 500) .WithMessage("Must be integer greater than 0"); } @@ -121,13 +121,9 @@ public TraktSettings() [FieldDefinition(99, Label = "Authenticate with Trakt", Type = FieldType.OAuth)] public string SignIn { get; set; } - public NzbDroneValidationResult Validate() { return new NzbDroneValidationResult(Validator.Validate(this)); } } - - - } diff --git a/src/NzbDrone.Core/Notifications/Boxcar/Boxcar.cs b/src/NzbDrone.Core/Notifications/Boxcar/Boxcar.cs index 248a075499..b2fc8ec1cd 100644 --- a/src/NzbDrone.Core/Notifications/Boxcar/Boxcar.cs +++ b/src/NzbDrone.Core/Notifications/Boxcar/Boxcar.cs @@ -23,7 +23,7 @@ public override void OnGrab(GrabMessage grabMessage) public override void OnDownload(DownloadMessage message) { - _proxy.SendNotification(MOVIE_DOWNLOADED_TITLE , message.Message, Settings); + _proxy.SendNotification(MOVIE_DOWNLOADED_TITLE, message.Message, Settings); } public override void OnHealthIssue(HealthCheck.HealthCheck message) diff --git a/src/NzbDrone.Core/Notifications/Boxcar/BoxcarException.cs b/src/NzbDrone.Core/Notifications/Boxcar/BoxcarException.cs index 139c3b1ab6..6108d4aab0 100644 --- a/src/NzbDrone.Core/Notifications/Boxcar/BoxcarException.cs +++ b/src/NzbDrone.Core/Notifications/Boxcar/BoxcarException.cs @@ -5,11 +5,13 @@ namespace NzbDrone.Core.Notifications.Boxcar { public class BoxcarException : NzbDroneException { - public BoxcarException(string message) : base(message) + public BoxcarException(string message) + : base(message) { } - public BoxcarException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public BoxcarException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Boxcar/BoxcarProxy.cs b/src/NzbDrone.Core/Notifications/Boxcar/BoxcarProxy.cs index bf0e848f7c..3bf8560d4c 100644 --- a/src/NzbDrone.Core/Notifications/Boxcar/BoxcarProxy.cs +++ b/src/NzbDrone.Core/Notifications/Boxcar/BoxcarProxy.cs @@ -2,9 +2,9 @@ using System.Net; using FluentValidation.Results; using NLog; -using RestSharp; -using NzbDrone.Core.Rest; using NzbDrone.Common.EnvironmentInfo; +using NzbDrone.Core.Rest; +using RestSharp; namespace NzbDrone.Core.Notifications.Boxcar { @@ -16,8 +16,8 @@ public interface IBoxcarProxy public class BoxcarProxy : IBoxcarProxy { - private readonly Logger _logger; private const string URL = "https://new.boxcar.io/api/notifications"; + private readonly Logger _logger; public BoxcarProxy(Logger logger) { diff --git a/src/NzbDrone.Core/Notifications/CustomScript/CustomScript.cs b/src/NzbDrone.Core/Notifications/CustomScript/CustomScript.cs index 4ccad0c375..f72bdb893f 100755 --- a/src/NzbDrone.Core/Notifications/CustomScript/CustomScript.cs +++ b/src/NzbDrone.Core/Notifications/CustomScript/CustomScript.cs @@ -8,8 +8,8 @@ using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; using NzbDrone.Common.Processes; -using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Movies; +using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Validation; namespace NzbDrone.Core.Notifications.CustomScript @@ -124,6 +124,7 @@ public override void OnHealthIssue(HealthCheck.HealthCheck healthCheck) ExecuteScript(environmentVariables); } + public override ValidationResult Test() { var failures = new List<ValidationFailure>(); diff --git a/src/NzbDrone.Core/Notifications/Discord/Discord.cs b/src/NzbDrone.Core/Notifications/Discord/Discord.cs index ddacbc63e7..cd44b65072 100644 --- a/src/NzbDrone.Core/Notifications/Discord/Discord.cs +++ b/src/NzbDrone.Core/Notifications/Discord/Discord.cs @@ -87,7 +87,6 @@ public ValidationFailure TestMessage() var payload = CreatePayload(message); _proxy.SendPayload(payload, Settings); - } catch (DiscordException ex) { diff --git a/src/NzbDrone.Core/Notifications/Discord/DiscordException.cs b/src/NzbDrone.Core/Notifications/Discord/DiscordException.cs index 1bc0d62940..79b2bbfaf2 100644 --- a/src/NzbDrone.Core/Notifications/Discord/DiscordException.cs +++ b/src/NzbDrone.Core/Notifications/Discord/DiscordException.cs @@ -3,13 +3,15 @@ namespace NzbDrone.Core.Notifications.Discord { - class DiscordException : NzbDroneException + public class DiscordException : NzbDroneException { - public DiscordException(string message) : base(message) + public DiscordException(string message) + : base(message) { } - public DiscordException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public DiscordException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Discord/DiscordProxy.cs b/src/NzbDrone.Core/Notifications/Discord/DiscordProxy.cs index 425364253c..37ecf794d6 100644 --- a/src/NzbDrone.Core/Notifications/Discord/DiscordProxy.cs +++ b/src/NzbDrone.Core/Notifications/Discord/DiscordProxy.cs @@ -34,7 +34,7 @@ public void SendPayload(DiscordPayload payload, DiscordSettings settings) request.Headers.ContentType = "application/json"; request.SetContent(payload.ToJson()); - _httpClient.Execute(request); + _httpClient.Execute(request); } catch (RestException ex) { diff --git a/src/NzbDrone.Core/Notifications/Discord/DiscordSettings.cs b/src/NzbDrone.Core/Notifications/Discord/DiscordSettings.cs index e4ba51571a..d986938241 100644 --- a/src/NzbDrone.Core/Notifications/Discord/DiscordSettings.cs +++ b/src/NzbDrone.Core/Notifications/Discord/DiscordSettings.cs @@ -26,7 +26,6 @@ public class DiscordSettings : IProviderConfig [FieldDefinition(2, Label = "Avatar", HelpText = "Change the avatar that is used for messages from this integration", Type = FieldType.Textbox)] public string Avatar { get; set; } - public NzbDroneValidationResult Validate() { return new NzbDroneValidationResult(Validator.Validate(this)); diff --git a/src/NzbDrone.Core/Notifications/Email/Email.cs b/src/NzbDrone.Core/Notifications/Email/Email.cs index 68f0777278..1dd7623c48 100644 --- a/src/NzbDrone.Core/Notifications/Email/Email.cs +++ b/src/NzbDrone.Core/Notifications/Email/Email.cs @@ -10,7 +10,6 @@ public class Email : NotificationBase<EmailSettings> public override string Name => "Email"; - public Email(IEmailService emailService) { _emailService = emailService; diff --git a/src/NzbDrone.Core/Notifications/Email/EmailService.cs b/src/NzbDrone.Core/Notifications/Email/EmailService.cs index d0cdbc497f..8f8f88a626 100644 --- a/src/NzbDrone.Core/Notifications/Email/EmailService.cs +++ b/src/NzbDrone.Core/Notifications/Email/EmailService.cs @@ -35,13 +35,15 @@ public void SendEmail(EmailSettings settings, string subject, string body, bool NetworkCredential credentials = null; if (!string.IsNullOrWhiteSpace(settings.Username)) + { credentials = new NetworkCredential(settings.Username, settings.Password); + } try { Send(email, settings.Server, settings.Port, settings.Ssl, credentials); } - catch(Exception ex) + catch (Exception ex) { _logger.Error("Error sending email. Subject: {0}", email.Subject); _logger.Debug(ex, ex.Message); diff --git a/src/NzbDrone.Core/Notifications/Gotify/GotifyPriority.cs b/src/NzbDrone.Core/Notifications/Gotify/GotifyPriority.cs index 8782d4dcd4..9a5f9c5dcf 100644 --- a/src/NzbDrone.Core/Notifications/Gotify/GotifyPriority.cs +++ b/src/NzbDrone.Core/Notifications/Gotify/GotifyPriority.cs @@ -1,5 +1,4 @@ namespace NzbDrone.Core.Notifications.Gotify - { public enum GotifyPriority { diff --git a/src/NzbDrone.Core/Notifications/Gotify/GotifyProxy.cs b/src/NzbDrone.Core/Notifications/Gotify/GotifyProxy.cs index b14b530d39..a6e711516c 100644 --- a/src/NzbDrone.Core/Notifications/Gotify/GotifyProxy.cs +++ b/src/NzbDrone.Core/Notifications/Gotify/GotifyProxy.cs @@ -1,5 +1,5 @@ -using RestSharp; using NzbDrone.Core.Rest; +using RestSharp; namespace NzbDrone.Core.Notifications.Gotify { diff --git a/src/NzbDrone.Core/Notifications/Gotify/InvalidResponseException.cs b/src/NzbDrone.Core/Notifications/Gotify/InvalidResponseException.cs index 0a4c20b4dd..acdc931f92 100644 --- a/src/NzbDrone.Core/Notifications/Gotify/InvalidResponseException.cs +++ b/src/NzbDrone.Core/Notifications/Gotify/InvalidResponseException.cs @@ -8,7 +8,8 @@ public InvalidResponseException() { } - public InvalidResponseException(string message) : base(message) + public InvalidResponseException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/Notifications/GrabMessage.cs b/src/NzbDrone.Core/Notifications/GrabMessage.cs index ecc25c4f17..0a6d6488fc 100644 --- a/src/NzbDrone.Core/Notifications/GrabMessage.cs +++ b/src/NzbDrone.Core/Notifications/GrabMessage.cs @@ -1,6 +1,6 @@ +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Notifications { diff --git a/src/NzbDrone.Core/Notifications/INotification.cs b/src/NzbDrone.Core/Notifications/INotification.cs index 07c5ee5884..ce589f6180 100644 --- a/src/NzbDrone.Core/Notifications/INotification.cs +++ b/src/NzbDrone.Core/Notifications/INotification.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Movies; +using NzbDrone.Core.Movies; +using NzbDrone.Core.ThingiProvider; namespace NzbDrone.Core.Notifications { diff --git a/src/NzbDrone.Core/Notifications/Join/JoinAuthException.cs b/src/NzbDrone.Core/Notifications/Join/JoinAuthException.cs index 92b9777222..12c55b2c38 100644 --- a/src/NzbDrone.Core/Notifications/Join/JoinAuthException.cs +++ b/src/NzbDrone.Core/Notifications/Join/JoinAuthException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Notifications.Join { public class JoinAuthException : JoinException { - public JoinAuthException(string message) : base(message) + public JoinAuthException(string message) + : base(message) { } - public JoinAuthException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public JoinAuthException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Join/JoinException.cs b/src/NzbDrone.Core/Notifications/Join/JoinException.cs index e0ad0e1c3c..18ef5e2f21 100644 --- a/src/NzbDrone.Core/Notifications/Join/JoinException.cs +++ b/src/NzbDrone.Core/Notifications/Join/JoinException.cs @@ -5,11 +5,13 @@ namespace NzbDrone.Core.Notifications.Join { public class JoinException : NzbDroneException { - public JoinException(string message) : base(message) + public JoinException(string message) + : base(message) { } - public JoinException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public JoinException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Join/JoinInvalidDeviceException.cs b/src/NzbDrone.Core/Notifications/Join/JoinInvalidDeviceException.cs index a6463abb4a..d79e989ecb 100644 --- a/src/NzbDrone.Core/Notifications/Join/JoinInvalidDeviceException.cs +++ b/src/NzbDrone.Core/Notifications/Join/JoinInvalidDeviceException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Notifications.Join { public class JoinInvalidDeviceException : JoinException { - public JoinInvalidDeviceException(string message) : base(message) + public JoinInvalidDeviceException(string message) + : base(message) { } - public JoinInvalidDeviceException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public JoinInvalidDeviceException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Join/JoinProxy.cs b/src/NzbDrone.Core/Notifications/Join/JoinProxy.cs index 2326fd5c69..d0d968ecb9 100644 --- a/src/NzbDrone.Core/Notifications/Join/JoinProxy.cs +++ b/src/NzbDrone.Core/Notifications/Join/JoinProxy.cs @@ -2,9 +2,9 @@ using FluentValidation.Results; using NLog; using NzbDrone.Common.Extensions; -using RestSharp; -using NzbDrone.Core.Rest; using NzbDrone.Common.Serializer; +using NzbDrone.Core.Rest; +using RestSharp; namespace NzbDrone.Core.Notifications.Join { @@ -16,8 +16,8 @@ public interface IJoinProxy public class JoinProxy : IJoinProxy { - private readonly Logger _logger; private const string URL = "https://joinjoaomgcd.appspot.com/_ah/api/messaging/v1/sendPush?"; + private readonly Logger _logger; public JoinProxy(Logger logger) { @@ -49,7 +49,7 @@ public ValidationFailure Test(JoinSettings settings) SendNotification(title, body, settings); return null; } - catch(JoinInvalidDeviceException ex) + catch (JoinInvalidDeviceException ex) { _logger.Error(ex, "Unable to send test Join message. Invalid Device IDs supplied."); return new ValidationFailure("DeviceIds", "Device IDs appear invalid."); @@ -59,7 +59,7 @@ public ValidationFailure Test(JoinSettings settings) _logger.Error(ex, "Unable to send test Join message."); return new ValidationFailure("ApiKey", ex.Message); } - catch(RestException ex) + catch (RestException ex) { _logger.Error(ex, "Unable to send test Join message. Server connection failed."); return new ValidationFailure("ApiKey", "Unable to connect to Join API. Please try again later."); @@ -73,7 +73,6 @@ public ValidationFailure Test(JoinSettings settings) private void SendNotification(string title, string message, RestRequest request, JoinSettings settings) { - var client = RestClientFactory.BuildClient(URL); if (settings.DeviceNames.IsNotNullOrWhiteSpace()) @@ -99,7 +98,10 @@ private void SendNotification(string title, string message, RestRequest request, var response = client.ExecuteAndValidate(request); var res = Json.Deserialize<JoinResponseModel>(response.Content); - if (res.success) return; + if (res.success) + { + return; + } if (res.userAuthError) { @@ -114,6 +116,7 @@ private void SendNotification(string title, string message, RestRequest request, { throw new JoinInvalidDeviceException(res.errorMessage); } + // Oddly enough, rather than give us an "Invalid API key", the Join API seems to assume the key is valid, // but fails when doing a device lookup associated with that key. // In our case we are using "deviceIds" rather than "deviceId" so when the singular form error shows up @@ -122,6 +125,7 @@ private void SendNotification(string title, string message, RestRequest request, { throw new JoinAuthException("Authentication failed."); } + throw new JoinException(res.errorMessage); } diff --git a/src/NzbDrone.Core/Notifications/Join/JoinSettings.cs b/src/NzbDrone.Core/Notifications/Join/JoinSettings.cs index 797e7230a3..db5c8550ab 100644 --- a/src/NzbDrone.Core/Notifications/Join/JoinSettings.cs +++ b/src/NzbDrone.Core/Notifications/Join/JoinSettings.cs @@ -16,7 +16,6 @@ public JoinSettingsValidator() public class JoinSettings : IProviderConfig { - public JoinSettings() { Priority = (int)JoinPriority.Normal; diff --git a/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowser.cs b/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowser.cs index 9b92dfb00d..fa6d1102a1 100644 --- a/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowser.cs +++ b/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowser.cs @@ -17,7 +17,6 @@ public MediaBrowser(IMediaBrowserService mediaBrowserService) public override string Link => "https://emby.media/"; public override string Name => "Emby"; - public override void OnGrab(GrabMessage grabMessage) { if (Settings.Notify) diff --git a/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserProxy.cs b/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserProxy.cs index 5042f9fc85..675d064357 100644 --- a/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserProxy.cs +++ b/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserProxy.cs @@ -22,11 +22,11 @@ public void Notify(MediaBrowserSettings settings, string title, string message) request.Headers.ContentType = "application/json"; request.SetContent(new - { - Name = title, - Description = message, - ImageUrl = "https://raw.github.com/Radarr/Radarr/develop/Logo/64.png" - }.ToJson()); + { + Name = title, + Description = message, + ImageUrl = "https://raw.github.com/Radarr/Radarr/develop/Logo/64.png" + }.ToJson()); ProcessRequest(request, settings); } diff --git a/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserService.cs b/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserService.cs index f7a42ccd37..62565a9b28 100644 --- a/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserService.cs +++ b/src/NzbDrone.Core/Notifications/MediaBrowser/MediaBrowserService.cs @@ -2,8 +2,8 @@ using System.Net; using FluentValidation.Results; using NLog; -using NzbDrone.Core.Rest; using NzbDrone.Core.Movies; +using NzbDrone.Core.Rest; namespace NzbDrone.Core.Notifications.Emby { diff --git a/src/NzbDrone.Core/Notifications/NotificationBase.cs b/src/NzbDrone.Core/Notifications/NotificationBase.cs index 7cc132d2bd..08841fdf0e 100644 --- a/src/NzbDrone.Core/Notifications/NotificationBase.cs +++ b/src/NzbDrone.Core/Notifications/NotificationBase.cs @@ -1,12 +1,13 @@ using System; using System.Collections.Generic; using FluentValidation.Results; -using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Movies; +using NzbDrone.Core.ThingiProvider; namespace NzbDrone.Core.Notifications { - public abstract class NotificationBase<TSettings> : INotification where TSettings : IProviderConfig, new() + public abstract class NotificationBase<TSettings> : INotification + where TSettings : IProviderConfig, new() { protected const string MOVIE_GRABBED_TITLE = "Movie Grabbed"; protected const string MOVIE_DOWNLOADED_TITLE = "Movie Downloaded"; @@ -31,22 +32,18 @@ namespace NzbDrone.Core.Notifications public virtual void OnGrab(GrabMessage grabMessage) { - } public virtual void OnDownload(DownloadMessage message) { - } public virtual void OnMovieRename(Movie movie) { - } public virtual void OnHealthIssue(HealthCheck.HealthCheck healthCheck) { - } public bool SupportsOnGrab => HasConcreteImplementation("OnGrab"); @@ -62,8 +59,10 @@ public override string ToString() return GetType().Name; } - public virtual object RequestAction(string action, IDictionary<string, string> query) { return null; } - + public virtual object RequestAction(string action, IDictionary<string, string> query) + { + return null; + } private bool HasConcreteImplementation(string methodName) { @@ -76,6 +75,5 @@ private bool HasConcreteImplementation(string methodName) return !method.DeclaringType.IsAbstract; } - } } diff --git a/src/NzbDrone.Core/Notifications/NotificationRepository.cs b/src/NzbDrone.Core/Notifications/NotificationRepository.cs index 6a67eb88ba..ccdaaf5413 100644 --- a/src/NzbDrone.Core/Notifications/NotificationRepository.cs +++ b/src/NzbDrone.Core/Notifications/NotificationRepository.cs @@ -2,12 +2,10 @@ using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.ThingiProvider; - namespace NzbDrone.Core.Notifications { public interface INotificationRepository : IProviderRepository<NotificationDefinition> { - } public class NotificationRepository : ProviderRepository<NotificationDefinition>, INotificationRepository diff --git a/src/NzbDrone.Core/Notifications/NotificationService.cs b/src/NzbDrone.Core/Notifications/NotificationService.cs index 99cedefc2b..302dff0454 100644 --- a/src/NzbDrone.Core/Notifications/NotificationService.cs +++ b/src/NzbDrone.Core/Notifications/NotificationService.cs @@ -6,9 +6,9 @@ using NzbDrone.Core.HealthCheck; using NzbDrone.Core.MediaFiles.Events; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Movies; using NzbDrone.Core.Qualities; using NzbDrone.Core.ThingiProvider; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Notifications { @@ -17,7 +17,6 @@ public class NotificationService IHandle<MovieGrabbedEvent>, IHandle<MovieDownloadedEvent>, IHandle<HealthCheckFailedEvent> - { private readonly INotificationFactory _notificationFactory; private readonly Logger _logger; @@ -31,18 +30,18 @@ public NotificationService(INotificationFactory notificationFactory, Logger logg private string GetMessage(Movie movie, QualityModel quality) { var qualityString = quality.Quality.ToString(); - var ImdbUrl = "https://www.imdb.com/title/" + movie.ImdbId + "/"; + var imdbUrl = "https://www.imdb.com/title/" + movie.ImdbId + "/"; if (quality.Revision.Version > 1) { - qualityString += " Proper"; + qualityString += " Proper"; } return string.Format("{0} ({1}) [{2}] {3}", movie.Title, movie.Year, qualityString, - ImdbUrl); + imdbUrl); } private bool ShouldHandleMovie(ProviderDefinition definition, Movie movie) @@ -95,10 +94,13 @@ public void Handle(MovieGrabbedEvent message) { try { - if (!ShouldHandleMovie(notification.Definition, message.Movie.Movie)) continue; + if (!ShouldHandleMovie(notification.Definition, message.Movie.Movie)) + { + continue; + } + notification.OnGrab(grabMessage); } - catch (Exception ex) { _logger.Error(ex, "Unable to send OnGrab notification to {0}", notification.Definition.Name); @@ -128,7 +130,6 @@ public void Handle(MovieDownloadedEvent message) } } } - catch (Exception ex) { _logger.Warn(ex, "Unable to send OnDownload notification to: " + notification.Definition.Name); @@ -147,7 +148,6 @@ public void Handle(MovieRenamedEvent message) notification.OnMovieRename(message.Movie); } } - catch (Exception ex) { _logger.Warn(ex, "Unable to send OnRename notification to: " + notification.Definition.Name); @@ -166,7 +166,6 @@ public void Handle(HealthCheckFailedEvent message) notification.OnHealthIssue(message.HealthCheck); } } - catch (Exception ex) { _logger.Warn(ex, "Unable to send OnHealthIssue notification to: " + notification.Definition.Name); diff --git a/src/NzbDrone.Core/Notifications/NotifyMyAndroid/NotifyMyAndroid.cs b/src/NzbDrone.Core/Notifications/NotifyMyAndroid/NotifyMyAndroid.cs index f0780642fe..a23c83998f 100644 --- a/src/NzbDrone.Core/Notifications/NotifyMyAndroid/NotifyMyAndroid.cs +++ b/src/NzbDrone.Core/Notifications/NotifyMyAndroid/NotifyMyAndroid.cs @@ -1,4 +1,3 @@ - using System.Collections.Generic; using FluentValidation.Results; using NzbDrone.Common.Extensions; diff --git a/src/NzbDrone.Core/Notifications/NotifyMyAndroid/NotifyMyAndroidProxy.cs b/src/NzbDrone.Core/Notifications/NotifyMyAndroid/NotifyMyAndroidProxy.cs index d983c96c4d..564d1b1adf 100644 --- a/src/NzbDrone.Core/Notifications/NotifyMyAndroid/NotifyMyAndroidProxy.cs +++ b/src/NzbDrone.Core/Notifications/NotifyMyAndroid/NotifyMyAndroidProxy.cs @@ -5,8 +5,8 @@ using FluentValidation.Results; using NLog; using NzbDrone.Core.Exceptions; -using RestSharp; using NzbDrone.Core.Rest; +using RestSharp; namespace NzbDrone.Core.Notifications.NotifyMyAndroid { @@ -18,8 +18,8 @@ public interface INotifyMyAndroidProxy public class NotifyMyAndroidProxy : INotifyMyAndroidProxy { - private readonly Logger _logger; private const string URL = "https://www.notifymyandroid.com/publicapi"; + private readonly Logger _logger; public NotifyMyAndroidProxy(Logger logger) { diff --git a/src/NzbDrone.Core/Notifications/Plex/PlexAuthenticationException.cs b/src/NzbDrone.Core/Notifications/Plex/PlexAuthenticationException.cs index 86a0d15ec5..4235168b46 100644 --- a/src/NzbDrone.Core/Notifications/Plex/PlexAuthenticationException.cs +++ b/src/NzbDrone.Core/Notifications/Plex/PlexAuthenticationException.cs @@ -2,7 +2,8 @@ { public class PlexAuthenticationException : PlexException { - public PlexAuthenticationException(string message) : base(message) + public PlexAuthenticationException(string message) + : base(message) { } diff --git a/src/NzbDrone.Core/Notifications/Plex/PlexException.cs b/src/NzbDrone.Core/Notifications/Plex/PlexException.cs index 402f4a4484..c545c20f50 100644 --- a/src/NzbDrone.Core/Notifications/Plex/PlexException.cs +++ b/src/NzbDrone.Core/Notifications/Plex/PlexException.cs @@ -5,15 +5,18 @@ namespace NzbDrone.Core.Notifications.Plex { public class PlexException : NzbDroneException { - public PlexException(string message) : base(message) + public PlexException(string message) + : base(message) { } - public PlexException(string message, params object[] args) : base(message, args) + public PlexException(string message, params object[] args) + : base(message, args) { } - public PlexException(string message, Exception innerException) : base(message, innerException) + public PlexException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/Notifications/Plex/PlexTv/PlexTvService.cs b/src/NzbDrone.Core/Notifications/Plex/PlexTv/PlexTvService.cs index d54ea0fefd..533f5d8666 100644 --- a/src/NzbDrone.Core/Notifications/Plex/PlexTv/PlexTvService.cs +++ b/src/NzbDrone.Core/Notifications/Plex/PlexTv/PlexTvService.cs @@ -42,10 +42,10 @@ public PlexTvPinUrlResponse GetPinUrl() var request = requestBuilder.Build(); return new PlexTvPinUrlResponse - { - Url = request.Url.ToString(), - Headers = request.Headers.ToDictionary(h => h.Key, h => h.Value) - }; + { + Url = request.Url.ToString(), + Headers = request.Headers.ToDictionary(h => h.Key, h => h.Value) + }; } public PlexTvSignInUrlResponse GetSignInUrl(string callbackUrl, int pinId, string pinCode) @@ -67,10 +67,10 @@ public PlexTvSignInUrlResponse GetSignInUrl(string callbackUrl, int pinId, strin var request = requestBuilder.Build(); return new PlexTvSignInUrlResponse - { - OauthUrl = request.Url.ToString(), - PinId = pinId - }; + { + OauthUrl = request.Url.ToString(), + PinId = pinId + }; } public string GetAuthToken(int pinId) diff --git a/src/NzbDrone.Core/Notifications/Plex/PlexVersionException.cs b/src/NzbDrone.Core/Notifications/Plex/PlexVersionException.cs index 439cb57acd..42c7889da9 100644 --- a/src/NzbDrone.Core/Notifications/Plex/PlexVersionException.cs +++ b/src/NzbDrone.Core/Notifications/Plex/PlexVersionException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Notifications.Plex { public class PlexVersionException : NzbDroneException { - public PlexVersionException(string message) : base(message) + public PlexVersionException(string message) + : base(message) { } - public PlexVersionException(string message, params object[] args) : base(message, args) + public PlexVersionException(string message, params object[] args) + : base(message, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Plex/Server/PlexServer.cs b/src/NzbDrone.Core/Notifications/Plex/Server/PlexServer.cs index db4cd299e0..6412b6e2b1 100644 --- a/src/NzbDrone.Core/Notifications/Plex/Server/PlexServer.cs +++ b/src/NzbDrone.Core/Notifications/Plex/Server/PlexServer.cs @@ -3,8 +3,8 @@ using FluentValidation.Results; using NzbDrone.Common.Extensions; using NzbDrone.Core.Exceptions; -using NzbDrone.Core.Notifications.Plex.PlexTv; using NzbDrone.Core.Movies; +using NzbDrone.Core.Notifications.Plex.PlexTv; using NzbDrone.Core.Validation; namespace NzbDrone.Core.Notifications.Plex.Server @@ -91,9 +91,9 @@ public override object RequestAction(string action, IDictionary<string, string> var authToken = _plexTvService.GetAuthToken(Convert.ToInt32(query["pinId"])); return new - { - authToken - }; + { + authToken + }; } return new { }; diff --git a/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerProxy.cs b/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerProxy.cs index 253a5ec65f..d90eb13650 100644 --- a/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerProxy.cs +++ b/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerProxy.cs @@ -26,7 +26,7 @@ public class PlexServerProxy : IPlexServerProxy private readonly IConfigService _configService; private readonly Logger _logger; - public PlexServerProxy(IHttpClient httpClient, IConfigService configService,Logger logger) + public PlexServerProxy(IHttpClient httpClient, IConfigService configService, Logger logger) { _httpClient = httpClient; _configService = configService; @@ -46,12 +46,12 @@ public List<PlexSection> GetMovieSections(PlexServerSettings settings) .Sections .Where(d => d.Type == "movie") .Select(s => new PlexSection - { - Id = s.Id, - Language = s.Language, - Locations = s.Locations, - Type = s.Type - }) + { + Id = s.Id, + Language = s.Language, + Locations = s.Locations, + Type = s.Type + }) .ToList(); } @@ -132,7 +132,6 @@ public List<PlexPreference> Preferences(PlexServerSettings settings) items = Json.Deserialize<PlexSectionResponseLegacy>(response) .Items; } - else { items = Json.Deserialize<PlexResponse<PlexSectionResponse>>(response) diff --git a/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerService.cs b/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerService.cs index d73f541459..6b2d1ccce0 100644 --- a/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerService.cs +++ b/src/NzbDrone.Core/Notifications/Plex/Server/PlexServerService.cs @@ -47,14 +47,12 @@ public void UpdateLibrary(Movie movie, PlexServerSettings settings) { UpdatePartialSection(movie, sections, settings); } - else { sections.ForEach(s => UpdateSection(s.Id, settings)); } } - - catch(Exception ex) + catch (Exception ex) { _logger.Warn(ex, "Failed to Update Plex host: " + settings.Host); throw; @@ -168,7 +166,7 @@ public ValidationFailure Test(PlexServerSettings settings) return new ValidationFailure("Host", "At least one Movie library is required"); } } - catch(PlexAuthenticationException ex) + catch (PlexAuthenticationException ex) { _logger.Error(ex, "Unable to connect to Plex Server"); return new ValidationFailure("AuthToken", "Invalid authentication token"); diff --git a/src/NzbDrone.Core/Notifications/PushBullet/PushBullet.cs b/src/NzbDrone.Core/Notifications/PushBullet/PushBullet.cs index c9f73def6c..024244a0db 100644 --- a/src/NzbDrone.Core/Notifications/PushBullet/PushBullet.cs +++ b/src/NzbDrone.Core/Notifications/PushBullet/PushBullet.cs @@ -51,23 +51,23 @@ public override object RequestAction(string action, IDictionary<string, string> if (Settings.ApiKey.IsNullOrWhiteSpace()) { return new - { - devices = new List<object>() - }; + { + devices = new List<object>() + }; } Settings.Validate().Filter("ApiKey").ThrowOnError(); var devices = _proxy.GetDevices(Settings); return new - { - options = devices.Where(d => d.Nickname.IsNotNullOrWhiteSpace()) + { + options = devices.Where(d => d.Nickname.IsNotNullOrWhiteSpace()) .OrderBy(d => d.Nickname, StringComparer.InvariantCultureIgnoreCase) .Select(d => new - { - id = d.Id, - name = d.Nickname - }) + { + id = d.Id, + name = d.Nickname + }) }; } diff --git a/src/NzbDrone.Core/Notifications/PushBullet/PushBulletException.cs b/src/NzbDrone.Core/Notifications/PushBullet/PushBulletException.cs index ce8b8417d2..f8207ef014 100644 --- a/src/NzbDrone.Core/Notifications/PushBullet/PushBulletException.cs +++ b/src/NzbDrone.Core/Notifications/PushBullet/PushBulletException.cs @@ -5,11 +5,13 @@ namespace NzbDrone.Core.Notifications.PushBullet { public class PushBulletException : NzbDroneException { - public PushBulletException(string message) : base(message) + public PushBulletException(string message) + : base(message) { } - public PushBulletException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public PushBulletException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } } diff --git a/src/NzbDrone.Core/Notifications/PushBullet/PushBulletProxy.cs b/src/NzbDrone.Core/Notifications/PushBullet/PushBulletProxy.cs index db5da246f0..451f3b828e 100644 --- a/src/NzbDrone.Core/Notifications/PushBullet/PushBulletProxy.cs +++ b/src/NzbDrone.Core/Notifications/PushBullet/PushBulletProxy.cs @@ -4,10 +4,10 @@ using System.Net; using FluentValidation.Results; using NLog; -using RestSharp; -using NzbDrone.Core.Rest; using NzbDrone.Common.Extensions; using NzbDrone.Common.Serializer; +using NzbDrone.Core.Rest; +using RestSharp; using RestSharp.Authenticators; namespace NzbDrone.Core.Notifications.PushBullet @@ -21,9 +21,9 @@ public interface IPushBulletProxy public class PushBulletProxy : IPushBulletProxy { - private readonly Logger _logger; private const string PUSH_URL = "https://api.pushbullet.com/v2/pushes"; private const string DEVICE_URL = "https://api.pushbullet.com/v2/devices"; + private readonly Logger _logger; public PushBulletProxy(Logger logger) { @@ -154,7 +154,6 @@ private RestRequest BuildDeviceRequest(string deviceId) { request.AddParameter("device_id", integerId); } - else { request.AddParameter("device_iden", deviceId); diff --git a/src/NzbDrone.Core/Notifications/Pushalot/PushalotProxy.cs b/src/NzbDrone.Core/Notifications/Pushalot/PushalotProxy.cs index b30b92b90b..02a61b4189 100644 --- a/src/NzbDrone.Core/Notifications/Pushalot/PushalotProxy.cs +++ b/src/NzbDrone.Core/Notifications/Pushalot/PushalotProxy.cs @@ -16,8 +16,8 @@ public interface IPushalotProxy public class PushalotProxy : IPushalotProxy { - private readonly Logger _logger; private const string URL = "https://pushalot.com/api/sendmessage"; + private readonly Logger _logger; public PushalotProxy(Logger logger) { diff --git a/src/NzbDrone.Core/Notifications/Pushover/InvalidResponseException.cs b/src/NzbDrone.Core/Notifications/Pushover/InvalidResponseException.cs index 7e6fc1f4aa..6f9c139a2a 100644 --- a/src/NzbDrone.Core/Notifications/Pushover/InvalidResponseException.cs +++ b/src/NzbDrone.Core/Notifications/Pushover/InvalidResponseException.cs @@ -8,7 +8,8 @@ public InvalidResponseException() { } - public InvalidResponseException(string message) : base(message) + public InvalidResponseException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/Notifications/Pushover/PushoverService.cs b/src/NzbDrone.Core/Notifications/Pushover/PushoverService.cs index 9960bc18a3..fddae9d91b 100644 --- a/src/NzbDrone.Core/Notifications/Pushover/PushoverService.cs +++ b/src/NzbDrone.Core/Notifications/Pushover/PushoverService.cs @@ -2,8 +2,8 @@ using FluentValidation.Results; using NLog; using NzbDrone.Common.Extensions; -using RestSharp; using NzbDrone.Core.Rest; +using RestSharp; namespace NzbDrone.Core.Notifications.Pushover { @@ -15,8 +15,8 @@ public interface IPushoverProxy public class PushoverProxy : IPushoverProxy { - private readonly Logger _logger; private const string URL = "https://api.pushover.net/1/messages.json"; + private readonly Logger _logger; public PushoverProxy(Logger logger) { @@ -44,7 +44,6 @@ public void SendNotification(string title, string message, PushoverSettings sett request.AddParameter("sound", settings.Sound); } - client.ExecuteAndValidate(request); } diff --git a/src/NzbDrone.Core/Notifications/Pushover/PushoverSettings.cs b/src/NzbDrone.Core/Notifications/Pushover/PushoverSettings.cs index 2f5c553a25..646538e383 100644 --- a/src/NzbDrone.Core/Notifications/Pushover/PushoverSettings.cs +++ b/src/NzbDrone.Core/Notifications/Pushover/PushoverSettings.cs @@ -1,8 +1,8 @@ -using FluentValidation; +using System.Collections.Generic; +using FluentValidation; using NzbDrone.Core.Annotations; using NzbDrone.Core.ThingiProvider; using NzbDrone.Core.Validation; -using System.Collections.Generic; namespace NzbDrone.Core.Notifications.Pushover { @@ -36,7 +36,7 @@ public PushoverSettings() [FieldDefinition(2, Label = "Devices", HelpText = "List of device names (leave blank to send to all devices)", Type = FieldType.Tag)] public IEnumerable<string> Devices { get; set; } - [FieldDefinition(3, Label = "Priority", Type = FieldType.Select, SelectOptions = typeof(PushoverPriority) )] + [FieldDefinition(3, Label = "Priority", Type = FieldType.Select, SelectOptions = typeof(PushoverPriority))] public int Priority { get; set; } [FieldDefinition(4, Label = "Retry", Type = FieldType.Textbox, HelpText = "Interval to retry Emergency alerts, minimum 30 seconds")] diff --git a/src/NzbDrone.Core/Notifications/Slack/Slack.cs b/src/NzbDrone.Core/Notifications/Slack/Slack.cs index 5173c36a31..b570d6aef9 100644 --- a/src/NzbDrone.Core/Notifications/Slack/Slack.cs +++ b/src/NzbDrone.Core/Notifications/Slack/Slack.cs @@ -2,11 +2,10 @@ using System.Collections.Generic; using FluentValidation.Results; using NzbDrone.Common.Extensions; -using NzbDrone.Core.Notifications.Slack.Payloads; using NzbDrone.Core.Movies; +using NzbDrone.Core.Notifications.Slack.Payloads; using NzbDrone.Core.Validation; - namespace NzbDrone.Core.Notifications.Slack { public class Slack : NotificationBase<SlackSettings> @@ -65,7 +64,7 @@ public override void OnMovieRename(Movie movie) } }; - var payload = CreatePayload("Renamed", attachments); + var payload = CreatePayload("Renamed", attachments); _proxy.SendPayload(payload, Settings); } @@ -105,7 +104,6 @@ public ValidationFailure TestMessage() var payload = CreatePayload(message); _proxy.SendPayload(payload, Settings); - } catch (SlackExeption ex) { diff --git a/src/NzbDrone.Core/Notifications/Slack/SlackExeption.cs b/src/NzbDrone.Core/Notifications/Slack/SlackExeption.cs index 1d7fd9b85c..952860b6da 100644 --- a/src/NzbDrone.Core/Notifications/Slack/SlackExeption.cs +++ b/src/NzbDrone.Core/Notifications/Slack/SlackExeption.cs @@ -3,13 +3,15 @@ namespace NzbDrone.Core.Notifications.Slack { - class SlackExeption : NzbDroneException + public class SlackExeption : NzbDroneException { - public SlackExeption(string message) : base(message) + public SlackExeption(string message) + : base(message) { } - public SlackExeption(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public SlackExeption(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Synology/SynologyException.cs b/src/NzbDrone.Core/Notifications/Synology/SynologyException.cs index f7534671b7..4c70e61b10 100644 --- a/src/NzbDrone.Core/Notifications/Synology/SynologyException.cs +++ b/src/NzbDrone.Core/Notifications/Synology/SynologyException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Notifications.Synology { public class SynologyException : NzbDroneException { - public SynologyException(string message) : base(message) + public SynologyException(string message) + : base(message) { } - public SynologyException(string message, params object[] args) : base(message, args) + public SynologyException(string message, params object[] args) + : base(message, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Synology/SynologyIndexer.cs b/src/NzbDrone.Core/Notifications/Synology/SynologyIndexer.cs index e6e457db5d..828b5044e2 100644 --- a/src/NzbDrone.Core/Notifications/Synology/SynologyIndexer.cs +++ b/src/NzbDrone.Core/Notifications/Synology/SynologyIndexer.cs @@ -19,7 +19,6 @@ public SynologyIndexer(ISynologyIndexerProxy indexerProxy) public override string Link => "https://www.synology.com"; public override string Name => "Synology Indexer"; - public override void OnDownload(DownloadMessage message) { if (Settings.UpdateLibrary) diff --git a/src/NzbDrone.Core/Notifications/Synology/SynologyIndexerSettings.cs b/src/NzbDrone.Core/Notifications/Synology/SynologyIndexerSettings.cs index 5f9be1a2f9..7b1084570c 100644 --- a/src/NzbDrone.Core/Notifications/Synology/SynologyIndexerSettings.cs +++ b/src/NzbDrone.Core/Notifications/Synology/SynologyIndexerSettings.cs @@ -9,7 +9,6 @@ public class SynologyIndexerSettingsValidator : AbstractValidator<SynologyIndexe { public SynologyIndexerSettingsValidator() { - } } diff --git a/src/NzbDrone.Core/Notifications/Telegram/InvalidResponseException.cs b/src/NzbDrone.Core/Notifications/Telegram/InvalidResponseException.cs index 137e7322b5..8ad8de02a6 100644 --- a/src/NzbDrone.Core/Notifications/Telegram/InvalidResponseException.cs +++ b/src/NzbDrone.Core/Notifications/Telegram/InvalidResponseException.cs @@ -8,7 +8,8 @@ public InvalidResponseException() { } - public InvalidResponseException(string message) : base(message) + public InvalidResponseException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/Notifications/Telegram/TelegramService.cs b/src/NzbDrone.Core/Notifications/Telegram/TelegramService.cs index 416373cede..cefc637ab8 100644 --- a/src/NzbDrone.Core/Notifications/Telegram/TelegramService.cs +++ b/src/NzbDrone.Core/Notifications/Telegram/TelegramService.cs @@ -1,12 +1,12 @@ using System; using System.Net; +using System.Web; using FluentValidation.Results; using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Common.Serializer; -using RestSharp; using NzbDrone.Core.Rest; -using System.Web; +using RestSharp; namespace NzbDrone.Core.Notifications.Telegram { @@ -18,8 +18,8 @@ public interface ITelegramProxy public class TelegramProxy : ITelegramProxy { - private readonly Logger _logger; private const string URL = "https://api.telegram.org"; + private readonly Logger _logger; public TelegramProxy(Logger logger) { diff --git a/src/NzbDrone.Core/Notifications/Twitter/OAuthToken.cs b/src/NzbDrone.Core/Notifications/Twitter/OAuthToken.cs index dde4bc1aac..8992ca0f88 100644 --- a/src/NzbDrone.Core/Notifications/Twitter/OAuthToken.cs +++ b/src/NzbDrone.Core/Notifications/Twitter/OAuthToken.cs @@ -1,4 +1,3 @@ - namespace NzbDrone.Core.Notifications.Twitter { public class OAuthToken diff --git a/src/NzbDrone.Core/Notifications/Twitter/Twitter.cs b/src/NzbDrone.Core/Notifications/Twitter/Twitter.cs index b0ef75e61f..38fd9ebb75 100644 --- a/src/NzbDrone.Core/Notifications/Twitter/Twitter.cs +++ b/src/NzbDrone.Core/Notifications/Twitter/Twitter.cs @@ -6,9 +6,8 @@ namespace NzbDrone.Core.Notifications.Twitter { - class Twitter : NotificationBase<TwitterSettings> + public class Twitter : NotificationBase<TwitterSettings> { - private readonly ITwitterService _twitterService; public Twitter(ITwitterService twitterService) @@ -72,6 +71,7 @@ public override object RequestAction(string action, IDictionary<string, string> accessTokenSecret = oauthToken.AccessTokenSecret }; } + return new { }; } @@ -84,5 +84,4 @@ public override ValidationResult Test() return new ValidationResult(failures); } } - } diff --git a/src/NzbDrone.Core/Notifications/Twitter/TwitterException.cs b/src/NzbDrone.Core/Notifications/Twitter/TwitterException.cs index 99146fa716..77676fbf2d 100644 --- a/src/NzbDrone.Core/Notifications/Twitter/TwitterException.cs +++ b/src/NzbDrone.Core/Notifications/Twitter/TwitterException.cs @@ -5,19 +5,23 @@ namespace NzbDrone.Core.Notifications.Twitter { public class TwitterException : NzbDroneException { - public TwitterException(string message, params object[] args) : base(message, args) + public TwitterException(string message, params object[] args) + : base(message, args) { } - public TwitterException(string message) : base(message) + public TwitterException(string message) + : base(message) { } - public TwitterException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public TwitterException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } - public TwitterException(string message, Exception innerException) : base(message, innerException) + public TwitterException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Core/Notifications/Twitter/TwitterService.cs b/src/NzbDrone.Core/Notifications/Twitter/TwitterService.cs index 87fb38eb9f..39af507f30 100644 --- a/src/NzbDrone.Core/Notifications/Twitter/TwitterService.cs +++ b/src/NzbDrone.Core/Notifications/Twitter/TwitterService.cs @@ -1,10 +1,10 @@ -using FluentValidation.Results; -using NLog; -using System; -using System.Net; +using System; using System.Collections.Specialized; using System.IO; +using System.Net; using System.Web; +using FluentValidation.Results; +using NLog; using NzbDrone.Common.Extensions; using NzbDrone.Common.Http; using NzbDrone.Common.OAuth; @@ -82,7 +82,6 @@ public void SendNotification(string message, TwitterSettings settings) { twitter.DirectMessage(message, settings.Mention); } - else { if (settings.Mention.IsNotNullOrWhiteSpace()) @@ -131,6 +130,7 @@ public ValidationFailure Test(TwitterSettings settings) _logger.Error(ex, "Unable to send test message"); return new ValidationFailure("Host", "Unable to send test message"); } + return null; } } diff --git a/src/NzbDrone.Core/Notifications/Twitter/TwitterSettings.cs b/src/NzbDrone.Core/Notifications/Twitter/TwitterSettings.cs index 15e404e953..bc1cf49c6b 100644 --- a/src/NzbDrone.Core/Notifications/Twitter/TwitterSettings.cs +++ b/src/NzbDrone.Core/Notifications/Twitter/TwitterSettings.cs @@ -14,6 +14,7 @@ public TwitterSettingsValidator() RuleFor(c => c.ConsumerSecret).NotEmpty(); RuleFor(c => c.AccessToken).NotEmpty(); RuleFor(c => c.AccessTokenSecret).NotEmpty(); + //TODO: Validate that it is a valid username (numbers, letters and underscores - I think) RuleFor(c => c.Mention).NotEmpty().When(c => c.DirectMessage); diff --git a/src/NzbDrone.Core/Notifications/Webhook/Webhook.cs b/src/NzbDrone.Core/Notifications/Webhook/Webhook.cs index 1c90c54b8e..caba855de9 100755 --- a/src/NzbDrone.Core/Notifications/Webhook/Webhook.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/Webhook.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; using FluentValidation.Results; -using NzbDrone.Core.Movies; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Movies; using NzbDrone.Core.Validation; namespace NzbDrone.Core.Notifications.Webhook diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookException.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookException.cs index b422d8621d..07d4c4666b 100644 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookException.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookException.cs @@ -5,11 +5,13 @@ namespace NzbDrone.Core.Notifications.Webhook { public class WebhookException : NzbDroneException { - public WebhookException(string message) : base(message) + public WebhookException(string message) + : base(message) { } - public WebhookException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public WebhookException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } } diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookGrabPayload.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookGrabPayload.cs index 57d8f040a2..aac72ff6f7 100755 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookGrabPayload.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookGrabPayload.cs @@ -1,6 +1,6 @@ namespace NzbDrone.Core.Notifications.Webhook { - class WebhookGrabPayload : WebhookPayload + public class WebhookGrabPayload : WebhookPayload { public WebhookRemoteMovie RemoteMovie { get; set; } public WebhookRelease Release { get; set; } diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookImportPayload.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookImportPayload.cs index 7043137c7d..f89077cf20 100755 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookImportPayload.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookImportPayload.cs @@ -1,6 +1,6 @@ namespace NzbDrone.Core.Notifications.Webhook { - class WebhookImportPayload : WebhookPayload + public class WebhookImportPayload : WebhookPayload { public WebhookRemoteMovie RemoteMovie { get; set; } public WebhookMovieFile MovieFile { get; set; } diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookMovie.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookMovie.cs index 459743f1d8..40ff6b4001 100755 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookMovie.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookMovie.cs @@ -1,6 +1,6 @@ using System.IO; - using NzbDrone.Core.Movies; using NzbDrone.Core.MediaFiles; +using NzbDrone.Core.Movies; namespace NzbDrone.Core.Notifications.Webhook { @@ -12,7 +12,9 @@ public class WebhookMovie public string ReleaseDate { get; set; } public string FolderPath { get; set; } - public WebhookMovie() { } + public WebhookMovie() + { + } public WebhookMovie(Movie movie) { @@ -22,7 +24,8 @@ public WebhookMovie(Movie movie) FolderPath = movie.Path; } - public WebhookMovie(Movie movie, MovieFile movieFile) : this(movie) + public WebhookMovie(Movie movie, MovieFile movieFile) + : this(movie) { FilePath = Path.Combine(movie.Path, movieFile.RelativePath); } diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookMovieFile.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookMovieFile.cs index cd19f29236..b3005f2333 100755 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookMovieFile.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookMovieFile.cs @@ -2,9 +2,11 @@ namespace NzbDrone.Core.Notifications.Webhook { - class WebhookMovieFile + public class WebhookMovieFile { - public WebhookMovieFile() { } + public WebhookMovieFile() + { + } public WebhookMovieFile(MovieFile movieFile) { diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookProxy.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookProxy.cs index 9ef82e8f79..f7eedec693 100755 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookProxy.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookProxy.cs @@ -10,7 +10,7 @@ public interface IWebhookProxy void SendWebhook(WebhookPayload payload, WebhookSettings settings); } - class WebhookProxy : IWebhookProxy + public class WebhookProxy : IWebhookProxy { private readonly IHttpClient _httpClient; @@ -35,6 +35,7 @@ public void SendWebhook(WebhookPayload body, WebhookSettings settings) { request.AddBasicAuthentication(settings.Username, settings.Password); } + _httpClient.Execute(request); } catch (RestException ex) diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookRelease.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookRelease.cs index 05d24ad99a..2ba11f3cf1 100755 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookRelease.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookRelease.cs @@ -5,7 +5,9 @@ namespace NzbDrone.Core.Notifications.Webhook { public class WebhookRelease { - public WebhookRelease() { } + public WebhookRelease() + { + } public WebhookRelease(QualityModel quality, RemoteMovie remoteMovie) { diff --git a/src/NzbDrone.Core/Notifications/Webhook/WebhookRemoteMovie.cs b/src/NzbDrone.Core/Notifications/Webhook/WebhookRemoteMovie.cs index cc8279290f..d14af047f7 100644 --- a/src/NzbDrone.Core/Notifications/Webhook/WebhookRemoteMovie.cs +++ b/src/NzbDrone.Core/Notifications/Webhook/WebhookRemoteMovie.cs @@ -10,7 +10,9 @@ public class WebhookRemoteMovie public string Title { get; set; } public int Year { get; set; } - public WebhookRemoteMovie() { } + public WebhookRemoteMovie() + { + } public WebhookRemoteMovie(RemoteMovie remoteMovie) { diff --git a/src/NzbDrone.Core/Notifications/Xbmc/XbmcJsonApiProxy.cs b/src/NzbDrone.Core/Notifications/Xbmc/XbmcJsonApiProxy.cs index e85b5b4e12..a436dc62f9 100644 --- a/src/NzbDrone.Core/Notifications/Xbmc/XbmcJsonApiProxy.cs +++ b/src/NzbDrone.Core/Notifications/Xbmc/XbmcJsonApiProxy.cs @@ -122,7 +122,6 @@ private IRestClient BuildClient(XbmcSettings settings) private void CheckForError(IRestResponse response) { - if (string.IsNullOrWhiteSpace(response.Content)) { throw new XbmcJsonException("Invalid response from XBMC, the response is not valid JSON"); diff --git a/src/NzbDrone.Core/Notifications/Xbmc/XbmcService.cs b/src/NzbDrone.Core/Notifications/Xbmc/XbmcService.cs index 9f96a68c7a..2118dd9716 100644 --- a/src/NzbDrone.Core/Notifications/Xbmc/XbmcService.cs +++ b/src/NzbDrone.Core/Notifications/Xbmc/XbmcService.cs @@ -68,10 +68,12 @@ public string GetMoviePath(XbmcSettings settings, Movie movie) var matchingMovies = allMovies.FirstOrDefault(s => { return s.ImdbNumber == movie.ImdbId || s.Label == movie.Title; - }); - if (matchingMovies != null) return matchingMovies.File; + if (matchingMovies != null) + { + return matchingMovies.File; + } return null; } @@ -87,11 +89,9 @@ private void UpdateMovieLibrary(XbmcSettings settings, Movie movie) moviePath = new OsPath(moviePath).Directory.FullPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); _logger.Debug("Updating movie {0} (Path: {1}) on XBMC host: {2}", movie, moviePath, settings.Address); } - else { - _logger.Debug("Movie {0} doesn't exist on XBMC host: {1}, Updating Entire Library", movie, - settings.Address); + _logger.Debug("Movie {0} doesn't exist on XBMC host: {1}, Updating Entire Library", movie, settings.Address); } var response = _proxy.UpdateLibrary(settings, moviePath); @@ -101,7 +101,6 @@ private void UpdateMovieLibrary(XbmcSettings settings, Movie movie) _logger.Debug("Failed to update library for: {0}", settings.Address); } } - catch (Exception ex) { _logger.Debug(ex, ex.Message); diff --git a/src/NzbDrone.Core/Organizer/Exception.cs b/src/NzbDrone.Core/Organizer/Exception.cs index c4e80b17de..18efe94cc7 100644 --- a/src/NzbDrone.Core/Organizer/Exception.cs +++ b/src/NzbDrone.Core/Organizer/Exception.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Organizer { public class NamingFormatException : NzbDroneException { - public NamingFormatException(string message, params object[] args) : base(message, args) + public NamingFormatException(string message, params object[] args) + : base(message, args) { } - public NamingFormatException(string message) : base(message) + public NamingFormatException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/Organizer/FileNameBuilder.cs b/src/NzbDrone.Core/Organizer/FileNameBuilder.cs index d2a3f4ca66..0c4b57f381 100644 --- a/src/NzbDrone.Core/Organizer/FileNameBuilder.cs +++ b/src/NzbDrone.Core/Organizer/FileNameBuilder.cs @@ -9,8 +9,8 @@ using NzbDrone.Common.Extensions; using NzbDrone.Core.MediaFiles; using NzbDrone.Core.MediaFiles.MediaInfo; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Movies; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Organizer { @@ -25,6 +25,8 @@ public interface IBuildFileNames public class FileNameBuilder : IBuildFileNames { + private const string MediaInfoVideoDynamicRangeToken = "{MediaInfo VideoDynamicRange}"; + private readonly INamingConfigService _namingConfigService; private readonly IQualityDefinitionService _qualityDefinitionService; private readonly IUpdateMediaInfo _mediaInfoUpdater; @@ -142,9 +144,8 @@ public string BuildMoviePath(Movie movie, NamingConfig namingConfig = null) AddReleaseDateTokens(tokenHandlers, movie.Year); AddIdTokens(tokenHandlers, movie); - if(movie.MovieFile != null) + if (movie.MovieFile != null) { - AddQualityTokens(tokenHandlers, movie, movieFile); AddMediaInfoTokens(tokenHandlers, movieFile); AddMovieFileTokens(tokenHandlers, movieFile); @@ -155,7 +156,6 @@ public string BuildMoviePath(Movie movie, NamingConfig namingConfig = null) AddMovieFileTokens(tokenHandlers, new MovieFile { SceneName = $"{movie.Title} {movie.Year}", RelativePath = $"{movie.Title} {movie.Year}" }); } - var directoryName = ReplaceTokens(pattern, tokenHandlers, namingConfig).Trim(); directoryName = FileNameCleanupRegex.Replace(directoryName, match => match.Captures[0].Value[0].ToString()); directoryName = TrimSeparatorsRegex.Replace(directoryName, string.Empty); @@ -166,7 +166,6 @@ public string BuildMoviePath(Movie movie, NamingConfig namingConfig = null) public BasicNamingConfig GetBasicNamingConfig(NamingConfig nameSpec) { return new BasicNamingConfig(); //For now let's be lazy - } public string GetMovieFolder(Movie movie, NamingConfig namingConfig = null) @@ -194,7 +193,7 @@ public string GetMovieFolder(Movie movie, NamingConfig namingConfig = null) } else { - AddMovieFileTokens(tokenHandlers, new MovieFile { SceneName = $"{movie.Title} {movie.Year}", RelativePath = $"{movie.Title} {movie.Year}"}); + AddMovieFileTokens(tokenHandlers, new MovieFile { SceneName = $"{movie.Title} {movie.Year}", RelativePath = $"{movie.Title} {movie.Year}" }); } string name = ReplaceTokens(namingConfig.MovieFolderFormat, tokenHandlers, namingConfig); @@ -286,6 +285,7 @@ private void AddMovieFileTokens(Dictionary<string, Func<TokenMatch, string>> tok { tokenHandlers["{Original Title}"] = m => GetOriginalTitle(movieFile); tokenHandlers["{Original Filename}"] = m => GetOriginalFileName(movieFile); + //tokenHandlers["{IMDb Id}"] = m => tokenHandlers["{Release Group}"] = m => movieFile.ReleaseGroup ?? m.DefaultValue("Radarr"); } @@ -305,17 +305,16 @@ private void AddQualityTokens(Dictionary<string, Func<TokenMatch, string>> token var qualityProper = GetQualityProper(movie, movieFile.Quality); var qualityReal = GetQualityReal(movie, movieFile.Quality); - tokenHandlers["{Quality Full}"] = m => String.Format("{0} {1} {2}", qualityTitle, qualityProper, qualityReal); + tokenHandlers["{Quality Full}"] = m => string.Format("{0} {1} {2}", qualityTitle, qualityProper, qualityReal); tokenHandlers["{Quality Title}"] = m => qualityTitle; tokenHandlers["{Quality Proper}"] = m => qualityProper; tokenHandlers["{Quality Real}"] = m => qualityReal; } - private const string MediaInfoVideoDynamicRangeToken = "{MediaInfo VideoDynamicRange}"; private static readonly IReadOnlyDictionary<string, int> MinimumMediaInfoSchemaRevisions = new Dictionary<string, int>(FileNameBuilderTokenEqualityComparer.Instance) { - {MediaInfoVideoDynamicRangeToken, 5} + { MediaInfoVideoDynamicRangeToken, 5 } }; private void AddMediaInfoTokens(Dictionary<string, Func<TokenMatch, string>> tokenHandlers, MovieFile movieFile) @@ -329,9 +328,8 @@ private void AddMediaInfoTokens(Dictionary<string, Func<TokenMatch, string>> tok var sceneName = movieFile.GetSceneOrFileName(); - - var videoCodec = MediaInfoFormatter.FormatVideoCodec(movieFile.MediaInfo, sceneName); - var audioCodec = MediaInfoFormatter.FormatAudioCodec(movieFile.MediaInfo, sceneName); + var videoCodec = MediaInfoFormatter.FormatVideoCodec(movieFile.MediaInfo, sceneName); + var audioCodec = MediaInfoFormatter.FormatAudioCodec(movieFile.MediaInfo, sceneName); var audioChannels = MediaInfoFormatter.FormatAudioChannels(movieFile.MediaInfo); var audioLanguages = movieFile.MediaInfo.AudioLanguages ?? string.Empty; var subtitles = movieFile.MediaInfo.Subtitles ?? string.Empty; @@ -389,7 +387,9 @@ private string GetLanguagesToken(string mediaInfoLanguages) foreach (var item in mediaInfoLanguages.Split('/')) { if (!string.IsNullOrWhiteSpace(item)) + { tokens.Add(item.Trim()); + } } var cultures = CultureInfo.GetCultures(CultureTypes.NeutralCultures); @@ -400,7 +400,9 @@ private string GetLanguagesToken(string mediaInfoLanguages) var cultureInfo = cultures.FirstOrDefault(p => p.EnglishName == tokens[i]); if (cultureInfo != null) + { tokens[i] = cultureInfo.TwoLetterISOLanguageName.ToUpper(); + } } catch { @@ -483,7 +485,10 @@ private string ReplaceToken(Match match, Dictionary<string, Func<TokenMatch, str private string ReplaceNumberToken(string token, int value) { var split = token.Trim('{', '}').Split(':'); - if (split.Length == 1) return value.ToString("0"); + if (split.Length == 1) + { + return value.ToString("0"); + } return value.ToString(split[1]); } @@ -495,7 +500,7 @@ private string GetQualityProper(Movie movie, QualityModel quality) return "Proper"; } - return String.Empty; + return string.Empty; } private string GetQualityReal(Movie movie, QualityModel quality) diff --git a/src/NzbDrone.Core/Organizer/FileNameBuilderTokenEqualityComparer.cs b/src/NzbDrone.Core/Organizer/FileNameBuilderTokenEqualityComparer.cs index 1b11f81c2e..e5ffe79f52 100644 --- a/src/NzbDrone.Core/Organizer/FileNameBuilderTokenEqualityComparer.cs +++ b/src/NzbDrone.Core/Organizer/FileNameBuilderTokenEqualityComparer.cs @@ -11,7 +11,6 @@ public class FileNameBuilderTokenEqualityComparer : IEqualityComparer<string> private FileNameBuilderTokenEqualityComparer() { - } public bool Equals(string s1, string s2) diff --git a/src/NzbDrone.Core/Organizer/FileNameSampleService.cs b/src/NzbDrone.Core/Organizer/FileNameSampleService.cs index 90ac354827..ad93b1a1d4 100644 --- a/src/NzbDrone.Core/Organizer/FileNameSampleService.cs +++ b/src/NzbDrone.Core/Organizer/FileNameSampleService.cs @@ -1,7 +1,7 @@ using NzbDrone.Core.MediaFiles; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; using NzbDrone.Core.MediaFiles.MediaInfo; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Organizer { diff --git a/src/NzbDrone.Core/Organizer/FileNameValidationService.cs b/src/NzbDrone.Core/Organizer/FileNameValidationService.cs index 83c9eb798b..86d3911ebe 100644 --- a/src/NzbDrone.Core/Organizer/FileNameValidationService.cs +++ b/src/NzbDrone.Core/Organizer/FileNameValidationService.cs @@ -16,7 +16,7 @@ public ValidationFailure ValidateMovieFilename(SampleResult sampleResult) var validationFailure = new ValidationFailure("MovieFormat", ERROR_MESSAGE); var parsedMovieInfo = Parser.Parser.ParseMovieTitle(sampleResult.FileName, false); //We are not lenient when testing naming schemes - if(parsedMovieInfo == null) + if (parsedMovieInfo == null) { return validationFailure; } diff --git a/src/NzbDrone.Core/Organizer/NamingConfig.cs b/src/NzbDrone.Core/Organizer/NamingConfig.cs index 036ac20f22..6c9ad3589e 100644 --- a/src/NzbDrone.Core/Organizer/NamingConfig.cs +++ b/src/NzbDrone.Core/Organizer/NamingConfig.cs @@ -30,10 +30,9 @@ public enum ColonReplacementFormat SpaceDashSpace = 3 } - static class ColonReplacementFormatMethods + public static class ColonReplacementFormatMethods { - - public static String GetFormatString(this ColonReplacementFormat format) + public static string GetFormatString(this ColonReplacementFormat format) { switch (format) { diff --git a/src/NzbDrone.Core/Organizer/NamingConfigRepository.cs b/src/NzbDrone.Core/Organizer/NamingConfigRepository.cs index 6c32eee621..ca0138b678 100644 --- a/src/NzbDrone.Core/Organizer/NamingConfigRepository.cs +++ b/src/NzbDrone.Core/Organizer/NamingConfigRepository.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.Organizer { public interface INamingConfigRepository : IBasicRepository<NamingConfig> { - } public class NamingConfigRepository : BasicRepository<NamingConfig>, INamingConfigRepository @@ -14,6 +13,5 @@ public NamingConfigRepository(IMainDatabase database, IEventAggregator eventAggr : base(database, eventAggregator) { } - } } diff --git a/src/NzbDrone.Core/Parser/Augmenters/AugmentWithAdditionalFormats.cs b/src/NzbDrone.Core/Parser/Augmenters/AugmentWithAdditionalFormats.cs index e50f82a5e8..54528815a1 100644 --- a/src/NzbDrone.Core/Parser/Augmenters/AugmentWithAdditionalFormats.cs +++ b/src/NzbDrone.Core/Parser/Augmenters/AugmentWithAdditionalFormats.cs @@ -7,7 +7,6 @@ namespace NzbDrone.Core.Parser.Augmenters { public class AugmentWithAdditionalFormats : IAugmentParsedMovieInfo - { public Type HelperType { @@ -28,7 +27,7 @@ public ParsedMovieInfo AugmentMovieInfo(ParsedMovieInfo movieInfo, object helper } else { - movieInfo.ExtraInfo["AdditionalFormats"] = new List<CustomFormat>{format}; + movieInfo.ExtraInfo["AdditionalFormats"] = new List<CustomFormat> { format }; } } diff --git a/src/NzbDrone.Core/Parser/Augmenters/AugmentWithFileSize.cs b/src/NzbDrone.Core/Parser/Augmenters/AugmentWithFileSize.cs index 77bfd29e70..770eb88202 100644 --- a/src/NzbDrone.Core/Parser/Augmenters/AugmentWithFileSize.cs +++ b/src/NzbDrone.Core/Parser/Augmenters/AugmentWithFileSize.cs @@ -4,7 +4,6 @@ namespace NzbDrone.Core.Parser.Augmenters { public class AugmentWithFileSize : IAugmentParsedMovieInfo - { public Type HelperType { diff --git a/src/NzbDrone.Core/Parser/Augmenters/AugmentWithHistory.cs b/src/NzbDrone.Core/Parser/Augmenters/AugmentWithHistory.cs index 2ded7942cc..daacb6d65c 100644 --- a/src/NzbDrone.Core/Parser/Augmenters/AugmentWithHistory.cs +++ b/src/NzbDrone.Core/Parser/Augmenters/AugmentWithHistory.cs @@ -9,7 +9,6 @@ namespace NzbDrone.Core.Parser.Augmenters { public class AugmentWithHistory : IAugmentParsedMovieInfo - { private readonly IIndexerFactory _indexerFactory; private readonly IEnumerable<IAugmentParsedMovieInfo> _augmenters; diff --git a/src/NzbDrone.Core/Parser/Augmenters/AugmentWithMediaInfo.cs b/src/NzbDrone.Core/Parser/Augmenters/AugmentWithMediaInfo.cs index 8fb41be3e1..5c94dd84fe 100644 --- a/src/NzbDrone.Core/Parser/Augmenters/AugmentWithMediaInfo.cs +++ b/src/NzbDrone.Core/Parser/Augmenters/AugmentWithMediaInfo.cs @@ -7,7 +7,6 @@ namespace NzbDrone.Core.Parser.Augmenters { public class AugmentWithMediaInfo : IAugmentParsedMovieInfo - { public Type HelperType { @@ -52,7 +51,6 @@ public ParsedMovieInfo AugmentMovieInfo(ParsedMovieInfo movieInfo, object helper movieInfo.Quality = quality; } } - } return movieInfo; diff --git a/src/NzbDrone.Core/Parser/Augmenters/AugmentWithReleaseInfo.cs b/src/NzbDrone.Core/Parser/Augmenters/AugmentWithReleaseInfo.cs index fd4df74004..34f3802105 100644 --- a/src/NzbDrone.Core/Parser/Augmenters/AugmentWithReleaseInfo.cs +++ b/src/NzbDrone.Core/Parser/Augmenters/AugmentWithReleaseInfo.cs @@ -8,7 +8,6 @@ namespace NzbDrone.Core.Parser.Augmenters { public class AugmentWithReleaseInfo : IAugmentParsedMovieInfo - { private readonly IIndexerFactory _indexerFactory; @@ -29,15 +28,16 @@ public ParsedMovieInfo AugmentMovieInfo(ParsedMovieInfo movieInfo, object helper { if (helper is ReleaseInfo releaseInfo) { - IIndexerSettings indexerSettings = null; - try { + try + { indexerSettings = _indexerFactory.Get(releaseInfo.IndexerId)?.Settings as IIndexerSettings; } catch (Exception) { //_logger.Debug("Indexer with id {0} does not exist, skipping minimum seeder checks.", subject.Release.IndexerId); } // First, let's augment the language! + var languageTitle = movieInfo.SimpleReleaseTitle; if (movieInfo.MovieTitle.IsNotNullOrWhiteSpace()) { @@ -45,12 +45,13 @@ public ParsedMovieInfo AugmentMovieInfo(ParsedMovieInfo movieInfo, object helper { foreach (var i in indexerSettings.MultiLanguages) { - var language = (Language) i; + var language = (Language)i; if (!movieInfo.Languages.Contains(language)) + { movieInfo.Languages.Add(language); + } } } - } //Next, let's add other useful info to the extra info dict @@ -58,8 +59,8 @@ public ParsedMovieInfo AugmentMovieInfo(ParsedMovieInfo movieInfo, object helper { movieInfo.ExtraInfo["Size"] = releaseInfo.Size; } - movieInfo.ExtraInfo["IndexerFlags"] = releaseInfo.IndexerFlags; + movieInfo.ExtraInfo["IndexerFlags"] = releaseInfo.IndexerFlags; } return movieInfo; diff --git a/src/NzbDrone.Core/Parser/InvalidDateException.cs b/src/NzbDrone.Core/Parser/InvalidDateException.cs index 722517d0ee..97c5da581d 100644 --- a/src/NzbDrone.Core/Parser/InvalidDateException.cs +++ b/src/NzbDrone.Core/Parser/InvalidDateException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Core.Parser { public class InvalidDateException : NzbDroneException { - public InvalidDateException(string message, params object[] args) : base(message, args) + public InvalidDateException(string message, params object[] args) + : base(message, args) { } - public InvalidDateException(string message) : base(message) + public InvalidDateException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Core/Parser/IsoLanguage.cs b/src/NzbDrone.Core/Parser/IsoLanguage.cs index dcf33e88a1..20ada28592 100644 --- a/src/NzbDrone.Core/Parser/IsoLanguage.cs +++ b/src/NzbDrone.Core/Parser/IsoLanguage.cs @@ -26,6 +26,5 @@ public IsoLanguage(List<string> twoLetterCodes, string threeLetterCode, Language Language = language; AltCodes.AddRange(twoLetterCodes); } - } } diff --git a/src/NzbDrone.Core/Parser/IsoLanguages.cs b/src/NzbDrone.Core/Parser/IsoLanguages.cs index 86cb821401..d6789ec6b4 100644 --- a/src/NzbDrone.Core/Parser/IsoLanguages.cs +++ b/src/NzbDrone.Core/Parser/IsoLanguages.cs @@ -8,7 +8,7 @@ public static class IsoLanguages { private static readonly HashSet<IsoLanguage> All = new HashSet<IsoLanguage> { - new IsoLanguage(new List<string> {"en", "us", "uk"}, "eng", Language.English), + new IsoLanguage(new List<string> { "en", "us", "uk" }, "eng", Language.English), new IsoLanguage("fr", "fra", Language.French), new IsoLanguage("es", "spa", Language.Spanish), new IsoLanguage("de", "deu", Language.German), @@ -16,6 +16,7 @@ public static class IsoLanguages new IsoLanguage("da", "dan", Language.Danish), new IsoLanguage("nl", "nld", Language.Dutch), new IsoLanguage("ja", "jpn", Language.Japanese), + // new IsoLanguage("", "", Language.Cantonese), // new IsoLanguage("", "", Language.Mandarin), new IsoLanguage("ru", "rus", Language.Russian), @@ -26,6 +27,7 @@ public static class IsoLanguages new IsoLanguage("fi", "fin", Language.Finnish), new IsoLanguage("tr", "tur", Language.Turkish), new IsoLanguage("pt", "por", Language.Portuguese), + // new IsoLanguage("nl", "nld", Language.Flemish), new IsoLanguage("el", "ell", Language.Greek), new IsoLanguage("ko", "kor", Language.Korean), diff --git a/src/NzbDrone.Core/Parser/LanguageParser.cs b/src/NzbDrone.Core/Parser/LanguageParser.cs index 6fc88a477e..641279c795 100644 --- a/src/NzbDrone.Core/Parser/LanguageParser.cs +++ b/src/NzbDrone.Core/Parser/LanguageParser.cs @@ -25,100 +25,161 @@ public static List<Language> ParseLanguages(string title) var languages = new List<Language>(); if (lowerTitle.Contains("english")) + { languages.Add(Language.English); + } if (lowerTitle.Contains("french")) + { languages.Add(Language.French); + } if (lowerTitle.Contains("spanish")) - languages.Add( Language.Spanish); + { + languages.Add(Language.Spanish); + } if (lowerTitle.Contains("danish")) - languages.Add( Language.Danish); + { + languages.Add(Language.Danish); + } if (lowerTitle.Contains("dutch")) - languages.Add( Language.Dutch); + { + languages.Add(Language.Dutch); + } if (lowerTitle.Contains("japanese")) - languages.Add( Language.Japanese); + { + languages.Add(Language.Japanese); + } if (lowerTitle.Contains("icelandic")) - languages.Add( Language.Icelandic); + { + languages.Add(Language.Icelandic); + } if (lowerTitle.Contains("mandarin") || lowerTitle.Contains("cantonese") || lowerTitle.Contains("chinese")) - languages.Add( Language.Chinese); + { + languages.Add(Language.Chinese); + } if (lowerTitle.Contains("korean")) - languages.Add( Language.Korean); + { + languages.Add(Language.Korean); + } if (lowerTitle.Contains("russian")) - languages.Add( Language.Russian); + { + languages.Add(Language.Russian); + } if (lowerTitle.Contains("polish")) - languages.Add( Language.Polish); + { + languages.Add(Language.Polish); + } if (lowerTitle.Contains("vietnamese")) - languages.Add( Language.Vietnamese); + { + languages.Add(Language.Vietnamese); + } if (lowerTitle.Contains("swedish")) - languages.Add( Language.Swedish); + { + languages.Add(Language.Swedish); + } if (lowerTitle.Contains("norwegian")) - languages.Add( Language.Norwegian); + { + languages.Add(Language.Norwegian); + } if (lowerTitle.Contains("nordic")) - languages.Add( Language.Norwegian); + { + languages.Add(Language.Norwegian); + } if (lowerTitle.Contains("finnish")) - languages.Add( Language.Finnish); + { + languages.Add(Language.Finnish); + } if (lowerTitle.Contains("turkish")) - languages.Add( Language.Turkish); + { + languages.Add(Language.Turkish); + } if (lowerTitle.Contains("portuguese")) - languages.Add( Language.Portuguese); + { + languages.Add(Language.Portuguese); + } if (lowerTitle.Contains("hungarian")) - languages.Add( Language.Hungarian); + { + languages.Add(Language.Hungarian); + } if (lowerTitle.Contains("hebrew")) - languages.Add( Language.Hebrew); + { + languages.Add(Language.Hebrew); + } if (lowerTitle.Contains("czech")) - languages.Add( Language.Czech); + { + languages.Add(Language.Czech); + } var match = LanguageRegex.Match(title); if (match.Groups["italian"].Captures.Cast<Capture>().Any()) - languages.Add( Language.Italian); + { + languages.Add(Language.Italian); + } if (match.Groups["german"].Captures.Cast<Capture>().Any()) - languages.Add( Language.German); + { + languages.Add(Language.German); + } if (match.Groups["flemish"].Captures.Cast<Capture>().Any()) - languages.Add( Language.Flemish); + { + languages.Add(Language.Flemish); + } if (match.Groups["greek"].Captures.Cast<Capture>().Any()) - languages.Add( Language.Greek); + { + languages.Add(Language.Greek); + } if (match.Groups["french"].Success) - languages.Add( Language.French); + { + languages.Add(Language.French); + } if (match.Groups["russian"].Success) - languages.Add( Language.Russian); + { + languages.Add(Language.Russian); + } if (match.Groups["dutch"].Success) - languages.Add( Language.Dutch); + { + languages.Add(Language.Dutch); + } if (match.Groups["hungarian"].Success) - languages.Add( Language.Hungarian); + { + languages.Add(Language.Hungarian); + } if (match.Groups["hebrew"].Success) - languages.Add( Language.Hebrew); + { + languages.Add(Language.Hebrew); + } if (match.Groups["czech"].Success) - languages.Add( Language.Czech); - + { + languages.Add(Language.Czech); + } return languages.DistinctBy(l => (int)l).ToList(); } @@ -134,7 +195,10 @@ public static List<Language> EnhanceLanguages(string title, List<Language> langu } } - if (!languages.Any()) languages.Add(Language.English); + if (!languages.Any()) + { + languages.Add(Language.English); + } return languages; } diff --git a/src/NzbDrone.Core/Parser/Model/LocalMovie.cs b/src/NzbDrone.Core/Parser/Model/LocalMovie.cs index b0999f55e3..d1f96956c2 100644 --- a/src/NzbDrone.Core/Parser/Model/LocalMovie.cs +++ b/src/NzbDrone.Core/Parser/Model/LocalMovie.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; -using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; -using NzbDrone.Core.MediaFiles.MediaInfo; using NzbDrone.Core.Languages; +using NzbDrone.Core.MediaFiles.MediaInfo; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Parser.Model { @@ -26,7 +26,6 @@ public LocalMovie() public string ReleaseGroup { get; set; } public string Edition { get; set; } - public override string ToString() { return Path; diff --git a/src/NzbDrone.Core/Parser/Model/ParsedMovieInfo.cs b/src/NzbDrone.Core/Parser/Model/ParsedMovieInfo.cs index e22c02cba4..a9dbc2c18d 100644 --- a/src/NzbDrone.Core/Parser/Model/ParsedMovieInfo.cs +++ b/src/NzbDrone.Core/Parser/Model/ParsedMovieInfo.cs @@ -1,42 +1,27 @@ using System.Collections.Generic; using Newtonsoft.Json; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Languages; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Parser.Model { - /// <summary> - /// Object containing all info our intelligent parser could find out from release / file title, release info and media info. - /// </summary> public class ParsedMovieInfo { - /// <summary> - /// The fully Parsed title. This is useful for finding the matching movie in the database. - /// </summary> public string MovieTitle { get; set; } - /// <summary> - /// The simple release title replaces the actual movie title parsed with A Movie in the release / file title. - /// This is useful to not accidentaly identify stuff inside the actual movie title as quality tags, etc. - /// It also removes unecessary stuff such as file extensions. - /// </summary> public string SimpleReleaseTitle { get; set; } public QualityModel Quality { get; set; } - /// <summary> - /// Extra info is a dictionary containing extra info needed for correct quality assignement. - /// It is expanded by the augmenters. - /// </summary> [JsonIgnore] public Dictionary<string, object> ExtraInfo = new Dictionary<string, object>(); public List<Language> Languages = new List<Language>(); public string ReleaseGroup { get; set; } public string ReleaseHash { get; set; } - public string Edition { get; set;} + public string Edition { get; set; } public int Year { get; set; } public string ImdbId { get; set; } public override string ToString() { - return String.Format("{0} - {1} {2}", MovieTitle, Year, Quality); + return string.Format("{0} - {1} {2}", MovieTitle, Year, Quality); } #if LIBRARY diff --git a/src/NzbDrone.Core/Parser/Model/ReleaseInfo.cs b/src/NzbDrone.Core/Parser/Model/ReleaseInfo.cs index 42f61184c1..3c18a28144 100644 --- a/src/NzbDrone.Core/Parser/Model/ReleaseInfo.cs +++ b/src/NzbDrone.Core/Parser/Model/ReleaseInfo.cs @@ -26,14 +26,11 @@ public class ReleaseInfo public string Codec { get; set; } public string Resolution { get; set; } - public IndexerFlags IndexerFlags { get; set; } + public IndexerFlags IndexerFlags { get; set; } public int Age { - get - { - return DateTime.UtcNow.Subtract(PublishDate).Days; - } + get { return DateTime.UtcNow.Subtract(PublishDate).Days; } //This prevents manually downloading a release from blowing up in mono //TODO: Is there a better way? @@ -42,10 +39,7 @@ private set { } public double AgeHours { - get - { - return DateTime.UtcNow.Subtract(PublishDate).TotalHours; - } + get { return DateTime.UtcNow.Subtract(PublishDate).TotalHours; } //This prevents manually downloading a release from blowing up in mono //TODO: Is there a better way? @@ -54,10 +48,7 @@ private set { } public double AgeMinutes { - get - { - return DateTime.UtcNow.Subtract(PublishDate).TotalMinutes; - } + get { return DateTime.UtcNow.Subtract(PublishDate).TotalMinutes; } //This prevents manually downloading a release from blowing up in mono //TODO: Is there a better way? diff --git a/src/NzbDrone.Core/Parser/Model/RemoteMovie.cs b/src/NzbDrone.Core/Parser/Model/RemoteMovie.cs index 26758db088..9274fcaff5 100644 --- a/src/NzbDrone.Core/Parser/Model/RemoteMovie.cs +++ b/src/NzbDrone.Core/Parser/Model/RemoteMovie.cs @@ -1,5 +1,5 @@ -using NzbDrone.Core.Movies; using NzbDrone.Core.Download.Clients; +using NzbDrone.Core.Movies; namespace NzbDrone.Core.Parser.Model { diff --git a/src/NzbDrone.Core/Parser/Parser.cs b/src/NzbDrone.Core/Parser/Parser.cs index 5eee7b4200..102c1e9231 100644 --- a/src/NzbDrone.Core/Parser/Parser.cs +++ b/src/NzbDrone.Core/Parser/Parser.cs @@ -3,10 +3,10 @@ using System.IO; using System.Linq; using System.Text.RegularExpressions; -using NzbDrone.Common.Extensions; -using NzbDrone.Core.Parser.Model; using NLog; +using NzbDrone.Common.Extensions; using NzbDrone.Common.Instrumentation; +using NzbDrone.Core.Parser.Model; #if !LIBRARY #endif @@ -37,7 +37,6 @@ public static class Parser //As a last resort for movies that have ( or [ in their title. new Regex(@"^(?<title>.+?)?(?:(?:[-_\W](?<![)\[!]))*(?<year>(1(8|9)|20)\d{2}(?!p|i|\d+|\]|\W\d+)))+(\W+|_|$)(?!\\)", RegexOptions.IgnoreCase | RegexOptions.Compiled), - }; private static readonly Regex[] ReportMovieTitleFolderRegex = new[] @@ -54,7 +53,6 @@ public static class Parser private static readonly Regex[] ReportMovieTitleLenientRegexAfter = new Regex[] { - }; private static readonly Regex[] RejectHashedReleasesRegex = new Regex[] @@ -138,11 +136,11 @@ public static class Parser private static readonly Regex ReportEditionRegex = new Regex(@"\b(?<edition>(((Extended.|Ultimate.)?(Director.?s|Collector.?s|Theatrical|Ultimate|Final(?=(.(Cut|Edition|Version)))|Extended|Rogue|Special|Despecialized|\d{2,3}(th)?.Anniversary)(.(Cut|Edition|Version))?(.(Extended|Uncensored|Remastered|Unrated|Uncut|IMAX|Fan.?Edit))?|((Uncensored|Remastered|Unrated|Uncut|IMAX|Fan.?Edit|Edition|Restored|((2|3|4)in1))))))\)?\b", RegexOptions.Compiled | RegexOptions.IgnoreCase); private static readonly string[] Numbers = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; - private static Dictionary<String, String> _umlautMappings = new Dictionary<string, string> + private static Dictionary<string, string> _umlautMappings = new Dictionary<string, string> { - {"ö", "oe"}, - {"ä", "ae"}, - {"ü", "ue"}, + { "ö", "oe" }, + { "ä", "ae" }, + { "ü", "ue" }, }; public static ParsedMovieInfo ParseMoviePath(string path, bool isLenient) @@ -164,14 +162,16 @@ public static ParsedMovieInfo ParseMoviePath(string path, bool isLenient) } return result; - } public static ParsedMovieInfo ParseMovieTitle(string title, bool isLenient, bool isDir = false) { try { - if (!ValidateBeforeParsing(title)) return null; + if (!ValidateBeforeParsing(title)) + { + return null; + } Logger.Debug("Parsing string '{0}'", title); @@ -234,7 +234,6 @@ public static ParsedMovieInfo ParseMovieTitle(string title, bool isLenient, bool if (result != null) { //TODO: Add tests for this! - var simpleReleaseTitle = SimpleReleaseTitleRegex.Replace(title, string.Empty); if (result.MovieTitle.IsNotNullOrWhiteSpace()) @@ -287,7 +286,9 @@ public static ParsedMovieInfo ParseMovieTitle(string title, bool isLenient, bool catch (Exception e) { if (!title.ToLower().Contains("password") && !title.ToLower().Contains("yenc")) + { Logger.Error(e, "An error has occurred while trying to parse {0}", title); + } } Logger.Debug("Unable to parse {0}", title); @@ -377,7 +378,9 @@ public static string CleanSeriesTitle(this string title) //If Title only contains numbers return it as is. if (long.TryParse(title, out number)) + { return title; + } return ReplaceGermanUmlauts(NormalizeRegex.Replace(title, string.Empty).ToLower()).RemoveAccent(); } @@ -445,6 +448,7 @@ public static string RemoveFileExtension(string title) { return string.Empty; } + return m.Value; }); @@ -458,7 +462,6 @@ private static ParsedMovieInfo ParseMovieMatchCollection(MatchCollection matchCo return null; } - var movieName = matchCollection[0].Groups["title"].Value./*Replace('.', ' ').*/Replace('_', ' '); movieName = RequestInfoRegex.Replace(movieName, "").Trim(' '); @@ -469,10 +472,11 @@ private static ParsedMovieInfo ParseMovieMatchCollection(MatchCollection matchCo string nextPart = ""; foreach (var part in parts) { - if (parts.Length >= n+2) + if (parts.Length >= n + 2) { - nextPart = parts[n+1]; + nextPart = parts[n + 1]; } + if (part.Length == 1 && part.ToLower() != "a" && !int.TryParse(part, out n)) { movieName += part + "."; @@ -490,8 +494,10 @@ private static ParsedMovieInfo ParseMovieMatchCollection(MatchCollection matchCo movieName += " "; previousAcronym = false; } + movieName += part + " "; } + n++; } diff --git a/src/NzbDrone.Core/Parser/ParsingService.cs b/src/NzbDrone.Core/Parser/ParsingService.cs index a97b395052..2eac5bde00 100644 --- a/src/NzbDrone.Core/Parser/ParsingService.cs +++ b/src/NzbDrone.Core/Parser/ParsingService.cs @@ -8,12 +8,12 @@ using NzbDrone.Core.CustomFormats; using NzbDrone.Core.DecisionEngine; using NzbDrone.Core.IndexerSearch.Definitions; +using NzbDrone.Core.Movies; using NzbDrone.Core.Movies.AlternativeTitles; +using NzbDrone.Core.Parser.Augmenters; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Parser.RomanNumerals; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; -using NzbDrone.Core.Parser.Augmenters; namespace NzbDrone.Core.Parser { @@ -82,7 +82,6 @@ public ParsedMovieInfo EnhanceMovieInfo(ParsedMovieInfo minimalInfo, List<object // minimalInfo.Quality.Quality = QualityFinder.FindBySourceAndResolution(minimalInfo.Quality.Quality.Source, minimalInfo.Quality.Quality.Resolution, // minimalInfo.Quality.Quality.Modifier); - if (minimalInfo != null) { minimalInfo.Quality.CustomFormats = ParseCustomFormat(minimalInfo); @@ -190,8 +189,9 @@ public MappingResult Map(ParsedMovieInfo parsedMovieInfo, string imdbId, SearchC { var result = GetMovie(parsedMovieInfo, imdbId, searchCriteria); - if (result == null) { - result = new MappingResult {MappingResultType = MappingResultType.Unknown}; + if (result == null) + { + result = new MappingResult { MappingResultType = MappingResultType.Unknown }; result.Movie = null; } @@ -204,7 +204,7 @@ private MappingResult GetMovie(ParsedMovieInfo parsedMovieInfo, string imdbId, S { // TODO: Answer me this: Wouldn't it be smarter to start out looking for a movie if we have an ImDb Id? MappingResult result = null; - if (!String.IsNullOrWhiteSpace(imdbId) && imdbId != "0") + if (!string.IsNullOrWhiteSpace(imdbId) && imdbId != "0") { if (TryGetMovieByImDbId(parsedMovieInfo, imdbId, out result)) { @@ -233,17 +233,23 @@ private MappingResult GetMovie(ParsedMovieInfo parsedMovieInfo, string imdbId, S private bool TryGetMovieByImDbId(ParsedMovieInfo parsedMovieInfo, string imdbId, out MappingResult result) { var movie = _movieService.FindByImdbId(imdbId); + //Should fix practically all problems, where indexer is shite at adding correct imdbids to movies. if (movie != null && parsedMovieInfo.Year > 1800 && (parsedMovieInfo.Year != movie.Year && movie.SecondaryYear != parsedMovieInfo.Year)) { - result = new MappingResult { Movie = movie, MappingResultType = MappingResultType.WrongYear}; + result = new MappingResult { Movie = movie, MappingResultType = MappingResultType.WrongYear }; return false; } - if (movie != null) { + + if (movie != null) + { result = new MappingResult { Movie = movie }; - } else { - result = new MappingResult { Movie = movie, MappingResultType = MappingResultType.TitleNotFound}; } + else + { + result = new MappingResult { Movie = movie, MappingResultType = MappingResultType.TitleNotFound }; + } + return movie != null; } @@ -264,7 +270,7 @@ private bool TryGetMovieByTitleAndOrYear(ParsedMovieInfo parsedMovieInfo, out Ma movieByTitleAndOrYear = _movieService.FindByTitle(parsedMovieInfo.MovieTitle); if (isNotNull(movieByTitleAndOrYear)) { - result = new MappingResult { Movie = movieByTitleAndOrYear, MappingResultType = MappingResultType.WrongYear}; + result = new MappingResult { Movie = movieByTitleAndOrYear, MappingResultType = MappingResultType.WrongYear }; return false; } @@ -273,12 +279,12 @@ private bool TryGetMovieByTitleAndOrYear(ParsedMovieInfo parsedMovieInfo, out Ma movieByTitleAndOrYear = _movieService.FindByTitleInexact(parsedMovieInfo.MovieTitle, parsedMovieInfo.Year); if (isNotNull(movieByTitleAndOrYear)) { - result = new MappingResult {Movie = movieByTitleAndOrYear, MappingResultType = MappingResultType.SuccessLenientMapping}; + result = new MappingResult { Movie = movieByTitleAndOrYear, MappingResultType = MappingResultType.SuccessLenientMapping }; return true; } } - result = new MappingResult { Movie = movieByTitleAndOrYear, MappingResultType = MappingResultType.TitleNotFound}; + result = new MappingResult { Movie = movieByTitleAndOrYear, MappingResultType = MappingResultType.TitleNotFound }; return false; } @@ -294,12 +300,12 @@ private bool TryGetMovieByTitleAndOrYear(ParsedMovieInfo parsedMovieInfo, out Ma movieByTitleAndOrYear = _movieService.FindByTitleInexact(parsedMovieInfo.MovieTitle, null); if (isNotNull(movieByTitleAndOrYear)) { - result = new MappingResult {Movie = movieByTitleAndOrYear, MappingResultType = MappingResultType.SuccessLenientMapping}; + result = new MappingResult { Movie = movieByTitleAndOrYear, MappingResultType = MappingResultType.SuccessLenientMapping }; return true; } } - result = new MappingResult { Movie = movieByTitleAndOrYear, MappingResultType = MappingResultType.TitleNotFound}; + result = new MappingResult { Movie = movieByTitleAndOrYear, MappingResultType = MappingResultType.TitleNotFound }; return false; } @@ -331,7 +337,6 @@ private bool TryGetMovieBySearchCriteria(ParsedMovieInfo parsedMovieInfo, Search string romanNumeral = numeralMapping.RomanNumeralLowerCase; //_logger.Debug(cleanTitle); - if (title.Replace(arabicNumeral, romanNumeral) == parsedMovieInfo.MovieTitle.CleanSeriesTitle()) { possibleMovie = searchCriteria.Movie; @@ -341,7 +346,6 @@ private bool TryGetMovieBySearchCriteria(ParsedMovieInfo parsedMovieInfo, Search { possibleMovie = searchCriteria.Movie; } - } } @@ -352,6 +356,7 @@ private bool TryGetMovieBySearchCriteria(ParsedMovieInfo parsedMovieInfo, Search result = new MappingResult { Movie = possibleMovie, MappingResultType = MappingResultType.Success }; return true; } + result = new MappingResult { Movie = possibleMovie, MappingResultType = MappingResultType.WrongYear }; return false; } @@ -362,9 +367,9 @@ private bool TryGetMovieBySearchCriteria(ParsedMovieInfo parsedMovieInfo, Search cleanTitle.Contains(searchCriteria.Movie.CleanTitle)) { possibleMovie = searchCriteria.Movie; - if (parsedMovieInfo.Year > 1800 && parsedMovieInfo.Year == possibleMovie.Year || possibleMovie.SecondaryYear == parsedMovieInfo.Year) + if ((parsedMovieInfo.Year > 1800 && parsedMovieInfo.Year == possibleMovie.Year) || possibleMovie.SecondaryYear == parsedMovieInfo.Year) { - result = new MappingResult {Movie = possibleMovie, MappingResultType = MappingResultType.SuccessLenientMapping}; + result = new MappingResult { Movie = possibleMovie, MappingResultType = MappingResultType.SuccessLenientMapping }; return true; } @@ -383,10 +388,8 @@ private bool TryGetMovieBySearchCriteria(ParsedMovieInfo parsedMovieInfo, Search return false; } - } - public class MappingResult { public string Message @@ -417,8 +420,10 @@ public string Message public RemoteMovie RemoteMovie; public MappingResultType MappingResultType { get; set; } - public Movie Movie { - get { + public Movie Movie + { + get + { return RemoteMovie.Movie; } set @@ -428,6 +433,7 @@ public Movie Movie { { parsedInfo = RemoteMovie.ParsedMovieInfo; } + RemoteMovie = new RemoteMovie { Movie = value, @@ -438,11 +444,13 @@ public Movie Movie { public string ReleaseName { get; set; } - public override string ToString() { + public override string ToString() + { return string.Format(Message, RemoteMovie.Movie); } - public Rejection ToRejection() { + public Rejection ToRejection() + { switch (MappingResultType) { case MappingResultType.Success: diff --git a/src/NzbDrone.Core/Parser/QualityParser.cs b/src/NzbDrone.Core/Parser/QualityParser.cs index 992a64681c..78606fb8c6 100644 --- a/src/NzbDrone.Core/Parser/QualityParser.cs +++ b/src/NzbDrone.Core/Parser/QualityParser.cs @@ -128,7 +128,6 @@ public static QualityModel ParseQualityName(string name) { if (sourceMatch.Groups["bluray"].Success) { - if (brDiskMatch) { result.Quality = Quality.BRDISK; @@ -352,7 +351,6 @@ public static QualityModel ParseQualityName(string name) } } - // Anime Bluray matching if (AnimeBlurayRegex.Match(normalizedName).Success) { @@ -474,12 +472,35 @@ private static Resolution ParseResolution(string name) { var match = ResolutionRegex.Match(name); - if (!match.Success) return Resolution.Unknown; - if (match.Groups["R480p"].Success) return Resolution.R480p; - if (match.Groups["R576p"].Success) return Resolution.R576p; - if (match.Groups["R720p"].Success) return Resolution.R720p; - if (match.Groups["R1080p"].Success) return Resolution.R1080p; - if (match.Groups["R2160p"].Success) return Resolution.R2160p; + if (!match.Success) + { + return Resolution.Unknown; + } + + if (match.Groups["R480p"].Success) + { + return Resolution.R480p; + } + + if (match.Groups["R576p"].Success) + { + return Resolution.R576p; + } + + if (match.Groups["R720p"].Success) + { + return Resolution.R720p; + } + + if (match.Groups["R1080p"].Success) + { + return Resolution.R1080p; + } + + if (match.Groups["R2160p"].Success) + { + return Resolution.R2160p; + } return Resolution.Unknown; } @@ -488,9 +509,20 @@ private static Quality OtherSourceMatch(string name) { var match = OtherSourceRegex.Match(name); - if (!match.Success) return Quality.Unknown; - if (match.Groups["sdtv"].Success) return Quality.SDTV; - if (match.Groups["hdtv"].Success) return Quality.HDTV720p; + if (!match.Success) + { + return Quality.Unknown; + } + + if (match.Groups["sdtv"].Success) + { + return Quality.SDTV; + } + + if (match.Groups["hdtv"].Success) + { + return Quality.HDTV720p; + } return Quality.Unknown; } diff --git a/src/NzbDrone.Core/Parser/RegexReplace.cs b/src/NzbDrone.Core/Parser/RegexReplace.cs index b27f0c4c1a..40ff075ce6 100644 --- a/src/NzbDrone.Core/Parser/RegexReplace.cs +++ b/src/NzbDrone.Core/Parser/RegexReplace.cs @@ -23,18 +23,27 @@ public RegexReplace(string pattern, MatchEvaluator replacement, RegexOptions reg public string Replace(string input) { if (_replacementFunc != null) + { return _regex.Replace(input, _replacementFunc); + } else + { return _regex.Replace(input, _replacementFormat); + } } public bool TryReplace(ref string input) { var result = _regex.IsMatch(input); if (_replacementFunc != null) + { input = _regex.Replace(input, _replacementFunc); + } else + { input = _regex.Replace(input, _replacementFormat); + } + return result; } } diff --git a/src/NzbDrone.Core/Parser/RomanNumerals/RomanNumeral.cs b/src/NzbDrone.Core/Parser/RomanNumerals/RomanNumeral.cs index 233bad2bce..bec6cb7dc8 100644 --- a/src/NzbDrone.Core/Parser/RomanNumerals/RomanNumeral.cs +++ b/src/NzbDrone.Core/Parser/RomanNumerals/RomanNumeral.cs @@ -9,8 +9,6 @@ namespace NzbDrone.Core.Parser.RomanNumerals /// </summary> public class RomanNumeral : IComparable, IComparable<RomanNumeral>, IEquatable<RomanNumeral>, IRomanNumeral { - #region Fields - /// <summary> /// The numeric value of the roman numeral. /// </summary> @@ -31,10 +29,6 @@ public class RomanNumeral : IComparable, IComparable<RomanNumeral>, IEquatable<R private static readonly string[] Tens = { "XC", "LXXX", "LXX", "LX", "L", "XL", "XXX", "XX", "X" }; private static readonly string[] Units = { "IX", "VIII", "VII", "VI", "V", "IV", "III", "II", "I" }; - #endregion - - #region Constructors - /// <summary> /// Initializes a new instance of the <see cref="RomanNumeral"/> class. /// </summary> @@ -66,10 +60,6 @@ public RomanNumeral(string romanNumeral) } } - #endregion - - #region Methods - /// <summary> /// Converts this instance to an integer. /// </summary> @@ -101,7 +91,11 @@ public long ToLong() public static bool TryParse(string text, out int value) { value = 0; - if (string.IsNullOrEmpty(text)) return false; + if (string.IsNullOrEmpty(text)) + { + return false; + } + text = text.ToUpper(); int len = 0; @@ -188,10 +182,26 @@ private static string ToRomanNumeral(int number) tens = number / 10; units = number % 10; var sb = new StringBuilder(); - if (thousands > 0) sb.Append(Thousands[3 - thousands]); - if (hundreds > 0) sb.Append(Hundreds[9 - hundreds]); - if (tens > 0) sb.Append(Tens[9 - tens]); - if (units > 0) sb.Append(Units[9 - units]); + if (thousands > 0) + { + sb.Append(Thousands[3 - thousands]); + } + + if (hundreds > 0) + { + sb.Append(Hundreds[9 - hundreds]); + } + + if (tens > 0) + { + sb.Append(Tens[9 - tens]); + } + + if (units > 0) + { + sb.Append(Units[9 - units]); + } + return sb.ToString(); } @@ -199,7 +209,7 @@ private static string ToRomanNumeral(int number) /// Returns the Roman numeral that was passed in as either an Arabic numeral /// or a Roman numeral. /// </summary> - /// <returns>A <see cref="System.String" /> representing a Roman Numeral</returns> + /// <returns>A <see cref="System.string" /> representing a Roman Numeral</returns> public string ToRomanNumeral() { return ToString(); @@ -217,17 +227,16 @@ public string ToRomanNumeral() private static void RangeGuard(int number) { if (number > MaxValue) - throw new ArgumentOutOfRangeException(nameof(number), number, - $"Roman numerals can not be larger than {MaxValue}."); + { + throw new ArgumentOutOfRangeException(nameof(number), number, $"Roman numerals can not be larger than {MaxValue}."); + } + if (number < MinValue) - throw new ArgumentOutOfRangeException(nameof(number), number, - $"Roman numerals can not be smaller than {MinValue}."); + { + throw new ArgumentOutOfRangeException(nameof(number), number, $"Roman numerals can not be smaller than {MinValue}."); + } } - #endregion - - #region Operators - /// <summary> /// Implements the operator *. /// </summary> @@ -280,10 +289,6 @@ private static void RangeGuard(int number) return new RomanNumeral(firstNumeral._value - secondNumeral._value); } - #endregion - - #region Interface Implementations - /// <summary> /// </summary> /// <param name="obj">The object.</param> @@ -344,14 +349,11 @@ public bool Equals(RomanNumeral other) /// during creation. /// </summary> /// <returns> - /// A <see cref="System.String" /> that represents a Roman Numeral. + /// A <see cref="System.string" /> that represents a Roman Numeral. /// </returns> public override string ToString() { return ToRomanNumeral(_value); } - - #endregion } - } diff --git a/src/NzbDrone.Core/Parser/RomanNumerals/RomanNumeralParser.cs b/src/NzbDrone.Core/Parser/RomanNumerals/RomanNumeralParser.cs index 38066af65e..e8d6368d71 100644 --- a/src/NzbDrone.Core/Parser/RomanNumerals/RomanNumeralParser.cs +++ b/src/NzbDrone.Core/Parser/RomanNumerals/RomanNumeralParser.cs @@ -4,8 +4,6 @@ namespace NzbDrone.Core.Parser.RomanNumerals { - - public static class RomanNumeralParser { private const int DICTIONARY_PREPOPULATION_SIZE = 20; @@ -21,13 +19,14 @@ static RomanNumeralParser() private static void PopluateDictionariesReasonablyLarge() { - if(_simpleArabicNumeralMappings != null || _arabicRomanNumeralsMapping != null) + if (_simpleArabicNumeralMappings != null || _arabicRomanNumeralsMapping != null) { return; } + _arabicRomanNumeralsMapping = new HashSet<ArabicRomanNumeral>(); _simpleArabicNumeralMappings = new Dictionary<SimpleArabicNumeral, SimpleRomanNumeral>(); - foreach (int arabicNumeral in Enumerable.Range(1,DICTIONARY_PREPOPULATION_SIZE +1)) + foreach (int arabicNumeral in Enumerable.Range(1, DICTIONARY_PREPOPULATION_SIZE + 1)) { string romanNumeralAsString, arabicNumeralAsString; GenerateRomanNumerals(arabicNumeral, out romanNumeralAsString, out arabicNumeralAsString); @@ -58,6 +57,7 @@ private static HashSet<ArabicRomanNumeral> GenerateAdditionalMappings(int offset ArabicRomanNumeral arm = new ArabicRomanNumeral(arabicNumeral, arabicNumeralAsString, romanNumeral); additionalArabicRomanNumerals.Add(arm); } + return additionalArabicRomanNumerals; } @@ -71,18 +71,20 @@ public static HashSet<ArabicRomanNumeral> GetArabicRomanNumeralsMapping(int upTo if (upToArabicNumber < DICTIONARY_PREPOPULATION_SIZE) { return - (HashSet<ArabicRomanNumeral>) - new HashSet<ArabicRomanNumeral>(_arabicRomanNumeralsMapping).Take(upToArabicNumber); + (HashSet<ArabicRomanNumeral>)new HashSet<ArabicRomanNumeral>(_arabicRomanNumeralsMapping).Take(upToArabicNumber); } + if (upToArabicNumber >= DICTIONARY_PREPOPULATION_SIZE) { if (_arabicRomanNumeralsMapping.Count >= upToArabicNumber) { return new HashSet<ArabicRomanNumeral>(_arabicRomanNumeralsMapping.Take(upToArabicNumber)); } + HashSet<ArabicRomanNumeral> largerMapping = GenerateAdditionalMappings(DICTIONARY_PREPOPULATION_SIZE + 1, upToArabicNumber); _arabicRomanNumeralsMapping = (HashSet<ArabicRomanNumeral>)_arabicRomanNumeralsMapping.Union(largerMapping); } + return _arabicRomanNumeralsMapping; } @@ -99,30 +101,32 @@ public static Dictionary<SimpleArabicNumeral, SimpleRomanNumeral> GetArabicRoman { return take(_simpleArabicNumeralMappings, upToArabicNumer); } + if (upToArabicNumer > DICTIONARY_PREPOPULATION_SIZE) { if (_simpleArabicNumeralMappings.Count >= upToArabicNumer) { return take(_simpleArabicNumeralMappings, upToArabicNumer); } + var moreSimpleNumerals = GenerateAdditionalSimpleNumerals(DICTIONARY_PREPOPULATION_SIZE, upToArabicNumer); _simpleArabicNumeralMappings = - (Dictionary<SimpleArabicNumeral, SimpleRomanNumeral>) - _simpleArabicNumeralMappings.Union(moreSimpleNumerals); + (Dictionary<SimpleArabicNumeral, SimpleRomanNumeral>)_simpleArabicNumeralMappings.Union(moreSimpleNumerals); return take(_simpleArabicNumeralMappings, _arabicRomanNumeralsMapping.Count); } + if (upToArabicNumer < DICTIONARY_PREPOPULATION_SIZE) { return take(_simpleArabicNumeralMappings, upToArabicNumer); } + return _simpleArabicNumeralMappings; } - private static Dictionary<SimpleArabicNumeral, SimpleRomanNumeral> GenerateAdditionalSimpleNumerals(int offset, int length) { - Dictionary<SimpleArabicNumeral,SimpleRomanNumeral> moreNumerals = new Dictionary<SimpleArabicNumeral, SimpleRomanNumeral>(); + Dictionary<SimpleArabicNumeral, SimpleRomanNumeral> moreNumerals = new Dictionary<SimpleArabicNumeral, SimpleRomanNumeral>(); foreach (int arabicNumeral in Enumerable.Range(offset, length)) { string romanNumeral; @@ -130,16 +134,10 @@ private static Dictionary<SimpleArabicNumeral, SimpleRomanNumeral> GenerateAddit GenerateRomanNumerals(arabicNumeral, out romanNumeral, out arabicNumeralAsString); SimpleArabicNumeral san = new SimpleArabicNumeral(arabicNumeral); SimpleRomanNumeral srn = new SimpleRomanNumeral(romanNumeral); - moreNumerals.Add(san,srn); + moreNumerals.Add(san, srn); } + return moreNumerals; } - - - - - - - } } diff --git a/src/NzbDrone.Core/Parser/SceneChecker.cs b/src/NzbDrone.Core/Parser/SceneChecker.cs index ba292da44f..9989b3ad98 100644 --- a/src/NzbDrone.Core/Parser/SceneChecker.cs +++ b/src/NzbDrone.Core/Parser/SceneChecker.cs @@ -1,4 +1,4 @@ -namespace NzbDrone.Core.Parser +namespace NzbDrone.Core.Parser { public static class SceneChecker { @@ -6,8 +6,15 @@ public static class SceneChecker //It's better not to use a title that might be scene than to use one that isn't scene public static bool IsSceneTitle(string title) { - if (!title.Contains(".")) return false; - if (title.Contains(" ")) return false; + if (!title.Contains(".")) + { + return false; + } + + if (title.Contains(" ")) + { + return false; + } var parsedTitle = Parser.ParseMovieTitle(title, false); //We are not lenient when it comes to scene checking! diff --git a/src/NzbDrone.Core/Profiles/Delay/DelayProfileRepository.cs b/src/NzbDrone.Core/Profiles/Delay/DelayProfileRepository.cs index 3766cfbbad..d268fbb6c9 100644 --- a/src/NzbDrone.Core/Profiles/Delay/DelayProfileRepository.cs +++ b/src/NzbDrone.Core/Profiles/Delay/DelayProfileRepository.cs @@ -5,7 +5,6 @@ namespace NzbDrone.Core.Profiles.Delay { public interface IDelayProfileRepository : IBasicRepository<DelayProfile> { - } public class DelayProfileRepository : BasicRepository<DelayProfile>, IDelayProfileRepository diff --git a/src/NzbDrone.Core/Profiles/Delay/DelayProfileService.cs b/src/NzbDrone.Core/Profiles/Delay/DelayProfileService.cs index 85d2aa0540..0179205d44 100644 --- a/src/NzbDrone.Core/Profiles/Delay/DelayProfileService.cs +++ b/src/NzbDrone.Core/Profiles/Delay/DelayProfileService.cs @@ -55,7 +55,10 @@ public void Delete(int id) for (int i = 0; i < all.Count; i++) { - if (all[i].Id == 1) continue; + if (all[i].Id == 1) + { + continue; + } all[i].Order = i + 1; } @@ -127,18 +130,15 @@ public List<DelayProfile> Reorder(int id, int? afterId) { delayProfile.Order = afterOrder + 1; } - else if (delayProfile.Id == after?.Id) { delayProfile.Order = afterOrder; } - else if (delayProfile.Order > afterOrder) { delayProfile.Order = afterCount; afterCount++; } - else if (delayProfile.Order > movingOrder) { delayProfile.Order--; diff --git a/src/NzbDrone.Core/Profiles/Delay/DelayProfileTagInUseValidator.cs b/src/NzbDrone.Core/Profiles/Delay/DelayProfileTagInUseValidator.cs index 4e7ad94fb7..cfd08a2f4c 100644 --- a/src/NzbDrone.Core/Profiles/Delay/DelayProfileTagInUseValidator.cs +++ b/src/NzbDrone.Core/Profiles/Delay/DelayProfileTagInUseValidator.cs @@ -17,14 +17,20 @@ public DelayProfileTagInUseValidator(IDelayProfileService delayProfileService) protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } dynamic instance = context.ParentContext.InstanceToValidate; var instanceId = (int)instance.Id; var collection = context.PropertyValue as HashSet<int>; - if (collection == null || collection.Empty()) return true; + if (collection == null || collection.Empty()) + { + return true; + } return _delayProfileService.All().None(d => d.Id != instanceId && d.Tags.Intersect(collection).Any()); } diff --git a/src/NzbDrone.Core/Profiles/ProfileInUseException.cs b/src/NzbDrone.Core/Profiles/ProfileInUseException.cs index 5753ef0cc7..6d2fef2c99 100644 --- a/src/NzbDrone.Core/Profiles/ProfileInUseException.cs +++ b/src/NzbDrone.Core/Profiles/ProfileInUseException.cs @@ -7,7 +7,6 @@ public class ProfileInUseException : NzbDroneException public ProfileInUseException(int profileId) : base("Profile [{0}] is in use.", profileId) { - } } } diff --git a/src/NzbDrone.Core/Profiles/ProfileService.cs b/src/NzbDrone.Core/Profiles/ProfileService.cs index a541978d85..80be985742 100644 --- a/src/NzbDrone.Core/Profiles/ProfileService.cs +++ b/src/NzbDrone.Core/Profiles/ProfileService.cs @@ -2,12 +2,12 @@ using System.Linq; using NLog; using NzbDrone.Core.CustomFormats; +using NzbDrone.Core.Languages; using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Messaging.Events; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Movies; using NzbDrone.Core.NetImport; -using NzbDrone.Core.Languages; +using NzbDrone.Core.Qualities; namespace NzbDrone.Core.Profiles { @@ -32,8 +32,11 @@ public class ProfileService : IProfileService, IHandle<ApplicationStartedEvent> private readonly ICustomFormatService _formatService; private readonly Logger _logger; - public ProfileService(IProfileRepository profileRepository, IMovieService movieService, - INetImportFactory netImportFactory, ICustomFormatService formatService, Logger logger) + public ProfileService(IProfileRepository profileRepository, + IMovieService movieService, + INetImportFactory netImportFactory, + ICustomFormatService formatService, + Logger logger) { _profileRepository = profileRepository; _movieService = movieService; @@ -111,11 +114,15 @@ public void Handle(ApplicationStartedEvent message) { // Hack to force custom formats to be loaded into memory, if you have a better solution please let me know. _formatService.All(); - if (All().Any()) return; + if (All().Any()) + { + return; + } _logger.Info("Setting up default quality profiles"); - AddDefaultProfile("Any", Quality.Bluray480p, + AddDefaultProfile("Any", + Quality.Bluray480p, Quality.WORKPRINT, Quality.CAM, Quality.TELESYNC, @@ -145,7 +152,8 @@ public void Handle(ApplicationStartedEvent message) Quality.Remux2160p, Quality.BRDISK); - AddDefaultProfile("SD", Quality.Bluray480p, + AddDefaultProfile("SD", + Quality.Bluray480p, Quality.WORKPRINT, Quality.CAM, Quality.TELESYNC, @@ -159,27 +167,31 @@ public void Handle(ApplicationStartedEvent message) Quality.Bluray480p, Quality.Bluray576p); - AddDefaultProfile("HD-720p", Quality.Bluray720p, + AddDefaultProfile("HD-720p", + Quality.Bluray720p, Quality.HDTV720p, Quality.WEBDL720p, Quality.WEBRip720p, Quality.Bluray720p); - AddDefaultProfile("HD-1080p", Quality.Bluray1080p, + AddDefaultProfile("HD-1080p", + Quality.Bluray1080p, Quality.HDTV1080p, Quality.WEBDL1080p, Quality.WEBRip1080p, Quality.Bluray1080p, Quality.Remux1080p); - AddDefaultProfile("Ultra-HD", Quality.Remux2160p, + AddDefaultProfile("Ultra-HD", + Quality.Remux2160p, Quality.HDTV2160p, Quality.WEBDL2160p, Quality.WEBRip2160p, Quality.Bluray2160p, Quality.Remux2160p); - AddDefaultProfile("HD - 720p/1080p", Quality.Bluray720p, + AddDefaultProfile("HD - 720p/1080p", + Quality.Bluray720p, Quality.HDTV720p, Quality.HDTV1080p, Quality.WEBDL720p, @@ -189,8 +201,7 @@ public void Handle(ApplicationStartedEvent message) Quality.Bluray720p, Quality.Bluray1080p, Quality.Remux1080p, - Quality.Remux2160p - ); + Quality.Remux2160p); } public Profile GetDefaultProfile(string name, Quality cutoff = null, params Quality[] allowed) diff --git a/src/NzbDrone.Core/ProgressMessaging/ProgressMessageContext.cs b/src/NzbDrone.Core/ProgressMessaging/ProgressMessageContext.cs index 9911c47229..fba9ca3f37 100644 --- a/src/NzbDrone.Core/ProgressMessaging/ProgressMessageContext.cs +++ b/src/NzbDrone.Core/ProgressMessaging/ProgressMessageContext.cs @@ -20,7 +20,9 @@ public static CommandModel CommandModel public static bool LockReentrancy() { if (_reentrancyLock) + { return false; + } _reentrancyLock = true; return true; diff --git a/src/NzbDrone.Core/ProgressMessaging/ProgressMessageTarget.cs b/src/NzbDrone.Core/ProgressMessaging/ProgressMessageTarget.cs index 60a863e387..37885c47dc 100644 --- a/src/NzbDrone.Core/ProgressMessaging/ProgressMessageTarget.cs +++ b/src/NzbDrone.Core/ProgressMessaging/ProgressMessageTarget.cs @@ -1,5 +1,5 @@ -using NLog.Config; -using NLog; +using NLog; +using NLog.Config; using NLog.Targets; using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Messaging.Commands; @@ -23,9 +23,16 @@ protected override void Write(LogEventInfo logEvent) { var command = ProgressMessageContext.CommandModel; - if (!IsClientMessage(logEvent, command)) return; + if (!IsClientMessage(logEvent, command)) + { + return; + } + + if (!ProgressMessageContext.LockReentrancy()) + { + return; + } - if (!ProgressMessageContext.LockReentrancy()) return; try { _commandQueueManager.SetMessage(command, logEvent.FormattedMessage); diff --git a/src/NzbDrone.Core/Qualities/Quality.cs b/src/NzbDrone.Core/Qualities/Quality.cs index ed0f34e811..a39d60a334 100644 --- a/src/NzbDrone.Core/Qualities/Quality.cs +++ b/src/NzbDrone.Core/Qualities/Quality.cs @@ -39,15 +39,30 @@ public override int GetHashCode() public bool Equals(Quality other) { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; + if (ReferenceEquals(null, other)) + { + return false; + } + + if (ReferenceEquals(this, other)) + { + return true; + } + return Id.Equals(other.Id); } public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; + if (ReferenceEquals(null, obj)) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } return Equals(obj as Quality); } @@ -192,7 +207,6 @@ static Quality() #endif } - public static readonly List<Quality> All; public static readonly Quality[] AllLookup; @@ -201,12 +215,17 @@ static Quality() #endif public static Quality FindById(int id) { - if (id == 0) return Unknown; + if (id == 0) + { + return Unknown; + } var quality = AllLookup[id]; if (quality == null) + { throw new ArgumentException("ID does not match a known quality", "id"); + } return quality; } diff --git a/src/NzbDrone.Core/Qualities/QualityDefinition.cs b/src/NzbDrone.Core/Qualities/QualityDefinition.cs index abdb7831f4..74fb217936 100644 --- a/src/NzbDrone.Core/Qualities/QualityDefinition.cs +++ b/src/NzbDrone.Core/Qualities/QualityDefinition.cs @@ -15,7 +15,6 @@ public class QualityDefinition : ModelBase public QualityDefinition() { - } public QualityDefinition(Quality quality) diff --git a/src/NzbDrone.Core/Qualities/QualityDefinitionRepository.cs b/src/NzbDrone.Core/Qualities/QualityDefinitionRepository.cs index 49941710c9..8663b6b4ae 100644 --- a/src/NzbDrone.Core/Qualities/QualityDefinitionRepository.cs +++ b/src/NzbDrone.Core/Qualities/QualityDefinitionRepository.cs @@ -1,7 +1,6 @@ using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; - namespace NzbDrone.Core.Qualities { public interface IQualityDefinitionRepository : IBasicRepository<QualityDefinition> diff --git a/src/NzbDrone.Core/Qualities/QualityDefinitionService.cs b/src/NzbDrone.Core/Qualities/QualityDefinitionService.cs index 31924867c1..166532ee56 100644 --- a/src/NzbDrone.Core/Qualities/QualityDefinitionService.cs +++ b/src/NzbDrone.Core/Qualities/QualityDefinitionService.cs @@ -1,10 +1,10 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using NLog; +using NzbDrone.Common.Cache; using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Messaging.Events; -using System; -using NzbDrone.Common.Cache; namespace NzbDrone.Core.Qualities { @@ -26,7 +26,7 @@ public class QualityDefinitionService : IQualityDefinitionService, IHandle<Appli public QualityDefinitionService(IQualityDefinitionRepository repo, ICacheManager cacheManager, Logger logger) { _repo = repo; - _cache = cacheManager.GetCache<Dictionary<Quality, QualityDefinition>>(this.GetType()); + _cache = cacheManager.GetCache<Dictionary<Quality, QualityDefinition>>(GetType()); _logger = logger; } @@ -78,7 +78,6 @@ private void InsertMissingDefinitions() { insertList.Add(definition); } - else { updateList.Add(existing); diff --git a/src/NzbDrone.Core/Qualities/QualityModel.cs b/src/NzbDrone.Core/Qualities/QualityModel.cs index 2dc53cb73e..b9ba426c36 100644 --- a/src/NzbDrone.Core/Qualities/QualityModel.cs +++ b/src/NzbDrone.Core/Qualities/QualityModel.cs @@ -12,7 +12,6 @@ public class QualityModel : IEmbeddedDocument, IEquatable<QualityModel> public List<CustomFormat> CustomFormats { get; set; } - public Revision Revision { get; set; } public string HardcodedSubs { get; set; } @@ -23,7 +22,6 @@ public class QualityModel : IEmbeddedDocument, IEquatable<QualityModel> public QualityModel() : this(Quality.Unknown, new Revision()) { - } public QualityModel(Quality quality, Revision revision = null, List<CustomFormat> customFormats = null) @@ -40,27 +38,42 @@ public override string ToString() public override int GetHashCode() { - unchecked // Overflow is fine, just wrap + // Overflow is fine, just wrap + unchecked { int hash = 17; - hash = hash * 23 + Revision.GetHashCode(); - hash = hash * 23 + Quality.GetHashCode(); + hash = (hash * 23) + Revision.GetHashCode(); + hash = (hash * 23) + Quality.GetHashCode(); return hash; } } public bool Equals(QualityModel other) { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; + if (ReferenceEquals(null, other)) + { + return false; + } + + if (ReferenceEquals(this, other)) + { + return true; + } return other.Quality.Id.Equals(Quality.Id) && other.Revision.Equals(Revision); } public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; + if (ReferenceEquals(null, obj)) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } return Equals(obj as QualityModel); } diff --git a/src/NzbDrone.Core/Qualities/Revision.cs b/src/NzbDrone.Core/Qualities/Revision.cs index d9590db597..4847150ffe 100644 --- a/src/NzbDrone.Core/Qualities/Revision.cs +++ b/src/NzbDrone.Core/Qualities/Revision.cs @@ -22,17 +22,35 @@ public Revision(int version = 1, int real = 0, bool isRepack = false) public bool Equals(Revision other) { - if (ReferenceEquals(null, other)) return false; + if (ReferenceEquals(null, other)) + { + return false; + } return other.Version.Equals(Version) && other.Real.Equals(Real); } public int CompareTo(Revision other) { - if (Real > other.Real) return 1; - if (Real < other.Real) return -1; - if (Version > other.Version) return 1; - if (Version < other.Version) return -1; + if (Real > other.Real) + { + return 1; + } + + if (Real < other.Real) + { + return -1; + } + + if (Version > other.Version) + { + return 1; + } + + if (Version < other.Version) + { + return -1; + } return 0; } @@ -58,8 +76,15 @@ public override int GetHashCode() public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; + if (ReferenceEquals(null, obj)) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } return Equals(obj as Revision); } @@ -76,32 +101,60 @@ public override bool Equals(object obj) public static bool operator >(Revision left, Revision right) { - if (ReferenceEquals(null, left)) return false; - if (ReferenceEquals(null, right)) return true; + if (ReferenceEquals(null, left)) + { + return false; + } + + if (ReferenceEquals(null, right)) + { + return true; + } return left.CompareTo(right) > 0; } public static bool operator <(Revision left, Revision right) { - if (ReferenceEquals(null, left)) return true; - if (ReferenceEquals(null, right)) return false; + if (ReferenceEquals(null, left)) + { + return true; + } + + if (ReferenceEquals(null, right)) + { + return false; + } return left.CompareTo(right) < 0; } public static bool operator >=(Revision left, Revision right) { - if (ReferenceEquals(null, left)) return false; - if (ReferenceEquals(null, right)) return true; + if (ReferenceEquals(null, left)) + { + return false; + } + + if (ReferenceEquals(null, right)) + { + return true; + } return left.CompareTo(right) >= 0; } public static bool operator <=(Revision left, Revision right) { - if (ReferenceEquals(null, left)) return true; - if (ReferenceEquals(null, right)) return false; + if (ReferenceEquals(null, left)) + { + return true; + } + + if (ReferenceEquals(null, right)) + { + return false; + } return left.CompareTo(right) <= 0; } diff --git a/src/NzbDrone.Core/Queue/Queue.cs b/src/NzbDrone.Core/Queue/Queue.cs index 95dd8f1593..a5f7463e24 100644 --- a/src/NzbDrone.Core/Queue/Queue.cs +++ b/src/NzbDrone.Core/Queue/Queue.cs @@ -4,9 +4,9 @@ using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.Indexers; using NzbDrone.Core.Languages; +using NzbDrone.Core.Movies; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.Qualities; -using NzbDrone.Core.Movies; namespace NzbDrone.Core.Queue { diff --git a/src/NzbDrone.Core/RemotePathMappings/RemotePathMapping.cs b/src/NzbDrone.Core/RemotePathMappings/RemotePathMapping.cs index c4a0bf81a1..1aa7f18a98 100644 --- a/src/NzbDrone.Core/RemotePathMappings/RemotePathMapping.cs +++ b/src/NzbDrone.Core/RemotePathMappings/RemotePathMapping.cs @@ -1,6 +1,5 @@ using NzbDrone.Core.Datastore; - namespace NzbDrone.Core.RemotePathMappings { public class RemotePathMapping : ModelBase diff --git a/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingRepository.cs b/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingRepository.cs index bfdfc00003..dc22743621 100644 --- a/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingRepository.cs +++ b/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingRepository.cs @@ -5,12 +5,10 @@ namespace NzbDrone.Core.RemotePathMappings { public interface IRemotePathMappingRepository : IBasicRepository<RemotePathMapping> { - } public class RemotePathMappingRepository : BasicRepository<RemotePathMapping>, IRemotePathMappingRepository { - public RemotePathMappingRepository(IMainDatabase database, IEventAggregator eventAggregator) : base(database, eventAggregator) { diff --git a/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingService.cs b/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingService.cs index 3167a49456..859bcbee47 100644 --- a/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingService.cs +++ b/src/NzbDrone.Core/RemotePathMappings/RemotePathMappingService.cs @@ -1,11 +1,11 @@ -using System.Linq; -using System; +using System; using System.Collections.Generic; using System.IO; +using System.Linq; using NLog; +using NzbDrone.Common.Cache; using NzbDrone.Common.Disk; using NzbDrone.Common.Extensions; -using NzbDrone.Common.Cache; using NzbDrone.Core.Download; namespace NzbDrone.Core.RemotePathMappings diff --git a/src/NzbDrone.Core/Rest/JsonNetSerializer.cs b/src/NzbDrone.Core/Rest/JsonNetSerializer.cs index c674fc51ea..e5bcdfb3af 100644 --- a/src/NzbDrone.Core/Rest/JsonNetSerializer.cs +++ b/src/NzbDrone.Core/Rest/JsonNetSerializer.cs @@ -7,7 +7,7 @@ public class JsonNetSerializer : ISerializer { public JsonNetSerializer() { - ContentType = "application/json"; + ContentType = "application/json"; } public string Serialize(object obj) diff --git a/src/NzbDrone.Core/Rest/RestClientFactory.cs b/src/NzbDrone.Core/Rest/RestClientFactory.cs index 99a3d10606..bcce3b8252 100644 --- a/src/NzbDrone.Core/Rest/RestClientFactory.cs +++ b/src/NzbDrone.Core/Rest/RestClientFactory.cs @@ -1,5 +1,5 @@ -using RestSharp; using NzbDrone.Common.EnvironmentInfo; +using RestSharp; namespace NzbDrone.Core.Rest { @@ -12,7 +12,6 @@ public static RestClient BuildClient(string baseUrl) UserAgent = $"{BuildInfo.AppName}/{BuildInfo.Version} ({OsInfo.Os})" }; - return restClient; } } diff --git a/src/NzbDrone.Core/Rest/RestSharpExtensions.cs b/src/NzbDrone.Core/Rest/RestSharpExtensions.cs index c18e0256ff..938b8723d5 100644 --- a/src/NzbDrone.Core/Rest/RestSharpExtensions.cs +++ b/src/NzbDrone.Core/Rest/RestSharpExtensions.cs @@ -1,5 +1,5 @@ -using System.Net; -using System.Linq; +using System.Linq; +using System.Net; using NLog; using NzbDrone.Common.EnsureThat; using NzbDrone.Common.Instrumentation; @@ -38,14 +38,17 @@ public static IRestResponse ValidateResponse(this IRestResponse response, IRestC { return response; } + case HttpStatusCode.NoContent: { return response; } + case HttpStatusCode.Created: { return response; } + default: { Logger.Warn("[{0}] [{1}] Failed. [{2}]", response.Request.Method, response.ResponseUri.ToString(), response.StatusCode); @@ -54,7 +57,8 @@ public static IRestResponse ValidateResponse(this IRestResponse response, IRestC } } - public static T Read<T>(this IRestResponse restResponse, IRestClient restClient) where T : class, new() + public static T Read<T>(this IRestResponse restResponse, IRestClient restClient) + where T : class, new() { restResponse.ValidateResponse(restClient); @@ -66,7 +70,8 @@ public static IRestResponse ValidateResponse(this IRestResponse response, IRestC return Json.Deserialize<T>(restResponse.Content); } - public static T ExecuteAndValidate<T>(this IRestClient client, IRestRequest request) where T : class, new() + public static T ExecuteAndValidate<T>(this IRestClient client, IRestRequest request) + where T : class, new() { return client.Execute(request).Read<T>(client); } @@ -85,7 +90,10 @@ public static object GetHeaderValue(this IRestResponse response, string key) { var header = response.Headers.FirstOrDefault(v => v.Name == key); - if (header == null) return null; + if (header == null) + { + return null; + } return header.Value; } diff --git a/src/NzbDrone.Core/Restrictions/TermMatcher.cs b/src/NzbDrone.Core/Restrictions/TermMatcher.cs index 0913f8bcc7..ceb5d66a93 100644 --- a/src/NzbDrone.Core/Restrictions/TermMatcher.cs +++ b/src/NzbDrone.Core/Restrictions/TermMatcher.cs @@ -38,7 +38,6 @@ private Predicate<string> CreateMatcherInternal(string term) else { return new CaseInsensitiveTermMatcher(term).IsMatch; - } } diff --git a/src/NzbDrone.Core/RootFolders/RootFolder.cs b/src/NzbDrone.Core/RootFolders/RootFolder.cs index 0ae3b0155a..7e6c5444b1 100644 --- a/src/NzbDrone.Core/RootFolders/RootFolder.cs +++ b/src/NzbDrone.Core/RootFolders/RootFolder.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using NzbDrone.Core.Datastore; - namespace NzbDrone.Core.RootFolders { public class RootFolder : ModelBase diff --git a/src/NzbDrone.Core/RootFolders/RootFolderRepository.cs b/src/NzbDrone.Core/RootFolders/RootFolderRepository.cs index f51376d283..21a1a5264c 100644 --- a/src/NzbDrone.Core/RootFolders/RootFolderRepository.cs +++ b/src/NzbDrone.Core/RootFolders/RootFolderRepository.cs @@ -5,12 +5,10 @@ namespace NzbDrone.Core.RootFolders { public interface IRootFolderRepository : IBasicRepository<RootFolder> { - } public class RootFolderRepository : BasicRepository<RootFolder>, IRootFolderRepository { - public RootFolderRepository(IMainDatabase database, IEventAggregator eventAggregator) : base(database, eventAggregator) { diff --git a/src/NzbDrone.Core/RootFolders/RootFolderService.cs b/src/NzbDrone.Core/RootFolders/RootFolderService.cs index a58ed182c7..0e0c2ad715 100644 --- a/src/NzbDrone.Core/RootFolders/RootFolderService.cs +++ b/src/NzbDrone.Core/RootFolders/RootFolderService.cs @@ -1,7 +1,7 @@ -using System.Linq; using System; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Threading.Tasks; using NLog; using NzbDrone.Common; @@ -43,7 +43,6 @@ public class RootFolderService : IRootFolderService ".grab" }; - public RootFolderService(IRootFolderRepository rootFolderRepository, IDiskProvider diskProvider, IMovieRepository movieRepository, @@ -77,6 +76,7 @@ public List<RootFolder> AllWithUnmappedFolders() GetDetails(folder); } } + //We don't want an exception to prevent the root folders from loading in the UI, so they can still be deleted catch (Exception ex) { @@ -152,7 +152,6 @@ private List<UnmappedFolder> GetUnmappedFolders(string path) { results.Add(new UnmappedFolder { Name = di.Name, Path = di.FullName }); } - } var setToRemove = SpecialFolders; diff --git a/src/NzbDrone.Core/Security/X509CertificateValidationService.cs b/src/NzbDrone.Core/Security/X509CertificateValidationService.cs index 37dc83ea93..c1ceeb3ec5 100644 --- a/src/NzbDrone.Core/Security/X509CertificateValidationService.cs +++ b/src/NzbDrone.Core/Security/X509CertificateValidationService.cs @@ -55,7 +55,6 @@ private bool ShouldByPassValidationError(object sender, X509Certificate certific return true; } - _logger.Error("Certificate validation for {0} failed. {1}", request.Address, sslPolicyErrors); return false; @@ -65,7 +64,7 @@ private IPAddress[] GetIPAddresses(string host) { if (IPAddress.TryParse(host, out var ipAddress)) { - return new []{ ipAddress }; + return new[] { ipAddress }; } return Dns.GetHostEntry(host).AddressList; diff --git a/src/NzbDrone.Core/Tags/TagDetails.cs b/src/NzbDrone.Core/Tags/TagDetails.cs index af60d6fb64..80ee15fa8e 100644 --- a/src/NzbDrone.Core/Tags/TagDetails.cs +++ b/src/NzbDrone.Core/Tags/TagDetails.cs @@ -17,7 +17,7 @@ public bool InUse { get { - return (MovieIds.Any() || NotificationIds.Any() || RestrictionIds.Any() || DelayProfileIds.Any()); + return MovieIds.Any() || NotificationIds.Any() || RestrictionIds.Any() || DelayProfileIds.Any(); } } } diff --git a/src/NzbDrone.Core/Tags/TagService.cs b/src/NzbDrone.Core/Tags/TagService.cs index 814c2d1fea..73c4d3c6ae 100644 --- a/src/NzbDrone.Core/Tags/TagService.cs +++ b/src/NzbDrone.Core/Tags/TagService.cs @@ -2,11 +2,11 @@ using System.Linq; using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; +using NzbDrone.Core.Movies; +using NzbDrone.Core.NetImport; using NzbDrone.Core.Notifications; using NzbDrone.Core.Profiles.Delay; using NzbDrone.Core.Restrictions; -using NzbDrone.Core.Movies; -using NzbDrone.Core.NetImport; namespace NzbDrone.Core.Tags { @@ -115,8 +115,7 @@ public List<TagDetails> Details() NotificationIds = notifications.Where(c => c.Tags.Contains(tag.Id)).Select(c => c.Id).ToList(), RestrictionIds = restrictions.Where(c => c.Tags.Contains(tag.Id)).Select(c => c.Id).ToList(), MovieIds = movies.Where(c => c.Tags.Contains(tag.Id)).Select(c => c.Id).ToList() - } - ); + }); } return details; diff --git a/src/NzbDrone.Core/ThingiProvider/ConfigContractNotFoundException.cs b/src/NzbDrone.Core/ThingiProvider/ConfigContractNotFoundException.cs index 47d6ecdf3d..83e4013ea4 100644 --- a/src/NzbDrone.Core/ThingiProvider/ConfigContractNotFoundException.cs +++ b/src/NzbDrone.Core/ThingiProvider/ConfigContractNotFoundException.cs @@ -8,6 +8,5 @@ public ConfigContractNotFoundException(string contract) : base("Couldn't find config contract " + contract) { } - } } diff --git a/src/NzbDrone.Core/ThingiProvider/IProviderRepository.cs b/src/NzbDrone.Core/ThingiProvider/IProviderRepository.cs index 802ca114e0..421cc68993 100644 --- a/src/NzbDrone.Core/ThingiProvider/IProviderRepository.cs +++ b/src/NzbDrone.Core/ThingiProvider/IProviderRepository.cs @@ -2,8 +2,9 @@ namespace NzbDrone.Core.ThingiProvider { - public interface IProviderRepository<TProvider> : IBasicRepository<TProvider> where TProvider : ModelBase, new() + public interface IProviderRepository<TProvider> : IBasicRepository<TProvider> + where TProvider : ModelBase, new() { -// void DeleteImplementations(string implementation); + // void DeleteImplementations(string implementation); } } diff --git a/src/NzbDrone.Core/ThingiProvider/ProviderRepository.cs b/src/NzbDrone.Core/ThingiProvider/ProviderRepository.cs index 019b50ee69..305f80efbd 100644 --- a/src/NzbDrone.Core/ThingiProvider/ProviderRepository.cs +++ b/src/NzbDrone.Core/ThingiProvider/ProviderRepository.cs @@ -12,9 +12,9 @@ protected ProviderRepository(IMainDatabase database, IEventAggregator eventAggre { } -// public void DeleteImplementations(string implementation) -// { -// DataMapper.Delete<TProviderDefinition>(c => c.Implementation == implementation); -// } + // public void DeleteImplementations(string implementation) + // { + // DataMapper.Delete<TProviderDefinition>(c => c.Implementation == implementation); + // } } } diff --git a/src/NzbDrone.Core/ThingiProvider/Status/ProviderStatusRepository.cs b/src/NzbDrone.Core/ThingiProvider/Status/ProviderStatusRepository.cs index ca40daa8c5..071f0ea9fb 100644 --- a/src/NzbDrone.Core/ThingiProvider/Status/ProviderStatusRepository.cs +++ b/src/NzbDrone.Core/ThingiProvider/Status/ProviderStatusRepository.cs @@ -12,7 +12,6 @@ public interface IProviderStatusRepository<TModel> : IBasicRepository<TModel> public class ProviderStatusRepository<TModel> : BasicRepository<TModel>, IProviderStatusRepository<TModel> where TModel : ProviderStatusBase, new() - { public ProviderStatusRepository(IMainDatabase database, IEventAggregator eventAggregator) : base(database, eventAggregator) diff --git a/src/NzbDrone.Core/TinyTwitter.cs b/src/NzbDrone.Core/TinyTwitter.cs index c6bf228b39..b1448d7e82 100644 --- a/src/NzbDrone.Core/TinyTwitter.cs +++ b/src/NzbDrone.Core/TinyTwitter.cs @@ -28,16 +28,16 @@ public class Tweet public class TinyTwitter { - private readonly OAuthInfo oauth; + private readonly OAuthInfo _oauth; public TinyTwitter(OAuthInfo oauth) { - this.oauth = oauth; + _oauth = oauth; } public void UpdateStatus(string message) { - new RequestBuilder(oauth, "POST", "https://api.twitter.com/1.1/statuses/update.json") + new RequestBuilder(_oauth, "POST", "https://api.twitter.com/1.1/statuses/update.json") .AddParameter("status", message) .Execute(); } @@ -49,38 +49,35 @@ public void UpdateStatus(string message) * and added this banner so it's not blindly updated. * **/ - public void DirectMessage(string message, string screenName) { - new RequestBuilder(oauth, "POST", "https://api.twitter.com/1.1/direct_messages/new.json") + new RequestBuilder(_oauth, "POST", "https://api.twitter.com/1.1/direct_messages/new.json") .AddParameter("text", message) .AddParameter("screen_name", screenName) .Execute(); } - #region RequestBuilder - public class RequestBuilder { private const string VERSION = "1.0"; private const string SIGNATURE_METHOD = "HMAC-SHA1"; - private readonly OAuthInfo oauth; - private readonly string method; - private readonly IDictionary<string, string> customParameters; - private readonly string url; + private readonly OAuthInfo _oauth; + private readonly string _method; + private readonly IDictionary<string, string> _customParameters; + private readonly string _url; public RequestBuilder(OAuthInfo oauth, string method, string url) { - this.oauth = oauth; - this.method = method; - this.url = url; - customParameters = new Dictionary<string, string>(); + _oauth = oauth; + _method = method; + _url = url; + _customParameters = new Dictionary<string, string>(); } public RequestBuilder AddParameter(string name, string value) { - customParameters.Add(name, value.EncodeRFC3986()); + _customParameters.Add(name, value.EncodeRFC3986()); return this; } @@ -89,14 +86,14 @@ public string Execute() var timespan = GetTimestamp(); var nonce = CreateNonce(); - var parameters = new Dictionary<string, string>(customParameters); + var parameters = new Dictionary<string, string>(_customParameters); AddOAuthParameters(parameters, timespan, nonce); var signature = GenerateSignature(parameters); var headerValue = GenerateAuthorizationHeaderValue(parameters, signature); var request = (HttpWebRequest)WebRequest.Create(GetRequestUrl()); - request.Method = method; + request.Method = _method; request.ContentType = "application/x-www-form-urlencoded"; request.Headers.Add("Authorization", headerValue); @@ -106,7 +103,6 @@ public string Execute() // It looks like a bug in HttpWebRequest. It throws random TimeoutExceptions // after some requests. Abort the request seems to work. More info: // http://stackoverflow.com/questions/2252762/getrequeststream-throws-timeout-exception-randomly - var response = request.GetResponse(); string content; @@ -126,25 +122,31 @@ public string Execute() private void WriteRequestBody(HttpWebRequest request) { - if (method == "GET") + if (_method == "GET") + { return; + } var requestBody = Encoding.ASCII.GetBytes(GetCustomParametersString()); using (var stream = request.GetRequestStream()) + { stream.Write(requestBody, 0, requestBody.Length); + } } private string GetRequestUrl() { - if (method != "GET" || customParameters.Count == 0) - return url; + if (_method != "GET" || _customParameters.Count == 0) + { + return _url; + } - return string.Format("{0}?{1}", url, GetCustomParametersString()); + return string.Format("{0}?{1}", _url, GetCustomParametersString()); } private string GetCustomParametersString() { - return customParameters.Select(x => string.Format("{0}={1}", x.Key, x.Value)).Join("&"); + return _customParameters.Select(x => string.Format("{0}={1}", x.Key, x.Value)).Join("&"); } private string GenerateAuthorizationHeaderValue(IEnumerable<KeyValuePair<string, string>> parameters, string signature) @@ -160,15 +162,15 @@ private string GenerateAuthorizationHeaderValue(IEnumerable<KeyValuePair<string, private string GenerateSignature(IEnumerable<KeyValuePair<string, string>> parameters) { var dataToSign = new StringBuilder() - .Append(method).Append("&") - .Append(url.EncodeRFC3986()).Append("&") + .Append(_method).Append("&") + .Append(_url.EncodeRFC3986()).Append("&") .Append(parameters .OrderBy(x => x.Key) .Select(x => string.Format("{0}={1}", x.Key, x.Value)) .Join("&") .EncodeRFC3986()); - var signatureKey = string.Format("{0}&{1}", oauth.ConsumerSecret.EncodeRFC3986(), oauth.AccessSecret.EncodeRFC3986()); + var signatureKey = string.Format("{0}&{1}", _oauth.ConsumerSecret.EncodeRFC3986(), _oauth.AccessSecret.EncodeRFC3986()); var sha1 = new HMACSHA1(Encoding.ASCII.GetBytes(signatureKey)); var signatureBytes = sha1.ComputeHash(Encoding.ASCII.GetBytes(dataToSign.ToString())); @@ -178,11 +180,11 @@ private string GenerateSignature(IEnumerable<KeyValuePair<string, string>> param private void AddOAuthParameters(IDictionary<string, string> parameters, string timestamp, string nonce) { parameters.Add("oauth_version", VERSION); - parameters.Add("oauth_consumer_key", oauth.ConsumerKey); + parameters.Add("oauth_consumer_key", _oauth.ConsumerKey); parameters.Add("oauth_nonce", nonce); parameters.Add("oauth_signature_method", SIGNATURE_METHOD); parameters.Add("oauth_timestamp", timestamp); - parameters.Add("oauth_token", oauth.AccessToken); + parameters.Add("oauth_token", _oauth.AccessToken); } private static string GetTimestamp() @@ -195,8 +197,6 @@ private static string CreateNonce() return new Random().Next(0x0000000, 0x7fffffff).ToString("X8"); } } - - #endregion } public static class TinyTwitterHelperExtensions @@ -214,9 +214,10 @@ public static IEnumerable<T> Concat<T>(this IEnumerable<T> items, T value) public static string EncodeRFC3986(this string value) { // From Twitterizer http://www.twitterizer.net/ - if (string.IsNullOrEmpty(value)) + { return string.Empty; + } var encoded = Uri.EscapeDataString(value); diff --git a/src/NzbDrone.Core/Update/InstallUpdateService.cs b/src/NzbDrone.Core/Update/InstallUpdateService.cs index 3562955870..ea644e2c3c 100644 --- a/src/NzbDrone.Core/Update/InstallUpdateService.cs +++ b/src/NzbDrone.Core/Update/InstallUpdateService.cs @@ -34,7 +34,6 @@ public class InstallUpdateService : IExecute<ApplicationUpdateCommand> private readonly IBackupService _backupService; private readonly IOsInfo _osInfo; - public InstallUpdateService(ICheckUpdateService checkUpdateService, IAppFolderInfo appFolderInfo, IDiskProvider diskProvider, @@ -54,6 +53,7 @@ public InstallUpdateService(ICheckUpdateService checkUpdateService, { throw new ArgumentNullException(nameof(configFileProvider)); } + _checkUpdateService = checkUpdateService; _appFolderInfo = appFolderInfo; _diskProvider = diskProvider; diff --git a/src/NzbDrone.Core/Update/UpdateCheckService.cs b/src/NzbDrone.Core/Update/UpdateCheckService.cs index fcce36d591..46e4b6b631 100644 --- a/src/NzbDrone.Core/Update/UpdateCheckService.cs +++ b/src/NzbDrone.Core/Update/UpdateCheckService.cs @@ -13,7 +13,6 @@ public class CheckUpdateService : ICheckUpdateService private readonly IUpdatePackageProvider _updatePackageProvider; private readonly IConfigFileProvider _configFileProvider; - public CheckUpdateService(IUpdatePackageProvider updatePackageProvider, IConfigFileProvider configFileProvider) { diff --git a/src/NzbDrone.Core/Update/UpdatePackageProvider.cs b/src/NzbDrone.Core/Update/UpdatePackageProvider.cs index e4d7ff22b7..91c8eff34e 100644 --- a/src/NzbDrone.Core/Update/UpdatePackageProvider.cs +++ b/src/NzbDrone.Core/Update/UpdatePackageProvider.cs @@ -48,7 +48,10 @@ public UpdatePackage GetLatestUpdate(string branch, Version currentVersion) var update = _httpClient.Get<UpdatePackageAvailable>(request.Build()).Resource; - if (!update.Available) return null; + if (!update.Available) + { + return null; + } return update.UpdatePackage; } diff --git a/src/NzbDrone.Core/Validation/FolderValidator.cs b/src/NzbDrone.Core/Validation/FolderValidator.cs index c3fce0d939..9eedeb4591 100644 --- a/src/NzbDrone.Core/Validation/FolderValidator.cs +++ b/src/NzbDrone.Core/Validation/FolderValidator.cs @@ -12,7 +12,11 @@ public FolderValidator() protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return false; + if (context.PropertyValue == null) + { + return false; + } + return context.PropertyValue.ToString().IsPathValid(); } } diff --git a/src/NzbDrone.Core/Validation/NzbDroneValidationFailure.cs b/src/NzbDrone.Core/Validation/NzbDroneValidationFailure.cs index c8db4a84bc..0cd3c90268 100644 --- a/src/NzbDrone.Core/Validation/NzbDroneValidationFailure.cs +++ b/src/NzbDrone.Core/Validation/NzbDroneValidationFailure.cs @@ -11,13 +11,11 @@ public class NzbDroneValidationFailure : ValidationFailure public NzbDroneValidationFailure(string propertyName, string error) : base(propertyName, error) { - } public NzbDroneValidationFailure(string propertyName, string error, object attemptedValue) : base(propertyName, error, attemptedValue) { - } public NzbDroneValidationFailure(ValidationFailure validationFailure) diff --git a/src/NzbDrone.Core/Validation/NzbDroneValidationResult.cs b/src/NzbDrone.Core/Validation/NzbDroneValidationResult.cs index bd8263b6bf..5de154984f 100644 --- a/src/NzbDrone.Core/Validation/NzbDroneValidationResult.cs +++ b/src/NzbDrone.Core/Validation/NzbDroneValidationResult.cs @@ -31,6 +31,7 @@ public NzbDroneValidationResult(IEnumerable<ValidationFailure> failures) { failure = new NzbDroneValidationFailure(failureBase); } + if (failure.IsWarning) { warnings.Add(failure); diff --git a/src/NzbDrone.Core/Validation/Paths/FolderWritableValidator.cs b/src/NzbDrone.Core/Validation/Paths/FolderWritableValidator.cs index 6e86db1054..c58b5a2730 100644 --- a/src/NzbDrone.Core/Validation/Paths/FolderWritableValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/FolderWritableValidator.cs @@ -16,9 +16,12 @@ public FolderWritableValidator(IDiskProvider diskProvider) protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return false; + if (context.PropertyValue == null) + { + return false; + } - return (_diskProvider.FolderWritable(context.PropertyValue.ToString())); + return _diskProvider.FolderWritable(context.PropertyValue.ToString()); } } } diff --git a/src/NzbDrone.Core/Validation/Paths/MappedNetworkDriveValidator.cs b/src/NzbDrone.Core/Validation/Paths/MappedNetworkDriveValidator.cs index 28a3192ab0..48e3da21eb 100644 --- a/src/NzbDrone.Core/Validation/Paths/MappedNetworkDriveValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/MappedNetworkDriveValidator.cs @@ -22,13 +22,27 @@ public MappedNetworkDriveValidator(IRuntimeInfo runtimeInfo, IDiskProvider diskP protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return false; - if (OsInfo.IsNotWindows) return true; - if (!_runtimeInfo.IsWindowsService) return true; + if (context.PropertyValue == null) + { + return false; + } + + if (OsInfo.IsNotWindows) + { + return true; + } + + if (!_runtimeInfo.IsWindowsService) + { + return true; + } var path = context.PropertyValue.ToString(); - if (!DriveRegex.IsMatch(path)) return true; + if (!DriveRegex.IsMatch(path)) + { + return true; + } var mount = _diskProvider.GetMount(path); diff --git a/src/NzbDrone.Core/Validation/Paths/MovieAncestorValidator.cs b/src/NzbDrone.Core/Validation/Paths/MovieAncestorValidator.cs index 91df0ffa3e..ad8ccf7eb6 100644 --- a/src/NzbDrone.Core/Validation/Paths/MovieAncestorValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/MovieAncestorValidator.cs @@ -17,7 +17,10 @@ public MovieAncestorValidator(IMovieService movieService) protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } return !_movieService.GetAllMovies().Any(s => context.PropertyValue.ToString().IsParentPath(s.Path)); } diff --git a/src/NzbDrone.Core/Validation/Paths/MovieExistsValidator.cs b/src/NzbDrone.Core/Validation/Paths/MovieExistsValidator.cs index 5b4a7745e7..656e108725 100644 --- a/src/NzbDrone.Core/Validation/Paths/MovieExistsValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/MovieExistsValidator.cs @@ -15,11 +15,14 @@ public MovieExistsValidator(IMovieService movieService) protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } int tmdbId = (int)context.PropertyValue; - return (_movieService.FindByTmdbId(tmdbId) == null); + return _movieService.FindByTmdbId(tmdbId) == null; } } } diff --git a/src/NzbDrone.Core/Validation/Paths/MoviePathValidation.cs b/src/NzbDrone.Core/Validation/Paths/MoviePathValidation.cs index bbd871432d..a86d180c7e 100644 --- a/src/NzbDrone.Core/Validation/Paths/MoviePathValidation.cs +++ b/src/NzbDrone.Core/Validation/Paths/MoviePathValidation.cs @@ -16,12 +16,15 @@ public MoviePathValidator(IMovieService moviesService) protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } dynamic instance = context.ParentContext.InstanceToValidate; var instanceId = (int)instance.Id; - return (!_moviesService.GetAllMovies().Exists(s => s.Path.PathEquals(context.PropertyValue.ToString()) && s.Id != instanceId)); + return !_moviesService.GetAllMovies().Exists(s => s.Path.PathEquals(context.PropertyValue.ToString()) && s.Id != instanceId); } } } diff --git a/src/NzbDrone.Core/Validation/Paths/PathExistsValidator.cs b/src/NzbDrone.Core/Validation/Paths/PathExistsValidator.cs index 970ecb9e52..77398b5e8d 100644 --- a/src/NzbDrone.Core/Validation/Paths/PathExistsValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/PathExistsValidator.cs @@ -15,9 +15,12 @@ public PathExistsValidator(IDiskProvider diskProvider) protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return false; + if (context.PropertyValue == null) + { + return false; + } - return (_diskProvider.FolderExists(context.PropertyValue.ToString())); + return _diskProvider.FolderExists(context.PropertyValue.ToString()); } } } diff --git a/src/NzbDrone.Core/Validation/Paths/PathValidator.cs b/src/NzbDrone.Core/Validation/Paths/PathValidator.cs index 69dcb2cca3..c546d3e79a 100644 --- a/src/NzbDrone.Core/Validation/Paths/PathValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/PathValidator.cs @@ -21,7 +21,11 @@ public PathValidator() protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return false; + if (context.PropertyValue == null) + { + return false; + } + return context.PropertyValue.ToString().IsPathValid(); } } diff --git a/src/NzbDrone.Core/Validation/Paths/RootFolderValidator.cs b/src/NzbDrone.Core/Validation/Paths/RootFolderValidator.cs index 7f3b03d4b1..8494ac28bd 100644 --- a/src/NzbDrone.Core/Validation/Paths/RootFolderValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/RootFolderValidator.cs @@ -16,9 +16,12 @@ public RootFolderValidator(IRootFolderService rootFolderService) protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } - return (!_rootFolderService.All().Exists(r => r.Path.PathEquals(context.PropertyValue.ToString()))); + return !_rootFolderService.All().Exists(r => r.Path.PathEquals(context.PropertyValue.ToString())); } } } diff --git a/src/NzbDrone.Core/Validation/Paths/StartupFolderValidator.cs b/src/NzbDrone.Core/Validation/Paths/StartupFolderValidator.cs index 9f9dbb722c..158a9ca316 100644 --- a/src/NzbDrone.Core/Validation/Paths/StartupFolderValidator.cs +++ b/src/NzbDrone.Core/Validation/Paths/StartupFolderValidator.cs @@ -8,7 +8,6 @@ public class StartupFolderValidator : PropertyValidator { private readonly IAppFolderInfo _appFolderInfo; - public StartupFolderValidator(IAppFolderInfo appFolderInfo) : base("Path cannot be an ancestor of the start up folder") { @@ -17,7 +16,10 @@ public StartupFolderValidator(IAppFolderInfo appFolderInfo) protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } return !_appFolderInfo.StartUpFolder.IsParentPath(context.PropertyValue.ToString()); } diff --git a/src/NzbDrone.Core/Validation/ProfileExistsValidator.cs b/src/NzbDrone.Core/Validation/ProfileExistsValidator.cs index 5ff2dc6f9b..d1875eceaa 100644 --- a/src/NzbDrone.Core/Validation/ProfileExistsValidator.cs +++ b/src/NzbDrone.Core/Validation/ProfileExistsValidator.cs @@ -15,7 +15,10 @@ public ProfileExistsValidator(IProfileService profileService) protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } return _profileService.Exists((int)context.PropertyValue); } diff --git a/src/NzbDrone.Core/Validation/UrlValidator.cs b/src/NzbDrone.Core/Validation/UrlValidator.cs index 9a278bc4d8..844ab80f2f 100644 --- a/src/NzbDrone.Core/Validation/UrlValidator.cs +++ b/src/NzbDrone.Core/Validation/UrlValidator.cs @@ -21,7 +21,11 @@ public UrlValidator() protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return false; + if (context.PropertyValue == null) + { + return false; + } + return context.PropertyValue.ToString().IsValidUrl(); } } diff --git a/src/NzbDrone.Host.Test/ContainerFixture.cs b/src/NzbDrone.Host.Test/ContainerFixture.cs index 1f1307ef68..8a7f8e0214 100644 --- a/src/NzbDrone.Host.Test/ContainerFixture.cs +++ b/src/NzbDrone.Host.Test/ContainerFixture.cs @@ -1,22 +1,22 @@ using System.Collections.Generic; +using System.Linq; +using FluentAssertions; +using Moq; using NUnit.Framework; using NzbDrone.Common; +using NzbDrone.Common.Composition; using NzbDrone.Common.EnvironmentInfo; +using NzbDrone.Core.Datastore; using NzbDrone.Core.Download; +using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.Core.Indexers; using NzbDrone.Core.Jobs; using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Messaging.Commands; using NzbDrone.Core.Messaging.Events; -using Radarr.Host; -using NzbDrone.Test.Common; -using FluentAssertions; -using System.Linq; -using NzbDrone.Common.Composition; -using NzbDrone.Core.Datastore; -using NzbDrone.Core.Download.TrackedDownloads; using NzbDrone.SignalR; -using Moq; +using NzbDrone.Test.Common; +using Radarr.Host; namespace NzbDrone.App.Test { diff --git a/src/NzbDrone.Host.Test/NzbDroneProcessServiceFixture.cs b/src/NzbDrone.Host.Test/NzbDroneProcessServiceFixture.cs index 5ec9161b7d..992c819386 100644 --- a/src/NzbDrone.Host.Test/NzbDroneProcessServiceFixture.cs +++ b/src/NzbDrone.Host.Test/NzbDroneProcessServiceFixture.cs @@ -3,8 +3,8 @@ using NUnit.Framework; using NzbDrone.Common.Model; using NzbDrone.Common.Processes; -using Radarr.Host; using NzbDrone.Test.Common; +using Radarr.Host; namespace NzbDrone.App.Test { @@ -35,7 +35,7 @@ public void should_continue_if_only_instance() .Setup(c => c.FindProcessByName(It.Is<string>(f => f.Contains("Radarr")))) .Returns(new List<ProcessInfo> { - new ProcessInfo {Id = CURRENT_PROCESS_ID} + new ProcessInfo { Id = CURRENT_PROCESS_ID } }); Subject.PreventStartIfAlreadyRunning(); @@ -50,8 +50,8 @@ public void should_enforce_if_another_console_is_running() .Setup(c => c.FindProcessByName(ProcessProvider.RADARR_CONSOLE_PROCESS_NAME)) .Returns(new List<ProcessInfo> { - new ProcessInfo {Id = 10}, - new ProcessInfo {Id = CURRENT_PROCESS_ID} + new ProcessInfo { Id = 10 }, + new ProcessInfo { Id = CURRENT_PROCESS_ID } }); Assert.Throws<TerminateApplicationException>(() => Subject.PreventStartIfAlreadyRunning()); @@ -66,9 +66,8 @@ public void should_return_false_if_another_gui_is_running() .Setup(c => c.FindProcessByName(ProcessProvider.RADARR_PROCESS_NAME)) .Returns(new List<ProcessInfo> { - new ProcessInfo {Id = CURRENT_PROCESS_ID}, - new ProcessInfo {Id = 10} - + new ProcessInfo { Id = CURRENT_PROCESS_ID }, + new ProcessInfo { Id = 10 } }); Assert.Throws<TerminateApplicationException>(() => Subject.PreventStartIfAlreadyRunning()); diff --git a/src/NzbDrone.Host.Test/RouterTest.cs b/src/NzbDrone.Host.Test/RouterTest.cs index 9c570a5f3a..fc64467072 100644 --- a/src/NzbDrone.Host.Test/RouterTest.cs +++ b/src/NzbDrone.Host.Test/RouterTest.cs @@ -4,8 +4,8 @@ using NzbDrone.Common; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Common.Processes; -using Radarr.Host; using NzbDrone.Test.Common; +using Radarr.Host; namespace NzbDrone.App.Test { @@ -18,7 +18,6 @@ public void Setup() WindowsOnly(); } - [Test] public void Route_should_call_install_service_when_application_mode_is_install() { @@ -36,7 +35,6 @@ public void Route_should_call_install_service_when_application_mode_is_install() serviceProviderMock.Verify(c => c.Install(ServiceProvider.SERVICE_NAME), Times.Once()); } - [Test] public void Route_should_call_uninstall_service_when_application_mode_is_uninstall() { @@ -77,7 +75,6 @@ public void Route_should_call_service_start_when_run_in_service_mode() serviceProvider.Verify(c => c.Run(It.IsAny<ServiceBase>()), Times.Once()); } - [Test] public void show_error_on_install_if_service_already_exist() { @@ -89,7 +86,6 @@ public void show_error_on_install_if_service_already_exist() serviceMock.Setup(c => c.ServiceExist(ServiceProvider.SERVICE_NAME)).Returns(true); Subject.Route(ApplicationModes.InstallService); - } [Test] @@ -103,7 +99,6 @@ public void show_error_on_uninstall_if_service_doesnt_exist() serviceMock.Setup(c => c.ServiceExist(ServiceProvider.SERVICE_NAME)).Returns(false); Subject.Route(ApplicationModes.UninstallService); - } } } diff --git a/src/NzbDrone.Host/AccessControl/FirewallAdapter.cs b/src/NzbDrone.Host/AccessControl/FirewallAdapter.cs index a31c6ec59b..232babb722 100644 --- a/src/NzbDrone.Host/AccessControl/FirewallAdapter.cs +++ b/src/NzbDrone.Host/AccessControl/FirewallAdapter.cs @@ -58,6 +58,7 @@ private bool IsNzbDronePortOpen(int port) { _logger.Warn(ex, "Failed to check for open port in firewall"); } + return false; } @@ -87,7 +88,10 @@ private void OpenFirewallPort(int portNumber) private bool IsFirewallEnabled() { - if (OsInfo.IsNotWindows) return false; + if (OsInfo.IsNotWindows) + { + return false; + } try { diff --git a/src/NzbDrone.Host/AccessControl/RemoteAccessException.cs b/src/NzbDrone.Host/AccessControl/RemoteAccessException.cs index be7917f903..aad1f9b773 100644 --- a/src/NzbDrone.Host/AccessControl/RemoteAccessException.cs +++ b/src/NzbDrone.Host/AccessControl/RemoteAccessException.cs @@ -5,19 +5,23 @@ namespace Radarr.Host.AccessControl { public class RemoteAccessException : NzbDroneException { - public RemoteAccessException(string message, params object[] args) : base(message, args) + public RemoteAccessException(string message, params object[] args) + : base(message, args) { } - public RemoteAccessException(string message) : base(message) + public RemoteAccessException(string message) + : base(message) { } - public RemoteAccessException(string message, Exception innerException, params object[] args) : base(message, innerException, args) + public RemoteAccessException(string message, Exception innerException, params object[] args) + : base(message, innerException, args) { } - public RemoteAccessException(string message, Exception innerException) : base(message, innerException) + public RemoteAccessException(string message, Exception innerException) + : base(message, innerException) { } } diff --git a/src/NzbDrone.Host/ApplicationServer.cs b/src/NzbDrone.Host/ApplicationServer.cs index e4cad82515..2e1bdf9614 100644 --- a/src/NzbDrone.Host/ApplicationServer.cs +++ b/src/NzbDrone.Host/ApplicationServer.cs @@ -62,8 +62,8 @@ public class NzbDroneConsoleFactory : INzbDroneConsoleFactory, IHandle<Applicati private readonly IBrowserService _browserService; private readonly IContainer _container; private readonly Logger _logger; - // private CancelHandler _cancelHandler; + // private CancelHandler _cancelHandler; public NzbDroneConsoleFactory(IConfigFileProvider configFileProvider, IHostController hostController, IRuntimeInfo runtimeInfo, @@ -99,7 +99,6 @@ public void Start() _browserService.LaunchWebUI(); } - _container.Resolve<IEventAggregator>().PublishEvent(new ApplicationStartedEvent()); } diff --git a/src/NzbDrone.Host/Bootstrap.cs b/src/NzbDrone.Host/Bootstrap.cs index d4181f1508..f0a7f473a8 100644 --- a/src/NzbDrone.Host/Bootstrap.cs +++ b/src/NzbDrone.Host/Bootstrap.cs @@ -14,8 +14,8 @@ namespace Radarr.Host { public static class Bootstrap { - private static IContainer _container; private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(Bootstrap)); + private static IContainer _container; public static void Start(StartupContext startupContext, IUserAlert userAlert, Action<IContainer> startCallback = null) { @@ -120,7 +120,6 @@ private static ApplicationModes GetApplicationMode(IStartupContext startupContex return ApplicationModes.RegisterUrl; } - if (OsInfo.IsWindows && startupContext.InstallService) { return ApplicationModes.InstallService; @@ -150,6 +149,7 @@ private static bool IsInUtilityMode(ApplicationModes applicationMode) { return true; } + default: { return false; diff --git a/src/NzbDrone.Host/CancelHandler.cs b/src/NzbDrone.Host/CancelHandler.cs index 7aa785b6d2..ad7a3f328a 100644 --- a/src/NzbDrone.Host/CancelHandler.cs +++ b/src/NzbDrone.Host/CancelHandler.cs @@ -9,11 +9,11 @@ public interface ICancelHandler void Attach(); } - class CancelHandler : ICancelHandler + internal class CancelHandler : ICancelHandler { + private readonly ILifecycleService _lifecycleService; private object _syncRoot; private volatile bool _cancelInitiated; - private readonly ILifecycleService _lifecycleService; public CancelHandler(ILifecycleService lifecycleService) { @@ -52,6 +52,7 @@ private void HandlerCancelKeyPress(object sender, ConsoleCancelEventArgs e) private void GracefulShutdown() { Console.WriteLine("Shutdown requested, press Ctrl+C again to terminate directly."); + // TODO: Sent ApplicationShutdownRequested event or something like it. _lifecycleService.Shutdown(); } @@ -59,6 +60,7 @@ private void GracefulShutdown() private void UngracefulShutdown() { Console.WriteLine("Termination requested."); + // TODO: Kill it. Shutdown NLog and invoke Environment.Exit. LogManager.Configuration = null; Environment.Exit(0); diff --git a/src/NzbDrone.Host/MainAppContainerBuilder.cs b/src/NzbDrone.Host/MainAppContainerBuilder.cs index 96307356f9..8092854fe9 100644 --- a/src/NzbDrone.Host/MainAppContainerBuilder.cs +++ b/src/NzbDrone.Host/MainAppContainerBuilder.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; using Nancy.Bootstrapper; -using Radarr.Http; using NzbDrone.Common.Composition; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.SignalR; +using Radarr.Http; namespace Radarr.Host { diff --git a/src/NzbDrone.Host/PlatformValidation.cs b/src/NzbDrone.Host/PlatformValidation.cs index 20662d6ec3..d1ec5522fc 100644 --- a/src/NzbDrone.Host/PlatformValidation.cs +++ b/src/NzbDrone.Host/PlatformValidation.cs @@ -9,10 +9,10 @@ namespace Radarr.Host { public static class PlatformValidation { - private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(PlatformValidation)); - private const string DOWNLOAD_LINK = "http://www.microsoft.com/en-us/download/details.aspx?id=42643"; + private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(PlatformValidation)); + public static bool IsValidate(IUserAlert userAlert) { if (OsInfo.IsNotWindows) @@ -39,7 +39,6 @@ public static bool IsValidate(IUserAlert userAlert) return true; } - private static bool IsAssemblyAvailable(string assemblyString) { try @@ -52,7 +51,6 @@ private static bool IsAssemblyAvailable(string assemblyString) Logger.Warn("Couldn't load {0}", e.Message); return false; } - } } } diff --git a/src/NzbDrone.Host/Router.cs b/src/NzbDrone.Host/Router.cs index 1ed08de235..e56b92ab32 100644 --- a/src/NzbDrone.Host/Router.cs +++ b/src/NzbDrone.Host/Router.cs @@ -5,7 +5,6 @@ using Radarr.Host.AccessControl; using IServiceProvider = NzbDrone.Common.IServiceProvider; - namespace Radarr.Host { public class Router @@ -57,6 +56,7 @@ public void Route(ApplicationModes applicationModes) _nzbDroneConsoleFactory.Start(); break; } + case ApplicationModes.InstallService: { _logger.Debug("Install Service selected"); @@ -74,8 +74,10 @@ public void Route(ApplicationModes applicationModes) // Ensures that there isn't an instance of Radarr already running that the service account cannot stop. _processProvider.SpawnNewProcess("sc.exe", $"start {ServiceProvider.SERVICE_NAME}", null, true); } + break; } + case ApplicationModes.UninstallService: { _logger.Debug("Uninstall Service selected"); @@ -90,6 +92,7 @@ public void Route(ApplicationModes applicationModes) break; } + case ApplicationModes.RegisterUrl: { _logger.Debug("Regiser URL selected"); @@ -97,6 +100,7 @@ public void Route(ApplicationModes applicationModes) break; } + default: { _consoleService.PrintHelp(); diff --git a/src/NzbDrone.Host/WebHost/Middleware/SignalRMiddleware.cs b/src/NzbDrone.Host/WebHost/Middleware/SignalRMiddleware.cs index 326f358d71..01de0cb6dc 100644 --- a/src/NzbDrone.Host/WebHost/Middleware/SignalRMiddleware.cs +++ b/src/NzbDrone.Host/WebHost/Middleware/SignalRMiddleware.cs @@ -68,10 +68,10 @@ public void Attach(IApplicationBuilder appBuilder) x.MapHub<MessageHub>("/signalr/messages"); }); #endif + // This is a side effect of haing multiple IoC containers, TinyIoC and whatever // Kestrel/SignalR is using. Ideally we'd have one IoC container, but that's non-trivial with TinyIoC // TODO: Use a single IoC container if supported for TinyIoC or if we switch to another system (ie Autofac). - var hubContext = appBuilder.ApplicationServices.GetService<IHubContext<MessageHub>>(); _container.Register(hubContext); } diff --git a/src/NzbDrone.Host/WebHost/WebHostController.cs b/src/NzbDrone.Host/WebHost/WebHostController.cs index 2ad8f7691d..69ffa4e786 100644 --- a/src/NzbDrone.Host/WebHost/WebHostController.cs +++ b/src/NzbDrone.Host/WebHost/WebHostController.cs @@ -92,14 +92,17 @@ public void StartServer() services .AddSignalR() #if !NETCOREAPP - .AddJsonProtocol( + .AddJsonProtocol(options => + { + options.PayloadSerializerSettings = Json.GetSerializerSettings(); + }); #else - .AddNewtonsoftJsonProtocol( + .AddNewtonsoftJsonProtocol(options => + { + options.PayloadSerializerSettings = Json.GetSerializerSettings(); + }); #endif - options => - { - options.PayloadSerializerSettings = Json.GetSerializerSettings(); - }); + }) .Configure(app => { diff --git a/src/NzbDrone.Integration.Test/ApiTests/CalendarFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/CalendarFixture.cs index 1a8815e0c7..5f3a180c12 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/CalendarFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/CalendarFixture.cs @@ -1,10 +1,10 @@ -using FluentAssertions; -using NUnit.Framework; -using Radarr.Api.V3.Movies; -using NzbDrone.Integration.Test.Client; using System; using System.Collections.Generic; using System.Linq; +using FluentAssertions; +using NUnit.Framework; +using NzbDrone.Integration.Test.Client; +using Radarr.Api.V3.Movies; namespace NzbDrone.Integration.Test.ApiTests { diff --git a/src/NzbDrone.Integration.Test/ApiTests/DiskSpaceFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/DiskSpaceFixture.cs index 1fd49f6a65..3eabc8b790 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/DiskSpaceFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/DiskSpaceFixture.cs @@ -1,8 +1,8 @@ using System.Linq; using FluentAssertions; using NUnit.Framework; -using Radarr.Api.V3.DiskSpace; using NzbDrone.Integration.Test.Client; +using Radarr.Api.V3.DiskSpace; namespace NzbDrone.Integration.Test.ApiTests { diff --git a/src/NzbDrone.Integration.Test/ApiTests/DownloadClientFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/DownloadClientFixture.cs index 6f0bd9b44d..25b512a92f 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/DownloadClientFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/DownloadClientFixture.cs @@ -7,8 +7,8 @@ namespace NzbDrone.Integration.Test.ApiTests [TestFixture] public class DownloadClientFixture : IntegrationTest { - - [Test, Order(0)] + [Test] + [Order(0)] public void add_downloadclient_without_name_should_return_badrequest() { IgnoreOnMonoVersions("5.12", "5.14"); @@ -24,7 +24,8 @@ public void add_downloadclient_without_name_should_return_badrequest() DownloadClients.InvalidPost(schema); } - [Test, Order(0)] + [Test] + [Order(0)] public void add_downloadclient_without_nzbfolder_should_return_badrequest() { IgnoreOnMonoVersions("5.12", "5.14"); @@ -40,7 +41,8 @@ public void add_downloadclient_without_nzbfolder_should_return_badrequest() DownloadClients.InvalidPost(schema); } - [Test, Order(0)] + [Test] + [Order(0)] public void add_downloadclient_without_watchfolder_should_return_badrequest() { IgnoreOnMonoVersions("5.12", "5.14"); @@ -56,7 +58,8 @@ public void add_downloadclient_without_watchfolder_should_return_badrequest() DownloadClients.InvalidPost(schema); } - [Test, Order(1)] + [Test] + [Order(1)] public void add_downloadclient() { EnsureNoDownloadClient(); @@ -73,7 +76,8 @@ public void add_downloadclient() result.Enable.Should().BeTrue(); } - [Test, Order(2)] + [Test] + [Order(2)] public void get_all_downloadclients() { EnsureDownloadClient(); @@ -83,7 +87,8 @@ public void get_all_downloadclients() clients.Should().NotBeNullOrEmpty(); } - [Test, Order(2)] + [Test] + [Order(2)] public void get_downloadclient_by_id() { var client = EnsureDownloadClient(); @@ -101,7 +106,8 @@ public void get_downloadclient_by_unknown_id_should_return_404() var result = DownloadClients.InvalidGet(1000000); } - [Test, Order(3)] + [Test] + [Order(3)] public void update_downloadclient() { EnsureNoDownloadClient(); @@ -113,7 +119,8 @@ public void update_downloadclient() result.Should().NotBeNull(); } - [Test, Order(4)] + [Test] + [Order(4)] public void delete_downloadclient() { var client = EnsureDownloadClient(); diff --git a/src/NzbDrone.Integration.Test/ApiTests/FileSystemFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/FileSystemFixture.cs index 3d2f470285..146e6f9e51 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/FileSystemFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/FileSystemFixture.cs @@ -1,14 +1,14 @@ -using FluentAssertions; -using NUnit.Framework; +using System.Collections.Generic; +using System.IO; using System.Linq; +using System.Net; +using System.Reflection; +using FluentAssertions; +using NUnit.Framework; +using NzbDrone.Common; +using NzbDrone.Common.Disk; using NzbDrone.Integration.Test.Client; using RestSharp; -using System.Net; -using NzbDrone.Common.Disk; -using System.Reflection; -using System.IO; -using System.Collections.Generic; -using NzbDrone.Common; namespace NzbDrone.Integration.Test.ApiTests { diff --git a/src/NzbDrone.Integration.Test/ApiTests/MovieEditorFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/MovieEditorFixture.cs index 35bb623978..ab8e1eb0d2 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/MovieEditorFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/MovieEditorFixture.cs @@ -1,8 +1,8 @@ +using System.Linq; using FluentAssertions; using NUnit.Framework; -using System.Linq; -using Radarr.Api.V3.Movies; using NzbDrone.Test.Common; +using Radarr.Api.V3.Movies; namespace NzbDrone.Integration.Test.ApiTests { diff --git a/src/NzbDrone.Integration.Test/ApiTests/MovieFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/MovieFixture.cs index 6616c09315..dca15687c0 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/MovieFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/MovieFixture.cs @@ -1,15 +1,16 @@ +using System.Collections.Generic; +using System.IO; +using System.Linq; using FluentAssertions; using NUnit.Framework; -using System.Linq; -using System.IO; -using System.Collections.Generic; namespace NzbDrone.Integration.Test.ApiTests { [TestFixture] public class MovieFixture : IntegrationTest { - [Test, Order(0)] + [Test] + [Order(0)] public void add_movie_with_tags_should_store_them() { EnsureNoMovie(680, "Pulp Fiction"); @@ -28,7 +29,8 @@ public void add_movie_with_tags_should_store_them() result.Tags.Should().Equal(tag.Id); } - [Test, Order(0)] + [Test] + [Order(0)] public void add_movie_without_profileid_should_return_badrequest() { IgnoreOnMonoVersions("5.12", "5.14"); @@ -42,7 +44,8 @@ public void add_movie_without_profileid_should_return_badrequest() Movies.InvalidPost(movie); } - [Test, Order(0)] + [Test] + [Order(0)] public void add_movie_without_path_should_return_badrequest() { IgnoreOnMonoVersions("5.12", "5.14"); @@ -56,7 +59,8 @@ public void add_movie_without_path_should_return_badrequest() Movies.InvalidPost(movie); } - [Test, Order(1)] + [Test] + [Order(1)] public void add_movie() { EnsureNoMovie(680, "Pulp Fiction"); @@ -74,8 +78,8 @@ public void add_movie() result.Path.Should().Be(Path.Combine(MovieRootFolder, movie.Title)); } - - [Test, Order(2)] + [Test] + [Order(2)] public void get_all_movies() { EnsureMovie(680, "Pulp Fiction"); @@ -86,7 +90,8 @@ public void get_all_movies() Movies.All().Should().Contain(v => v.ImdbId == "tt0468569"); } - [Test, Order(2)] + [Test] + [Order(2)] public void get_movie_by_id() { var movie = EnsureMovie(680, "Pulp Fiction"); @@ -104,7 +109,8 @@ public void get_movie_by_unknown_id_should_return_404() var result = Movies.InvalidGet(1000000); } - [Test, Order(2)] + [Test] + [Order(2)] public void update_movie_profile_id() { var movie = EnsureMovie(680, "Pulp Fiction"); @@ -122,7 +128,8 @@ public void update_movie_profile_id() Movies.Get(movie.Id).QualityProfileId.Should().Be(profileId); } - [Test, Order(3)] + [Test] + [Order(3)] public void update_movie_monitored() { var movie = EnsureMovie(680, "Pulp Fiction", false); @@ -136,7 +143,8 @@ public void update_movie_monitored() result.Monitored.Should().BeTrue(); } - [Test, Order(3)] + [Test] + [Order(3)] public void update_movie_tags() { var movie = EnsureMovie(680, "Pulp Fiction"); @@ -158,7 +166,8 @@ public void update_movie_tags() } } - [Test, Order(4)] + [Test] + [Order(4)] public void delete_movie() { var movie = EnsureMovie(680, "Pulp Fiction"); diff --git a/src/NzbDrone.Integration.Test/ApiTests/NamingConfigFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/NamingConfigFixture.cs index 96cc07f529..e8f7bd3c65 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/NamingConfigFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/NamingConfigFixture.cs @@ -6,7 +6,6 @@ namespace NzbDrone.Integration.Test.ApiTests [TestFixture] public class NamingConfigFixture : IntegrationTest { - [Test] public void should_be_able_to_get() { @@ -31,7 +30,6 @@ public void should_be_able_to_update() var result = NamingConfig.Put(config); result.RenameMovies.Should().BeFalse(); result.StandardMovieFormat.Should().Be(config.StandardMovieFormat); - } [Test] diff --git a/src/NzbDrone.Integration.Test/ApiTests/NotificationFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/NotificationFixture.cs index fe3dd538f1..fec812487a 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/NotificationFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/NotificationFixture.cs @@ -3,7 +3,6 @@ using FluentAssertions; using NUnit.Framework; - namespace NzbDrone.Integration.Test.ApiTests { [TestFixture] diff --git a/src/NzbDrone.Integration.Test/ApiTests/ReleaseFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/ReleaseFixture.cs index 199ad94d1a..d0aedb2c9a 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/ReleaseFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/ReleaseFixture.cs @@ -1,8 +1,8 @@ +using System.Linq; +using System.Net; using FluentAssertions; using NUnit.Framework; using Radarr.Api.V3.Indexers; -using System.Linq; -using System.Net; namespace NzbDrone.Integration.Test.ApiTests { @@ -38,7 +38,6 @@ public void should_accept_request_with_only_guid_supplied() // TODO: Maybe we should create a full mock Newznab server endpoint. //var result = Releases.Post(new ReleaseResource { Guid = releases.First().Guid }); //result.Guid.Should().Be(releases.First().Guid); - var result = Releases.Post(new ReleaseResource { Guid = releases.First().Guid }, HttpStatusCode.InternalServerError); } @@ -49,10 +48,10 @@ private bool BeValidRelease(ReleaseResource releaseResource) releaseResource.Title.Should().NotBeNullOrWhiteSpace(); releaseResource.DownloadUrl.Should().NotBeNullOrWhiteSpace(); releaseResource.MovieTitle.Should().NotBeNullOrWhiteSpace(); + //TODO: uncomment these after moving to restsharp for rss //releaseResource.NzbInfoUrl.Should().NotBeNullOrWhiteSpace(); //releaseResource.Size.Should().BeGreaterThan(0); - return true; } } diff --git a/src/NzbDrone.Integration.Test/ApiTests/RootFolderFixture.cs b/src/NzbDrone.Integration.Test/ApiTests/RootFolderFixture.cs index 7d0db2368b..bf2072aa61 100644 --- a/src/NzbDrone.Integration.Test/ApiTests/RootFolderFixture.cs +++ b/src/NzbDrone.Integration.Test/ApiTests/RootFolderFixture.cs @@ -32,12 +32,10 @@ public void should_add_and_delete_root_folders() RootFolders.All().Should().OnlyContain(c => c.Id == postResponse.Id); - RootFolders.Delete(postResponse.Id); RootFolders.All().Should().BeEmpty(); - SignalRMessages.Should().Contain(c => c.Name == "rootfolder"); } diff --git a/src/NzbDrone.Integration.Test/Client/ClientBase.cs b/src/NzbDrone.Integration.Test/Client/ClientBase.cs index 861f36ff84..3695b27e17 100644 --- a/src/NzbDrone.Integration.Test/Client/ClientBase.cs +++ b/src/NzbDrone.Integration.Test/Client/ClientBase.cs @@ -1,12 +1,12 @@ using System.Collections.Generic; +using System.Linq; using System.Net; using FluentAssertions; using NLog; -using Radarr.Http.REST; -using Radarr.Http; using NzbDrone.Common.Serializer; +using Radarr.Http; +using Radarr.Http.REST; using RestSharp; -using System.Linq; namespace NzbDrone.Integration.Test.Client { @@ -60,7 +60,8 @@ public string Execute(IRestRequest request, HttpStatusCode statusCode) return response.Content; } - public T Execute<T>(IRestRequest request, HttpStatusCode statusCode) where T : class, new() + public T Execute<T>(IRestRequest request, HttpStatusCode statusCode) + where T : class, new() { var content = Execute(request, statusCode); @@ -83,7 +84,6 @@ public class ClientBase<TResource> : ClientBase public ClientBase(IRestClient restClient, string apiKey, string resource = null) : base(restClient, apiKey, resource ?? new TResource().ResourceName) { - } public List<TResource> All() @@ -161,19 +161,22 @@ public object InvalidPut(TResource body, HttpStatusCode statusCode = HttpStatusC return Put<object>(request, statusCode); } - public T Get<T>(IRestRequest request, HttpStatusCode statusCode = HttpStatusCode.OK) where T : class, new() + public T Get<T>(IRestRequest request, HttpStatusCode statusCode = HttpStatusCode.OK) + where T : class, new() { request.Method = Method.GET; return Execute<T>(request, statusCode); } - public T Post<T>(IRestRequest request, HttpStatusCode statusCode = HttpStatusCode.Created) where T : class, new() + public T Post<T>(IRestRequest request, HttpStatusCode statusCode = HttpStatusCode.Created) + where T : class, new() { request.Method = Method.POST; return Execute<T>(request, statusCode); } - public T Put<T>(IRestRequest request, HttpStatusCode statusCode = HttpStatusCode.Accepted) where T : class, new() + public T Put<T>(IRestRequest request, HttpStatusCode statusCode = HttpStatusCode.Accepted) + where T : class, new() { request.Method = Method.PUT; return Execute<T>(request, statusCode); diff --git a/src/NzbDrone.Integration.Test/Client/CommandClient.cs b/src/NzbDrone.Integration.Test/Client/CommandClient.cs index 7b96ae63cf..eee3c7fd71 100644 --- a/src/NzbDrone.Integration.Test/Client/CommandClient.cs +++ b/src/NzbDrone.Integration.Test/Client/CommandClient.cs @@ -1,12 +1,12 @@ -using RestSharp; -using NzbDrone.Core.Messaging.Commands; -using FluentAssertions; -using System.Threading; -using NUnit.Framework; +using System; using System.Linq; -using System; -using Radarr.Http.REST; +using System.Threading; +using FluentAssertions; using Newtonsoft.Json; +using NUnit.Framework; +using NzbDrone.Core.Messaging.Commands; +using Radarr.Http.REST; +using RestSharp; namespace NzbDrone.Integration.Test.Client { @@ -27,7 +27,10 @@ public class SimpleCommandResource : RestResource [JsonIgnore] public Command Body { get; set; } [JsonProperty("body")] - public Command BodyReadOnly { get { return Body; } } + public Command BodyReadOnly + { + get { return Body; } + } } public class CommandClient : ClientBase<SimpleCommandResource> @@ -37,7 +40,8 @@ public CommandClient(IRestClient restClient, string apiKey) { } - public SimpleCommandResource PostAndWait<T>(T command) where T : Command, new() + public SimpleCommandResource PostAndWait<T>(T command) + where T : Command, new() { var request = BuildRequest(); request.AddJsonBody(command); diff --git a/src/NzbDrone.Integration.Test/Client/MovieClient.cs b/src/NzbDrone.Integration.Test/Client/MovieClient.cs index 52b508fca8..87f10925c1 100644 --- a/src/NzbDrone.Integration.Test/Client/MovieClient.cs +++ b/src/NzbDrone.Integration.Test/Client/MovieClient.cs @@ -31,7 +31,6 @@ public MovieResource Get(string slug, HttpStatusCode statusCode = HttpStatusCode var request = BuildRequest(slug); return Get<MovieResource>(request, statusCode); } - } public class SystemInfoClient : ClientBase<MovieResource> diff --git a/src/NzbDrone.Integration.Test/GenericApiFixture.cs b/src/NzbDrone.Integration.Test/GenericApiFixture.cs index 52472dd5af..63c6e9dbc4 100644 --- a/src/NzbDrone.Integration.Test/GenericApiFixture.cs +++ b/src/NzbDrone.Integration.Test/GenericApiFixture.cs @@ -16,7 +16,6 @@ public class GenericApiFixture : IntegrationTest [TestCase("")] public void should_get_json_with_accept_header(string header) { - var request = new RestRequest("system/status") { RequestFormat = DataFormat.None diff --git a/src/NzbDrone.Integration.Test/IndexHtmlFixture.cs b/src/NzbDrone.Integration.Test/IndexHtmlFixture.cs index b931620ca0..8bd1a26fc2 100644 --- a/src/NzbDrone.Integration.Test/IndexHtmlFixture.cs +++ b/src/NzbDrone.Integration.Test/IndexHtmlFixture.cs @@ -13,6 +13,5 @@ public void should_get_index_html() var text = new WebClient().DownloadString(RootUrl); text.Should().NotBeNullOrWhiteSpace(); } - } } diff --git a/src/NzbDrone.Integration.Test/IntegrationTestBase.cs b/src/NzbDrone.Integration.Test/IntegrationTestBase.cs index 7da8593bb5..3a9f924273 100644 --- a/src/NzbDrone.Integration.Test/IntegrationTestBase.cs +++ b/src/NzbDrone.Integration.Test/IntegrationTestBase.cs @@ -4,29 +4,29 @@ using System.IO; using System.Linq; using System.Threading; +using System.Threading.Tasks; using FluentAssertions; +using Microsoft.AspNetCore.SignalR.Client; using NLog; using NLog.Config; using NLog.Targets; using NUnit.Framework; -using Radarr.Api.V3.Blacklist; -using Radarr.Api.V3.Config; -using Radarr.Api.V3.DownloadClient; -using Radarr.Api.V3.MovieFiles; -using Radarr.Api.V3.History; -using Radarr.Api.V3.Profiles.Quality; -using Radarr.Api.V3.RootFolders; -using Radarr.Api.V3.Movies; -using Radarr.Api.V3.Tags; using NzbDrone.Common.EnvironmentInfo; -using NzbDrone.Core.Qualities; using NzbDrone.Core.Movies.Commands; +using NzbDrone.Core.Qualities; using NzbDrone.Integration.Test.Client; using NzbDrone.SignalR; using NzbDrone.Test.Common.Categories; +using Radarr.Api.V3.Blacklist; +using Radarr.Api.V3.Config; +using Radarr.Api.V3.DownloadClient; +using Radarr.Api.V3.History; +using Radarr.Api.V3.MovieFiles; +using Radarr.Api.V3.Movies; +using Radarr.Api.V3.Profiles.Quality; +using Radarr.Api.V3.RootFolders; +using Radarr.Api.V3.Tags; using RestSharp; -using System.Threading.Tasks; -using Microsoft.AspNetCore.SignalR.Client; namespace NzbDrone.Integration.Test { @@ -134,7 +134,6 @@ public async Task IntegrationTearDown() { if (_signalrConnection != null) { - await _signalrConnection.StopAsync(); _signalrConnection = null; @@ -183,7 +182,6 @@ protected async Task ConnectSignalR() _signalRReceived = new List<SignalRMessage>(); _signalrConnection = new HubConnectionBuilder().WithUrl("http://localhost:7878/signalr/messages").Build(); - var cts = new CancellationTokenSource(); _signalrConnection.Closed += e => @@ -206,7 +204,7 @@ protected async Task ConnectSignalR() { Console.WriteLine("Connecting to signalR"); - await _signalrConnection.StartAsync(); + await _signalrConnection.StartAsync(); connected = true; break; } @@ -229,13 +227,17 @@ public static void WaitForCompletion(Func<bool> predicate, int timeout = 10000, for (var i = 0; i < count; i++) { if (predicate()) + { return; + } Thread.Sleep(interval); } if (predicate()) + { return; + } Assert.Fail("Timed on wait"); } diff --git a/src/NzbDrone.Mono.Test/DiskProviderTests/DiskProviderFixture.cs b/src/NzbDrone.Mono.Test/DiskProviderTests/DiskProviderFixture.cs index 17b5133437..65c126403b 100644 --- a/src/NzbDrone.Mono.Test/DiskProviderTests/DiskProviderFixture.cs +++ b/src/NzbDrone.Mono.Test/DiskProviderTests/DiskProviderFixture.cs @@ -13,7 +13,7 @@ namespace NzbDrone.Mono.Test.DiskProviderTests { [TestFixture] - [Platform(Exclude="Win")] + [Platform(Exclude = "Win")] public class DiskProviderFixture : DiskProviderFixtureBase<DiskProvider> { public DiskProviderFixture() @@ -29,7 +29,6 @@ protected override void SetWritePermissions(string path, bool writable) } // Remove Write permissions, we're still owner so we can clean it up, but we'll have to do that explicitly. - var entry = UnixFileSystemInfo.GetFileSystemEntry(path); if (writable) @@ -100,7 +99,8 @@ private void GivenSpecialMount(string rootDir) Mocker.GetMock<IProcMountProvider>() .Setup(v => v.GetMounts()) - .Returns(new List<IMount> { + .Returns(new List<IMount> + { new ProcMount(DriveType.Fixed, rootDir, rootDir, "myfs", new MountOptions(new Dictionary<string, string>())) }); } diff --git a/src/NzbDrone.Mono.Test/DiskProviderTests/FreeSpaceFixture.cs b/src/NzbDrone.Mono.Test/DiskProviderTests/FreeSpaceFixture.cs index 904693e112..619194cdd5 100644 --- a/src/NzbDrone.Mono.Test/DiskProviderTests/FreeSpaceFixture.cs +++ b/src/NzbDrone.Mono.Test/DiskProviderTests/FreeSpaceFixture.cs @@ -5,7 +5,7 @@ namespace NzbDrone.Mono.Test.DiskProviderTests { [TestFixture] - [Platform(Exclude="Win")] + [Platform(Exclude = "Win")] public class FreeSpaceFixture : FreeSpaceFixtureBase<DiskProvider> { public FreeSpaceFixture() diff --git a/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/MacOsVersionAdapterFixture.cs b/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/MacOsVersionAdapterFixture.cs index ab191f390b..f0dbe0a858 100644 --- a/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/MacOsVersionAdapterFixture.cs +++ b/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/MacOsVersionAdapterFixture.cs @@ -38,7 +38,6 @@ public void should_get_version_info(string versionString) versionName.FullName.Should().Be("macOS " + versionString); } - [TestCase] public void should_detect_server() { diff --git a/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapterFixture.cs b/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapterFixture.cs index 0795865514..73726a18e0 100644 --- a/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapterFixture.cs +++ b/src/NzbDrone.Mono.Test/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapterFixture.cs @@ -37,7 +37,6 @@ public void should_return_null_if_etc_doestn_exist() Subject.Read().Should().BeNull(); } - [Test] public void should_return_null_if_release_file_doestn_exist() { @@ -76,7 +75,6 @@ public void should_detect_version() version.Name.Should().Be("ubuntu"); version.Version.Should().Be("14.04"); version.FullName.Should().Be("Ubuntu 14.04.5 LTS"); - } } } diff --git a/src/NzbDrone.Mono/Disk/DiskProvider.cs b/src/NzbDrone.Mono/Disk/DiskProvider.cs index cb2329db40..ca60c400f5 100644 --- a/src/NzbDrone.Mono/Disk/DiskProvider.cs +++ b/src/NzbDrone.Mono/Disk/DiskProvider.cs @@ -14,15 +14,15 @@ namespace NzbDrone.Mono.Disk { public class DiskProvider : DiskProviderBase { + // Mono supports sending -1 for a uint to indicate that the owner or group should not be set + // `unchecked((uint)-1)` and `uint.MaxValue` are the same thing. + private const uint UNCHANGED_ID = uint.MaxValue; + private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(DiskProvider)); private readonly IProcMountProvider _procMountProvider; private readonly ISymbolicLinkResolver _symLinkResolver; - // Mono supports sending -1 for a uint to indicate that the owner or group should not be set - // `unchecked((uint)-1)` and `uint.MaxValue` are the same thing. - private const uint UNCHANGED_ID = uint.MaxValue; - public DiskProvider(IProcMountProvider procMountProvider, ISymbolicLinkResolver symLinkResolver) { _procMountProvider = procMountProvider; @@ -197,7 +197,10 @@ public override bool TryCreateHardLink(string source, string destination) { var fileInfo = UnixFileSystemInfo.GetFileSystemEntry(source); - if (fileInfo.IsSymbolicLink) return false; + if (fileInfo.IsSymbolicLink) + { + return false; + } fileInfo.CreateLink(destination); return true; diff --git a/src/NzbDrone.Mono/Disk/LinuxPermissionsException.cs b/src/NzbDrone.Mono/Disk/LinuxPermissionsException.cs index 964eb3a082..4886230930 100644 --- a/src/NzbDrone.Mono/Disk/LinuxPermissionsException.cs +++ b/src/NzbDrone.Mono/Disk/LinuxPermissionsException.cs @@ -4,11 +4,13 @@ namespace NzbDrone.Mono.Disk { public class LinuxPermissionsException : NzbDroneException { - public LinuxPermissionsException(string message, params object[] args) : base(message, args) + public LinuxPermissionsException(string message, params object[] args) + : base(message, args) { } - public LinuxPermissionsException(string message) : base(message) + public LinuxPermissionsException(string message) + : base(message) { } } diff --git a/src/NzbDrone.Mono/Disk/ProcMountProvider.cs b/src/NzbDrone.Mono/Disk/ProcMountProvider.cs index 88e834d8a3..f95f2a88cf 100644 --- a/src/NzbDrone.Mono/Disk/ProcMountProvider.cs +++ b/src/NzbDrone.Mono/Disk/ProcMountProvider.cs @@ -16,17 +16,17 @@ public interface IProcMountProvider public class ProcMountProvider : IProcMountProvider { - private static string[] _fixedTypes = new [] { "ext3", "ext2", "ext4", "vfat", "fuseblk", "xfs", "jfs", "msdos", "ntfs", "minix", "hfs", "hfsplus", "qnx4", "ufs", "btrfs" }; - private static string[] _networkDriveTypes = new [] { "cifs", "nfs", "nfs4", "nfsd", "sshfs" }; - private static readonly Regex OctalRegex = new Regex(@"\\\d{3}", RegexOptions.Compiled); - private const string PROC_MOUNTS_FILENAME = @"/proc/mounts"; private const string PROC_FILESYSTEMS_FILENAME = @"/proc/filesystems"; - private static Dictionary<string, bool> _fileSystems; - + private static readonly Regex OctalRegex = new Regex(@"\\\d{3}", RegexOptions.Compiled); private readonly Logger _logger; + private static string[] _fixedTypes = new[] { "ext3", "ext2", "ext4", "vfat", "fuseblk", "xfs", "jfs", "msdos", "ntfs", "minix", "hfs", "hfsplus", "qnx4", "ufs", "btrfs" }; + private static string[] _networkDriveTypes = new[] { "cifs", "nfs", "nfs4", "nfsd", "sshfs" }; + + private static Dictionary<string, bool> _fileSystems; + public ProcMountProvider(Logger logger) { _logger = logger; diff --git a/src/NzbDrone.Mono/Disk/SymbolicLinkResolver.cs b/src/NzbDrone.Mono/Disk/SymbolicLinkResolver.cs index 91aec48c3c..8291975221 100644 --- a/src/NzbDrone.Mono/Disk/SymbolicLinkResolver.cs +++ b/src/NzbDrone.Mono/Disk/SymbolicLinkResolver.cs @@ -24,7 +24,10 @@ public SymbolicLinkResolver(Logger logger) public string GetCompleteRealPath(string path) { - if (path == null) return null; + if (path == null) + { + return null; + } try { @@ -39,6 +42,7 @@ public string GetCompleteRealPath(string path) dir += dirs[0]; realPath.Append(GetRealPath(dir)); } + for (var i = 1; i < lastIndex; ++i) { realPath.Append("/").Append(dirs[i]); @@ -46,6 +50,7 @@ public string GetCompleteRealPath(string path) realPath.Remove(0, realPath.Length); realPath.Append(realSubPath); } + return realPath.ToString(); } catch (Exception ex) @@ -55,7 +60,6 @@ public string GetCompleteRealPath(string path) } } - private static void GetPathComponents(string path, out string[] components, out int lastIndex) { var dirs = path.Split(UnixPath.DirectorySeparatorChar); @@ -83,6 +87,7 @@ private static void GetPathComponents(string path, out string[] components, out dirs[target++] = dirs[i]; } } + components = dirs; lastIndex = target; } @@ -113,8 +118,8 @@ public string GetRealPath(string path) path = UnixPath.GetDirectoryName(path) + UnixPath.DirectorySeparatorChar + link; path = UnixPath.GetCanonicalPath(path); } - } while (true); + } + while (true); } - } } diff --git a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/IssueFileVersionAdapter.cs b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/IssueFileVersionAdapter.cs index 321a8c12e6..2965f5a1aa 100644 --- a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/IssueFileVersionAdapter.cs +++ b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/IssueFileVersionAdapter.cs @@ -30,7 +30,6 @@ public OsVersionModel Read() var fileContent = _diskProvider.ReadAllText(issueFile); - // Ubuntu 14.04.5 LTS \n \l // Ubuntu 16.04.1 LTS \n \l diff --git a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/MacOsVersionAdapter.cs b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/MacOsVersionAdapter.cs index c9521588e4..175219d61e 100644 --- a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/MacOsVersionAdapter.cs +++ b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/MacOsVersionAdapter.cs @@ -9,13 +9,10 @@ namespace NzbDrone.Mono.EnvironmentInfo.VersionAdapters { public class MacOsVersionAdapter : IOsVersionAdapter { - private static readonly Regex DarwinVersionRegex = new Regex("<string>(?<version>10\\.\\d{1,2}\\.?\\d{0,2}?)<\\/string>", - RegexOptions.Compiled | - RegexOptions.IgnoreCase - ); - private const string PLIST_DIR = "/System/Library/CoreServices/"; + private static readonly Regex DarwinVersionRegex = new Regex("<string>(?<version>10\\.\\d{1,2}\\.?\\d{0,2}?)<\\/string>", + RegexOptions.Compiled | RegexOptions.IgnoreCase); private readonly IDiskProvider _diskProvider; private readonly Logger _logger; @@ -40,8 +37,7 @@ public OsVersionModel Read() var versionFile = allFiles.SingleOrDefault(c => c.EndsWith("SystemVersion.plist") || - c.EndsWith("ServerVersion.plist") - ); + c.EndsWith("ServerVersion.plist")); if (string.IsNullOrWhiteSpace(versionFile)) { @@ -52,8 +48,6 @@ public OsVersionModel Read() var text = _diskProvider.ReadAllText(versionFile); var match = DarwinVersionRegex.Match(text); - - if (match.Success) { version = match.Groups["version"].Value; diff --git a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapter.cs b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapter.cs index d0b5cb3bed..78dcceec61 100644 --- a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapter.cs +++ b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/ReleaseFileVersionAdapter.cs @@ -33,7 +33,7 @@ public OsVersionModel Read() foreach (var releaseFile in releaseFiles) { var fileContent = _diskProvider.ReadAllText(releaseFile); - var lines = Regex.Split(fileContent, "\r\n|\r|\n"); ; + var lines = Regex.Split(fileContent, "\r\n|\r|\n"); foreach (var line in lines) { @@ -71,7 +71,6 @@ public OsVersionModel Read() } return new OsVersionModel(name, version, fullName); - } public bool Enabled => OsInfo.IsLinux; diff --git a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/SynologyVersionAdapter.cs b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/SynologyVersionAdapter.cs index 02bba34b11..994867527b 100644 --- a/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/SynologyVersionAdapter.cs +++ b/src/NzbDrone.Mono/EnvironmentInfo/VersionAdapters/SynologyVersionAdapter.cs @@ -8,10 +8,9 @@ namespace NzbDrone.Mono.EnvironmentInfo.VersionAdapters { public class SynologyVersionAdapter : IOsVersionAdapter { - private readonly IDiskProvider _diskProvider; private const string NAME = "DSM"; private const string FULL_NAME = "Synology DSM"; - + private readonly IDiskProvider _diskProvider; public SynologyVersionAdapter(IDiskProvider diskProvider) { @@ -37,7 +36,7 @@ public OsVersionModel Read() var minor = "0"; var fileContent = _diskProvider.ReadAllText(versionFile); - var lines = Regex.Split(fileContent, "\r\n|\r|\n"); ; + var lines = Regex.Split(fileContent, "\r\n|\r|\n"); foreach (var line in lines) { diff --git a/src/NzbDrone.Test.Common/AutoMoq/AutoMoqer.cs b/src/NzbDrone.Test.Common/AutoMoq/AutoMoqer.cs index d3fef1dfe2..04abf96e90 100644 --- a/src/NzbDrone.Test.Common/AutoMoq/AutoMoqer.cs +++ b/src/NzbDrone.Test.Common/AutoMoq/AutoMoqer.cs @@ -6,12 +6,12 @@ using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; -using Unity; using Moq; using Moq.Language.Flow; using NzbDrone.Common.Composition; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Test.Common.AutoMoq.Unity; +using Unity; [assembly: InternalsVisibleTo("AutoMoq.Tests")] @@ -34,7 +34,6 @@ public AutoMoqer(MockBehavior defaultBehavior) { DefaultBehavior = defaultBehavior; SetupAutoMoqer(new UnityContainer()); - } public AutoMoqer(IUnityContainer container) @@ -51,12 +50,14 @@ public virtual T Resolve<T>() return result; } - public virtual Mock<T> GetMock<T>() where T : class + public virtual Mock<T> GetMock<T>() + where T : class { return GetMock<T>(DefaultBehavior); } - public virtual Mock<T> GetMock<T>(MockBehavior behavior) where T : class + public virtual Mock<T> GetMock<T>(MockBehavior behavior) + where T : class { ResolveType = null; var type = GetTheMockType<T>(); @@ -78,9 +79,14 @@ public virtual Mock<T> GetMock<T>(MockBehavior behavior) where T : class public virtual void SetMock(Type type, Mock mock) { if (_registeredMocks.ContainsKey(type) == false) + { _registeredMocks.Add(type, mock); + } + if (mock != null) + { _container.RegisterInstance(type, mock.Object); + } } public virtual void SetConstant<T>(T instance) @@ -89,32 +95,38 @@ public virtual void SetConstant<T>(T instance) SetMock(instance.GetType(), null); } - public ISetup<T> Setup<T>(Expression<Action<T>> expression) where T : class + public ISetup<T> Setup<T>(Expression<Action<T>> expression) + where T : class { return GetMock<T>().Setup(expression); } - public ISetup<T, TResult> Setup<T, TResult>(Expression<Func<T, TResult>> expression) where T : class + public ISetup<T, TResult> Setup<T, TResult>(Expression<Func<T, TResult>> expression) + where T : class { return GetMock<T>().Setup(expression); } - public void Verify<T>(Expression<Action<T>> expression) where T : class + public void Verify<T>(Expression<Action<T>> expression) + where T : class { GetMock<T>().Verify(expression); } - public void Verify<T>(Expression<Action<T>> expression, string failMessage) where T : class + public void Verify<T>(Expression<Action<T>> expression, string failMessage) + where T : class { GetMock<T>().Verify(expression, failMessage); } - public void Verify<T>(Expression<Action<T>> expression, Times times) where T : class + public void Verify<T>(Expression<Action<T>> expression, Times times) + where T : class { GetMock<T>().Verify(expression, times); } - public void Verify<T>(Expression<Action<T>> expression, Times times, string failMessage) where T : class + public void Verify<T>(Expression<Action<T>> expression, Times times, string failMessage) + where T : class { GetMock<T>().Verify(expression, times, failMessage); } @@ -125,12 +137,12 @@ public void VerifyAllMocks() { var mock = registeredMock.Value as Mock; if (mock != null) + { mock.VerifyAll(); + } } } - #region private methods - private void SetupAutoMoqer(IUnityContainer container) { _container = container; @@ -140,9 +152,8 @@ private void SetupAutoMoqer(IUnityContainer container) _registeredMocks = new Dictionary<Type, object>(); AddTheAutoMockingContainerExtensionToTheContainer(container); - #if NETCOREAPP - ContainerBuilderBase.RegisterNativeResolver(new [] {"System.Data.SQLite", "Radarr.Core"}); + ContainerBuilderBase.RegisterNativeResolver(new[] { "System.Data.SQLite", "Radarr.Core" }); #endif } @@ -152,12 +163,14 @@ private static void AddTheAutoMockingContainerExtensionToTheContainer(IUnityCont return; } - private Mock<T> TheRegisteredMockForThisType<T>(Type type) where T : class + private Mock<T> TheRegisteredMockForThisType<T>(Type type) + where T : class { return (Mock<T>)_registeredMocks.First(x => x.Key == type).Value; } - private void CreateANewMockAndRegisterIt<T>(Type type, MockBehavior behavior) where T : class + private void CreateANewMockAndRegisterIt<T>(Type type, MockBehavior behavior) + where T : class { var mock = new Mock<T>(behavior); _container.RegisterInstance(mock.Object); @@ -169,7 +182,8 @@ private bool GetMockHasNotBeenCalledForThisType(Type type) return _registeredMocks.ContainsKey(type) == false; } - private static Type GetTheMockType<T>() where T : class + private static Type GetTheMockType<T>() + where T : class { return typeof(T); } @@ -190,7 +204,5 @@ private void RegisterPlatformLibrary(IUnityContainer container) Assembly.Load(assemblyName); } - - #endregion } } diff --git a/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingBuilderStrategy.cs b/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingBuilderStrategy.cs index 1756fe6566..c841dc7d7b 100644 --- a/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingBuilderStrategy.cs +++ b/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingBuilderStrategy.cs @@ -2,10 +2,10 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; -using Unity; using Moq; -using Unity.Strategies; +using Unity; using Unity.Builder; +using Unity.Strategies; namespace NzbDrone.Test.Common.AutoMoq.Unity { @@ -36,8 +36,6 @@ public override void PreBuildUp(ref BuilderContext context) } } - #region private methods - private bool AMockObjectShouldBeCreatedForThisType(Type type) { var mocker = _container.Resolve<AutoMoqer>(); @@ -78,7 +76,5 @@ private static Type[] EmptyArgumentList() { return new[] { typeof(object[]) }; } - - #endregion } } diff --git a/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingContainerExtension.cs b/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingContainerExtension.cs index b764c929d0..71838c545f 100644 --- a/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingContainerExtension.cs +++ b/src/NzbDrone.Test.Common/AutoMoq/Unity/AutoMockingContainerExtension.cs @@ -7,7 +7,7 @@ namespace NzbDrone.Test.Common.AutoMoq.Unity { public class AutoMockingContainerExtension : UnityContainerExtension { - private readonly IList<Type> registeredTypes = new List<Type>(); + private readonly IList<Type> _registeredTypes = new List<Type>(); protected override void Initialize() { @@ -15,25 +15,21 @@ protected override void Initialize() SetBuildingStrategyForBuildingUnregisteredTypes(); } - #region private methods - private void SetEventsOnContainerToTrackAllRegisteredTypes() { - Context.Registering += ((sender, e) => RegisterType(e.TypeFrom)); - Context.RegisteringInstance += ((sender, e) => RegisterType(e.RegisteredType)); + Context.Registering += (sender, e) => RegisterType(e.TypeFrom); + Context.RegisteringInstance += (sender, e) => RegisterType(e.RegisteredType); } private void RegisterType(Type typeToRegister) { - registeredTypes.Add(typeToRegister); + _registeredTypes.Add(typeToRegister); } private void SetBuildingStrategyForBuildingUnregisteredTypes() { - var strategy = new AutoMockingBuilderStrategy(registeredTypes, Container); + var strategy = new AutoMockingBuilderStrategy(_registeredTypes, Container); Context.Strategies.Add(strategy, UnityBuildStage.PreCreation); } - - #endregion } } diff --git a/src/NzbDrone.Test.Common/Categories/DiskAccessTestAttribute.cs b/src/NzbDrone.Test.Common/Categories/DiskAccessTestAttribute.cs index c9588d9cdd..d62a0dce02 100644 --- a/src/NzbDrone.Test.Common/Categories/DiskAccessTestAttribute.cs +++ b/src/NzbDrone.Test.Common/Categories/DiskAccessTestAttribute.cs @@ -7,7 +7,6 @@ public class DiskAccessTestAttribute : CategoryAttribute public DiskAccessTestAttribute() : base("DiskAccessTest") { - } } } diff --git a/src/NzbDrone.Test.Common/Categories/IntegrationTestAttribute.cs b/src/NzbDrone.Test.Common/Categories/IntegrationTestAttribute.cs index bae8833e47..f26c5e84e1 100644 --- a/src/NzbDrone.Test.Common/Categories/IntegrationTestAttribute.cs +++ b/src/NzbDrone.Test.Common/Categories/IntegrationTestAttribute.cs @@ -7,7 +7,6 @@ public class IntegrationTestAttribute : CategoryAttribute public IntegrationTestAttribute() : base("IntegrationTest") { - } } } diff --git a/src/NzbDrone.Test.Common/Categories/ManualTestAttribute.cs b/src/NzbDrone.Test.Common/Categories/ManualTestAttribute.cs index 1553226500..0dd8fdec3b 100644 --- a/src/NzbDrone.Test.Common/Categories/ManualTestAttribute.cs +++ b/src/NzbDrone.Test.Common/Categories/ManualTestAttribute.cs @@ -7,7 +7,6 @@ public class ManualTestAttribute : CategoryAttribute public ManualTestAttribute() : base("ManualTest") { - } } } diff --git a/src/NzbDrone.Test.Common/ConcurrencyCounter.cs b/src/NzbDrone.Test.Common/ConcurrencyCounter.cs index 6f42624a67..6ee4554db4 100644 --- a/src/NzbDrone.Test.Common/ConcurrencyCounter.cs +++ b/src/NzbDrone.Test.Common/ConcurrencyCounter.cs @@ -6,9 +6,9 @@ namespace NzbDrone.Test.Common { public class ConcurrencyCounter { + private readonly object _mutex = new object(); + private readonly Dictionary<int, int> _threads = new Dictionary<int, int>(); private int _items; - readonly object _mutex = new object(); - readonly Dictionary<int, int> _threads = new Dictionary<int, int>(); public int MaxThreads => _threads.Count; @@ -30,7 +30,6 @@ public int Start() int threadId = Thread.CurrentThread.ManagedThreadId; lock (_mutex) { - _threads[threadId] = 1; } diff --git a/src/NzbDrone.Test.Common/ExceptionVerification.cs b/src/NzbDrone.Test.Common/ExceptionVerification.cs index e6b8118b3c..bcf4174340 100644 --- a/src/NzbDrone.Test.Common/ExceptionVerification.cs +++ b/src/NzbDrone.Test.Common/ExceptionVerification.cs @@ -55,6 +55,7 @@ private static string GetLogsString(IEnumerable<LogEventInfo> logs) errors += Environment.NewLine + string.Format("[{0}] {1}: {2} {3}", log.Level, log.LoggerName, log.FormattedMessage, exception); } + return errors; } @@ -75,7 +76,9 @@ public static void WaitForErrors(int count, int msec) } if (!_waitEvent.Wait(msec)) + { break; + } } Expected(LogLevel.Error, count); @@ -142,9 +145,11 @@ private static void Expected(LogLevel level, int count) if (levelLogs.Count != count) { - var message = string.Format("{0} {1}(s) were expected but {2} were logged.\n\r{3}", - count, level, levelLogs.Count, GetLogsString(levelLogs)); + count, + level, + levelLogs.Count, + GetLogsString(levelLogs)); message = "\n\r****************************************************************************************\n\r" + message + diff --git a/src/NzbDrone.Test.Common/LoggingTest.cs b/src/NzbDrone.Test.Common/LoggingTest.cs index 45f666c09e..f08d3aa4b6 100644 --- a/src/NzbDrone.Test.Common/LoggingTest.cs +++ b/src/NzbDrone.Test.Common/LoggingTest.cs @@ -1,8 +1,8 @@ +using System; +using System.IO; using NLog; using NLog.Config; using NLog.Targets; -using System; -using System.IO; using NUnit.Framework; using NUnit.Framework.Interfaces; using NzbDrone.Common.EnvironmentInfo; diff --git a/src/NzbDrone.Test.Common/NzbDroneRunner.cs b/src/NzbDrone.Test.Common/NzbDroneRunner.cs index 4139301943..55fce6be99 100644 --- a/src/NzbDrone.Test.Common/NzbDroneRunner.cs +++ b/src/NzbDrone.Test.Common/NzbDroneRunner.cs @@ -109,7 +109,6 @@ private void Start(string outputRadarrConsoleExe) { var args = "-nobrowser -data=\"" + AppData + "\""; _nzbDroneProcess = _processProvider.Start(outputRadarrConsoleExe, args, null, OnOutputDataReceived, OnOutputDataReceived); - } private void OnOutputDataReceived(string data) @@ -133,9 +132,7 @@ private void GenerateConfigFile() new XDeclaration("1.0", "utf-8", "yes"), new XElement(ConfigFileProvider.CONFIG_ELEMENT_NAME, new XElement(nameof(ConfigFileProvider.ApiKey), apiKey), - new XElement(nameof(ConfigFileProvider.AnalyticsEnabled), false) - ) - ); + new XElement(nameof(ConfigFileProvider.AnalyticsEnabled), false))); var data = xDoc.ToString(); diff --git a/src/NzbDrone.Test.Common/StringExtensions.cs b/src/NzbDrone.Test.Common/StringExtensions.cs index 97b23ade62..659be61704 100644 --- a/src/NzbDrone.Test.Common/StringExtensions.cs +++ b/src/NzbDrone.Test.Common/StringExtensions.cs @@ -14,6 +14,7 @@ public static string AsOsAgnostic(this string path) path = path.Replace(":", ""); path = Path.DirectorySeparatorChar + path; } + path = path.Replace("\\", Path.DirectorySeparatorChar.ToString()); } diff --git a/src/NzbDrone.Test.Common/TestBase.cs b/src/NzbDrone.Test.Common/TestBase.cs index 8b1e0fc9bd..03876da687 100644 --- a/src/NzbDrone.Test.Common/TestBase.cs +++ b/src/NzbDrone.Test.Common/TestBase.cs @@ -14,16 +14,15 @@ namespace NzbDrone.Test.Common { - public abstract class TestBase<TSubject> : TestBase where TSubject : class + public abstract class TestBase<TSubject> : TestBase + where TSubject : class { - private TSubject _subject; [SetUp] public void CoreTestSetup() { _subject = null; - } protected TSubject Subject @@ -37,14 +36,11 @@ protected TSubject Subject return _subject; } - } - } public abstract class TestBase : LoggingTest { - private static readonly Random _random = new Random(); private static int _nextUid; @@ -65,7 +61,6 @@ protected AutoMoqer Mocker } } - protected int RandomNumber { get @@ -80,7 +75,10 @@ private string VirtualPath get { var virtualPath = Path.Combine(TempFolder, "VirtualNzbDrone"); - if (!Directory.Exists(virtualPath)) Directory.CreateDirectory(virtualPath); + if (!Directory.Exists(virtualPath)) + { + Directory.CreateDirectory(virtualPath); + } return virtualPath; } @@ -120,7 +118,6 @@ public void TestBaseTearDown() DeleteTempFolder(_tempFolder); } - public static string GetUID() { return Process.GetCurrentProcess().Id + "_" + DateTime.Now.Ticks + "_" + Interlocked.Increment(ref _nextUid); @@ -133,7 +130,6 @@ public static void DeleteTempFolder(string folder) return; } - try { var tempFolder = new DirectoryInfo(folder); @@ -202,17 +198,20 @@ protected string GetTempFilePath() return Path.Combine(TempFolder, Path.GetRandomFileName()); } - protected void VerifyEventPublished<TEvent>() where TEvent : class, IEvent + protected void VerifyEventPublished<TEvent>() + where TEvent : class, IEvent { VerifyEventPublished<TEvent>(Times.Once()); } - protected void VerifyEventPublished<TEvent>(Times times) where TEvent : class, IEvent + protected void VerifyEventPublished<TEvent>(Times times) + where TEvent : class, IEvent { Mocker.GetMock<IEventAggregator>().Verify(c => c.PublishEvent(It.IsAny<TEvent>()), times); } - protected void VerifyEventNotPublished<TEvent>() where TEvent : class, IEvent + protected void VerifyEventNotPublished<TEvent>() + where TEvent : class, IEvent { Mocker.GetMock<IEventAggregator>().Verify(c => c.PublishEvent(It.IsAny<TEvent>()), Times.Never()); } diff --git a/src/NzbDrone.Test.Dummy/DummyApp.cs b/src/NzbDrone.Test.Dummy/DummyApp.cs index 125c129a2e..7d3482a9e2 100644 --- a/src/NzbDrone.Test.Dummy/DummyApp.cs +++ b/src/NzbDrone.Test.Dummy/DummyApp.cs @@ -7,7 +7,7 @@ public class DummyApp { public const string DUMMY_PROCCESS_NAME = "Radarr.Test.Dummy"; - static void Main(string[] args) + private static void Main(string[] args) { var process = Process.GetCurrentProcess(); diff --git a/src/NzbDrone.Update.Test/InstallUpdateServiceFixture.cs b/src/NzbDrone.Update.Test/InstallUpdateServiceFixture.cs index 6d9a95687d..91e41b6928 100644 --- a/src/NzbDrone.Update.Test/InstallUpdateServiceFixture.cs +++ b/src/NzbDrone.Update.Test/InstallUpdateServiceFixture.cs @@ -13,8 +13,8 @@ namespace NzbDrone.Update.Test [TestFixture] public class InstallUpdateServiceFixture : TestBase<InstallUpdateService> { - private string _targetFolder = @"C:\NzbDrone\".AsOsAgnostic(); private const int _processId = 12; + private string _targetFolder = @"C:\NzbDrone\".AsOsAgnostic(); [SetUp] public void Setup() diff --git a/src/NzbDrone.Update.Test/ProgramFixture.cs b/src/NzbDrone.Update.Test/ProgramFixture.cs index abf8c24b79..78a4b4f63b 100644 --- a/src/NzbDrone.Update.Test/ProgramFixture.cs +++ b/src/NzbDrone.Update.Test/ProgramFixture.cs @@ -11,15 +11,12 @@ namespace NzbDrone.Update.Test [TestFixture] public class ProgramFixture : TestBase<UpdateApp> { - - [Test] public void should_throw_if_null_passed_in() { Assert.Throws<ArgumentOutOfRangeException>(() => Subject.Start(null)); } - [TestCase("d", "")] [TestCase("", "")] [TestCase("0", "")] @@ -34,18 +31,14 @@ public void should_throw_if_first_arg_isnt_an_int(string arg1, string arg2) [Test] public void should_call_update_with_correct_path() { - var ProcessPath = @"C:\Radarr\radarr.exe".AsOsAgnostic(); + var processPath = @"C:\Radarr\radarr.exe".AsOsAgnostic(); Mocker.GetMock<IProcessProvider>().Setup(c => c.GetProcessById(12)) - .Returns(new ProcessInfo() { StartPath = ProcessPath }); - - - Subject.Start(new[] { "12", "", ProcessPath }); + .Returns(new ProcessInfo() { StartPath = processPath }); + Subject.Start(new[] { "12", "", processPath }); Mocker.GetMock<IInstallUpdateService>().Verify(c => c.Start(@"C:\Radarr".AsOsAgnostic(), 12), Times.Once()); } - - } } diff --git a/src/NzbDrone.Update/UpdateApp.cs b/src/NzbDrone.Update/UpdateApp.cs index 3e91d49779..0cc7ab8da9 100644 --- a/src/NzbDrone.Update/UpdateApp.cs +++ b/src/NzbDrone.Update/UpdateApp.cs @@ -15,10 +15,10 @@ public class UpdateApp { private readonly IInstallUpdateService _installUpdateService; private readonly IProcessProvider _processProvider; - private static IContainer _container; - private static readonly Logger Logger = NzbDroneLogger.GetLogger(typeof(UpdateApp)); + private static IContainer _container; + public UpdateApp(IInstallUpdateService installUpdateService, IProcessProvider processProvider) { _installUpdateService = installUpdateService; @@ -114,7 +114,6 @@ private string GetInstallationDirectory(UpdateStartupContext startupContext) return exeFileInfo.DirectoryName; } - else { Logger.Debug("Using executing application: {0}", startupContext.ExecutingApplication); diff --git a/src/NzbDrone.Update/UpdateContainerBuilder.cs b/src/NzbDrone.Update/UpdateContainerBuilder.cs index ee5e086d22..942914d1a6 100644 --- a/src/NzbDrone.Update/UpdateContainerBuilder.cs +++ b/src/NzbDrone.Update/UpdateContainerBuilder.cs @@ -9,7 +9,6 @@ public class UpdateContainerBuilder : ContainerBuilderBase private UpdateContainerBuilder(IStartupContext startupContext, List<string> assemblies) : base(startupContext, assemblies) { - } public static IContainer Build(IStartupContext startupContext) diff --git a/src/NzbDrone.Update/UpdateEngine/InstallUpdateService.cs b/src/NzbDrone.Update/UpdateEngine/InstallUpdateService.cs index 5dc752e303..a7f1c1b973 100644 --- a/src/NzbDrone.Update/UpdateEngine/InstallUpdateService.cs +++ b/src/NzbDrone.Update/UpdateEngine/InstallUpdateService.cs @@ -57,10 +57,14 @@ private void Verify(string targetFolder, int processId) _logger.Info("Verifying requirements before update..."); if (string.IsNullOrWhiteSpace(targetFolder)) + { throw new ArgumentException("Target folder can not be null or empty"); + } if (!_diskProvider.FolderExists(targetFolder)) + { throw new DirectoryNotFoundException("Target folder doesn't exist " + targetFolder); + } if (processId < 1) { @@ -74,7 +78,9 @@ private void Verify(string targetFolder, int processId) _logger.Info("Verifying Update Folder"); if (!_diskProvider.FolderExists(_appFolderInfo.GetUpdatePackageFolder())) + { throw new DirectoryNotFoundException("Update folder doesn't exist " + _appFolderInfo.GetUpdatePackageFolder()); + } } public void Start(string installationFolder, int processId) @@ -157,7 +163,6 @@ public void Start(string installationFolder, int processId) } } } - } } } diff --git a/src/NzbDrone.Update/UpdateEngine/StartNzbDrone.cs b/src/NzbDrone.Update/UpdateEngine/StartNzbDrone.cs index 341fd25270..c5968b2028 100644 --- a/src/NzbDrone.Update/UpdateEngine/StartNzbDrone.cs +++ b/src/NzbDrone.Update/UpdateEngine/StartNzbDrone.cs @@ -37,7 +37,6 @@ public void Start(AppType appType, string installationFolder) try { StartService(); - } catch (InvalidOperationException e) { diff --git a/src/NzbDrone.Windows.Test/DiskProviderTests/DiskProviderFixture.cs b/src/NzbDrone.Windows.Test/DiskProviderTests/DiskProviderFixture.cs index ac1b5bb6fc..0f8d96c0a0 100644 --- a/src/NzbDrone.Windows.Test/DiskProviderTests/DiskProviderFixture.cs +++ b/src/NzbDrone.Windows.Test/DiskProviderTests/DiskProviderFixture.cs @@ -19,7 +19,6 @@ public DiskProviderFixture() protected override void SetWritePermissions(string path, bool writable) { // Remove Write permissions, we're owner and have Delete permissions, so we can still clean it up. - var owner = WindowsIdentity.GetCurrent().Owner; var accessControlType = writable ? AccessControlType.Allow : AccessControlType.Deny; diff --git a/src/NzbDrone.Windows/Disk/DiskProvider.cs b/src/NzbDrone.Windows/Disk/DiskProvider.cs index ba3d889a44..10d1fe1161 100644 --- a/src/NzbDrone.Windows/Disk/DiskProvider.cs +++ b/src/NzbDrone.Windows/Disk/DiskProvider.cs @@ -14,14 +14,14 @@ public class DiskProvider : DiskProviderBase [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] - static extern bool GetDiskFreeSpaceEx(string lpDirectoryName, + private static extern bool GetDiskFreeSpaceEx(string lpDirectoryName, out ulong lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes, out ulong lpTotalNumberOfFreeBytes); [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] - static extern bool CreateHardLink(string lpFileName, string lpExistingFileName, IntPtr lpSecurityAttributes); + private static extern bool CreateHardLink(string lpFileName, string lpExistingFileName, IntPtr lpSecurityAttributes); public override long? GetAvailableSpace(string path) { @@ -30,7 +30,9 @@ static extern bool GetDiskFreeSpaceEx(string lpDirectoryName, var root = GetPathRoot(path); if (!FolderExists(root)) + { throw new DirectoryNotFoundException(root); + } return DriveFreeSpaceEx(root); } @@ -47,7 +49,6 @@ public override void InheritFolderPermissions(string filename) public override void SetPermissions(string path, string mask, string user, string group) { - } public override long? GetTotalSize(string path) @@ -57,7 +58,9 @@ public override void SetPermissions(string path, string mask, string user, strin var root = GetPathRoot(path); if (!FolderExists(root)) + { throw new DirectoryNotFoundException(root); + } return DriveTotalSizeEx(root); } @@ -104,7 +107,6 @@ private static long DriveTotalSizeEx(string folderName) return 0; } - public override bool TryCreateHardLink(string source, string destination) { try diff --git a/src/NzbDrone/Properties/Resources.Designer.cs b/src/NzbDrone/Properties/Resources.Designer.cs index 062c5f8d97..f632431734 100644 --- a/src/NzbDrone/Properties/Resources.Designer.cs +++ b/src/NzbDrone/Properties/Resources.Designer.cs @@ -23,23 +23,28 @@ namespace NzbDrone.Properties [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources { + internal class Resources + { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() { + internal Resources() + { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if (object.ReferenceEquals(resourceMan, null)) + { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("NzbDrone.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } @@ -52,11 +57,14 @@ internal Resources() { /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { + internal static global::System.Globalization.CultureInfo Culture + { + get + { return resourceCulture; } - set { + set + { resourceCulture = value; } } @@ -64,8 +72,10 @@ internal Resources() { /// <summary> /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// </summary> - internal static System.Drawing.Icon Radarr { - get { + internal static System.Drawing.Icon Radarr + { + get + { object obj = ResourceManager.GetObject("Radarr", resourceCulture); return ((System.Drawing.Icon)(obj)); } diff --git a/src/NzbDrone/SysTray/SysTrayApp.cs b/src/NzbDrone/SysTray/SysTrayApp.cs index 3c27e993b0..157ce4e47b 100644 --- a/src/NzbDrone/SysTray/SysTrayApp.cs +++ b/src/NzbDrone/SysTray/SysTrayApp.cs @@ -76,9 +76,8 @@ protected override void Dispose(bool isDisposing) if (InvokeRequired) { - base.Invoke(new MethodInvoker(() => Dispose(isDisposing))); + Invoke(new MethodInvoker(() => Dispose(isDisposing))); } - else { base.Dispose(isDisposing); @@ -99,7 +98,6 @@ private void LaunchBrowser(object sender, EventArgs e) } catch (Exception) { - } } @@ -129,7 +127,6 @@ private void DisposeTrayIcon() } catch (Exception) { - } } } diff --git a/src/NzbDrone/WindowsApp.cs b/src/NzbDrone/WindowsApp.cs index 8cd0fdc6f0..8033102409 100644 --- a/src/NzbDrone/WindowsApp.cs +++ b/src/NzbDrone/WindowsApp.cs @@ -3,8 +3,8 @@ using NLog; using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Common.Instrumentation; -using Radarr.Host; using NzbDrone.SysTray; +using Radarr.Host; namespace NzbDrone { diff --git a/src/Radarr.Api.V3/Blacklist/BlacklistResource.cs b/src/Radarr.Api.V3/Blacklist/BlacklistResource.cs index eb95ccdc06..9cef0409ed 100644 --- a/src/Radarr.Api.V3/Blacklist/BlacklistResource.cs +++ b/src/Radarr.Api.V3/Blacklist/BlacklistResource.cs @@ -26,7 +26,10 @@ public static class BlacklistResourceMapper { public static BlacklistResource MapToResource(this NzbDrone.Core.Blacklisting.Blacklist model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new BlacklistResource { diff --git a/src/Radarr.Api.V3/Calendar/CalendarFeedModule.cs b/src/Radarr.Api.V3/Calendar/CalendarFeedModule.cs index f32575cef1..516c53830b 100644 --- a/src/Radarr.Api.V3/Calendar/CalendarFeedModule.cs +++ b/src/Radarr.Api.V3/Calendar/CalendarFeedModule.cs @@ -1,4 +1,3 @@ -using Nancy; using System; using System.Collections.Generic; using System.Linq; @@ -6,10 +5,11 @@ using Ical.Net.CalendarComponents; using Ical.Net.DataTypes; using Ical.Net.Serialization; -using NzbDrone.Core.Movies; +using Nancy; using Nancy.Responses; -using NzbDrone.Core.Tags; using NzbDrone.Common.Extensions; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Tags; namespace Radarr.Api.V3.Calendar { @@ -24,7 +24,7 @@ public CalendarFeedModule(IMovieService movieService, ITagService tagService) _movieService = movieService; _tagService = tagService; - Get("/Radarr.ics", options => GetCalendarFeed()); + Get("/Radarr.ics", options => GetCalendarFeed()); } private object GetCalendarFeed() @@ -44,8 +44,15 @@ private object GetCalendarFeed() var queryUnmonitored = Request.Query.Unmonitored; var queryTags = Request.Query.Tags; - if (queryStart.HasValue) start = DateTime.Parse(queryStart.Value); - if (queryEnd.HasValue) end = DateTime.Parse(queryEnd.Value); + if (queryStart.HasValue) + { + start = DateTime.Parse(queryStart.Value); + } + + if (queryEnd.HasValue) + { + end = DateTime.Parse(queryEnd.Value); + } if (queryPastDays.HasValue) { @@ -89,7 +96,6 @@ private object GetCalendarFeed() CreateEvent(calendar, movie, true); CreateEvent(calendar, movie, false); - } var serializer = (IStringSerializer)new SerializerFactory().Build(calendar.GetType(), new SerializationContext()); diff --git a/src/Radarr.Api.V3/Calendar/CalendarModule.cs b/src/Radarr.Api.V3/Calendar/CalendarModule.cs index 72a06fdd0e..2a43afaa2c 100644 --- a/src/Radarr.Api.V3/Calendar/CalendarModule.cs +++ b/src/Radarr.Api.V3/Calendar/CalendarModule.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.Linq; using Nancy; -using Radarr.Api.V3.Movies; using NzbDrone.Core.Movies; using NzbDrone.SignalR; +using Radarr.Api.V3.Movies; using Radarr.Http; namespace Radarr.Api.V3.Calendar @@ -32,9 +32,20 @@ private List<MovieResource> GetCalendar() var queryEnd = Request.Query.End; var queryIncludeUnmonitored = Request.Query.Unmonitored; - if (queryStart.HasValue) start = DateTime.Parse(queryStart.Value); - if (queryEnd.HasValue) end = DateTime.Parse(queryEnd.Value); - if (queryIncludeUnmonitored.HasValue) includeUnmonitored = Convert.ToBoolean(queryIncludeUnmonitored.Value); + if (queryStart.HasValue) + { + start = DateTime.Parse(queryStart.Value); + } + + if (queryEnd.HasValue) + { + end = DateTime.Parse(queryEnd.Value); + } + + if (queryIncludeUnmonitored.HasValue) + { + includeUnmonitored = Convert.ToBoolean(queryIncludeUnmonitored.Value); + } var resources = _moviesService.GetMoviesBetweenDates(start, end, includeUnmonitored).Select(MapToResource); @@ -43,7 +54,10 @@ private List<MovieResource> GetCalendar() protected MovieResource MapToResource(Movie movie) { - if (movie == null) return null; + if (movie == null) + { + return null; + } var resource = movie.ToResource(); diff --git a/src/Radarr.Api.V3/Commands/CommandModule.cs b/src/Radarr.Api.V3/Commands/CommandModule.cs index 607f1b9adc..7ffdc966b7 100644 --- a/src/Radarr.Api.V3/Commands/CommandModule.cs +++ b/src/Radarr.Api.V3/Commands/CommandModule.cs @@ -48,7 +48,7 @@ private CommandResource GetCommand(int id) private int StartCommand(CommandResource commandResource) { var commandType = - _serviceFactory.GetImplementations(typeof (Command)) + _serviceFactory.GetImplementations(typeof(Command)) .Single(c => c.Name.Replace("Command", "") .Equals(commandResource.Name, StringComparison.InvariantCultureIgnoreCase)); diff --git a/src/Radarr.Api.V3/Commands/CommandResource.cs b/src/Radarr.Api.V3/Commands/CommandResource.cs index 4474baa6f5..c3d22c0a4d 100644 --- a/src/Radarr.Api.V3/Commands/CommandResource.cs +++ b/src/Radarr.Api.V3/Commands/CommandResource.cs @@ -30,37 +30,51 @@ public DateTime? StateChangeTime { get { - - if (Started.HasValue) return Started.Value; + if (Started.HasValue) + { + return Started.Value; + } return Ended; } - set { } + set + { + } } public bool SendUpdatesToClient { get { - if (Body != null) return Body.SendUpdatesToClient; + if (Body != null) + { + return Body.SendUpdatesToClient; + } return false; } - set { } + set + { + } } public bool UpdateScheduledTask { get { - if (Body != null) return Body.UpdateScheduledTask; + if (Body != null) + { + return Body.UpdateScheduledTask; + } return false; } - set { } + set + { + } } public DateTime? LastExecutionTime { get; set; } @@ -70,7 +84,10 @@ public static class CommandResourceMapper { public static CommandResource ToResource(this CommandModel model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new CommandResource { diff --git a/src/Radarr.Api.V3/Config/DownloadClientConfigModule.cs b/src/Radarr.Api.V3/Config/DownloadClientConfigModule.cs index 7246eeda85..4ee70d0561 100644 --- a/src/Radarr.Api.V3/Config/DownloadClientConfigModule.cs +++ b/src/Radarr.Api.V3/Config/DownloadClientConfigModule.cs @@ -7,7 +7,6 @@ public class DownloadClientConfigModule : RadarrConfigModule<DownloadClientConfi public DownloadClientConfigModule(IConfigService configService) : base(configService) { - } protected override DownloadClientConfigResource ToResource(IConfigService model) diff --git a/src/Radarr.Api.V3/Config/DownloadClientConfigResource.cs b/src/Radarr.Api.V3/Config/DownloadClientConfigResource.cs index 58c7fd9052..ad1ac291f9 100644 --- a/src/Radarr.Api.V3/Config/DownloadClientConfigResource.cs +++ b/src/Radarr.Api.V3/Config/DownloadClientConfigResource.cs @@ -1,5 +1,5 @@ -using Radarr.Http.REST; using NzbDrone.Core.Configuration; +using Radarr.Http.REST; namespace Radarr.Api.V3.Config { diff --git a/src/Radarr.Api.V3/Config/HostConfigModule.cs b/src/Radarr.Api.V3/Config/HostConfigModule.cs index 3cae0845ca..1bd43d31c1 100644 --- a/src/Radarr.Api.V3/Config/HostConfigModule.cs +++ b/src/Radarr.Api.V3/Config/HostConfigModule.cs @@ -51,7 +51,6 @@ public HostConfigModule(IConfigFileProvider configFileProvider, IConfigService c SharedValidator.RuleFor(c => c.BackupFolder).IsValidPath().When(c => Path.IsPathRooted(c.BackupFolder)); SharedValidator.RuleFor(c => c.BackupInterval).InclusiveBetween(1, 7); SharedValidator.RuleFor(c => c.BackupRetention).InclusiveBetween(1, 90); - } private HostConfigResource GetHostConfig() diff --git a/src/Radarr.Api.V3/Config/HostConfigResource.cs b/src/Radarr.Api.V3/Config/HostConfigResource.cs index a0b651e171..0dbe541bbc 100644 --- a/src/Radarr.Api.V3/Config/HostConfigResource.cs +++ b/src/Radarr.Api.V3/Config/HostConfigResource.cs @@ -1,9 +1,9 @@ -using Radarr.Http.REST; +using NzbDrone.Common.Http.Proxy; using NzbDrone.Core.Authentication; using NzbDrone.Core.Configuration; using NzbDrone.Core.Security; using NzbDrone.Core.Update; -using NzbDrone.Common.Http.Proxy; +using Radarr.Http.REST; namespace Radarr.Api.V3.Config { @@ -56,6 +56,7 @@ public static HostConfigResource ToResource(this IConfigFileProvider model, ICon LaunchBrowser = model.LaunchBrowser, AuthenticationMethod = model.AuthenticationMethod, AnalyticsEnabled = model.AnalyticsEnabled, + //Username //Password LogLevel = model.LogLevel, diff --git a/src/Radarr.Api.V3/Config/IndexerConfigModule.cs b/src/Radarr.Api.V3/Config/IndexerConfigModule.cs index 93b8dcace1..7ad2fe8d90 100644 --- a/src/Radarr.Api.V3/Config/IndexerConfigModule.cs +++ b/src/Radarr.Api.V3/Config/IndexerConfigModule.cs @@ -1,12 +1,11 @@ using FluentValidation; -using Radarr.Http.Validation; using NzbDrone.Core.Configuration; +using Radarr.Http.Validation; namespace Radarr.Api.V3.Config { public class IndexerConfigModule : RadarrConfigModule<IndexerConfigResource> { - public IndexerConfigModule(IConfigService configService) : base(configService) { diff --git a/src/Radarr.Api.V3/Config/IndexerConfigResource.cs b/src/Radarr.Api.V3/Config/IndexerConfigResource.cs index 7092c29718..3e9910460c 100644 --- a/src/Radarr.Api.V3/Config/IndexerConfigResource.cs +++ b/src/Radarr.Api.V3/Config/IndexerConfigResource.cs @@ -1,6 +1,6 @@ -using Radarr.Http.REST; using NzbDrone.Core.Configuration; using NzbDrone.Core.Parser; +using Radarr.Http.REST; namespace Radarr.Api.V3.Config { diff --git a/src/Radarr.Api.V3/Config/MediaManagementConfigResource.cs b/src/Radarr.Api.V3/Config/MediaManagementConfigResource.cs index ce5dcfd8f1..5880b889bf 100644 --- a/src/Radarr.Api.V3/Config/MediaManagementConfigResource.cs +++ b/src/Radarr.Api.V3/Config/MediaManagementConfigResource.cs @@ -1,6 +1,6 @@ -using Radarr.Http.REST; using NzbDrone.Core.Configuration; using NzbDrone.Core.MediaFiles; +using Radarr.Http.REST; namespace Radarr.Api.V3.Config { diff --git a/src/Radarr.Api.V3/Config/NamingConfigModule.cs b/src/Radarr.Api.V3/Config/NamingConfigModule.cs index 306db70042..785ce954a1 100644 --- a/src/Radarr.Api.V3/Config/NamingConfigModule.cs +++ b/src/Radarr.Api.V3/Config/NamingConfigModule.cs @@ -2,9 +2,9 @@ using System.Linq; using FluentValidation; using FluentValidation.Results; +using Nancy.ModelBinding; using NzbDrone.Common.Extensions; using NzbDrone.Core.Organizer; -using Nancy.ModelBinding; using Radarr.Http; namespace Radarr.Api.V3.Config @@ -30,7 +30,7 @@ public NamingConfigModule(INamingConfigService namingConfigService, GetResourceById = GetNamingConfig; UpdateResource = UpdateNamingConfig; - Get("/examples", x => GetExamples(this.Bind<NamingConfigResource>())); + Get("/examples", x => GetExamples(this.Bind<NamingConfigResource>())); SharedValidator.RuleFor(c => c.StandardMovieFormat).ValidMovieFormat(); SharedValidator.RuleFor(c => c.MovieFolderFormat).ValidMovieFolderFormat(); diff --git a/src/Radarr.Api.V3/Config/NamingConfigResource.cs b/src/Radarr.Api.V3/Config/NamingConfigResource.cs index 336a536041..be04537102 100644 --- a/src/Radarr.Api.V3/Config/NamingConfigResource.cs +++ b/src/Radarr.Api.V3/Config/NamingConfigResource.cs @@ -1,5 +1,5 @@ -using Radarr.Http.REST; using NzbDrone.Core.Organizer; +using Radarr.Http.REST; namespace Radarr.Api.V3.Config { diff --git a/src/Radarr.Api.V3/Config/NamingExampleResource.cs b/src/Radarr.Api.V3/Config/NamingExampleResource.cs index a871d015e6..dd57df6b7e 100644 --- a/src/Radarr.Api.V3/Config/NamingExampleResource.cs +++ b/src/Radarr.Api.V3/Config/NamingExampleResource.cs @@ -21,6 +21,7 @@ public static NamingConfigResource ToResource(this NamingConfig model) ColonReplacementFormat = model.ColonReplacementFormat, StandardMovieFormat = model.StandardMovieFormat, MovieFolderFormat = model.MovieFolderFormat, + //IncludeQuality //ReplaceSpaces //Separator diff --git a/src/Radarr.Api.V3/Config/NetImportConfigModule.cs b/src/Radarr.Api.V3/Config/NetImportConfigModule.cs index f6c77d1c4e..653e196d11 100644 --- a/src/Radarr.Api.V3/Config/NetImportConfigModule.cs +++ b/src/Radarr.Api.V3/Config/NetImportConfigModule.cs @@ -1,11 +1,10 @@ -using Radarr.Http.Validation; using NzbDrone.Core.Configuration; +using Radarr.Http.Validation; namespace Radarr.Api.V3.Config { public class NetImportConfigModule : RadarrConfigModule<NetImportConfigResource> { - public NetImportConfigModule(IConfigService configService) : base(configService) { diff --git a/src/Radarr.Api.V3/Config/NetImportConfigResource.cs b/src/Radarr.Api.V3/Config/NetImportConfigResource.cs index ad3b7cab72..8b4a2c8030 100644 --- a/src/Radarr.Api.V3/Config/NetImportConfigResource.cs +++ b/src/Radarr.Api.V3/Config/NetImportConfigResource.cs @@ -1,5 +1,5 @@ -using Radarr.Http.REST; using NzbDrone.Core.Configuration; +using Radarr.Http.REST; namespace Radarr.Api.V3.Config { diff --git a/src/Radarr.Api.V3/Config/RadarrConfigModule.cs b/src/Radarr.Api.V3/Config/RadarrConfigModule.cs index 3f37ec9d09..ec21274b04 100644 --- a/src/Radarr.Api.V3/Config/RadarrConfigModule.cs +++ b/src/Radarr.Api.V3/Config/RadarrConfigModule.cs @@ -1,12 +1,13 @@ using System.Linq; using System.Reflection; +using NzbDrone.Core.Configuration; using Radarr.Http; using Radarr.Http.REST; -using NzbDrone.Core.Configuration; namespace Radarr.Api.V3.Config { - public abstract class RadarrConfigModule<TResource> : RadarrRestModule<TResource> where TResource : RestResource, new() + public abstract class RadarrConfigModule<TResource> : RadarrRestModule<TResource> + where TResource : RestResource, new() { private readonly IConfigService _configService; @@ -15,8 +16,8 @@ protected RadarrConfigModule(IConfigService configService) { } - protected RadarrConfigModule(string resource, IConfigService configService) : - base("config/" + resource.Trim('/')) + protected RadarrConfigModule(string resource, IConfigService configService) + : base("config/" + resource.Trim('/')) { _configService = configService; diff --git a/src/Radarr.Api.V3/Config/UiConfigModule.cs b/src/Radarr.Api.V3/Config/UiConfigModule.cs index 5c3953b76d..03308ccf2b 100644 --- a/src/Radarr.Api.V3/Config/UiConfigModule.cs +++ b/src/Radarr.Api.V3/Config/UiConfigModule.cs @@ -7,7 +7,6 @@ public class UiConfigModule : RadarrConfigModule<UiConfigResource> public UiConfigModule(IConfigService configService) : base(configService) { - } protected override UiConfigResource ToResource(IConfigService model) diff --git a/src/Radarr.Api.V3/Config/UiConfigResource.cs b/src/Radarr.Api.V3/Config/UiConfigResource.cs index f9bd8a51df..ed074313cb 100644 --- a/src/Radarr.Api.V3/Config/UiConfigResource.cs +++ b/src/Radarr.Api.V3/Config/UiConfigResource.cs @@ -1,5 +1,5 @@ -using Radarr.Http.REST; using NzbDrone.Core.Configuration; +using Radarr.Http.REST; namespace Radarr.Api.V3.Config { diff --git a/src/Radarr.Api.V3/CustomFilters/CustomFilterResource.cs b/src/Radarr.Api.V3/CustomFilters/CustomFilterResource.cs index 66e6e53b8a..358d6865ed 100644 --- a/src/Radarr.Api.V3/CustomFilters/CustomFilterResource.cs +++ b/src/Radarr.Api.V3/CustomFilters/CustomFilterResource.cs @@ -17,28 +17,34 @@ public static class CustomFilterResourceMapper { public static CustomFilterResource ToResource(this CustomFilter model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new CustomFilterResource - { - Id = model.Id, - Type = model.Type, - Label = model.Label, - Filters = Json.Deserialize<List<dynamic>>(model.Filters) - }; + { + Id = model.Id, + Type = model.Type, + Label = model.Label, + Filters = Json.Deserialize<List<dynamic>>(model.Filters) + }; } public static CustomFilter ToModel(this CustomFilterResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new CustomFilter - { - Id = resource.Id, - Type = resource.Type, - Label = resource.Label, - Filters = Json.ToJson(resource.Filters) - }; + { + Id = resource.Id, + Type = resource.Type, + Label = resource.Label, + Filters = Json.ToJson(resource.Filters) + }; } public static List<CustomFilterResource> ToResource(this IEnumerable<CustomFilter> filters) diff --git a/src/Radarr.Api.V3/DiskSpace/DiskSpaceModule.cs b/src/Radarr.Api.V3/DiskSpace/DiskSpaceModule.cs index 00be647ff5..4b192ff06d 100644 --- a/src/Radarr.Api.V3/DiskSpace/DiskSpaceModule.cs +++ b/src/Radarr.Api.V3/DiskSpace/DiskSpaceModule.cs @@ -9,7 +9,7 @@ public class DiskSpaceModule : RadarrRestModule<DiskSpaceResource> private readonly IDiskSpaceService _diskSpaceService; public DiskSpaceModule(IDiskSpaceService diskSpaceService) - :base("diskspace") + : base("diskspace") { _diskSpaceService = diskSpaceService; GetResourceAll = GetFreeSpace; diff --git a/src/Radarr.Api.V3/DiskSpace/DiskSpaceResource.cs b/src/Radarr.Api.V3/DiskSpace/DiskSpaceResource.cs index e56e571a43..9bc8f5d341 100644 --- a/src/Radarr.Api.V3/DiskSpace/DiskSpaceResource.cs +++ b/src/Radarr.Api.V3/DiskSpace/DiskSpaceResource.cs @@ -14,7 +14,10 @@ public static class DiskSpaceResourceMapper { public static DiskSpaceResource MapToResource(this NzbDrone.Core.DiskSpace.DiskSpace model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new DiskSpaceResource { diff --git a/src/Radarr.Api.V3/DownloadClient/DownloadClientModule.cs b/src/Radarr.Api.V3/DownloadClient/DownloadClientModule.cs index d187e5f3ac..e3633af22e 100644 --- a/src/Radarr.Api.V3/DownloadClient/DownloadClientModule.cs +++ b/src/Radarr.Api.V3/DownloadClient/DownloadClientModule.cs @@ -13,7 +13,11 @@ public DownloadClientModule(IDownloadClientFactory downloadClientFactory) protected override void Validate(DownloadClientDefinition definition, bool includeWarnings) { - if (!definition.Enable) return; + if (!definition.Enable) + { + return; + } + base.Validate(definition, includeWarnings); } } diff --git a/src/Radarr.Api.V3/DownloadClient/DownloadClientResource.cs b/src/Radarr.Api.V3/DownloadClient/DownloadClientResource.cs index 6282f8a3af..f3d846ab15 100644 --- a/src/Radarr.Api.V3/DownloadClient/DownloadClientResource.cs +++ b/src/Radarr.Api.V3/DownloadClient/DownloadClientResource.cs @@ -14,7 +14,10 @@ public class DownloadClientResourceMapper : ProviderResourceMapper<DownloadClien { public override DownloadClientResource ToResource(DownloadClientDefinition definition) { - if (definition == null) return null; + if (definition == null) + { + return null; + } var resource = base.ToResource(definition); @@ -27,7 +30,10 @@ public override DownloadClientResource ToResource(DownloadClientDefinition defin public override DownloadClientDefinition ToModel(DownloadClientResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } var definition = base.ToModel(resource); diff --git a/src/Radarr.Api.V3/FileSystem/FileSystemModule.cs b/src/Radarr.Api.V3/FileSystem/FileSystemModule.cs index 939dccaeae..7331e0674e 100644 --- a/src/Radarr.Api.V3/FileSystem/FileSystemModule.cs +++ b/src/Radarr.Api.V3/FileSystem/FileSystemModule.cs @@ -22,9 +22,9 @@ public FileSystemModule(IFileSystemLookupService fileSystemLookupService, _fileSystemLookupService = fileSystemLookupService; _diskProvider = diskProvider; _diskScanService = diskScanService; - Get("/", x => GetContents()); - Get("/type", x => GetEntityType()); - Get("/mediafiles", x => GetMediaFiles()); + Get("/", x => GetContents()); + Get("/type", x => GetEntityType()); + Get("/mediafiles", x => GetMediaFiles()); } private object GetContents() @@ -60,7 +60,8 @@ private object GetMediaFiles() return new string[0]; } - return _diskScanService.GetVideoFiles(path).Select(f => new { + return _diskScanService.GetVideoFiles(path).Select(f => new + { Path = f, RelativePath = path.GetRelativePath(f), Name = Path.GetFileName(f) diff --git a/src/Radarr.Api.V3/Health/HealthResource.cs b/src/Radarr.Api.V3/Health/HealthResource.cs index 090d30cf36..ab5f8fe0a7 100644 --- a/src/Radarr.Api.V3/Health/HealthResource.cs +++ b/src/Radarr.Api.V3/Health/HealthResource.cs @@ -18,7 +18,10 @@ public static class HealthResourceMapper { public static HealthResource ToResource(this HealthCheck model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new HealthResource { diff --git a/src/Radarr.Api.V3/History/HistoryModule.cs b/src/Radarr.Api.V3/History/HistoryModule.cs index 7feb64cd11..8c1f57a9fa 100644 --- a/src/Radarr.Api.V3/History/HistoryModule.cs +++ b/src/Radarr.Api.V3/History/HistoryModule.cs @@ -28,9 +28,9 @@ public HistoryModule(IHistoryService historyService, _failedDownloadService = failedDownloadService; GetResourcePaged = GetHistory; - Get("/since", x => GetHistorySince()); - Get("/movie", x => GetMovieHistory()); - Post("/failed", x => MarkAsFailed()); + Get("/since", x => GetHistorySince()); + Get("/movie", x => GetMovieHistory()); + Post("/failed", x => MarkAsFailed()); } protected HistoryResource MapToResource(NzbDrone.Core.History.History model, bool includeMovie) diff --git a/src/Radarr.Api.V3/History/HistoryResource.cs b/src/Radarr.Api.V3/History/HistoryResource.cs index ec3d4c2612..a235e35542 100644 --- a/src/Radarr.Api.V3/History/HistoryResource.cs +++ b/src/Radarr.Api.V3/History/HistoryResource.cs @@ -29,7 +29,10 @@ public static class HistoryResourceMapper { public static HistoryResource ToResource(this NzbDrone.Core.History.History model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new HistoryResource { @@ -39,6 +42,7 @@ public static HistoryResource ToResource(this NzbDrone.Core.History.History mode SourceTitle = model.SourceTitle, Languages = model.Languages, Quality = model.Quality, + //QualityCutoffNotMet Date = model.Date, DownloadId = model.DownloadId, diff --git a/src/Radarr.Api.V3/Indexers/IndexerModule.cs b/src/Radarr.Api.V3/Indexers/IndexerModule.cs index 5252de7e35..51ae28d306 100644 --- a/src/Radarr.Api.V3/Indexers/IndexerModule.cs +++ b/src/Radarr.Api.V3/Indexers/IndexerModule.cs @@ -13,7 +13,11 @@ public IndexerModule(IndexerFactory indexerFactory) protected override void Validate(IndexerDefinition definition, bool includeWarnings) { - if (!definition.Enable) return; + if (!definition.Enable) + { + return; + } + base.Validate(definition, includeWarnings); } } diff --git a/src/Radarr.Api.V3/Indexers/IndexerResource.cs b/src/Radarr.Api.V3/Indexers/IndexerResource.cs index f53dbcfdc7..ae4e9413c8 100644 --- a/src/Radarr.Api.V3/Indexers/IndexerResource.cs +++ b/src/Radarr.Api.V3/Indexers/IndexerResource.cs @@ -16,7 +16,10 @@ public class IndexerResourceMapper : ProviderResourceMapper<IndexerResource, Ind { public override IndexerResource ToResource(IndexerDefinition definition) { - if (definition == null) return null; + if (definition == null) + { + return null; + } var resource = base.ToResource(definition); @@ -32,7 +35,10 @@ public override IndexerResource ToResource(IndexerDefinition definition) public override IndexerDefinition ToModel(IndexerResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } var definition = base.ToModel(resource); diff --git a/src/Radarr.Api.V3/Indexers/ReleaseModule.cs b/src/Radarr.Api.V3/Indexers/ReleaseModule.cs index c3bdfbc1dd..67da1ae78e 100644 --- a/src/Radarr.Api.V3/Indexers/ReleaseModule.cs +++ b/src/Radarr.Api.V3/Indexers/ReleaseModule.cs @@ -45,7 +45,7 @@ public ReleaseModule(IFetchAndParseRss rssFetcherAndParser, PostValidator.RuleFor(s => s.Guid).NotEmpty(); GetResourceAll = GetReleases; - Post("/", x => DownloadRelease(ReadResourceFromRequest())); + Post("/", x => DownloadRelease(ReadResourceFromRequest())); _remoteMovieCache = cacheManager.GetCache<RemoteMovie>(GetType(), "remoteMovies"); } diff --git a/src/Radarr.Api.V3/Indexers/ReleasePushModule.cs b/src/Radarr.Api.V3/Indexers/ReleasePushModule.cs index 7a4e315d18..109e77b8be 100644 --- a/src/Radarr.Api.V3/Indexers/ReleasePushModule.cs +++ b/src/Radarr.Api.V3/Indexers/ReleasePushModule.cs @@ -12,7 +12,7 @@ namespace Radarr.Api.V3.Indexers { - class ReleasePushModule : ReleaseModuleBase + public class ReleasePushModule : ReleaseModuleBase { private readonly IMakeDownloadDecision _downloadDecisionMaker; private readonly IProcessDownloadDecisions _downloadDecisionProcessor; @@ -34,7 +34,7 @@ public ReleasePushModule(IMakeDownloadDecision downloadDecisionMaker, PostValidator.RuleFor(s => s.Protocol).NotEmpty(); PostValidator.RuleFor(s => s.PublishDate).NotEmpty(); - Post("/push", x => ProcessRelease(ReadResourceFromRequest())); + Post("/push", x => ProcessRelease(ReadResourceFromRequest())); } private object ProcessRelease(ReleaseResource release) @@ -54,10 +54,10 @@ private object ProcessRelease(ReleaseResource release) if (firstDecision?.RemoteMovie.ParsedMovieInfo == null) { - throw new ValidationException(new List<ValidationFailure>{ new ValidationFailure("Title", "Unable to parse", release.Title) }); + throw new ValidationException(new List<ValidationFailure> { new ValidationFailure("Title", "Unable to parse", release.Title) }); } - return MapDecisions(new [] { firstDecision }); + return MapDecisions(new[] { firstDecision }); } private void ResolveIndexer(ReleaseInfo release) diff --git a/src/Radarr.Api.V3/Indexers/ReleaseResource.cs b/src/Radarr.Api.V3/Indexers/ReleaseResource.cs index 3f2afc65bd..514974ecbb 100644 --- a/src/Radarr.Api.V3/Indexers/ReleaseResource.cs +++ b/src/Radarr.Api.V3/Indexers/ReleaseResource.cs @@ -53,10 +53,8 @@ public class ReleaseResource : RestResource public bool Special { get; set; } // Sent when queuing an unknown release - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? MovieId { get; set; } - } public static class ReleaseResourceMapper @@ -73,6 +71,7 @@ public static ReleaseResource ToResource(this DownloadDecision model) { Guid = releaseInfo.Guid, Quality = parsedMovieInfo.Quality, + //QualityWeight Age = releaseInfo.Age, AgeHours = releaseInfo.AgeHours, @@ -95,16 +94,14 @@ public static ReleaseResource ToResource(this DownloadDecision model) DownloadUrl = releaseInfo.DownloadUrl, InfoUrl = releaseInfo.InfoUrl, DownloadAllowed = remoteMovie.DownloadAllowed, + //ReleaseWeight - - MagnetUrl = torrentInfo.MagnetUrl, InfoHash = torrentInfo.InfoHash, Seeders = torrentInfo.Seeders, Leechers = (torrentInfo.Peers.HasValue && torrentInfo.Seeders.HasValue) ? (torrentInfo.Peers.Value - torrentInfo.Seeders.Value) : (int?)null, Protocol = releaseInfo.DownloadProtocol }; - } public static ReleaseInfo ToModel(this ReleaseResource resource) diff --git a/src/Radarr.Api.V3/Logs/LogFileModule.cs b/src/Radarr.Api.V3/Logs/LogFileModule.cs index e8a0c2ff99..43c6708890 100644 --- a/src/Radarr.Api.V3/Logs/LogFileModule.cs +++ b/src/Radarr.Api.V3/Logs/LogFileModule.cs @@ -38,6 +38,5 @@ protected override string DownloadUrlRoot return "logfile"; } } - } } diff --git a/src/Radarr.Api.V3/Logs/LogFileModuleBase.cs b/src/Radarr.Api.V3/Logs/LogFileModuleBase.cs index fbf72387a0..a970f672a4 100644 --- a/src/Radarr.Api.V3/Logs/LogFileModuleBase.cs +++ b/src/Radarr.Api.V3/Logs/LogFileModuleBase.cs @@ -26,7 +26,7 @@ public LogFileModuleBase(IDiskProvider diskProvider, _configFileProvider = configFileProvider; GetResourceAll = GetLogFilesResponse; - Get(LOGFILE_ROUTE, options => GetLogFileResponse(options.filename)); + Get(LOGFILE_ROUTE, options => GetLogFileResponse(options.filename)); } private List<LogFileResource> GetLogFilesResponse() @@ -60,7 +60,9 @@ private object GetLogFileResponse(string filename) var filePath = GetLogFilePath(filename); if (!_diskProvider.FileExists(filePath)) + { return new NotFoundResponse(); + } var data = _diskProvider.ReadAllText(filePath); diff --git a/src/Radarr.Api.V3/Logs/LogResource.cs b/src/Radarr.Api.V3/Logs/LogResource.cs index 42721c2e35..51e682912f 100644 --- a/src/Radarr.Api.V3/Logs/LogResource.cs +++ b/src/Radarr.Api.V3/Logs/LogResource.cs @@ -19,7 +19,10 @@ public static class LogResourceMapper { public static LogResource ToResource(this Log model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new LogResource { diff --git a/src/Radarr.Api.V3/Logs/UpdateLogFileModule.cs b/src/Radarr.Api.V3/Logs/UpdateLogFileModule.cs index 5301f153df..5e3924bd1f 100644 --- a/src/Radarr.Api.V3/Logs/UpdateLogFileModule.cs +++ b/src/Radarr.Api.V3/Logs/UpdateLogFileModule.cs @@ -25,7 +25,10 @@ public UpdateLogFileModule(IAppFolderInfo appFolderInfo, protected override IEnumerable<string> GetLogFiles() { - if (!_diskProvider.FolderExists(_appFolderInfo.GetUpdateLogFolder())) return Enumerable.Empty<string>(); + if (!_diskProvider.FolderExists(_appFolderInfo.GetUpdateLogFolder())) + { + return Enumerable.Empty<string>(); + } return _diskProvider.GetFiles(_appFolderInfo.GetUpdateLogFolder(), SearchOption.TopDirectoryOnly) .Where(f => Regex.IsMatch(Path.GetFileName(f), LOGFILE_ROUTE.TrimStart('/'), RegexOptions.IgnoreCase)) diff --git a/src/Radarr.Api.V3/ManualImport/ManualImportResource.cs b/src/Radarr.Api.V3/ManualImport/ManualImportResource.cs index bed3c6fd63..5919596cc0 100644 --- a/src/Radarr.Api.V3/ManualImport/ManualImportResource.cs +++ b/src/Radarr.Api.V3/ManualImport/ManualImportResource.cs @@ -29,19 +29,24 @@ public static class ManualImportResourceMapper { public static ManualImportResource ToResource(this ManualImportItem model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ManualImportResource { Id = HashConverter.GetHashInt31(model.Path), Path = model.Path, RelativePath = model.RelativePath, + // FolderName = model.FolderName, Name = model.Name, Size = model.Size, Movie = model.Movie.ToResource(), Quality = model.Quality, Languages = model.Languages, + //QualityWeight DownloadId = model.DownloadId, Rejections = model.Rejections diff --git a/src/Radarr.Api.V3/Metadata/MetadataModule.cs b/src/Radarr.Api.V3/Metadata/MetadataModule.cs index 252633309e..cde0fed2a7 100644 --- a/src/Radarr.Api.V3/Metadata/MetadataModule.cs +++ b/src/Radarr.Api.V3/Metadata/MetadataModule.cs @@ -13,7 +13,11 @@ public MetadataModule(IMetadataFactory metadataFactory) protected override void Validate(MetadataDefinition definition, bool includeWarnings) { - if (!definition.Enable) return; + if (!definition.Enable) + { + return; + } + base.Validate(definition, includeWarnings); } } diff --git a/src/Radarr.Api.V3/Metadata/MetadataResource.cs b/src/Radarr.Api.V3/Metadata/MetadataResource.cs index 3dcf83e600..72e31307db 100644 --- a/src/Radarr.Api.V3/Metadata/MetadataResource.cs +++ b/src/Radarr.Api.V3/Metadata/MetadataResource.cs @@ -11,7 +11,10 @@ public class MetadataResourceMapper : ProviderResourceMapper<MetadataResource, M { public override MetadataResource ToResource(MetadataDefinition definition) { - if (definition == null) return null; + if (definition == null) + { + return null; + } var resource = base.ToResource(definition); @@ -22,7 +25,10 @@ public override MetadataResource ToResource(MetadataDefinition definition) public override MetadataDefinition ToModel(MetadataResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } var definition = base.ToModel(resource); diff --git a/src/Radarr.Api.V3/MovieFiles/MediaInfoResource.cs b/src/Radarr.Api.V3/MovieFiles/MediaInfoResource.cs index 4c455d49cf..3a9e2b1113 100644 --- a/src/Radarr.Api.V3/MovieFiles/MediaInfoResource.cs +++ b/src/Radarr.Api.V3/MovieFiles/MediaInfoResource.cs @@ -32,25 +32,24 @@ public static MediaInfoResource ToResource(this MediaInfoModel model, string sce } return new MediaInfoResource - { - AudioAdditionalFeatures = model.AudioAdditionalFeatures, - AudioBitrate = model.AudioBitrate, - AudioChannels = MediaInfoFormatter.FormatAudioChannels(model), - AudioLanguages = model.AudioLanguages, - AudioStreamCount = model.AudioStreamCount, - AudioCodec = MediaInfoFormatter.FormatAudioCodec(model, sceneName), - VideoBitDepth = model.VideoBitDepth, - VideoBitrate = model.VideoBitrate, - VideoCodec = MediaInfoFormatter.FormatVideoCodec(model, sceneName), - VideoFps = model.VideoFps, - Resolution = $"{model.Width}x{model.Height}", - RunTime = FormatRuntime(model.RunTime), - ScanType = model.ScanType, - Subtitles = model.Subtitles - }; + { + AudioAdditionalFeatures = model.AudioAdditionalFeatures, + AudioBitrate = model.AudioBitrate, + AudioChannels = MediaInfoFormatter.FormatAudioChannels(model), + AudioLanguages = model.AudioLanguages, + AudioStreamCount = model.AudioStreamCount, + AudioCodec = MediaInfoFormatter.FormatAudioCodec(model, sceneName), + VideoBitDepth = model.VideoBitDepth, + VideoBitrate = model.VideoBitrate, + VideoCodec = MediaInfoFormatter.FormatVideoCodec(model, sceneName), + VideoFps = model.VideoFps, + Resolution = $"{model.Width}x{model.Height}", + RunTime = FormatRuntime(model.RunTime), + ScanType = model.ScanType, + Subtitles = model.Subtitles + }; } - private static string FormatRuntime(TimeSpan runTime) { var formattedRuntime = ""; diff --git a/src/Radarr.Api.V3/MovieFiles/MovieFileModule.cs b/src/Radarr.Api.V3/MovieFiles/MovieFileModule.cs index dece4d30d1..771f1944c1 100644 --- a/src/Radarr.Api.V3/MovieFiles/MovieFileModule.cs +++ b/src/Radarr.Api.V3/MovieFiles/MovieFileModule.cs @@ -46,8 +46,8 @@ public MovieFileModule(IBroadcastSignalRMessage signalRBroadcaster, UpdateResource = SetMovieFile; DeleteResource = DeleteMovieFile; - Put("/editor", movieFiles => SetMovieFile()); - Delete("/bulk", movieFiles => DeleteMovieFiles()); + Put("/editor", movieFiles => SetMovieFile()); + Delete("/bulk", movieFiles => DeleteMovieFiles()); } private MovieFileResource GetMovieFile(int id) @@ -75,7 +75,6 @@ private List<MovieFileResource> GetMovieFiles() return _mediaFileService.GetFilesByMovie(movieId).ConvertAll(f => f.ToResource(movie, _qualityUpgradableSpecification)); } - else { string movieFileIdsValue = movieFileIdsQuery.Value.ToString(); @@ -88,7 +87,7 @@ private List<MovieFileResource> GetMovieFiles() return movieFiles.GroupBy(e => e.MovieId) .SelectMany(f => f.ToList() - .ConvertAll( e => e.ToResource(_movieService.GetMovie(f.Key), _qualityUpgradableSpecification))) + .ConvertAll(e => e.ToResource(_movieService.GetMovie(f.Key), _qualityUpgradableSpecification))) .ToList(); } } @@ -108,24 +107,23 @@ private object SetMovieFile() foreach (var movieFile in movieFiles) { - if (resource.Quality != null) { movieFile.Quality = resource.Quality; } + if (resource.Languages != null) { movieFile.Languages = resource.Languages; } - } _mediaFileService.Update(movieFiles); var movie = _movieService.GetMovie(movieFiles.First().MovieId); - return ResponseWithCode(movieFiles.ConvertAll(f => f.ToResource(movie, _qualityUpgradableSpecification)) - , HttpStatusCode.Accepted); + return ResponseWithCode(movieFiles.ConvertAll(f => f.ToResource(movie, _qualityUpgradableSpecification)), + HttpStatusCode.Accepted); } private void DeleteMovieFile(int id) @@ -137,6 +135,7 @@ private void DeleteMovieFile(int id) _logger.Info("Deleting movie file: {0}", fullPath); _recycleBinProvider.DeleteFile(fullPath); _mediaFileService.Delete(movieFile, DeleteMediaFileReason.Manual); + // TODO: Pull MediaFileDeletionService from Sonarr //_mediaFileDeletionService.Delete(series, episodeFile); } @@ -153,6 +152,7 @@ private object DeleteMovieFiles() _logger.Info("Deleting movie file: {0}", fullPath); _recycleBinProvider.DeleteFile(fullPath); _mediaFileService.Delete(movieFile, DeleteMediaFileReason.Manual); + // TODO: Pull MediaFileDeletionService from Sonarr //_mediaFileDeletionService.DeleteEpisodeFile(movie, movieFile); } diff --git a/src/Radarr.Api.V3/MovieFiles/MovieFileResource.cs b/src/Radarr.Api.V3/MovieFiles/MovieFileResource.cs index 2f266671a0..c6339f464f 100644 --- a/src/Radarr.Api.V3/MovieFiles/MovieFileResource.cs +++ b/src/Radarr.Api.V3/MovieFiles/MovieFileResource.cs @@ -27,7 +27,10 @@ public static class MovieFileResourceMapper { private static MovieFileResource ToResource(this MovieFile model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new MovieFileResource { @@ -35,6 +38,7 @@ private static MovieFileResource ToResource(this MovieFile model) MovieId = model.MovieId, RelativePath = model.RelativePath, + //Path Size = model.Size, DateAdded = model.DateAdded, @@ -42,14 +46,17 @@ private static MovieFileResource ToResource(this MovieFile model) Quality = model.Quality, Languages = model.Languages, MediaInfo = model.MediaInfo.ToResource(model.SceneName), + //QualityCutoffNotMet }; - } public static MovieFileResource ToResource(this MovieFile model, NzbDrone.Core.Movies.Movie movie) { - if (model == null) return null; + if (model == null) + { + return null; + } return new MovieFileResource { @@ -64,13 +71,17 @@ public static MovieFileResource ToResource(this MovieFile model, NzbDrone.Core.M Quality = model.Quality, Languages = model.Languages, MediaInfo = model.MediaInfo.ToResource(model.SceneName), + // QualityCutoffNotMet = upgradableSpecification.CutoffNotMet(movie.Profile.Value, model.Quality) }; } public static MovieFileResource ToResource(this MovieFile model, NzbDrone.Core.Movies.Movie movie, IUpgradableSpecification upgradableSpecification) { - if (model == null) return null; + if (model == null) + { + return null; + } return new MovieFileResource { diff --git a/src/Radarr.Api.V3/Movies/AlternativeTitleModule.cs b/src/Radarr.Api.V3/Movies/AlternativeTitleModule.cs index ecd6049d09..bf3005f9ae 100644 --- a/src/Radarr.Api.V3/Movies/AlternativeTitleModule.cs +++ b/src/Radarr.Api.V3/Movies/AlternativeTitleModule.cs @@ -2,8 +2,8 @@ using System.Collections.Generic; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.MetadataSource.RadarrAPI; -using NzbDrone.Core.Movies.AlternativeTitles; using NzbDrone.Core.Movies; +using NzbDrone.Core.Movies.AlternativeTitles; using NzbDrone.Core.Movies.Events; using Radarr.Http; diff --git a/src/Radarr.Api.V3/Movies/AlternativeTitleResource.cs b/src/Radarr.Api.V3/Movies/AlternativeTitleResource.cs index 93c2ed0b28..a85b40a42c 100644 --- a/src/Radarr.Api.V3/Movies/AlternativeTitleResource.cs +++ b/src/Radarr.Api.V3/Movies/AlternativeTitleResource.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; -using NzbDrone.Core.Movies.AlternativeTitles; using NzbDrone.Core.Languages; +using NzbDrone.Core.Movies.AlternativeTitles; +using Radarr.Http.REST; namespace Radarr.Api.V3.Movies { @@ -10,13 +10,11 @@ public class AlternativeTitleResource : RestResource { public AlternativeTitleResource() { - } //Todo: Sorters should be done completely on the client //Todo: Is there an easy way to keep IgnoreArticlesWhenSorting in sync between, Series, History, Missing? //Todo: We should get the entire Profile instead of ID and Name separately - public SourceType SourceType { get; set; } public int MovieId { get; set; } public string Title { get; set; } @@ -33,7 +31,10 @@ public static class AlternativeTitleResourceMapper { public static AlternativeTitleResource ToResource(this AlternativeTitle model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new AlternativeTitleResource { @@ -50,7 +51,10 @@ public static AlternativeTitleResource ToResource(this AlternativeTitle model) public static AlternativeTitle ToModel(this AlternativeTitleResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new AlternativeTitle { diff --git a/src/Radarr.Api.V3/Movies/AlternativeYearResource.cs b/src/Radarr.Api.V3/Movies/AlternativeYearResource.cs index 2e4daefe32..94569efd1b 100644 --- a/src/Radarr.Api.V3/Movies/AlternativeYearResource.cs +++ b/src/Radarr.Api.V3/Movies/AlternativeYearResource.cs @@ -6,13 +6,11 @@ public class AlternativeYearResource : RestResource { public AlternativeYearResource() { - } //Todo: Sorters should be done completely on the client //Todo: Is there an easy way to keep IgnoreArticlesWhenSorting in sync between, Series, History, Missing? //Todo: We should get the entire Profile instead of ID and Name separately - public int MovieId { get; set; } public int Year { get; set; } diff --git a/src/Radarr.Api.V3/Movies/FetchMovieListModule.cs b/src/Radarr.Api.V3/Movies/FetchMovieListModule.cs index b910d0fa25..8fd4615d5d 100644 --- a/src/Radarr.Api.V3/Movies/FetchMovieListModule.cs +++ b/src/Radarr.Api.V3/Movies/FetchMovieListModule.cs @@ -1,10 +1,10 @@ using System.Collections.Generic; +using System.Linq; using Nancy; using NzbDrone.Core.MediaCover; using NzbDrone.Core.MetadataSource; -using System.Linq; -using NzbDrone.Core.NetImport; using NzbDrone.Core.Movies; +using NzbDrone.Core.NetImport; using Radarr.Http; namespace Radarr.Api.V3.Movies @@ -19,13 +19,12 @@ public FetchMovieListModule(IFetchNetImport netImport, ISearchForNewMovie movieS { _fetchNetImport = netImport; _movieSearch = movieSearch; - Get("/", x => Search()); + Get("/", x => Search()); } - private object Search() { - var results = _fetchNetImport.FetchAndFilter((int) Request.Query.listId, false); + var results = _fetchNetImport.FetchAndFilter((int)Request.Query.listId, false); List<Movie> realResults = new List<Movie>(); @@ -42,7 +41,6 @@ private object Search() return MapToResource(realResults); } - private static IEnumerable<MovieResource> MapToResource(IEnumerable<Movie> movies) { foreach (var currentSeries in movies) diff --git a/src/Radarr.Api.V3/Movies/MovieDiscoverModule.cs b/src/Radarr.Api.V3/Movies/MovieDiscoverModule.cs index e3de85f9cb..f69d914486 100644 --- a/src/Radarr.Api.V3/Movies/MovieDiscoverModule.cs +++ b/src/Radarr.Api.V3/Movies/MovieDiscoverModule.cs @@ -1,12 +1,12 @@ using System.Collections.Generic; -using NzbDrone.Core.Movies; +using System.Linq; using NzbDrone.Core.MediaCover; using NzbDrone.Core.MetadataSource; -using System.Linq; -using Radarr.Http; +using NzbDrone.Core.Movies; using NzbDrone.Core.NetImport; -using Radarr.Api.V3.NetImport; using NzbDrone.Core.Organizer; +using Radarr.Api.V3.NetImport; +using Radarr.Http; namespace Radarr.Api.V3.Movies { @@ -22,8 +22,8 @@ public MovieDiscoverModule(IDiscoverNewMovies searchProxy, INetImportFactory net _searchProxy = searchProxy; _netImportFactory = netImportFactory; _fileNameBuilder = fileNameBuilder; - Get("/lists", x => GetLists()); - Get("/{action?recommendations}", x => Search(x.action)); + Get("/lists", x => GetLists()); + Get("/{action?recommendations}", x => Search(x.action)); } private object Search(string action) @@ -36,7 +36,8 @@ private object GetLists() { var lists = _netImportFactory.Discoverable(); - return lists.Select(definition => { + return lists.Select(definition => + { var resource = new NetImportResource(); resource.Id = definition.Definition.Id; diff --git a/src/Radarr.Api.V3/Movies/MovieEditorModule.cs b/src/Radarr.Api.V3/Movies/MovieEditorModule.cs index d9c460deba..66f22257a2 100644 --- a/src/Radarr.Api.V3/Movies/MovieEditorModule.cs +++ b/src/Radarr.Api.V3/Movies/MovieEditorModule.cs @@ -1,11 +1,11 @@ using System.Collections.Generic; using System.Linq; using Nancy; -using Radarr.Http.Extensions; -using NzbDrone.Core.Movies; using NzbDrone.Common.Extensions; -using NzbDrone.Core.Movies.Commands; using NzbDrone.Core.Messaging.Commands; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Movies.Commands; +using Radarr.Http.Extensions; namespace Radarr.Api.V3.Movies { @@ -19,8 +19,8 @@ public MovieEditorModule(IMovieService movieService, IManageCommandQueue command { _movieService = movieService; _commandQueueManager = commandQueueManager; - Put("/", movie => SaveAll()); - Delete("/", movie => DeleteMovies()); + Put("/", movie => SaveAll()); + Delete("/", movie => DeleteMovies()); } private object SaveAll() @@ -86,8 +86,8 @@ private object SaveAll() } return ResponseWithCode(_movieService.UpdateMovie(moviesToUpdate) - .ToResource() - , HttpStatusCode.Accepted); + .ToResource(), + HttpStatusCode.Accepted); } private object DeleteMovies() diff --git a/src/Radarr.Api.V3/Movies/MovieFolderAsRootFolderValidator.cs b/src/Radarr.Api.V3/Movies/MovieFolderAsRootFolderValidator.cs index f5af3f6a75..8fd1131cfd 100644 --- a/src/Radarr.Api.V3/Movies/MovieFolderAsRootFolderValidator.cs +++ b/src/Radarr.Api.V3/Movies/MovieFolderAsRootFolderValidator.cs @@ -18,18 +18,27 @@ public MovieFolderAsRootFolderValidator(IBuildFileNames fileNameBuilder) protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } var movieResource = context.Instance as MovieResource; - if (movieResource == null) return true; + if (movieResource == null) + { + return true; + } var rootFolderPath = context.PropertyValue.ToString(); var rootFolder = new DirectoryInfo(rootFolderPath).Name; var movie = movieResource.ToModel(); var movieFolder = _fileNameBuilder.GetMovieFolder(movie); - if (movieFolder == rootFolder) return false; + if (movieFolder == rootFolder) + { + return false; + } var distance = movieFolder.LevenshteinDistance(rootFolder); diff --git a/src/Radarr.Api.V3/Movies/MovieImportModule.cs b/src/Radarr.Api.V3/Movies/MovieImportModule.cs index 1886f5bc58..14b36d4195 100644 --- a/src/Radarr.Api.V3/Movies/MovieImportModule.cs +++ b/src/Radarr.Api.V3/Movies/MovieImportModule.cs @@ -14,10 +14,9 @@ public MovieImportModule(IMovieService movieService) : base("/movie/import") { _movieService = movieService; - Post("/", x => Import()); + Post("/", x => Import()); } - private object Import() { var resource = Request.Body.FromJson<List<MovieResource>>(); diff --git a/src/Radarr.Api.V3/Movies/MovieLookupModule.cs b/src/Radarr.Api.V3/Movies/MovieLookupModule.cs index 3ffc0c9a63..e0a445a854 100644 --- a/src/Radarr.Api.V3/Movies/MovieLookupModule.cs +++ b/src/Radarr.Api.V3/Movies/MovieLookupModule.cs @@ -1,13 +1,13 @@ +using System; using System.Collections.Generic; +using System.Linq; using Nancy; -using NzbDrone.Core.Movies; using NzbDrone.Core.MediaCover; using NzbDrone.Core.MetadataSource; -using System.Linq; -using System; +using NzbDrone.Core.Movies; +using NzbDrone.Core.Organizer; using Radarr.Http; using Radarr.Http.REST; -using NzbDrone.Core.Organizer; namespace Radarr.Api.V3.Movies { @@ -23,15 +23,15 @@ public MovieLookupModule(ISearchForNewMovie searchProxy, IProvideMovieInfo movie _movieInfo = movieInfo; _searchProxy = searchProxy; _fileNameBuilder = fileNameBuilder; - Get("/", x => Search()); - Get("/tmdb", x => SearchByTmdbId()); - Get("/imdb", x => SearchByImdbId()); + Get("/", x => Search()); + Get("/tmdb", x => SearchByTmdbId()); + Get("/imdb", x => SearchByImdbId()); } private object SearchByTmdbId() { int tmdbId = -1; - if(Int32.TryParse(Request.Query.tmdbId, out tmdbId)) + if (int.TryParse(Request.Query.tmdbId, out tmdbId)) { var result = _movieInfo.GetMovieInfo(tmdbId, null, true); return result.ToResource(); diff --git a/src/Radarr.Api.V3/Movies/MovieModule.cs b/src/Radarr.Api.V3/Movies/MovieModule.cs index 3822c3f132..1fab16beab 100644 --- a/src/Radarr.Api.V3/Movies/MovieModule.cs +++ b/src/Radarr.Api.V3/Movies/MovieModule.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using FluentValidation; +using Nancy; using NzbDrone.Common.Extensions; -using Radarr.Http.Extensions; using NzbDrone.Core.Datastore.Events; using NzbDrone.Core.MediaCover; using NzbDrone.Core.MediaFiles; @@ -9,11 +9,11 @@ using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Movies; using NzbDrone.Core.Movies.Events; -using NzbDrone.Core.Validation.Paths; using NzbDrone.Core.Validation; +using NzbDrone.Core.Validation.Paths; using NzbDrone.SignalR; -using Nancy; using Radarr.Http; +using Radarr.Http.Extensions; namespace Radarr.Api.V3.Movies { @@ -25,21 +25,19 @@ public class MovieModule : RadarrRestModuleWithSignalR<MovieResource, Movie>, IHandle<MovieDeletedEvent>, IHandle<MovieRenamedEvent>, IHandle<MediaCoversUpdatedEvent> - { protected readonly IMovieService _moviesService; private readonly IMapCoversToLocal _coverMapper; public MovieModule(IBroadcastSignalRMessage signalRBroadcaster, - IMovieService moviesService, - IMapCoversToLocal coverMapper, - RootFolderValidator rootFolderValidator, - MoviePathValidator moviesPathValidator, - MovieExistsValidator moviesExistsValidator, - MovieAncestorValidator moviesAncestorValidator, - ProfileExistsValidator profileExistsValidator, - MovieFolderAsRootFolderValidator movieFolderAsRootFolderValidator - ) + IMovieService moviesService, + IMapCoversToLocal coverMapper, + RootFolderValidator rootFolderValidator, + MoviePathValidator moviesPathValidator, + MovieExistsValidator moviesExistsValidator, + MovieAncestorValidator moviesAncestorValidator, + ProfileExistsValidator profileExistsValidator, + MovieFolderAsRootFolderValidator movieFolderAsRootFolderValidator) : base(signalRBroadcaster) { _moviesService = moviesService; @@ -93,7 +91,10 @@ private MovieResource GetMovie(int id) protected MovieResource MapToResource(Movie movies) { - if (movies == null) return null; + if (movies == null) + { + return null; + } var resource = movies.ToResource(); MapCoversToLocal(resource); @@ -159,7 +160,10 @@ public void Handle(MovieImportedEvent message) public void Handle(MovieFileDeletedEvent message) { - if (message.Reason == DeleteMediaFileReason.Upgrade) return; + if (message.Reason == DeleteMediaFileReason.Upgrade) + { + return; + } BroadcastResourceChange(ModelAction.Updated, message.MovieFile.MovieId); } diff --git a/src/Radarr.Api.V3/Movies/MovieResource.cs b/src/Radarr.Api.V3/Movies/MovieResource.cs index ce220f1485..4fae2d762d 100644 --- a/src/Radarr.Api.V3/Movies/MovieResource.cs +++ b/src/Radarr.Api.V3/Movies/MovieResource.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.MediaCover; using NzbDrone.Core.Movies; using Radarr.Api.V3.MovieFiles; +using Radarr.Http.REST; namespace Radarr.Api.V3.Movies { @@ -33,6 +33,7 @@ public MovieResource() public string PhysicalReleaseNote { get; set; } public List<MediaCover> Images { get; set; } public string Website { get; set; } + //public bool Downloaded { get; set; } public string RemotePoster { get; set; } public int Year { get; set; } @@ -66,14 +67,16 @@ public MovieResource() public AddMovieOptions AddOptions { get; set; } public Ratings Ratings { get; set; } public MovieFileResource MovieFile { get; set; } - } public static class MovieResourceMapper { public static MovieResource ToResource(this Movie model) { - if (model == null) return null; + if (model == null) + { + return null; + } long size = model.MovieFile?.Size ?? 0; MovieFileResource movieFile = model.MovieFile?.ToResource(model); @@ -131,7 +134,10 @@ public static MovieResource ToResource(this Movie model) public static Movie ToModel(this MovieResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new Movie { diff --git a/src/Radarr.Api.V3/Movies/RenameMovieModule.cs b/src/Radarr.Api.V3/Movies/RenameMovieModule.cs index 849544184b..964c28f6a9 100644 --- a/src/Radarr.Api.V3/Movies/RenameMovieModule.cs +++ b/src/Radarr.Api.V3/Movies/RenameMovieModule.cs @@ -1,7 +1,7 @@ -using Radarr.Http.REST; -using NzbDrone.Core.MediaFiles; using System.Collections.Generic; +using NzbDrone.Core.MediaFiles; using Radarr.Http; +using Radarr.Http.REST; namespace Radarr.Api.V3.Movies { @@ -21,7 +21,7 @@ private List<RenameMovieResource> GetMovies() { int movieId; - if(Request.Query.MovieId.HasValue) + if (Request.Query.MovieId.HasValue) { movieId = (int)Request.Query.MovieId; } @@ -32,6 +32,5 @@ private List<RenameMovieResource> GetMovies() return _renameMovieFileService.GetRenamePreviews(movieId).ToResource(); } - } } diff --git a/src/Radarr.Api.V3/Movies/RenameMovieResource.cs b/src/Radarr.Api.V3/Movies/RenameMovieResource.cs index c88fb701e5..5f9f710610 100644 --- a/src/Radarr.Api.V3/Movies/RenameMovieResource.cs +++ b/src/Radarr.Api.V3/Movies/RenameMovieResource.cs @@ -1,7 +1,7 @@ -using NzbDrone.Core.MediaFiles; -using Radarr.Http.REST; using System.Collections.Generic; using System.Linq; +using NzbDrone.Core.MediaFiles; +using Radarr.Http.REST; namespace Radarr.Api.V3.Movies { @@ -17,7 +17,10 @@ public static class RenameMovieResourceMapper { public static RenameMovieResource ToResource(this RenameMovieFilePreview model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new RenameMovieResource { diff --git a/src/Radarr.Api.V3/NetImport/ImportExclusionsModule.cs b/src/Radarr.Api.V3/NetImport/ImportExclusionsModule.cs index 6d07370475..ad440f1ed4 100644 --- a/src/Radarr.Api.V3/NetImport/ImportExclusionsModule.cs +++ b/src/Radarr.Api.V3/NetImport/ImportExclusionsModule.cs @@ -10,7 +10,8 @@ public class ImportExclusionsModule : RadarrRestModule<ImportExclusionsResource> { private readonly IImportExclusionsService _exclusionService; - public ImportExclusionsModule(NetImportFactory netImportFactory, IImportExclusionsService exclusionService) : base("exclusions") + public ImportExclusionsModule(NetImportFactory netImportFactory, IImportExclusionsService exclusionService) + : base("exclusions") { _exclusionService = exclusionService; GetResourceAll = GetAll; @@ -38,11 +39,10 @@ public int AddExclusion(ImportExclusionsResource exclusionResource) var model = exclusionResource.ToModel(); // TODO: Add some more validation here and auto pull the title if not provided - return _exclusionService.AddExclusion(model).Id; } - public void RemoveExclusion (int id) + public void RemoveExclusion(int id) { _exclusionService.RemoveExclusion(new ImportExclusion { Id = id }); } diff --git a/src/Radarr.Api.V3/NetImport/ImportExclusionsResource.cs b/src/Radarr.Api.V3/NetImport/ImportExclusionsResource.cs index 68a2b34524..718819e0af 100644 --- a/src/Radarr.Api.V3/NetImport/ImportExclusionsResource.cs +++ b/src/Radarr.Api.V3/NetImport/ImportExclusionsResource.cs @@ -15,7 +15,10 @@ public static class ImportExclusionsResourceMapper { public static ImportExclusionsResource ToResource(this NzbDrone.Core.NetImport.ImportExclusions.ImportExclusion model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new ImportExclusionsResource { diff --git a/src/Radarr.Api.V3/NetImport/ListImportModule.cs b/src/Radarr.Api.V3/NetImport/ListImportModule.cs index b28a4ca297..6dad28771a 100644 --- a/src/Radarr.Api.V3/NetImport/ListImportModule.cs +++ b/src/Radarr.Api.V3/NetImport/ListImportModule.cs @@ -2,10 +2,10 @@ using System.Linq; using Nancy; using Nancy.Extensions; -using Radarr.Http.Extensions; -using Radarr.Api.V3.Movies; using NzbDrone.Core.MetadataSource; using NzbDrone.Core.Movies; +using Radarr.Api.V3.Movies; +using Radarr.Http.Extensions; namespace Radarr.Api.V3.NetImport { @@ -19,16 +19,16 @@ public ListImportModule(IMovieService movieService, ISearchForNewMovie movieSear { _movieService = movieService; _movieSearch = movieSearch; - Put("/", Movie => SaveAll()); + Put("/", movie => SaveAll()); } private object SaveAll() { var resources = Request.Body.FromJson<List<MovieResource>>(); - var Movies = resources.Select(MovieResource => _movieSearch.MapMovieToTmdbMovie(MovieResource.ToModel())).Where(m => m != null).DistinctBy(m => m.TmdbId).ToList(); + var movies = resources.Select(movieResource => _movieSearch.MapMovieToTmdbMovie(movieResource.ToModel())).Where(m => m != null).DistinctBy(m => m.TmdbId).ToList(); - return ResponseWithCode(_movieService.AddMovies(Movies).ToResource(), HttpStatusCode.Accepted); + return ResponseWithCode(_movieService.AddMovies(movies).ToResource(), HttpStatusCode.Accepted); } } } diff --git a/src/Radarr.Api.V3/NetImport/NetImportModule.cs b/src/Radarr.Api.V3/NetImport/NetImportModule.cs index a93a340e10..390da99e06 100644 --- a/src/Radarr.Api.V3/NetImport/NetImportModule.cs +++ b/src/Radarr.Api.V3/NetImport/NetImportModule.cs @@ -18,7 +18,11 @@ public NetImportModule(NetImportFactory netImportFactory) protected override void Validate(NetImportDefinition definition, bool includeWarnings) { - if (!definition.Enable) return; + if (!definition.Enable) + { + return; + } + base.Validate(definition, includeWarnings); } } diff --git a/src/Radarr.Api.V3/Notifications/NotificationModule.cs b/src/Radarr.Api.V3/Notifications/NotificationModule.cs index 25b43fbc4f..a6c37aeb5c 100644 --- a/src/Radarr.Api.V3/Notifications/NotificationModule.cs +++ b/src/Radarr.Api.V3/Notifications/NotificationModule.cs @@ -13,7 +13,11 @@ public NotificationModule(NotificationFactory notificationFactory) protected override void Validate(NotificationDefinition definition, bool includeWarnings) { - if (!definition.OnGrab && !definition.OnDownload) return; + if (!definition.OnGrab && !definition.OnDownload) + { + return; + } + base.Validate(definition, includeWarnings); } } diff --git a/src/Radarr.Api.V3/Notifications/NotificationResource.cs b/src/Radarr.Api.V3/Notifications/NotificationResource.cs index 258799ae7b..f04302fb09 100644 --- a/src/Radarr.Api.V3/Notifications/NotificationResource.cs +++ b/src/Radarr.Api.V3/Notifications/NotificationResource.cs @@ -23,7 +23,10 @@ public class NotificationResourceMapper : ProviderResourceMapper<NotificationRes { public override NotificationResource ToResource(NotificationDefinition definition) { - if (definition == null) return default(NotificationResource); + if (definition == null) + { + return default(NotificationResource); + } var resource = base.ToResource(definition); @@ -44,7 +47,10 @@ public override NotificationResource ToResource(NotificationDefinition definitio public override NotificationDefinition ToModel(NotificationResource resource) { - if (resource == null) return default(NotificationDefinition); + if (resource == null) + { + return default(NotificationDefinition); + } var definition = base.ToModel(resource); diff --git a/src/Radarr.Api.V3/Profiles/Delay/DelayProfileModule.cs b/src/Radarr.Api.V3/Profiles/Delay/DelayProfileModule.cs index 1764f53b1e..4af4bcd9e3 100644 --- a/src/Radarr.Api.V3/Profiles/Delay/DelayProfileModule.cs +++ b/src/Radarr.Api.V3/Profiles/Delay/DelayProfileModule.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; using FluentValidation; -using Radarr.Http.REST; -using Radarr.Http.Validation; using NzbDrone.Core.Profiles.Delay; using Radarr.Http; +using Radarr.Http.REST; +using Radarr.Http.Validation; namespace Radarr.Api.V3.Profiles.Delay { diff --git a/src/Radarr.Api.V3/Profiles/Delay/DelayProfileResource.cs b/src/Radarr.Api.V3/Profiles/Delay/DelayProfileResource.cs index 9b1350ea4b..214f85f439 100644 --- a/src/Radarr.Api.V3/Profiles/Delay/DelayProfileResource.cs +++ b/src/Radarr.Api.V3/Profiles/Delay/DelayProfileResource.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.Indexers; using NzbDrone.Core.Profiles.Delay; +using Radarr.Http.REST; namespace Radarr.Api.V3.Profiles.Delay { @@ -21,7 +21,10 @@ public static class DelayProfileResourceMapper { public static DelayProfileResource ToResource(this DelayProfile model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new DelayProfileResource { @@ -39,7 +42,10 @@ public static DelayProfileResource ToResource(this DelayProfile model) public static DelayProfile ToModel(this DelayProfileResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new DelayProfile { diff --git a/src/Radarr.Api.V3/Profiles/Languages/LanguageModule.cs b/src/Radarr.Api.V3/Profiles/Languages/LanguageModule.cs index f96e450a33..de5d0a87d3 100644 --- a/src/Radarr.Api.V3/Profiles/Languages/LanguageModule.cs +++ b/src/Radarr.Api.V3/Profiles/Languages/LanguageModule.cs @@ -27,10 +27,10 @@ private LanguageResource GetById(int id) private List<LanguageResource> GetAll() { return Language.All.Select(l => new LanguageResource - { - Id = (int)l, - Name = l.ToString() - }) + { + Id = (int)l, + Name = l.ToString() + }) .OrderBy(l => l.Name) .ToList(); } diff --git a/src/Radarr.Api.V3/Profiles/Quality/QualityCutoffValidator.cs b/src/Radarr.Api.V3/Profiles/Quality/QualityCutoffValidator.cs index 0d1e5ff455..8ef3077847 100644 --- a/src/Radarr.Api.V3/Profiles/Quality/QualityCutoffValidator.cs +++ b/src/Radarr.Api.V3/Profiles/Quality/QualityCutoffValidator.cs @@ -18,7 +18,6 @@ public class ValidCutoffValidator<T> : PropertyValidator public ValidCutoffValidator() : base("Cutoff must be an allowed quality or group") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -29,9 +28,15 @@ protected override bool IsValid(PropertyValidatorContext context) var cutoffItem = items.SingleOrDefault(i => (i.Quality == null && i.Id == cutoff) || i.Quality?.Id == cutoff); - if (cutoffItem == null) return false; + if (cutoffItem == null) + { + return false; + } - if (!cutoffItem.Allowed) return false; + if (!cutoffItem.Allowed) + { + return false; + } return true; } diff --git a/src/Radarr.Api.V3/Profiles/Quality/QualityItemsValidator.cs b/src/Radarr.Api.V3/Profiles/Quality/QualityItemsValidator.cs index 025a71db34..ba74a24c83 100644 --- a/src/Radarr.Api.V3/Profiles/Quality/QualityItemsValidator.cs +++ b/src/Radarr.Api.V3/Profiles/Quality/QualityItemsValidator.cs @@ -26,7 +26,6 @@ public class AllowedValidator<T> : PropertyValidator public AllowedValidator() : base("Must contain at least one allowed quality") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -52,7 +51,6 @@ public class GroupItemValidator<T> : PropertyValidator public GroupItemValidator() : base("Groups must contain multiple qualities") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -73,7 +71,6 @@ public class QualityNameValidator<T> : PropertyValidator public QualityNameValidator() : base("Individual qualities should not be named") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -94,7 +91,6 @@ public class ItemGroupNameValidator<T> : PropertyValidator public ItemGroupNameValidator() : base("Groups must have a name") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -115,7 +111,6 @@ public class ItemGroupIdValidator<T> : PropertyValidator public ItemGroupIdValidator() : base("Groups must have an ID") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -136,7 +131,6 @@ public class UniqueIdValidator<T> : PropertyValidator public UniqueIdValidator() : base("Groups must have a unique ID") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -157,7 +151,6 @@ public class UniqueQualityIdValidator<T> : PropertyValidator public UniqueQualityIdValidator() : base("Qualities can only be used once") { - } protected override bool IsValid(PropertyValidatorContext context) @@ -179,7 +172,6 @@ protected override bool IsValid(PropertyValidatorContext context) qualityIds.Add(quality.Quality.Id); } } - else { if (qualityIds.Contains(item.Quality.Id)) diff --git a/src/Radarr.Api.V3/Profiles/Quality/QualityProfileModule.cs b/src/Radarr.Api.V3/Profiles/Quality/QualityProfileModule.cs index 8e5aa23608..d453342b79 100644 --- a/src/Radarr.Api.V3/Profiles/Quality/QualityProfileModule.cs +++ b/src/Radarr.Api.V3/Profiles/Quality/QualityProfileModule.cs @@ -18,6 +18,7 @@ public QualityProfileModule(IProfileService profileService, ICustomFormatService _profileService = profileService; _formatService = formatService; SharedValidator.RuleFor(c => c.Name).NotEmpty(); + // TODO: Need to validate the cutoff is allowed and the ID/quality ID exists // TODO: Need to validate the Items to ensure groups have names and at no item has no name, no items and no quality SharedValidator.RuleFor(c => c.Cutoff).ValidCutoff(); diff --git a/src/Radarr.Api.V3/Profiles/Quality/QualityProfileResource.cs b/src/Radarr.Api.V3/Profiles/Quality/QualityProfileResource.cs index 8d2bb65026..a6bda6d6ed 100644 --- a/src/Radarr.Api.V3/Profiles/Quality/QualityProfileResource.cs +++ b/src/Radarr.Api.V3/Profiles/Quality/QualityProfileResource.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; -using NzbDrone.Core.Profiles; -using NzbDrone.Core.Languages; using NzbDrone.Core.CustomFormats; +using NzbDrone.Core.Languages; +using NzbDrone.Core.Profiles; +using Radarr.Http.REST; namespace Radarr.Api.V3.Profiles.Quality { @@ -42,7 +42,10 @@ public static class ProfileResourceMapper { public static QualityProfileResource ToResource(this Profile model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new QualityProfileResource { @@ -60,7 +63,10 @@ public static QualityProfileResource ToResource(this Profile model) public static QualityProfileQualityItemResource ToResource(this ProfileQualityItem model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new QualityProfileQualityItemResource { @@ -83,7 +89,10 @@ public static ProfileFormatItemResource ToResource(this ProfileFormatItem model) public static Profile ToModel(this QualityProfileResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new Profile { @@ -101,7 +110,10 @@ public static Profile ToModel(this QualityProfileResource resource) public static ProfileQualityItem ToModel(this QualityProfileQualityItemResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new ProfileQualityItem { diff --git a/src/Radarr.Api.V3/ProviderModuleBase.cs b/src/Radarr.Api.V3/ProviderModuleBase.cs index 1f3f1c46b8..54250be050 100644 --- a/src/Radarr.Api.V3/ProviderModuleBase.cs +++ b/src/Radarr.Api.V3/ProviderModuleBase.cs @@ -24,10 +24,10 @@ protected ProviderModuleBase(IProviderFactory<TProvider, TProviderDefinition> pr _providerFactory = providerFactory; _resourceMapper = resourceMapper; - Get("schema", x => GetTemplates()); - Post("test", x => Test(ReadResourceFromRequest(true))); - Post("testall", x => TestAll()); - Post("action/{action}", x => RequestAction(x.action, ReadResourceFromRequest(true))); + Get("schema", x => GetTemplates()); + Post("test", x => Test(ReadResourceFromRequest(true))); + Post("testall", x => TestAll()); + Post("action/{action}", x => RequestAction(x.action, ReadResourceFromRequest(true))); GetResourceAll = GetAll; GetResourceById = GetProviderById; @@ -36,7 +36,7 @@ protected ProviderModuleBase(IProviderFactory<TProvider, TProviderDefinition> pr DeleteResource = DeleteProvider; SharedValidator.RuleFor(c => c.Name).NotEmpty(); - SharedValidator.RuleFor(c => c.Name).Must((v,c) => !_providerFactory.All().Any(p => p.Name == c && p.Id != v.Id)).WithMessage("Should be unique"); + SharedValidator.RuleFor(c => c.Name).Must((v, c) => !_providerFactory.All().Any(p => p.Name == c && p.Id != v.Id)).WithMessage("Should be unique"); SharedValidator.RuleFor(c => c.Implementation).NotEmpty(); SharedValidator.RuleFor(c => c.ConfigContract).NotEmpty(); @@ -155,10 +155,10 @@ private object TestAll() var validationResult = _providerFactory.Test(definition); result.Add(new ProviderTestAllResult - { - Id = definition.Id, - ValidationFailures = validationResult.Errors.ToList() - }); + { + Id = definition.Id, + ValidationFailures = validationResult.Errors.ToList() + }); } return ResponseWithCode(result, result.Any(c => !c.IsValid) ? HttpStatusCode.BadRequest : HttpStatusCode.OK); diff --git a/src/Radarr.Api.V3/ProviderResource.cs b/src/Radarr.Api.V3/ProviderResource.cs index e14944f691..376d8b5ae9 100644 --- a/src/Radarr.Api.V3/ProviderResource.cs +++ b/src/Radarr.Api.V3/ProviderResource.cs @@ -25,7 +25,6 @@ public class ProviderResourceMapper<TProviderResource, TProviderDefinition> where TProviderDefinition : ProviderDefinition, new() { public virtual TProviderResource ToResource(TProviderDefinition definition) - { return new TProviderResource { @@ -47,7 +46,10 @@ public virtual TProviderResource ToResource(TProviderDefinition definition) public virtual TProviderDefinition ToModel(TProviderResource resource) { - if (resource == null) return default(TProviderDefinition); + if (resource == null) + { + return default(TProviderDefinition); + } var definition = new TProviderDefinition { diff --git a/src/Radarr.Api.V3/Qualities/CustomFormatModule.cs b/src/Radarr.Api.V3/Qualities/CustomFormatModule.cs index f39a3c81b1..b7c185dde6 100644 --- a/src/Radarr.Api.V3/Qualities/CustomFormatModule.cs +++ b/src/Radarr.Api.V3/Qualities/CustomFormatModule.cs @@ -31,7 +31,7 @@ public CustomFormatModule(ICustomFormatService formatService, IParsingService pa var allNewTags = c.Split(',').Select(t => t.ToLower()); var enumerable = allTags.ToList(); var newTags = allNewTags.ToList(); - return (enumerable.All(newTags.Contains) && f.Id != v.Id && enumerable.Count() == newTags.Count()); + return enumerable.All(newTags.Contains) && f.Id != v.Id && enumerable.Count() == newTags.Count(); }); }) .WithMessage("Should be unique."); @@ -46,11 +46,11 @@ public CustomFormatModule(ICustomFormatService formatService, IParsingService pa DeleteResource = DeleteFormat; - Get("/test", x => Test()); + Get("/test", x => Test()); - Post("/test", x => TestWithNewModel()); + Post("/test", x => TestWithNewModel()); - Get("schema", x => GetTemplates()); + Get("schema", x => GetTemplates()); } private int Create(CustomFormatResource customFormatResource) @@ -95,11 +95,12 @@ private object GetTemplates() private CustomFormatTestResource Test() { - var parsed = _parsingService.ParseMovieInfo((string) Request.Query.title, new List<object>()); + var parsed = _parsingService.ParseMovieInfo((string)Request.Query.title, new List<object>()); if (parsed == null) { return null; } + return new CustomFormatTestResource { Matches = _parsingService.MatchFormatTags(parsed).ToResource(), @@ -109,18 +110,19 @@ private CustomFormatTestResource Test() private CustomFormatTestResource TestWithNewModel() { - var queryTitle = (string) Request.Query.title; + var queryTitle = (string)Request.Query.title; var resource = ReadResourceFromRequest(); var model = resource.ToModel(); model.Name = model.Name += " (New)"; - var parsed = _parsingService.ParseMovieInfo(queryTitle, new List<object>{model}); + var parsed = _parsingService.ParseMovieInfo(queryTitle, new List<object> { model }); if (parsed == null) { return null; } + return new CustomFormatTestResource { Matches = _parsingService.MatchFormatTags(parsed).ToResource(), diff --git a/src/Radarr.Api.V3/Qualities/CustomFormatResource.cs b/src/Radarr.Api.V3/Qualities/CustomFormatResource.cs index 098de14fcc..a7ba6b78c6 100644 --- a/src/Radarr.Api.V3/Qualities/CustomFormatResource.cs +++ b/src/Radarr.Api.V3/Qualities/CustomFormatResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.CustomFormats; +using Radarr.Http.REST; namespace Radarr.Api.V3.Qualities { diff --git a/src/Radarr.Api.V3/Qualities/FormatTagMatchResultResource.cs b/src/Radarr.Api.V3/Qualities/FormatTagMatchResultResource.cs index 2df8801457..9890a2235e 100644 --- a/src/Radarr.Api.V3/Qualities/FormatTagMatchResultResource.cs +++ b/src/Radarr.Api.V3/Qualities/FormatTagMatchResultResource.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Common.Extensions; using NzbDrone.Core.CustomFormats; +using Radarr.Http.REST; namespace Radarr.Api.V3.Qualities { @@ -29,7 +29,10 @@ public static class QualityTagMatchResultResourceMapper { public static FormatTagMatchResultResource ToResource(this FormatTagMatchResult model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new FormatTagMatchResultResource { diff --git a/src/Radarr.Api.V3/Qualities/FormatTagValidator.cs b/src/Radarr.Api.V3/Qualities/FormatTagValidator.cs index 0d77966749..bd0bcca364 100644 --- a/src/Radarr.Api.V3/Qualities/FormatTagValidator.cs +++ b/src/Radarr.Api.V3/Qualities/FormatTagValidator.cs @@ -7,7 +7,8 @@ namespace Radarr.Api.V3.Qualities { public class FormatTagValidator : PropertyValidator { - public FormatTagValidator() : base("{ValidationMessage}") + public FormatTagValidator() + : base("{ValidationMessage}") { } @@ -19,11 +20,14 @@ protected override bool IsValid(PropertyValidatorContext context) return false; } - var tags = (IEnumerable<string>) context.PropertyValue.ToString().Split(','); + var tags = (IEnumerable<string>)context.PropertyValue.ToString().Split(','); var invalidTags = tags.Where(t => !FormatTag.QualityTagRegex.IsMatch(t)); - if (invalidTags.Count() == 0) return true; + if (invalidTags.Count() == 0) + { + return true; + } var formatMessage = $"Format Tags ({string.Join(", ", invalidTags)}) are in an invalid format! Check the Wiki to learn how they should look."; diff --git a/src/Radarr.Api.V3/Qualities/QualityDefinitionModule.cs b/src/Radarr.Api.V3/Qualities/QualityDefinitionModule.cs index 281a8ac3c3..82887084ff 100644 --- a/src/Radarr.Api.V3/Qualities/QualityDefinitionModule.cs +++ b/src/Radarr.Api.V3/Qualities/QualityDefinitionModule.cs @@ -47,8 +47,8 @@ private object UpdateMany() _qualityDefinitionService.UpdateMany(qualityDefinitions); return ResponseWithCode(_qualityDefinitionService.All() - .ToResource() - , HttpStatusCode.Accepted); + .ToResource(), + HttpStatusCode.Accepted); } } } diff --git a/src/Radarr.Api.V3/Qualities/QualityDefinitionResource.cs b/src/Radarr.Api.V3/Qualities/QualityDefinitionResource.cs index 716cfddfc0..eb0c0ec185 100644 --- a/src/Radarr.Api.V3/Qualities/QualityDefinitionResource.cs +++ b/src/Radarr.Api.V3/Qualities/QualityDefinitionResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.Qualities; +using Radarr.Http.REST; namespace Radarr.Api.V3.Qualities { @@ -21,7 +21,10 @@ public static class QualityDefinitionResourceMapper { public static QualityDefinitionResource ToResource(this QualityDefinition model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new QualityDefinitionResource { @@ -40,7 +43,10 @@ public static QualityDefinitionResource ToResource(this QualityDefinition model) public static QualityDefinition ToModel(this QualityDefinitionResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new QualityDefinition { diff --git a/src/Radarr.Api.V3/Queue/QueueActionModule.cs b/src/Radarr.Api.V3/Queue/QueueActionModule.cs index 66acba5a48..5d48c6e7f4 100644 --- a/src/Radarr.Api.V3/Queue/QueueActionModule.cs +++ b/src/Radarr.Api.V3/Queue/QueueActionModule.cs @@ -33,11 +33,11 @@ public QueueActionModule(IQueueService queueService, _pendingReleaseService = pendingReleaseService; _downloadService = downloadService; - Post(@"/grab/(?<id>[\d]{1,10})", x => Grab((int)x.Id)); - Post("/grab/bulk", x => Grab()); + Post(@"/grab/(?<id>[\d]{1,10})", x => Grab((int)x.Id)); + Post("/grab/bulk", x => Grab()); - Delete(@"/(?<id>[\d]{1,10})", x => Remove((int)x.Id)); - Delete("/bulk", x => Remove()); + Delete(@"/(?<id>[\d]{1,10})", x => Remove((int)x.Id)); + Delete("/bulk", x => Remove()); } private object Grab(int id) diff --git a/src/Radarr.Api.V3/Queue/QueueModule.cs b/src/Radarr.Api.V3/Queue/QueueModule.cs index cb3223eb4f..c9c52059ed 100644 --- a/src/Radarr.Api.V3/Queue/QueueModule.cs +++ b/src/Radarr.Api.V3/Queue/QueueModule.cs @@ -20,7 +20,7 @@ public class QueueModule : RadarrRestModuleWithSignalR<QueueResource, NzbDrone.C private readonly IQueueService _queueService; private readonly IPendingReleaseService _pendingReleaseService; - private readonly QualityModelComparer QUALITY_COMPARER; + private readonly QualityModelComparer _qualityComparer; public QueueModule(IBroadcastSignalRMessage broadcastSignalRMessage, IQueueService queueService, @@ -32,7 +32,7 @@ public QueueModule(IBroadcastSignalRMessage broadcastSignalRMessage, _pendingReleaseService = pendingReleaseService; GetResourcePaged = GetQueue; - QUALITY_COMPARER = new QualityModelComparer(qualityProfileService.GetDefaultProfile(string.Empty)); + _qualityComparer = new QualityModelComparer(qualityProfileService.GetDefaultProfile(string.Empty)); } private PagingResource<QueueResource> GetQueue(PagingResource<QueueResource> pagingResource) @@ -61,7 +61,6 @@ private PagingResource<QueueResource> GetQueue(PagingResource<QueueResource> pag ? fullQueue.OrderBy(q => q.Timeleft, new TimeleftComparer()) : fullQueue.OrderByDescending(q => q.Timeleft, new TimeleftComparer()); } - else if (pagingSpec.SortKey == "estimatedCompletionTime") { ordered = ascending @@ -69,41 +68,36 @@ private PagingResource<QueueResource> GetQueue(PagingResource<QueueResource> pag : fullQueue.OrderByDescending(q => q.EstimatedCompletionTime, new EstimatedCompletionTimeComparer()); } - else if (pagingSpec.SortKey == "protocol") { ordered = ascending ? fullQueue.OrderBy(q => q.Protocol) : fullQueue.OrderByDescending(q => q.Protocol); } - else if (pagingSpec.SortKey == "indexer") { ordered = ascending ? fullQueue.OrderBy(q => q.Indexer, StringComparer.InvariantCultureIgnoreCase) : fullQueue.OrderByDescending(q => q.Indexer, StringComparer.InvariantCultureIgnoreCase); } - else if (pagingSpec.SortKey == "downloadClient") { ordered = ascending ? fullQueue.OrderBy(q => q.DownloadClient, StringComparer.InvariantCultureIgnoreCase) : fullQueue.OrderByDescending(q => q.DownloadClient, StringComparer.InvariantCultureIgnoreCase); } - else if (pagingSpec.SortKey == "quality") { ordered = ascending - ? fullQueue.OrderBy(q => q.Quality, QUALITY_COMPARER) - : fullQueue.OrderByDescending(q => q.Quality, QUALITY_COMPARER); + ? fullQueue.OrderBy(q => q.Quality, _qualityComparer) + : fullQueue.OrderByDescending(q => q.Quality, _qualityComparer); } - else { ordered = ascending ? fullQueue.OrderBy(orderByFunc) : fullQueue.OrderByDescending(orderByFunc); } - ordered = ordered.ThenByDescending(q => q.Size == 0 ? 0 : 100 - q.Sizeleft / q.Size * 100); + ordered = ordered.ThenByDescending(q => q.Size == 0 ? 0 : 100 - (q.Sizeleft / q.Size * 100)); pagingSpec.Records = ordered.Skip((pagingSpec.Page - 1) * pagingSpec.PageSize).Take(pagingSpec.PageSize).ToList(); pagingSpec.TotalRecords = fullQueue.Count; @@ -117,7 +111,7 @@ private PagingResource<QueueResource> GetQueue(PagingResource<QueueResource> pag return pagingSpec; } - private Func<NzbDrone.Core.Queue.Queue, Object> GetOrderByFunc(PagingSpec<NzbDrone.Core.Queue.Queue> pagingSpec) + private Func<NzbDrone.Core.Queue.Queue, object> GetOrderByFunc(PagingSpec<NzbDrone.Core.Queue.Queue> pagingSpec) { switch (pagingSpec.SortKey) { @@ -133,7 +127,7 @@ private PagingResource<QueueResource> GetQueue(PagingResource<QueueResource> pag return q => q.Quality; case "progress": // Avoid exploding if a download's size is 0 - return q => 100 - q.Sizeleft / Math.Max(q.Size * 100, 1); + return q => 100 - (q.Sizeleft / Math.Max(q.Size * 100, 1)); default: return q => q.Timeleft; } diff --git a/src/Radarr.Api.V3/Queue/QueueResource.cs b/src/Radarr.Api.V3/Queue/QueueResource.cs index b64b354331..5cffcae514 100644 --- a/src/Radarr.Api.V3/Queue/QueueResource.cs +++ b/src/Radarr.Api.V3/Queue/QueueResource.cs @@ -36,7 +36,10 @@ public static class QueueResourceMapper { public static QueueResource ToResource(this NzbDrone.Core.Queue.Queue model, bool includeMovie) { - if (model == null) return null; + if (model == null) + { + return null; + } return new QueueResource { diff --git a/src/Radarr.Api.V3/Queue/QueueStatusModule.cs b/src/Radarr.Api.V3/Queue/QueueStatusModule.cs index c01bf1d302..cd7196122e 100644 --- a/src/Radarr.Api.V3/Queue/QueueStatusModule.cs +++ b/src/Radarr.Api.V3/Queue/QueueStatusModule.cs @@ -17,7 +17,6 @@ public class QueueStatusModule : RadarrRestModuleWithSignalR<QueueStatusResource private readonly IPendingReleaseService _pendingReleaseService; private readonly Debouncer _broadcastDebounce; - public QueueStatusModule(IBroadcastSignalRMessage broadcastSignalRMessage, IQueueService queueService, IPendingReleaseService pendingReleaseService) : base(broadcastSignalRMessage, "queue/status") { @@ -26,8 +25,7 @@ public QueueStatusModule(IBroadcastSignalRMessage broadcastSignalRMessage, IQueu _broadcastDebounce = new Debouncer(BroadcastChange, TimeSpan.FromSeconds(5)); - - Get("/", x => GetQueueStatusResponse()); + Get("/", x => GetQueueStatusResponse()); } private object GetQueueStatusResponse() diff --git a/src/Radarr.Api.V3/RemotePathMappings/RemotePathMappingResource.cs b/src/Radarr.Api.V3/RemotePathMappings/RemotePathMappingResource.cs index 87f4c24deb..fef52fd705 100644 --- a/src/Radarr.Api.V3/RemotePathMappings/RemotePathMappingResource.cs +++ b/src/Radarr.Api.V3/RemotePathMappings/RemotePathMappingResource.cs @@ -16,7 +16,10 @@ public static class RemotePathMappingResourceMapper { public static RemotePathMappingResource ToResource(this RemotePathMapping model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new RemotePathMappingResource { @@ -30,7 +33,10 @@ public static RemotePathMappingResource ToResource(this RemotePathMapping model) public static RemotePathMapping ToModel(this RemotePathMappingResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new RemotePathMapping { diff --git a/src/Radarr.Api.V3/Restrictions/RestrictionModule.cs b/src/Radarr.Api.V3/Restrictions/RestrictionModule.cs index 91363f02af..38edc94762 100644 --- a/src/Radarr.Api.V3/Restrictions/RestrictionModule.cs +++ b/src/Radarr.Api.V3/Restrictions/RestrictionModule.cs @@ -10,7 +10,6 @@ public class RestrictionModule : RadarrRestModule<RestrictionResource> { private readonly IRestrictionService _restrictionService; - public RestrictionModule(IRestrictionService restrictionService) { _restrictionService = restrictionService; diff --git a/src/Radarr.Api.V3/Restrictions/RestrictionResource.cs b/src/Radarr.Api.V3/Restrictions/RestrictionResource.cs index 3ca323bd48..c40cb43b3c 100644 --- a/src/Radarr.Api.V3/Restrictions/RestrictionResource.cs +++ b/src/Radarr.Api.V3/Restrictions/RestrictionResource.cs @@ -22,7 +22,10 @@ public static class RestrictionResourceMapper { public static RestrictionResource ToResource(this Restriction model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new RestrictionResource { @@ -37,7 +40,10 @@ public static RestrictionResource ToResource(this Restriction model) public static Restriction ToModel(this RestrictionResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new Restriction { diff --git a/src/Radarr.Api.V3/RootFolders/RootFolderModule.cs b/src/Radarr.Api.V3/RootFolders/RootFolderModule.cs index d8ac2240aa..517b5fb9e0 100644 --- a/src/Radarr.Api.V3/RootFolders/RootFolderModule.cs +++ b/src/Radarr.Api.V3/RootFolders/RootFolderModule.cs @@ -18,9 +18,8 @@ public RootFolderModule(IRootFolderService rootFolderService, MappedNetworkDriveValidator mappedNetworkDriveValidator, StartupFolderValidator startupFolderValidator, SystemFolderValidator systemFolderValidator, - FolderWritableValidator folderWritableValidator - ) - : base(signalRBroadcaster) + FolderWritableValidator folderWritableValidator) + : base(signalRBroadcaster) { _rootFolderService = rootFolderService; diff --git a/src/Radarr.Api.V3/RootFolders/RootFolderResource.cs b/src/Radarr.Api.V3/RootFolders/RootFolderResource.cs index ed78d6f2b6..88c97df63b 100644 --- a/src/Radarr.Api.V3/RootFolders/RootFolderResource.cs +++ b/src/Radarr.Api.V3/RootFolders/RootFolderResource.cs @@ -19,7 +19,10 @@ public static class RootFolderResourceMapper { public static RootFolderResource ToResource(this RootFolder model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new RootFolderResource { @@ -34,13 +37,17 @@ public static RootFolderResource ToResource(this RootFolder model) public static RootFolder ToModel(this RootFolderResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new RootFolder { Id = resource.Id, Path = resource.Path + //Accessible //FreeSpace //UnmappedFolders diff --git a/src/Radarr.Api.V3/System/Backup/BackupModule.cs b/src/Radarr.Api.V3/System/Backup/BackupModule.cs index b3f7e0d2af..cfdda1ce12 100644 --- a/src/Radarr.Api.V3/System/Backup/BackupModule.cs +++ b/src/Radarr.Api.V3/System/Backup/BackupModule.cs @@ -30,8 +30,8 @@ public BackupModule(IBackupService backupService, GetResourceAll = GetBackupFiles; DeleteResource = DeleteBackup; - Post(@"/restore/(?<id>[\d]{1,10})", x => Restore((int)x.Id)); - Post("/restore/upload", x => UploadAndRestore()); + Post(@"/restore/(?<id>[\d]{1,10})", x => Restore((int)x.Id)); + Post("/restore/upload", x => UploadAndRestore()); } public List<BackupResource> GetBackupFiles() @@ -39,13 +39,13 @@ public List<BackupResource> GetBackupFiles() var backups = _backupService.GetBackups(); return backups.Select(b => new BackupResource - { - Id = GetBackupId(b), - Name = b.Name, - Path = $"/backup/{b.Type.ToString().ToLower()}/{b.Name}", - Type = b.Type, - Time = b.Time - }) + { + Id = GetBackupId(b), + Name = b.Name, + Path = $"/backup/{b.Type.ToString().ToLower()}/{b.Name}", + Type = b.Type, + Time = b.Time + }) .OrderByDescending(b => b.Time) .ToList(); } @@ -77,9 +77,9 @@ public object Restore(int id) _backupService.Restore(path); return new - { - RestartRequired = true - }; + { + RestartRequired = true + }; } public object UploadAndRestore() @@ -108,9 +108,9 @@ public object UploadAndRestore() _diskProvider.DeleteFile(path); return new - { - RestartRequired = true - }; + { + RestartRequired = true + }; } private string GetBackupPath(NzbDrone.Core.Backup.Backup backup) diff --git a/src/Radarr.Api.V3/System/Backup/BackupResource.cs b/src/Radarr.Api.V3/System/Backup/BackupResource.cs index 78d86f245a..605e5fb989 100644 --- a/src/Radarr.Api.V3/System/Backup/BackupResource.cs +++ b/src/Radarr.Api.V3/System/Backup/BackupResource.cs @@ -1,6 +1,6 @@ using System; -using Radarr.Http.REST; using NzbDrone.Core.Backup; +using Radarr.Http.REST; namespace Radarr.Api.V3.System.Backup { diff --git a/src/Radarr.Api.V3/System/SystemModule.cs b/src/Radarr.Api.V3/System/SystemModule.cs index 0a6c9b6584..7a3b27bb22 100644 --- a/src/Radarr.Api.V3/System/SystemModule.cs +++ b/src/Radarr.Api.V3/System/SystemModule.cs @@ -37,42 +37,42 @@ public SystemModule(IAppFolderInfo appFolderInfo, _configFileProvider = configFileProvider; _database = database; _lifecycleService = lifecycleService; - Get("/status", x => GetStatus()); - Get("/routes", x => GetRoutes()); - Post("/shutdown", x => Shutdown()); - Post("/restart", x => Restart()); + Get("/status", x => GetStatus()); + Get("/routes", x => GetRoutes()); + Post("/shutdown", x => Shutdown()); + Post("/restart", x => Restart()); } private object GetStatus() { return new - { - Version = BuildInfo.Version.ToString(), - BuildTime = BuildInfo.BuildDateTime, - IsDebug = BuildInfo.IsDebug, - IsProduction = RuntimeInfo.IsProduction, - IsAdmin = _runtimeInfo.IsAdmin, - IsUserInteractive = RuntimeInfo.IsUserInteractive, - StartupPath = _appFolderInfo.StartUpFolder, - AppData = _appFolderInfo.GetAppDataPath(), - OsName = _osInfo.Name, - OsVersion = _osInfo.Version, - IsNetCore = PlatformInfo.IsNetCore, - IsMono = PlatformInfo.IsMono, - IsLinux = OsInfo.IsLinux, - IsOsx = OsInfo.IsOsx, - IsWindows = OsInfo.IsWindows, - IsDocker = _osInfo.IsDocker, - Mode = _runtimeInfo.Mode, - Branch = _configFileProvider.Branch, - Authentication = _configFileProvider.AuthenticationMethod, - SqliteVersion = _database.Version, - MigrationVersion = _database.Migration, - UrlBase = _configFileProvider.UrlBase, - RuntimeVersion = _platformInfo.Version, - RuntimeName = PlatformInfo.Platform, - StartTime = _runtimeInfo.StartTime - }; + { + Version = BuildInfo.Version.ToString(), + BuildTime = BuildInfo.BuildDateTime, + IsDebug = BuildInfo.IsDebug, + IsProduction = RuntimeInfo.IsProduction, + IsAdmin = _runtimeInfo.IsAdmin, + IsUserInteractive = RuntimeInfo.IsUserInteractive, + StartupPath = _appFolderInfo.StartUpFolder, + AppData = _appFolderInfo.GetAppDataPath(), + OsName = _osInfo.Name, + OsVersion = _osInfo.Version, + IsNetCore = PlatformInfo.IsNetCore, + IsMono = PlatformInfo.IsMono, + IsLinux = OsInfo.IsLinux, + IsOsx = OsInfo.IsOsx, + IsWindows = OsInfo.IsWindows, + IsDocker = _osInfo.IsDocker, + Mode = _runtimeInfo.Mode, + Branch = _configFileProvider.Branch, + Authentication = _configFileProvider.AuthenticationMethod, + SqliteVersion = _database.Version, + MigrationVersion = _database.Migration, + UrlBase = _configFileProvider.UrlBase, + RuntimeVersion = _platformInfo.Version, + RuntimeName = PlatformInfo.Platform, + StartTime = _runtimeInfo.StartTime + }; } private object GetRoutes() diff --git a/src/Radarr.Api.V3/System/Tasks/TaskModule.cs b/src/Radarr.Api.V3/System/Tasks/TaskModule.cs index 8949142f79..55548ae2d0 100644 --- a/src/Radarr.Api.V3/System/Tasks/TaskModule.cs +++ b/src/Radarr.Api.V3/System/Tasks/TaskModule.cs @@ -47,15 +47,15 @@ private static TaskResource ConvertToResource(ScheduledTask scheduledTask) var taskName = scheduledTask.TypeName.Split('.').Last().Replace("Command", ""); return new TaskResource - { - Id = scheduledTask.Id, - Name = taskName.SplitCamelCase(), - TaskName = taskName, - Interval = scheduledTask.Interval, - LastExecution = scheduledTask.LastExecution, - LastStartTime = scheduledTask.LastStartTime, - NextExecution = scheduledTask.LastExecution.AddMinutes(scheduledTask.Interval) - }; + { + Id = scheduledTask.Id, + Name = taskName.SplitCamelCase(), + TaskName = taskName, + Interval = scheduledTask.Interval, + LastExecution = scheduledTask.LastExecution, + LastStartTime = scheduledTask.LastStartTime, + NextExecution = scheduledTask.LastExecution.AddMinutes(scheduledTask.Interval) + }; } public void Handle(CommandExecutedEvent message) diff --git a/src/Radarr.Api.V3/Tags/TagDetailsResource.cs b/src/Radarr.Api.V3/Tags/TagDetailsResource.cs index 4ba530795d..2981069f0d 100644 --- a/src/Radarr.Api.V3/Tags/TagDetailsResource.cs +++ b/src/Radarr.Api.V3/Tags/TagDetailsResource.cs @@ -19,7 +19,10 @@ public static class TagDetailsResourceMapper { public static TagDetailsResource ToResource(this TagDetails model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new TagDetailsResource { diff --git a/src/Radarr.Api.V3/Tags/TagResource.cs b/src/Radarr.Api.V3/Tags/TagResource.cs index b890c4f109..0b8f39114a 100644 --- a/src/Radarr.Api.V3/Tags/TagResource.cs +++ b/src/Radarr.Api.V3/Tags/TagResource.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using Radarr.Http.REST; using NzbDrone.Core.Tags; +using Radarr.Http.REST; namespace Radarr.Api.V3.Tags { @@ -14,7 +14,10 @@ public static class TagResourceMapper { public static TagResource ToResource(this Tag model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new TagResource { @@ -25,7 +28,10 @@ public static TagResource ToResource(this Tag model) public static Tag ToModel(this TagResource resource) { - if (resource == null) return null; + if (resource == null) + { + return null; + } return new Tag { diff --git a/src/Radarr.Api.V3/Update/UpdateResource.cs b/src/Radarr.Api.V3/Update/UpdateResource.cs index d887371e93..127ae45b4d 100644 --- a/src/Radarr.Api.V3/Update/UpdateResource.cs +++ b/src/Radarr.Api.V3/Update/UpdateResource.cs @@ -27,7 +27,10 @@ public static class UpdateResourceMapper { public static UpdateResource ToResource(this UpdatePackage model) { - if (model == null) return null; + if (model == null) + { + return null; + } return new UpdateResource { @@ -37,6 +40,7 @@ public static UpdateResource ToResource(this UpdatePackage model) ReleaseDate = model.ReleaseDate, FileName = model.FileName, Url = model.Url, + //Installed //Installable //Latest diff --git a/src/Radarr.Http/Authentication/AuthenticationModule.cs b/src/Radarr.Http/Authentication/AuthenticationModule.cs index a4a8d9a429..35c51f205f 100644 --- a/src/Radarr.Http/Authentication/AuthenticationModule.cs +++ b/src/Radarr.Http/Authentication/AuthenticationModule.cs @@ -16,8 +16,8 @@ public AuthenticationModule(IAuthenticationService authService, IConfigFileProvi { _authService = authService; _configFileProvider = configFileProvider; - Post("/login", x => Login(this.Bind<LoginResource>())); - Get("/logout", x => Logout()); + Post("/login", x => Login(this.Bind<LoginResource>())); + Get("/logout", x => Logout()); } private Response Login(LoginResource resource) diff --git a/src/Radarr.Http/Authentication/AuthenticationService.cs b/src/Radarr.Http/Authentication/AuthenticationService.cs index 17b6c7820f..cb5c5e8445 100644 --- a/src/Radarr.Http/Authentication/AuthenticationService.cs +++ b/src/Radarr.Http/Authentication/AuthenticationService.cs @@ -25,8 +25,8 @@ public interface IAuthenticationService : IUserValidator, IUserMapper public class AuthenticationService : IAuthenticationService { - private static readonly Logger _authLogger = LogManager.GetLogger("Auth"); private const string AnonymousUser = "Anonymous"; + private static readonly Logger _authLogger = LogManager.GetLogger("Auth"); private readonly IUserService _userService; private static string API_KEY; @@ -170,14 +170,20 @@ public bool IsAuthenticated(NancyContext context) private bool ValidUser(NancyContext context) { - if (context.CurrentUser != null) return true; + if (context.CurrentUser != null) + { + return true; + } return false; } private bool ValidApiKey(string apiKey) { - if (API_KEY.Equals(apiKey)) return true; + if (API_KEY.Equals(apiKey)) + { + return true; + } return false; } diff --git a/src/Radarr.Http/Authentication/EnableAuthInNancy.cs b/src/Radarr.Http/Authentication/EnableAuthInNancy.cs index 48da0683ac..cff6ed3b9c 100644 --- a/src/Radarr.Http/Authentication/EnableAuthInNancy.cs +++ b/src/Radarr.Http/Authentication/EnableAuthInNancy.cs @@ -19,7 +19,7 @@ public class EnableAuthInNancy : IRegisterNancyPipeline private readonly IAuthenticationService _authenticationService; private readonly IConfigService _configService; private readonly IConfigFileProvider _configFileProvider; - private FormsAuthenticationConfiguration FormsAuthConfig; + private FormsAuthenticationConfiguration _formsAuthConfig; public EnableAuthInNancy(IAuthenticationService authenticationService, IConfigService configService, @@ -39,7 +39,6 @@ public void Register(IPipelines pipelines) RegisterFormsAuth(pipelines); pipelines.AfterRequest.AddItemToEndOfPipeline((Action<NancyContext>)SlidingAuthenticationForFormsAuth); } - else if (_configFileProvider.AuthenticationMethod == AuthenticationType.Basic) { pipelines.EnableBasicAuthentication(new BasicAuthenticationConfiguration(_authenticationService, "Radarr")); @@ -57,7 +56,6 @@ private Response CaptureContext(NancyContext context) return null; } - private Response RequiresAuthentication(NancyContext context) { Response response = null; @@ -77,10 +75,9 @@ private void RegisterFormsAuth(IPipelines pipelines) var cryptographyConfiguration = new CryptographyConfiguration( new AesEncryptionProvider(new PassphraseKeyGenerator(_configService.RijndaelPassphrase, Encoding.ASCII.GetBytes(_configService.RijndaelSalt))), - new DefaultHmacProvider(new PassphraseKeyGenerator(_configService.HmacPassphrase, Encoding.ASCII.GetBytes(_configService.HmacSalt))) - ); + new DefaultHmacProvider(new PassphraseKeyGenerator(_configService.HmacPassphrase, Encoding.ASCII.GetBytes(_configService.HmacSalt)))); - FormsAuthConfig = new FormsAuthenticationConfiguration + _formsAuthConfig = new FormsAuthenticationConfiguration { RedirectUrl = _configFileProvider.UrlBase + "/login", UserMapper = _authenticationService, @@ -88,7 +85,7 @@ private void RegisterFormsAuth(IPipelines pipelines) CryptographyConfiguration = cryptographyConfiguration }; - FormsAuthentication.Enable(pipelines, FormsAuthConfig); + FormsAuthentication.Enable(pipelines, _formsAuthConfig); } private void RemoveLoginHooksForApiCalls(NancyContext context) @@ -118,7 +115,7 @@ private void SlidingAuthenticationForFormsAuth(NancyContext context) { var formsAuthCookieValue = context.Request.Cookies[formsAuthCookieName]; - if (FormsAuthentication.DecryptAndValidateAuthenticationCookie(formsAuthCookieValue, FormsAuthConfig).IsNotNullOrWhiteSpace()) + if (FormsAuthentication.DecryptAndValidateAuthenticationCookie(formsAuthCookieValue, _formsAuthConfig).IsNotNullOrWhiteSpace()) { var formsAuthCookie = new NancyCookie(formsAuthCookieName, formsAuthCookieValue, true, false, DateTime.UtcNow.AddDays(7)) { diff --git a/src/Radarr.Http/ClientSchema/SchemaBuilder.cs b/src/Radarr.Http/ClientSchema/SchemaBuilder.cs index 5f348c2d9d..7c2fb86488 100644 --- a/src/Radarr.Http/ClientSchema/SchemaBuilder.cs +++ b/src/Radarr.Http/ClientSchema/SchemaBuilder.cs @@ -50,7 +50,6 @@ public static object ReadFromSchema(List<Field> fields, Type targetType) } return target; - } public static T ReadFromSchema<T>(List<Field> fields) @@ -58,7 +57,6 @@ public static T ReadFromSchema<T>(List<Field> fields) return (T)ReadFromSchema(fields, typeof(T)); } - // Ideally this function should begin a System.Linq.Expression expression tree since it's faster. // But it's probably not needed till performance issues pop up. public static FieldMapping[] GetFieldMappings(Type type) @@ -78,6 +76,7 @@ public static FieldMapping[] GetFieldMappings(Type type) _mappings[type] = result; } + return result; } } @@ -156,32 +155,26 @@ private static Func<object, object> GetValueConverter(Type propertyType) { return fieldValue => fieldValue?.ToString().ParseInt32() ?? 0; } - else if (propertyType == typeof(long)) { return fieldValue => fieldValue?.ToString().ParseInt64() ?? 0; } - else if (propertyType == typeof(double)) { return fieldValue => fieldValue?.ToString().ParseDouble() ?? 0.0; } - else if (propertyType == typeof(int?)) { return fieldValue => fieldValue?.ToString().ParseInt32(); } - - else if (propertyType == typeof(Int64?)) + else if (propertyType == typeof(long?)) { return fieldValue => fieldValue?.ToString().ParseInt64(); } - else if (propertyType == typeof(double?)) { return fieldValue => fieldValue?.ToString().ParseDouble(); } - else if (propertyType == typeof(IEnumerable<int>)) { return fieldValue => @@ -196,7 +189,6 @@ private static Func<object, object> GetValueConverter(Type propertyType) } }; } - else if (propertyType == typeof(IEnumerable<string>)) { return fieldValue => @@ -211,7 +203,6 @@ private static Func<object, object> GetValueConverter(Type propertyType) } }; } - else { return fieldValue => fieldValue; @@ -220,7 +211,7 @@ private static Func<object, object> GetValueConverter(Type propertyType) private static string GetCamelCaseName(string name) { - return Char.ToLowerInvariant(name[0]) + name.Substring(1); + return char.ToLowerInvariant(name[0]) + name.Substring(1); } } } diff --git a/src/Radarr.Http/ErrorManagement/RadarrErrorPipeline.cs b/src/Radarr.Http/ErrorManagement/RadarrErrorPipeline.cs index 07ded72d15..08e50d6f8a 100644 --- a/src/Radarr.Http/ErrorManagement/RadarrErrorPipeline.cs +++ b/src/Radarr.Http/ErrorManagement/RadarrErrorPipeline.cs @@ -69,10 +69,12 @@ public Response HandleException(NancyContext context, Exception exception) if (context.Request.Method == "PUT" || context.Request.Method == "POST") { if (sqLiteException.Message.Contains("constraint failed")) + { return new ErrorModel { Message = exception.Message, }.AsResponse(context, HttpStatusCode.Conflict); + } } _logger.Error(sqLiteException, "[{0} {1}]", context.Request.Method, context.Request.Path); diff --git a/src/Radarr.Http/Exceptions/InvalidApiKeyException.cs b/src/Radarr.Http/Exceptions/InvalidApiKeyException.cs index d6306a5d04..7d6452f4a4 100644 --- a/src/Radarr.Http/Exceptions/InvalidApiKeyException.cs +++ b/src/Radarr.Http/Exceptions/InvalidApiKeyException.cs @@ -8,7 +8,8 @@ public InvalidApiKeyException() { } - public InvalidApiKeyException(string message) : base(message) + public InvalidApiKeyException(string message) + : base(message) { } } diff --git a/src/Radarr.Http/Extensions/Pipelines/CacheHeaderPipeline.cs b/src/Radarr.Http/Extensions/Pipelines/CacheHeaderPipeline.cs index 77befa3b17..66d2557372 100644 --- a/src/Radarr.Http/Extensions/Pipelines/CacheHeaderPipeline.cs +++ b/src/Radarr.Http/Extensions/Pipelines/CacheHeaderPipeline.cs @@ -18,12 +18,15 @@ public CacheHeaderPipeline(ICacheableSpecification cacheableSpecification) public void Register(IPipelines pipelines) { - pipelines.AfterRequest.AddItemToStartOfPipeline((Action<NancyContext>) Handle); + pipelines.AfterRequest.AddItemToStartOfPipeline((Action<NancyContext>)Handle); } private void Handle(NancyContext context) { - if (context.Request.Method == "OPTIONS") return; + if (context.Request.Method == "OPTIONS") + { + return; + } if (_cacheableSpecification.IsCacheable(context)) { diff --git a/src/Radarr.Http/Extensions/Pipelines/GZipPipeline.cs b/src/Radarr.Http/Extensions/Pipelines/GZipPipeline.cs index 3d88041958..6e9d69a919 100644 --- a/src/Radarr.Http/Extensions/Pipelines/GZipPipeline.cs +++ b/src/Radarr.Http/Extensions/Pipelines/GZipPipeline.cs @@ -51,7 +51,6 @@ private void CompressResponse(NancyContext context) response.Contents = responseStream => _writeGZipStream(contents, responseStream); } } - catch (Exception ex) { _logger.Error(ex, "Unable to gzip response"); diff --git a/src/Radarr.Http/Extensions/Pipelines/IfModifiedPipeline.cs b/src/Radarr.Http/Extensions/Pipelines/IfModifiedPipeline.cs index bcd050d87a..b614373330 100644 --- a/src/Radarr.Http/Extensions/Pipelines/IfModifiedPipeline.cs +++ b/src/Radarr.Http/Extensions/Pipelines/IfModifiedPipeline.cs @@ -18,7 +18,7 @@ public IfModifiedPipeline(ICacheableSpecification cacheableSpecification) public void Register(IPipelines pipelines) { - pipelines.BeforeRequest.AddItemToStartOfPipeline((Func<NancyContext, Response>) Handle); + pipelines.BeforeRequest.AddItemToStartOfPipeline((Func<NancyContext, Response>)Handle); } private Response Handle(NancyContext context) diff --git a/src/Radarr.Http/Extensions/Pipelines/RadarrVersionPipeline.cs b/src/Radarr.Http/Extensions/Pipelines/RadarrVersionPipeline.cs index c71c927b89..d991bd2392 100644 --- a/src/Radarr.Http/Extensions/Pipelines/RadarrVersionPipeline.cs +++ b/src/Radarr.Http/Extensions/Pipelines/RadarrVersionPipeline.cs @@ -11,7 +11,7 @@ public class RadarrVersionPipeline : IRegisterNancyPipeline public void Register(IPipelines pipelines) { - pipelines.AfterRequest.AddItemToStartOfPipeline((Action<NancyContext>) Handle); + pipelines.AfterRequest.AddItemToStartOfPipeline((Action<NancyContext>)Handle); } private void Handle(NancyContext context) diff --git a/src/Radarr.Http/Extensions/Pipelines/UrlBasePipeline.cs b/src/Radarr.Http/Extensions/Pipelines/UrlBasePipeline.cs index 9d7768a782..0eedb208e0 100644 --- a/src/Radarr.Http/Extensions/Pipelines/UrlBasePipeline.cs +++ b/src/Radarr.Http/Extensions/Pipelines/UrlBasePipeline.cs @@ -22,7 +22,7 @@ public void Register(IPipelines pipelines) { if (_urlBase.IsNotNullOrWhiteSpace()) { - pipelines.BeforeRequest.AddItemToStartOfPipeline((Func<NancyContext, Response>) Handle); + pipelines.BeforeRequest.AddItemToStartOfPipeline((Func<NancyContext, Response>)Handle); } } diff --git a/src/Radarr.Http/Extensions/ReqResExtensions.cs b/src/Radarr.Http/Extensions/ReqResExtensions.cs index 6326d907ac..d0265a996d 100644 --- a/src/Radarr.Http/Extensions/ReqResExtensions.cs +++ b/src/Radarr.Http/Extensions/ReqResExtensions.cs @@ -14,7 +14,8 @@ public static class ReqResExtensions public static readonly string LastModified = BuildInfo.BuildDateTime.ToString("r"); - public static T FromJson<T>(this Stream body) where T : class, new() + public static T FromJson<T>(this Stream body) + where T : class, new() { return FromJson<T>(body, typeof(T)); } diff --git a/src/Radarr.Http/Extensions/RequestExtensions.cs b/src/Radarr.Http/Extensions/RequestExtensions.cs index 593fa0d012..9c5e615320 100644 --- a/src/Radarr.Http/Extensions/RequestExtensions.cs +++ b/src/Radarr.Http/Extensions/RequestExtensions.cs @@ -22,9 +22,9 @@ public static bool IsSignalRRequest(this Request request) public static bool IsLocalRequest(this Request request) { - return (request.UserHostAddress.Equals("localhost") || + return request.UserHostAddress.Equals("localhost") || request.UserHostAddress.Equals("127.0.0.1") || - request.UserHostAddress.Equals("::1")); + request.UserHostAddress.Equals("::1"); } public static bool IsLoginRequest(this Request request) diff --git a/src/Radarr.Http/Frontend/CacheableSpecification.cs b/src/Radarr.Http/Frontend/CacheableSpecification.cs index 7ef86febe8..7d0ca8b44e 100644 --- a/src/Radarr.Http/Frontend/CacheableSpecification.cs +++ b/src/Radarr.Http/Frontend/CacheableSpecification.cs @@ -19,19 +19,40 @@ public bool IsCacheable(NancyContext context) return false; } - if (((DynamicDictionary)context.Request.Query).ContainsKey("h")) return true; + if (((DynamicDictionary)context.Request.Query).ContainsKey("h")) + { + return true; + } if (context.Request.Path.StartsWith("/api", StringComparison.CurrentCultureIgnoreCase)) { - if (context.Request.Path.ContainsIgnoreCase("/MediaCover")) return true; + if (context.Request.Path.ContainsIgnoreCase("/MediaCover")) + { + return true; + } return false; } - if (context.Request.Path.StartsWith("/signalr", StringComparison.CurrentCultureIgnoreCase)) return false; - if (context.Request.Path.EndsWith("index.js")) return false; - if (context.Request.Path.EndsWith("initialize.js")) return false; - if (context.Request.Path.StartsWith("/feed", StringComparison.CurrentCultureIgnoreCase)) return false; + if (context.Request.Path.StartsWith("/signalr", StringComparison.CurrentCultureIgnoreCase)) + { + return false; + } + + if (context.Request.Path.EndsWith("index.js")) + { + return false; + } + + if (context.Request.Path.EndsWith("initialize.js")) + { + return false; + } + + if (context.Request.Path.StartsWith("/feed", StringComparison.CurrentCultureIgnoreCase)) + { + return false; + } if (context.Request.Path.StartsWith("/log", StringComparison.CurrentCultureIgnoreCase) && context.Request.Path.EndsWith(".txt", StringComparison.CurrentCultureIgnoreCase)) @@ -41,7 +62,10 @@ public bool IsCacheable(NancyContext context) if (context.Response != null) { - if (context.Response.ContentType.Contains("text/html")) return false; + if (context.Response.ContentType.Contains("text/html")) + { + return false; + } } return true; diff --git a/src/Radarr.Http/Frontend/InitializeJsModule.cs b/src/Radarr.Http/Frontend/InitializeJsModule.cs index ae1fb6001c..c049f223f5 100644 --- a/src/Radarr.Http/Frontend/InitializeJsModule.cs +++ b/src/Radarr.Http/Frontend/InitializeJsModule.cs @@ -27,7 +27,7 @@ public InitializeJsModule(IConfigFileProvider configFileProvider, _apiKey = configFileProvider.ApiKey; _urlBase = configFileProvider.UrlBase; - Get("/initialize.js", x => Index()); + Get("/initialize.js", x => Index()); } private Response Index() diff --git a/src/Radarr.Http/Frontend/Mappers/FaviconMapper.cs b/src/Radarr.Http/Frontend/Mappers/FaviconMapper.cs index 250aa695e0..65efb29035 100644 --- a/src/Radarr.Http/Frontend/Mappers/FaviconMapper.cs +++ b/src/Radarr.Http/Frontend/Mappers/FaviconMapper.cs @@ -11,7 +11,7 @@ public class FaviconMapper : StaticResourceMapperBase private readonly IAppFolderInfo _appFolderInfo; private readonly IConfigFileProvider _configFileProvider; - public FaviconMapper(IAppFolderInfo appFolderInfo, IDiskProvider diskProvider,IConfigFileProvider configFileProvider, Logger logger) + public FaviconMapper(IAppFolderInfo appFolderInfo, IDiskProvider diskProvider, IConfigFileProvider configFileProvider, Logger logger) : base(diskProvider, logger) { _appFolderInfo = appFolderInfo; diff --git a/src/Radarr.Http/Frontend/Mappers/HtmlMapperBase.cs b/src/Radarr.Http/Frontend/Mappers/HtmlMapperBase.cs index c844313f14..4c52523033 100644 --- a/src/Radarr.Http/Frontend/Mappers/HtmlMapperBase.cs +++ b/src/Radarr.Http/Frontend/Mappers/HtmlMapperBase.cs @@ -18,7 +18,8 @@ public abstract class HtmlMapperBase : StaticResourceMapperBase protected HtmlMapperBase(IDiskProvider diskProvider, Func<ICacheBreakerProvider> cacheBreakProviderFactory, - Logger logger) : base(diskProvider, logger) + Logger logger) + : base(diskProvider, logger) { _diskProvider = diskProvider; _cacheBreakProviderFactory = cacheBreakProviderFactory; @@ -65,7 +66,6 @@ protected string GetHtmlText() { url = match.Groups["path"].Value; } - else { url = cacheBreakProvider.AddCacheBreakerToPath(match.Groups["path"].Value); diff --git a/src/Radarr.Http/Frontend/Mappers/IMapHttpRequestsToDisk.cs b/src/Radarr.Http/Frontend/Mappers/IMapHttpRequestsToDisk.cs index aa2edb49bc..0bdc8c600e 100644 --- a/src/Radarr.Http/Frontend/Mappers/IMapHttpRequestsToDisk.cs +++ b/src/Radarr.Http/Frontend/Mappers/IMapHttpRequestsToDisk.cs @@ -1,5 +1,4 @@ - -using Nancy; +using Nancy; namespace Radarr.Http.Frontend.Mappers { diff --git a/src/Radarr.Http/Frontend/StaticResourceModule.cs b/src/Radarr.Http/Frontend/StaticResourceModule.cs index 5661f6276d..83c1625514 100644 --- a/src/Radarr.Http/Frontend/StaticResourceModule.cs +++ b/src/Radarr.Http/Frontend/StaticResourceModule.cs @@ -12,14 +12,13 @@ public class StaticResourceModule : NancyModule private readonly IEnumerable<IMapHttpRequestsToDisk> _requestMappers; private readonly Logger _logger; - public StaticResourceModule(IEnumerable<IMapHttpRequestsToDisk> requestMappers, Logger logger) { _requestMappers = requestMappers; _logger = logger; - Get("/{resource*}", x => Index()); - Get("/", x => Index()); + Get("/{resource*}", x => Index()); + Get("/", x => Index()); } private Response Index() diff --git a/src/Radarr.Http/Mapping/MappingValidation.cs b/src/Radarr.Http/Mapping/MappingValidation.cs index 67db3c70ec..0598669193 100644 --- a/src/Radarr.Http/Mapping/MappingValidation.cs +++ b/src/Radarr.Http/Mapping/MappingValidation.cs @@ -10,7 +10,7 @@ public static class MappingValidation { public static void ValidateMapping(Type modelType, Type resourceType) { - var errors = modelType.GetSimpleProperties().Where(c=>!c.GetGetMethod().IsStatic).Select(p => GetError(resourceType, p)).Where(c => c != null).ToList(); + var errors = modelType.GetSimpleProperties().Where(c => !c.GetGetMethod().IsStatic).Select(p => GetError(resourceType, p)).Where(c => c != null).ToList(); if (errors.Any()) { diff --git a/src/Radarr.Http/Mapping/ResourceMappingException.cs b/src/Radarr.Http/Mapping/ResourceMappingException.cs index 425a0299da..e200ae678b 100644 --- a/src/Radarr.Http/Mapping/ResourceMappingException.cs +++ b/src/Radarr.Http/Mapping/ResourceMappingException.cs @@ -9,7 +9,6 @@ public class ResourceMappingException : ApplicationException public ResourceMappingException(IEnumerable<string> error) : base(Environment.NewLine + string.Join(Environment.NewLine, error.OrderBy(c => c))) { - } } } diff --git a/src/Radarr.Http/PagingResource.cs b/src/Radarr.Http/PagingResource.cs index 15a34e1563..867ee65511 100644 --- a/src/Radarr.Http/PagingResource.cs +++ b/src/Radarr.Http/PagingResource.cs @@ -29,7 +29,7 @@ public static PagingSpec<TModel> MapToPagingSpec<TResource, TModel>(this PagingR if (pagingResource.SortKey == null) { pagingSpec.SortKey = defaultSortKey; - if(pagingResource.SortDirection == SortDirection.Default) + if (pagingResource.SortDirection == SortDirection.Default) { pagingSpec.SortDirection = defaultSortDirection; } diff --git a/src/Radarr.Http/REST/ResourceValidator.cs b/src/Radarr.Http/REST/ResourceValidator.cs index 421fad93a5..1c6ccd4964 100644 --- a/src/Radarr.Http/REST/ResourceValidator.cs +++ b/src/Radarr.Http/REST/ResourceValidator.cs @@ -23,7 +23,6 @@ public IRuleBuilderInitial<TResource, TProperty> RuleForField<TProperty>(Express private static object GetValue(object container, Func<TResource, IEnumerable<Field>> fieldListAccessor, string fieldName) { - var resource = fieldListAccessor((TResource)container).SingleOrDefault(c => c.Name == fieldName); if (resource == null) diff --git a/src/Radarr.Http/REST/RestModule.cs b/src/Radarr.Http/REST/RestModule.cs index 2147425138..815363837e 100644 --- a/src/Radarr.Http/REST/RestModule.cs +++ b/src/Radarr.Http/REST/RestModule.cs @@ -16,7 +16,7 @@ public abstract class RestModule<TResource> : NancyModule private const string ROOT_ROUTE = "/"; private const string ID_ROUTE = @"/(?<id>[\d]{1,10})"; - private HashSet<string> EXCLUDED_KEYS = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase) + private readonly HashSet<string> _excludedKeys = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase) { "page", "pageSize", @@ -56,10 +56,12 @@ protected RestModule(string modulePath) SharedValidator = new ResourceValidator<TResource>(); } - private void ValidateModule() { - if (GetResourceById != null) return; + if (GetResourceById != null) + { + return; + } if (CreateResource != null || UpdateResource != null) { @@ -69,7 +71,11 @@ private void ValidateModule() protected Action<int> DeleteResource { - private get { return _deleteResource; } + private get + { + return _deleteResource; + } + set { _deleteResource = value; @@ -85,7 +91,11 @@ protected Action<int> DeleteResource protected Func<int, TResource> GetResourceById { - get { return _getResourceById; } + get + { + return _getResourceById; + } + set { _getResourceById = value; @@ -113,11 +123,14 @@ protected Func<int, TResource> GetResourceById protected Func<List<TResource>> GetResourceAll { - private get { return _getResourceAll; } + private get + { + return _getResourceAll; + } + set { _getResourceAll = value; - Get(ROOT_ROUTE, options => { var resource = GetResourceAll(); @@ -128,11 +141,14 @@ protected Func<List<TResource>> GetResourceAll protected Func<PagingResource<TResource>, PagingResource<TResource>> GetResourcePaged { - private get { return _getResourcePaged; } + private get + { + return _getResourcePaged; + } + set { _getResourcePaged = value; - Get(ROOT_ROUTE, options => { var resource = GetResourcePaged(ReadPagingResourceFromRequest()); @@ -143,11 +159,14 @@ protected Func<PagingResource<TResource>, PagingResource<TResource>> GetResource protected Func<TResource> GetResourceSingle { - private get { return _getResourceSingle; } + private get + { + return _getResourceSingle; + } + set { _getResourceSingle = value; - Get(ROOT_ROUTE, options => { var resource = GetResourceSingle(); @@ -158,7 +177,11 @@ protected Func<TResource> GetResourceSingle protected Func<TResource, int> CreateResource { - private get { return _createResource; } + private get + { + return _createResource; + } + set { _createResource = value; @@ -172,7 +195,11 @@ protected Func<TResource, int> CreateResource protected Action<TResource> UpdateResource { - private get { return _updateResource; } + private get + { + return _updateResource; + } + set { _updateResource = value; @@ -182,7 +209,6 @@ protected Action<TResource> UpdateResource UpdateResource(resource); return ResponseWithCode(GetResourceById(resource.Id), HttpStatusCode.Accepted); }); - Put(ID_ROUTE, options => { var resource = ReadResourceFromRequest(); @@ -239,12 +265,17 @@ private PagingResource<TResource> ReadPagingResourceFromRequest() { int pageSize; int.TryParse(Request.Query.PageSize.ToString(), out pageSize); - if (pageSize == 0) pageSize = 10; + if (pageSize == 0) + { + pageSize = 10; + } int page; int.TryParse(Request.Query.Page.ToString(), out page); - if (page == 0) page = 1; - + if (page == 0) + { + page = 1; + } var pagingResource = new PagingResource<TResource> { @@ -280,9 +311,9 @@ private PagingResource<TResource> ReadPagingResourceFromRequest() if (Request.Query.FilterKey != null) { var filter = new PagingResourceFilter - { - Key = Request.Query.FilterKey.ToString() - }; + { + Key = Request.Query.FilterKey.ToString() + }; if (Request.Query.FilterValue != null) { @@ -293,19 +324,18 @@ private PagingResource<TResource> ReadPagingResourceFromRequest() } // v3 uses filters in key=value format - foreach (var key in Request.Query) { - if (EXCLUDED_KEYS.Contains(key)) + if (_excludedKeys.Contains(key)) { continue; } pagingResource.Filters.Add(new PagingResourceFilter - { - Key = key, - Value = Request.Query[key] - }); + { + Key = key, + Value = Request.Query[key] + }); } return pagingResource; diff --git a/src/Radarr.Http/RadarrBootstrapper.cs b/src/Radarr.Http/RadarrBootstrapper.cs index 15b25cfcb3..c6d5f7e8b8 100644 --- a/src/Radarr.Http/RadarrBootstrapper.cs +++ b/src/Radarr.Http/RadarrBootstrapper.cs @@ -57,7 +57,8 @@ protected override Func<ITypeCatalog, NancyInternalConfiguration> InternalConfig get { // We don't support Xml Serialization atm - return NancyInternalConfiguration.WithOverrides(x => { + return NancyInternalConfiguration.WithOverrides(x => + { x.ResponseProcessors.Remove(typeof(ViewProcessor)); x.ResponseProcessors.Remove(typeof(XmlProcessor)); }); diff --git a/src/Radarr.Http/RadarrRestModule.cs b/src/Radarr.Http/RadarrRestModule.cs index f1f36c6cb0..e351314b5b 100644 --- a/src/Radarr.Http/RadarrRestModule.cs +++ b/src/Radarr.Http/RadarrRestModule.cs @@ -5,11 +5,11 @@ namespace Radarr.Http { - public abstract class RadarrRestModule<TResource> : RestModule<TResource> where TResource : RestResource, new() + public abstract class RadarrRestModule<TResource> : RestModule<TResource> + where TResource : RestResource, new() { protected string Resource { get; private set; } - private static string BaseUrl() { var isV3 = typeof(TResource).Namespace.Contains(".V3."); @@ -17,6 +17,7 @@ private static string BaseUrl() { return "/api/v3/"; } + return "/api/"; } diff --git a/src/Radarr.Http/RadarrRestModuleWithSignalR.cs b/src/Radarr.Http/RadarrRestModuleWithSignalR.cs index b67127ab3d..67b6bec60e 100644 --- a/src/Radarr.Http/RadarrRestModuleWithSignalR.cs +++ b/src/Radarr.Http/RadarrRestModuleWithSignalR.cs @@ -25,7 +25,10 @@ protected RadarrRestModuleWithSignalR(IBroadcastSignalRMessage signalRBroadcaste public void Handle(ModelEvent<TModel> message) { - if (!_signalRBroadcaster.IsConnected) return; + if (!_signalRBroadcaster.IsConnected) + { + return; + } if (message.Action == ModelAction.Deleted || message.Action == ModelAction.Sync) { @@ -37,11 +40,14 @@ public void Handle(ModelEvent<TModel> message) protected void BroadcastResourceChange(ModelAction action, int id) { - if (!_signalRBroadcaster.IsConnected) return; + if (!_signalRBroadcaster.IsConnected) + { + return; + } if (action == ModelAction.Deleted) { - BroadcastResourceChange(action, new TResource {Id = id}); + BroadcastResourceChange(action, new TResource { Id = id }); } else { @@ -52,16 +58,19 @@ protected void BroadcastResourceChange(ModelAction action, int id) protected void BroadcastResourceChange(ModelAction action, TResource resource) { - if (!_signalRBroadcaster.IsConnected) return; + if (!_signalRBroadcaster.IsConnected) + { + return; + } if (GetType().Namespace.Contains("V3")) { var signalRMessage = new SignalRMessage - { - Name = Resource, - Body = new ResourceChangeMessage<TResource>(resource, action), - Action = action - }; + { + Name = Resource, + Body = new ResourceChangeMessage<TResource>(resource, action), + Action = action + }; _signalRBroadcaster.BroadcastMessage(signalRMessage); } @@ -69,16 +78,19 @@ protected void BroadcastResourceChange(ModelAction action, TResource resource) protected void BroadcastResourceChange(ModelAction action) { - if (!_signalRBroadcaster.IsConnected) return; + if (!_signalRBroadcaster.IsConnected) + { + return; + } if (GetType().Namespace.Contains("V3")) { var signalRMessage = new SignalRMessage - { - Name = Resource, - Body = new ResourceChangeMessage<TResource>(action), - Action = action - }; + { + Name = Resource, + Body = new ResourceChangeMessage<TResource>(action), + Action = action + }; _signalRBroadcaster.BroadcastMessage(signalRMessage); } diff --git a/src/Radarr.Http/ResourceChangeMessage.cs b/src/Radarr.Http/ResourceChangeMessage.cs index 29aabc6b6b..03b88fc11c 100644 --- a/src/Radarr.Http/ResourceChangeMessage.cs +++ b/src/Radarr.Http/ResourceChangeMessage.cs @@ -4,7 +4,8 @@ namespace Radarr.Http { - public class ResourceChangeMessage<TResource> where TResource : RestResource + public class ResourceChangeMessage<TResource> + where TResource : RestResource { public TResource Resource { get; private set; } public ModelAction Action { get; private set; } @@ -25,5 +26,4 @@ public ResourceChangeMessage(TResource resource, ModelAction action) Action = action; } } - } diff --git a/src/Radarr.Http/TinyIoCNancyBootstrapper.cs b/src/Radarr.Http/TinyIoCNancyBootstrapper.cs index ed9bdf89f3..22506f3090 100644 --- a/src/Radarr.Http/TinyIoCNancyBootstrapper.cs +++ b/src/Radarr.Http/TinyIoCNancyBootstrapper.cs @@ -1,17 +1,17 @@ -using TinyIoC; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Nancy; -using Nancy.Diagnostics; using Nancy.Bootstrapper; using Nancy.Configuration; +using Nancy.Diagnostics; +using TinyIoC; + +#pragma warning disable SX1101 namespace Radarr.Http { - - /// <summary> /// TinyIoC bootstrapper - registers default route resolver and registers itself as /// INancyModuleCatalog for resolving modules but behaviour can be overridden if required. @@ -53,42 +53,32 @@ protected override sealed INancyEngine GetEngineInternal() return this.ApplicationContainer.Resolve<INancyEngine>(); } - // - // Summary: - // Gets the Nancy.Configuration.INancyEnvironmentConfigurator used by th. - // - // Returns: - // An Nancy.Configuration.INancyEnvironmentConfigurator instance. + /// <summary></summary> + /// Gets the Nancy.Configuration.INancyEnvironmentConfigurator used by th. + /// </summary> + /// <returns>An Nancy.Configuration.INancyEnvironmentConfigurator instance.</returns> protected override INancyEnvironmentConfigurator GetEnvironmentConfigurator() { return this.ApplicationContainer.Resolve<INancyEnvironmentConfigurator>(); } - // - // Summary: - // Get the Nancy.Configuration.INancyEnvironment instance. - // - // Returns: - // An configured Nancy.Configuration.INancyEnvironment instance. - // - // Remarks: - // The boostrapper must be initialised (Nancy.Bootstrapper.INancyBootstrapper.Initialise) - // prior to calling this. + /// <summary> + /// Get the Nancy.Configuration.INancyEnvironment instance. + /// </summary> + /// <returns>An configured Nancy.Configuration.INancyEnvironment instance.</returns> + /// <remarks> + /// The boostrapper must be initialised (Nancy.Bootstrapper.INancyBootstrapper.Initialise) prior to calling this. + /// </remarks> public override INancyEnvironment GetEnvironment() { return this.ApplicationContainer.Resolve<INancyEnvironment>(); } - // - // Summary: - // Registers an Nancy.Configuration.INancyEnvironment instance in the container. - // - // Parameters: - // container: - // The container to register into. - // - // environment: - // The Nancy.Configuration.INancyEnvironment instance to register. + /// <summary> + /// Registers an Nancy.Configuration.INancyEnvironment instance in the container. + /// </summary> + /// <param name="container">The container to register into.</param> + /// <param name="environment">The Nancy.Configuration.INancyEnvironment instance to register.</param> protected override void RegisterNancyEnvironment(TinyIoCContainer container, INancyEnvironment environment) { ApplicationContainer.Register<INancyEnvironment>(environment); diff --git a/src/Radarr.Http/Validation/EmptyCollectionValidator.cs b/src/Radarr.Http/Validation/EmptyCollectionValidator.cs index 1ebd9ed514..8358326182 100644 --- a/src/Radarr.Http/Validation/EmptyCollectionValidator.cs +++ b/src/Radarr.Http/Validation/EmptyCollectionValidator.cs @@ -13,7 +13,10 @@ public EmptyCollectionValidator() protected override bool IsValid(PropertyValidatorContext context) { - if (context.PropertyValue == null) return true; + if (context.PropertyValue == null) + { + return true; + } var collection = context.PropertyValue as IEnumerable<T>; diff --git a/src/ServiceHelpers/ServiceInstall/Program.cs b/src/ServiceHelpers/ServiceInstall/Program.cs index 02938247b9..2cd9e7f376 100644 --- a/src/ServiceHelpers/ServiceInstall/Program.cs +++ b/src/ServiceHelpers/ServiceInstall/Program.cs @@ -2,7 +2,7 @@ { public static class Program { - static void Main() + private static void Main() { ServiceHelper.Run(@"/i"); } diff --git a/src/ServiceHelpers/ServiceInstall/ServiceHelper.cs b/src/ServiceHelpers/ServiceInstall/ServiceHelper.cs index 2b8fa682b2..a651ae3178 100644 --- a/src/ServiceHelpers/ServiceInstall/ServiceHelper.cs +++ b/src/ServiceHelpers/ServiceInstall/ServiceHelper.cs @@ -31,18 +31,18 @@ public static void Run(string arg) } var startInfo = new ProcessStartInfo - { - FileName = RadarrExe, - Arguments = arg, - UseShellExecute = false, - RedirectStandardOutput = true, - RedirectStandardError = true, - CreateNoWindow = true - }; + { + FileName = RadarrExe, + Arguments = arg, + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true + }; var process = new Process { StartInfo = startInfo }; - process.OutputDataReceived += (OnDataReceived); - process.ErrorDataReceived += (OnDataReceived); + process.OutputDataReceived += OnDataReceived; + process.ErrorDataReceived += OnDataReceived; process.Start(); @@ -50,13 +50,11 @@ public static void Run(string arg) process.BeginOutputReadLine(); process.WaitForExit(); - } private static void OnDataReceived(object sender, DataReceivedEventArgs e) { Console.WriteLine(e.Data); } - } } diff --git a/src/ServiceHelpers/ServiceUninstall/Program.cs b/src/ServiceHelpers/ServiceUninstall/Program.cs index c8bc4f181f..f57066bb77 100644 --- a/src/ServiceHelpers/ServiceUninstall/Program.cs +++ b/src/ServiceHelpers/ServiceUninstall/Program.cs @@ -2,7 +2,7 @@ { public static class Program { - static void Main() + private static void Main() { ServiceHelper.Run(@"/u"); } diff --git a/src/ServiceHelpers/ServiceUninstall/ServiceHelper.cs b/src/ServiceHelpers/ServiceUninstall/ServiceHelper.cs index 22e08424fa..174a79ffde 100644 --- a/src/ServiceHelpers/ServiceUninstall/ServiceHelper.cs +++ b/src/ServiceHelpers/ServiceUninstall/ServiceHelper.cs @@ -31,18 +31,18 @@ public static void Run(string arg) } var startInfo = new ProcessStartInfo - { - FileName = RadarrExe, - Arguments = arg, - UseShellExecute = false, - RedirectStandardOutput = true, - RedirectStandardError = true, - CreateNoWindow = true - }; + { + FileName = RadarrExe, + Arguments = arg, + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true + }; var process = new Process { StartInfo = startInfo }; - process.OutputDataReceived += (OnDataReceived); - process.ErrorDataReceived += (OnDataReceived); + process.OutputDataReceived += OnDataReceived; + process.ErrorDataReceived += OnDataReceived; process.Start(); @@ -50,13 +50,11 @@ public static void Run(string arg) process.BeginOutputReadLine(); process.WaitForExit(); - } private static void OnDataReceived(object sender, DataReceivedEventArgs e) { Console.WriteLine(e.Data); } - } } diff --git a/src/Stylecop.ruleset b/src/Stylecop.ruleset new file mode 100644 index 0000000000..2cc451f2d2 --- /dev/null +++ b/src/Stylecop.ruleset @@ -0,0 +1,115 @@ +<RuleSet Name="Stylecop.ruleset" Description="Rules for Radarr" ToolsVersion="15.0"> + <Rules AnalyzerId="StyleCop.CSharp.SpecialRules" + RuleNamespace="StyleCop.CSharp.SpecialRules"> + <Rule Id="SA0001" Action="None" /> + </Rules> + <Rules AnalyzerId="StyleCop.CSharp.SpacingRules" + RuleNamespace="StyleCop.CSharp.SpacingRules"> + <Rule Id="SA1005" Action="None" /> + <Rule Id="SA1025" Action="None" /> + </Rules> + <Rules AnalyzerId="StyleCop.CSharp.ReadabilityRules" + RuleNamespace="StyleCop.CSharp.ReadabilityRules"> + <Rule Id="SA1101" Action="None" /> + <Rule Id="SA1116" Action="None" /> + <Rule Id="SA1118" Action="None" /> + <Rule Id="SA1122" Action="None" /> + </Rules> + <Rules AnalyzerId="StyleCop.CSharp.OrderingRules" + RuleNamespace="StyleCop.CSharp.OrderingRules"> + <Rule Id="SA1201" Action="Info" /> + <Rule Id="SA1202" Action="Info" /> + <Rule Id="SA1204" Action="Info" /> + </Rules> + <Rules AnalyzerId="StyleCop.CSharp.NamingRules" + RuleNamespace="StyleCop.CSharp.NamingRules"> + <Rule Id="SA1300" Action="None" /> + <Rule Id="SA1301" Action="None" /> + <Rule Id="SA1303" Action="None" /> + <Rule Id="SA1304" Action="None" /> + <Rule Id="SA1306" Action="None" /> + <Rule Id="SA1309" Action="None" /> + <Rule Id="SA1310" Action="None" /> + </Rules> + <Rules AnalyzerId="StyleCop.CSharp.MaintainabilityRules" + RuleNamespace="StyleCop.CSharp.MaintainabilityRules"> + <Rule Id="SA1400" Action="Warning" /> + <Rule Id="SA1401" Action="None" /> + <Rule Id="SA1402" Action="None" /> + <Rule Id="SA1404" Action="Info" /> + <Rule Id="SA1405" Action="Info" /> + <Rule Id="SA1406" Action="Info" /> + <Rule Id="SA1409" Action="Info" /> + <Rule Id="SA1410" Action="Info" /> + <Rule Id="SA1411" Action="Info" /> + <Rule Id="SA1412" Action="None" /> + <Rule Id="SA1413" Action="None" /> + <Rule Id="SA1414" Action="None" /> + </Rules> + <Rules AnalyzerId="StyleCop.CSharp.LayoutRules" + RuleNamespace="StyleCop.CSharp.LayoutRules"> + <Rule Id="SA1516" Action="None" /> + </Rules> + <Rules AnalyzerId="StyleCop.CSharp.DocumentationRules" + RuleNamespace="StyleCop.CSharp.DocumentationRules"> + <Rule Id="SA1600" Action="None" /> + <Rule Id="SA1601" Action="None" /> + <Rule Id="SA1602" Action="None" /> + <Rule Id="SA1603" Action="None" /> + <Rule Id="SA1604" Action="None" /> + <Rule Id="SA1605" Action="None" /> + <Rule Id="SA1606" Action="None" /> + <Rule Id="SA1607" Action="None" /> + <Rule Id="SA1608" Action="None" /> + <Rule Id="SA1609" Action="None" /> + <Rule Id="SA1610" Action="None" /> + <Rule Id="SA1611" Action="None" /> + <Rule Id="SA1612" Action="None" /> + <Rule Id="SA1613" Action="None" /> + <Rule Id="SA1614" Action="None" /> + <Rule Id="SA1615" Action="None" /> + <Rule Id="SA1616" Action="None" /> + <Rule Id="SA1617" Action="None" /> + <Rule Id="SA1618" Action="None" /> + <Rule Id="SA1619" Action="None" /> + <Rule Id="SA1620" Action="None" /> + <Rule Id="SA1621" Action="None" /> + <Rule Id="SA1622" Action="None" /> + <Rule Id="SA1623" Action="None" /> + <Rule Id="SA1624" Action="None" /> + <Rule Id="SA1625" Action="None" /> + <Rule Id="SA1626" Action="None" /> + <Rule Id="SA1627" Action="None" /> + <Rule Id="SA1628" Action="None" /> + <Rule Id="SA1629" Action="None" /> + <Rule Id="SA1630" Action="None" /> + <Rule Id="SA1631" Action="None" /> + <Rule Id="SA1632" Action="None" /> + <Rule Id="SA1633" Action="None" /> + <Rule Id="SA1634" Action="None" /> + <Rule Id="SA1635" Action="None" /> + <Rule Id="SA1636" Action="None" /> + <Rule Id="SA1637" Action="None" /> + <Rule Id="SA1638" Action="None" /> + <Rule Id="SA1639" Action="None" /> + <Rule Id="SA1640" Action="None" /> + <Rule Id="SA1641" Action="None" /> + <Rule Id="SA1642" Action="None" /> + <Rule Id="SA1643" Action="None" /> + <Rule Id="SA1644" Action="None" /> + <Rule Id="SA1645" Action="None" /> + <Rule Id="SA1646" Action="None" /> + <Rule Id="SA1647" Action="None" /> + <Rule Id="SA1648" Action="None" /> + <Rule Id="SA1649" Action="None" /> + <Rule Id="SA1650" Action="None" /> + <Rule Id="SA1651" Action="None" /> + <Rule Id="SA1652" Action="None" /> + </Rules> + <Rules AnalyzerId="StyleCop.CSharp.AlternativeRules" + RuleNamespace="StyleCop.CSharp.AlternativeRules"> + <!-- Do not prefix local members with this --> + <Rule Id="SX1101" Action="Warning" /> + <Rule Id="SX1309" Action="Warning" /> + </Rules> +</RuleSet> diff --git a/src/stylecop.json b/src/stylecop.json new file mode 100644 index 0000000000..b4321a13b1 --- /dev/null +++ b/src/stylecop.json @@ -0,0 +1,21 @@ +{ + "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json", + "settings": { + "documentationRules": { + "xmlHeader": false, + "documentInterfaces": false, + "documentInternalElements": false + }, + "indentation": { + "indentationSize": 4, + "useTabs": false + }, + "layoutRules": { + "newlineAtEndOfFile": "require" + }, + "orderingRules": { + "systemUsingDirectivesFirst": true, + "usingDirectivesPlacement": "outsideNamespace" + } + } +}